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 // If we know that the selected element is always zero, we don't need the
3980 // select value element.
3981 APInt DemandedSel = DemandedElts & ~KnownZero;
3982 if (DemandedSel != DemandedElts)
3983 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3984 Depth + 1))
3985 return true;
3986
3987 break;
3988 }
3989 case ISD::VECTOR_SHUFFLE: {
3990 SDValue LHS = Op.getOperand(0);
3991 SDValue RHS = Op.getOperand(1);
3992 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3993
3994 // Collect demanded elements from shuffle operands..
3995 APInt DemandedLHS(NumElts, 0);
3996 APInt DemandedRHS(NumElts, 0);
3997 for (unsigned i = 0; i != NumElts; ++i) {
3998 int M = ShuffleMask[i];
3999 if (M < 0 || !DemandedElts[i])
4000 continue;
4001 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
4002 if (M < (int)NumElts)
4003 DemandedLHS.setBit(M);
4004 else
4005 DemandedRHS.setBit(M - NumElts);
4006 }
4007
4008 // If either side isn't demanded, replace it by UNDEF. We handle this
4009 // explicitly here to also simplify in case of multiple uses (on the
4010 // contrary to the SimplifyDemandedVectorElts calls below).
4011 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
4012 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
4013 if (FoldLHS || FoldRHS) {
4014 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
4015 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
4016 SDValue NewOp =
4017 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
4018 return TLO.CombineTo(Op, NewOp);
4019 }
4020
4021 // See if we can simplify either shuffle operand.
4022 APInt UndefLHS, ZeroLHS;
4023 APInt UndefRHS, ZeroRHS;
4024 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
4025 Depth + 1))
4026 return true;
4027 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
4028 Depth + 1))
4029 return true;
4030
4031 // Simplify mask using undef elements from LHS/RHS.
4032 bool Updated = false;
4033 bool IdentityLHS = true, IdentityRHS = true;
4034 SmallVector<int, 32> NewMask(ShuffleMask);
4035 for (unsigned i = 0; i != NumElts; ++i) {
4036 int &M = NewMask[i];
4037 if (M < 0)
4038 continue;
4039 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
4040 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
4041 Updated = true;
4042 M = -1;
4043 }
4044 IdentityLHS &= (M < 0) || (M == (int)i);
4045 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
4046 }
4047
4048 // Update legal shuffle masks based on demanded elements if it won't reduce
4049 // to Identity which can cause premature removal of the shuffle mask.
4050 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
4051 SDValue LegalShuffle =
4052 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
4053 if (LegalShuffle)
4054 return TLO.CombineTo(Op, LegalShuffle);
4055 }
4056
4057 // Propagate undef/zero elements from LHS/RHS.
4058 for (unsigned i = 0; i != NumElts; ++i) {
4059 int M = ShuffleMask[i];
4060 if (M < 0) {
4061 KnownUndef.setBit(i);
4062 } else if (M < (int)NumElts) {
4063 if (UndefLHS[M])
4064 KnownUndef.setBit(i);
4065 if (ZeroLHS[M])
4066 KnownZero.setBit(i);
4067 } else {
4068 if (UndefRHS[M - NumElts])
4069 KnownUndef.setBit(i);
4070 if (ZeroRHS[M - NumElts])
4071 KnownZero.setBit(i);
4072 }
4073 }
4074 break;
4075 }
4077 SDValue Src = Op.getOperand(0);
4078 SDValue Mask = Op.getOperand(1);
4079
4080 // Result element i only depends on mask element i, so the elements required
4081 // from the mask are the same as the demanded result elements.
4082 APInt DemandedMask = DemandedElts;
4083 APInt UndefMask, ZeroMask;
4084 if (!DemandedMask.isAllOnes() &&
4085 SimplifyDemandedVectorElts(Mask, DemandedMask, UndefMask, ZeroMask, TLO,
4086 Depth + 1))
4087 return true;
4088
4089 // Only those source elements are required which are indexed by the demanded
4090 // elements of the mask. So source elements that are not in the range
4091 // specified by the following are not required.
4093 Mask, DemandedMask, /*ForSigned=*/false, Depth + 1);
4094 // Indexes >= NumElts produce poison, so they don't require any source
4095 // elements.
4096 unsigned Lo = KnownRange.getUnsignedMin().getLimitedValue(NumElts);
4097 unsigned Hi = KnownRange.getUnsignedMax().getLimitedValue(NumElts - 1) + 1;
4098
4099 APInt DemandedSrc = APInt::getBitsSet(NumElts, Lo, Hi);
4100 APInt UndefSrc, ZeroSrc;
4101 if (!DemandedSrc.isAllOnes() &&
4102 SimplifyDemandedVectorElts(Src, DemandedSrc, UndefSrc, ZeroSrc, TLO,
4103 Depth + 1))
4104 return true;
4105
4106 break;
4107 }
4111 APInt SrcUndef, SrcZero;
4112 SDValue Src = Op.getOperand(0);
4113 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4114 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
4115 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
4116 Depth + 1))
4117 return true;
4118 KnownZero = SrcZero.zextOrTrunc(NumElts);
4119 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
4120
4121 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
4122 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
4123 DemandedSrcElts == 1) {
4124 // aext - if we just need the bottom element then we can bitcast.
4125 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
4126 }
4127
4128 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
4129 // zext(undef) upper bits are guaranteed to be zero.
4130 if (DemandedElts.isSubsetOf(KnownUndef))
4131 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4132 KnownUndef.clearAllBits();
4133
4134 // zext - if we just need the bottom element then we can mask:
4135 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
4136 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
4137 Op->isOnlyUserOf(Src.getNode()) &&
4138 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
4139 SDLoc DL(Op);
4140 EVT SrcVT = Src.getValueType();
4141 EVT SrcSVT = SrcVT.getScalarType();
4142
4143 // If we're after type legalization and SrcSVT is not legal, use the
4144 // promoted type for creating constants to avoid creating nodes with
4145 // illegal types.
4146 if (TLO.LegalTypes())
4147 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
4148
4149 SmallVector<SDValue> MaskElts;
4150 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
4151 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
4152 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
4153 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
4154 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
4155 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
4156 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
4157 }
4158 }
4159 }
4160 break;
4161 }
4162
4163 // TODO: There are more binop opcodes that could be handled here - MIN,
4164 // MAX, saturated math, etc.
4165 case ISD::ADD: {
4166 SDValue Op0 = Op.getOperand(0);
4167 SDValue Op1 = Op.getOperand(1);
4168 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
4169 APInt UndefLHS, ZeroLHS;
4170 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4171 Depth + 1, /*AssumeSingleUse*/ true))
4172 return true;
4173 }
4174 [[fallthrough]];
4175 }
4176 case ISD::AVGCEILS:
4177 case ISD::AVGCEILU:
4178 case ISD::AVGFLOORS:
4179 case ISD::AVGFLOORU:
4180 case ISD::AVGSUBFLOORS:
4181 case ISD::AVGSUBFLOORU:
4182 case ISD::OR:
4183 case ISD::XOR:
4184 case ISD::SUB:
4185 case ISD::FADD:
4186 case ISD::FSUB:
4187 case ISD::FMUL:
4188 case ISD::FDIV:
4189 case ISD::FREM:
4190 case ISD::PSEUDO_FMIN:
4191 case ISD::PSEUDO_FMAX: {
4192 SDValue Op0 = Op.getOperand(0);
4193 SDValue Op1 = Op.getOperand(1);
4194
4195 APInt UndefRHS, ZeroRHS;
4196 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4197 Depth + 1))
4198 return true;
4199 APInt UndefLHS, ZeroLHS;
4200 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4201 Depth + 1))
4202 return true;
4203
4204 // 0.0 / 0.0 and frem(0.0, 0.0) are NaN, not zero.
4205 if (Opcode != ISD::FDIV && Opcode != ISD::FREM)
4206 KnownZero = ZeroLHS & ZeroRHS;
4207 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
4208
4209 // Attempt to avoid multi-use ops if we don't need anything from them.
4210 // TODO - use KnownUndef to relax the demandedelts?
4211 if (!DemandedElts.isAllOnes())
4212 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4213 return true;
4214 break;
4215 }
4216 case ISD::SHL:
4217 case ISD::SRL:
4218 case ISD::SRA:
4219 case ISD::ROTL:
4220 case ISD::ROTR: {
4221 SDValue Op0 = Op.getOperand(0);
4222 SDValue Op1 = Op.getOperand(1);
4223
4224 APInt UndefRHS, ZeroRHS;
4225 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4226 Depth + 1))
4227 return true;
4228 APInt UndefLHS, ZeroLHS;
4229 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4230 Depth + 1))
4231 return true;
4232
4233 KnownZero = ZeroLHS & ~UndefRHS;
4234 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
4235
4236 // Attempt to avoid multi-use ops if we don't need anything from them.
4237 // TODO - use KnownUndef to relax the demandedelts?
4238 if (!DemandedElts.isAllOnes())
4239 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4240 return true;
4241 break;
4242 }
4243 case ISD::MUL:
4244 case ISD::MULHU:
4245 case ISD::MULHS:
4246 case ISD::AND: {
4247 SDValue Op0 = Op.getOperand(0);
4248 SDValue Op1 = Op.getOperand(1);
4249
4250 APInt SrcUndef, SrcZero;
4251 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
4252 Depth + 1))
4253 return true;
4254 // FIXME: If we know that a demanded element was zero in Op1 we don't need
4255 // to demand it in Op0 - its guaranteed to be zero. There is however a
4256 // restriction, as we must not make any of the originally demanded elements
4257 // more poisonous. We could reduce amount of elements demanded, but then we
4258 // also need a to inform SimplifyDemandedVectorElts that some elements must
4259 // not be made more poisonous.
4260 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
4261 TLO, Depth + 1))
4262 return true;
4263
4264 KnownUndef &= DemandedElts;
4265 KnownZero &= DemandedElts;
4266
4267 // If every element pair has a zero/undef/poison then just fold to zero.
4268 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
4269 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
4270 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
4271 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4272
4273 // If either side has a zero element, then the result element is zero, even
4274 // if the other is an UNDEF.
4275 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
4276 // and then handle 'and' nodes with the rest of the binop opcodes.
4277 KnownZero |= SrcZero;
4278 KnownUndef &= SrcUndef;
4279 KnownUndef &= ~KnownZero;
4280
4281 // Attempt to avoid multi-use ops if we don't need anything from them.
4282 if (!DemandedElts.isAllOnes())
4283 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4284 return true;
4285 break;
4286 }
4287 case ISD::TRUNCATE:
4288 case ISD::SIGN_EXTEND:
4289 case ISD::ZERO_EXTEND:
4290 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4291 KnownZero, TLO, Depth + 1))
4292 return true;
4293
4294 if (!DemandedElts.isAllOnes())
4296 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
4297 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
4298
4299 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
4300 // zext(undef) upper bits are guaranteed to be zero.
4301 if (DemandedElts.isSubsetOf(KnownUndef))
4302 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4303 KnownUndef.clearAllBits();
4304 }
4305 break;
4306 case ISD::SINT_TO_FP:
4307 case ISD::UINT_TO_FP:
4308 case ISD::FP_TO_SINT:
4309 case ISD::FP_TO_UINT:
4310 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4311 KnownZero, TLO, Depth + 1))
4312 return true;
4313 // Don't fall through to generic undef -> undef handling.
4314 return false;
4315 default: {
4316 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
4317 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
4318 KnownZero, TLO, Depth))
4319 return true;
4320 } else {
4322 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
4323 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
4324 TLO, Depth, AssumeSingleUse))
4325 return true;
4326 }
4327 break;
4328 }
4329 }
4330
4331 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
4332
4333 // Constant fold all undef cases.
4334 // TODO: Handle zero cases as well.
4335 if (DemandedElts.isSubsetOf(KnownUndef))
4336 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
4337
4338 return false;
4339}
4340
4341/// Determine which of the bits specified in Mask are known to be either zero or
4342/// one and return them in the Known.
4345 const APInt &DemandedElts,
4346 const SelectionDAG &DAG,
4347 unsigned Depth) const {
4348 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4349 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4350 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4351 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4352 "Should use MaskedValueIsZero if you don't know whether Op"
4353 " is a target node!");
4354 Known.resetAll();
4355}
4356
4359 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4360 unsigned Depth) const {
4361 Known.resetAll();
4362}
4363
4366 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4367 unsigned Depth) const {
4368 Known.resetAll();
4369}
4370
4372 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4373 // The low bits are known zero if the pointer is aligned.
4374 Known.Zero.setLowBits(Log2(Alignment));
4375}
4376
4378 SelectionDAG &DAG,
4379 const SDLoc &DL,
4380 Align Alignment) const {
4381 // Materialize leading-zero stack object pointer facts as AssertZext.
4382 // Alignment-derived low zero bits are not represented on the returned DAG
4383 // value here.
4384 EVT PtrVT = Ptr.getValueType();
4385
4386 unsigned RegSize = PtrVT.getScalarSizeInBits();
4389 Alignment);
4390
4391 unsigned NumZeroBits = Known.countMinLeadingZeros();
4392 if (!NumZeroBits)
4393 return Ptr;
4394
4395 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4396 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4397}
4398
4404
4405/// This method can be implemented by targets that want to expose additional
4406/// information about sign bits to the DAG Combiner.
4408 const APInt &,
4409 const SelectionDAG &,
4410 unsigned Depth) const {
4411 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4412 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4413 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4414 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4415 "Should use ComputeNumSignBits if you don't know whether Op"
4416 " is a target node!");
4417 return 1;
4418}
4419
4421 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4422 const MachineRegisterInfo &MRI, unsigned Depth) const {
4423 return 1;
4424}
4425
4427 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4428 TargetLoweringOpt &TLO, unsigned Depth) const {
4429 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4430 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4431 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4432 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4433 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4434 " is a target node!");
4435 return false;
4436}
4437
4439 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4440 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4441 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4442 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4443 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4444 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4445 "Should use SimplifyDemandedBits if you don't know whether Op"
4446 " is a target node!");
4447 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4448 return false;
4449}
4450
4452 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4453 SelectionDAG &DAG, unsigned Depth) const {
4454 assert(
4455 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4456 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4457 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4458 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4459 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4460 " is a target node!");
4461 return SDValue();
4462}
4463
4464SDValue
4467 SelectionDAG &DAG) const {
4468 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4469 if (!LegalMask) {
4470 std::swap(N0, N1);
4472 LegalMask = isShuffleMaskLegal(Mask, VT);
4473 }
4474
4475 if (!LegalMask)
4476 return SDValue();
4477
4478 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4479}
4480
4482 return nullptr;
4483}
4484
4486 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4487 UndefPoisonKind Kind, unsigned Depth) const {
4488 assert(
4489 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4490 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4491 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4492 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4493 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4494 " is a target node!");
4495
4496 // If Op can't create undef/poison and none of its operands are undef/poison
4497 // then Op is never undef/poison.
4498 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4499 /*ConsiderFlags*/ true, Depth) &&
4500 all_of(Op->ops(), [&](SDValue V) {
4501 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4502 });
4503}
4504
4506 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4507 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4508 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4509 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4510 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4511 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4512 "Should use canCreateUndefOrPoison if you don't know whether Op"
4513 " is a target node!");
4514 // Be conservative and return true.
4515 return true;
4516}
4517
4520 const APInt &DemandedElts,
4521 const SelectionDAG &DAG,
4522 unsigned Depth) const {
4523 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4524 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4525 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4526 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4527 "Should use computeKnownFPClass if you don't know whether Op"
4528 " is a target node!");
4529}
4530
4532 const APInt &DemandedElts,
4533 const SelectionDAG &DAG,
4534 bool SNaN,
4535 unsigned Depth) const {
4536 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4537 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4538 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4539 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4540 "Should use isKnownNeverNaN if you don't know whether Op"
4541 " is a target node!");
4542 return false;
4543}
4544
4546 const APInt &DemandedElts,
4547 APInt &UndefElts,
4548 const SelectionDAG &DAG,
4549 unsigned Depth) const {
4550 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4551 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4552 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4553 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4554 "Should use isSplatValue if you don't know whether Op"
4555 " is a target node!");
4556 return false;
4557}
4558
4559// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4560// work with truncating build vectors and vectors with elements of less than
4561// 8 bits.
4563 if (!N)
4564 return false;
4565
4566 unsigned EltWidth;
4567 APInt CVal;
4568 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4569 /*AllowTruncation=*/true)) {
4570 CVal = CN->getAPIntValue();
4571 EltWidth = N.getValueType().getScalarSizeInBits();
4572 } else
4573 return false;
4574
4575 // If this is a truncating splat, truncate the splat value.
4576 // Otherwise, we may fail to match the expected values below.
4577 if (EltWidth < CVal.getBitWidth())
4578 CVal = CVal.trunc(EltWidth);
4579
4580 switch (getBooleanContents(N.getValueType())) {
4582 return CVal[0];
4584 return CVal.isOne();
4586 return CVal.isAllOnes();
4587 }
4588
4589 llvm_unreachable("Invalid boolean contents");
4590}
4591
4593 if (!N)
4594 return false;
4595
4597 if (!CN) {
4599 if (!BV)
4600 return false;
4601
4602 // Only interested in constant splats, we don't care about undef
4603 // elements in identifying boolean constants and getConstantSplatNode
4604 // returns NULL if all ops are undef;
4605 CN = BV->getConstantSplatNode();
4606 if (!CN)
4607 return false;
4608 }
4609
4610 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4611 return !CN->getAPIntValue()[0];
4612
4613 return CN->isZero();
4614}
4615
4617 bool SExt) const {
4618 if (VT == MVT::i1)
4619 return N->isOne();
4620
4622 switch (Cnt) {
4624 // An extended value of 1 is always true, unless its original type is i1,
4625 // in which case it will be sign extended to -1.
4626 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4629 return N->isAllOnes() && SExt;
4630 }
4631 llvm_unreachable("Unexpected enumeration.");
4632}
4633
4634/// This helper function of SimplifySetCC tries to optimize the comparison when
4635/// either operand of the SetCC node is a bitwise-and instruction.
4636SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4637 ISD::CondCode Cond, const SDLoc &DL,
4638 DAGCombinerInfo &DCI) const {
4639 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4640 std::swap(N0, N1);
4641
4642 SelectionDAG &DAG = DCI.DAG;
4643 EVT OpVT = N0.getValueType();
4644 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4645 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4646 return SDValue();
4647
4648 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4649 // iff everything but LSB is known zero:
4650 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4653 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4654 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4655 if (DAG.MaskedValueIsZero(N0, UpperBits))
4656 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4657 }
4658
4659 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4660 // test in a narrow type that we can truncate to with no cost. Examples:
4661 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4662 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4663 // TODO: This conservatively checks for type legality on the source and
4664 // destination types. That may inhibit optimizations, but it also
4665 // allows setcc->shift transforms that may be more beneficial.
4666 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4667 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4668 isTypeLegal(OpVT) && N0.hasOneUse()) {
4669 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4670 AndC->getAPIntValue().getActiveBits());
4671 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4672 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4673 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4674 return DAG.getSetCC(DL, VT, Trunc, Zero,
4676 }
4677 }
4678
4679 // Match these patterns in any of their permutations:
4680 // (X & Y) == Y
4681 // (X & Y) != Y
4682 SDValue X, Y;
4683 if (N0.getOperand(0) == N1) {
4684 X = N0.getOperand(1);
4685 Y = N0.getOperand(0);
4686 } else if (N0.getOperand(1) == N1) {
4687 X = N0.getOperand(0);
4688 Y = N0.getOperand(1);
4689 } else {
4690 return SDValue();
4691 }
4692
4693 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4694 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4695 // its liable to create and infinite loop.
4696 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4697 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4699 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4700 // Note that where Y is variable and is known to have at most one bit set
4701 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4702 // equivalent when Y == 0.
4703 assert(OpVT.isInteger());
4705 if (DCI.isBeforeLegalizeOps() ||
4707 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4708 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4709 // If the target supports an 'and-not' or 'and-complement' logic operation,
4710 // try to use that to make a comparison operation more efficient.
4711 // But don't do this transform if the mask is a single bit because there are
4712 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4713 // 'rlwinm' on PPC).
4714
4715 // Bail out if the compare operand that we want to turn into a zero is
4716 // already a zero (otherwise, infinite loop).
4717 if (isNullConstant(Y))
4718 return SDValue();
4719
4720 // Transform this into: ~X & Y == 0.
4721 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4722 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4723 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4724 }
4725
4726 return SDValue();
4727}
4728
4729/// This helper function of SimplifySetCC tries to optimize the comparison when
4730/// either operand of the SetCC node is a bitwise-or instruction.
4731/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4732SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4733 ISD::CondCode Cond, const SDLoc &DL,
4734 DAGCombinerInfo &DCI) const {
4735 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4736 std::swap(N0, N1);
4737
4738 SelectionDAG &DAG = DCI.DAG;
4739 EVT OpVT = N0.getValueType();
4740 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4741 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4742 return SDValue();
4743
4744 // (X | Y) == Y
4745 // (X | Y) != Y
4746 SDValue X;
4747 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4748 // If the target supports an 'and-not' or 'and-complement' logic operation,
4749 // try to use that to make a comparison operation more efficient.
4750
4751 // Bail out if the compare operand that we want to turn into a zero is
4752 // already a zero (otherwise, infinite loop).
4753 if (isNullConstant(N1))
4754 return SDValue();
4755
4756 // Transform this into: X & ~Y ==/!= 0.
4757 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4758 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4759 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4760 }
4761
4762 return SDValue();
4763}
4764
4765/// There are multiple IR patterns that could be checking whether certain
4766/// truncation of a signed number would be lossy or not. The pattern which is
4767/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4768/// We are looking for the following pattern: (KeptBits is a constant)
4769/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4770/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4771/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4772/// We will unfold it into the natural trunc+sext pattern:
4773/// ((%x << C) a>> C) dstcond %x
4774/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4775SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4776 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4777 const SDLoc &DL) const {
4778 // We must be comparing with a constant.
4779 ConstantSDNode *C1;
4780 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4781 return SDValue();
4782
4783 // N0 should be: add %x, (1 << (KeptBits-1))
4784 if (N0->getOpcode() != ISD::ADD)
4785 return SDValue();
4786
4787 // And we must be 'add'ing a constant.
4788 ConstantSDNode *C01;
4789 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4790 return SDValue();
4791
4792 SDValue X = N0->getOperand(0);
4793 EVT XVT = X.getValueType();
4794
4795 // Validate constants ...
4796
4797 APInt I1 = C1->getAPIntValue();
4798
4799 ISD::CondCode NewCond;
4800 if (Cond == ISD::CondCode::SETULT) {
4801 NewCond = ISD::CondCode::SETEQ;
4802 } else if (Cond == ISD::CondCode::SETULE) {
4803 NewCond = ISD::CondCode::SETEQ;
4804 // But need to 'canonicalize' the constant.
4805 I1 += 1;
4806 } else if (Cond == ISD::CondCode::SETUGT) {
4807 NewCond = ISD::CondCode::SETNE;
4808 // But need to 'canonicalize' the constant.
4809 I1 += 1;
4810 } else if (Cond == ISD::CondCode::SETUGE) {
4811 NewCond = ISD::CondCode::SETNE;
4812 } else
4813 return SDValue();
4814
4815 APInt I01 = C01->getAPIntValue();
4816
4817 auto checkConstants = [&I1, &I01]() -> bool {
4818 // Both of them must be power-of-two, and the constant from setcc is bigger.
4819 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4820 };
4821
4822 if (checkConstants()) {
4823 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4824 } else {
4825 // What if we invert constants? (and the target predicate)
4826 I1.negate();
4827 I01.negate();
4828 assert(XVT.isInteger());
4829 NewCond = getSetCCInverse(NewCond, XVT);
4830 if (!checkConstants())
4831 return SDValue();
4832 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4833 }
4834
4835 // They are power-of-two, so which bit is set?
4836 const unsigned KeptBits = I1.logBase2();
4837 const unsigned KeptBitsMinusOne = I01.logBase2();
4838
4839 // Magic!
4840 if (KeptBits != (KeptBitsMinusOne + 1))
4841 return SDValue();
4842 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4843
4844 // We don't want to do this in every single case.
4845 SelectionDAG &DAG = DCI.DAG;
4846 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4847 return SDValue();
4848
4849 // Unfold into: sext_inreg(%x) cond %x
4850 // Where 'cond' will be either 'eq' or 'ne'.
4851 SDValue SExtInReg = DAG.getNode(
4853 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4854 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4855}
4856
4857// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4858SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4859 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4860 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4862 "Should be a comparison with 0.");
4863 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4864 "Valid only for [in]equality comparisons.");
4865
4866 unsigned NewShiftOpcode;
4867 SDValue X, C, Y;
4868
4869 SelectionDAG &DAG = DCI.DAG;
4870
4871 // Look for '(C l>>/<< Y)'.
4872 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4873 // The shift should be one-use.
4874 if (!V.hasOneUse())
4875 return false;
4876 unsigned OldShiftOpcode = V.getOpcode();
4877 switch (OldShiftOpcode) {
4878 case ISD::SHL:
4879 NewShiftOpcode = ISD::SRL;
4880 break;
4881 case ISD::SRL:
4882 NewShiftOpcode = ISD::SHL;
4883 break;
4884 default:
4885 return false; // must be a logical shift.
4886 }
4887 // We should be shifting a constant.
4888 // FIXME: best to use isConstantOrConstantVector().
4889 C = V.getOperand(0);
4890 ConstantSDNode *CC =
4891 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4892 if (!CC)
4893 return false;
4894 Y = V.getOperand(1);
4895
4896 ConstantSDNode *XC =
4897 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4899 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4900 };
4901
4902 // LHS of comparison should be an one-use 'and'.
4903 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4904 return SDValue();
4905
4906 X = N0.getOperand(0);
4907 SDValue Mask = N0.getOperand(1);
4908
4909 // 'and' is commutative!
4910 if (!Match(Mask)) {
4911 std::swap(X, Mask);
4912 if (!Match(Mask))
4913 return SDValue();
4914 }
4915
4916 EVT VT = X.getValueType();
4917
4918 // Produce:
4919 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4920 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4921 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4922 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4923 return T2;
4924}
4925
4926/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4927/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4928/// handle the commuted versions of these patterns.
4929SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4930 ISD::CondCode Cond, const SDLoc &DL,
4931 DAGCombinerInfo &DCI) const {
4932 unsigned BOpcode = N0.getOpcode();
4933 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4934 "Unexpected binop");
4935 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4936
4937 // (X + Y) == X --> Y == 0
4938 // (X - Y) == X --> Y == 0
4939 // (X ^ Y) == X --> Y == 0
4940 SelectionDAG &DAG = DCI.DAG;
4941 EVT OpVT = N0.getValueType();
4942 SDValue X = N0.getOperand(0);
4943 SDValue Y = N0.getOperand(1);
4944 if (X == N1)
4945 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4946
4947 if (Y != N1)
4948 return SDValue();
4949
4950 // (X + Y) == Y --> X == 0
4951 // (X ^ Y) == Y --> X == 0
4952 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4953 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4954
4955 // The shift would not be valid if the operands are boolean (i1).
4956 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4957 return SDValue();
4958
4959 // (X - Y) == Y --> X == Y << 1
4960 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4961 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4962 if (!DCI.isCalledByLegalizer())
4963 DCI.AddToWorklist(YShl1.getNode());
4964 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4965}
4966
4968 SDValue N0, const APInt &C1,
4969 ISD::CondCode Cond, const SDLoc &dl,
4970 SelectionDAG &DAG) {
4971 // Look through truncs that don't change the value of a ctpop.
4972 // FIXME: Add vector support? Need to be careful with setcc result type below.
4973 SDValue CTPOP = N0;
4974 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4976 CTPOP = N0.getOperand(0);
4977
4978 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4979 return SDValue();
4980
4981 EVT CTVT = CTPOP.getValueType();
4982 SDValue CTOp = CTPOP.getOperand(0);
4983
4984 // Expand a power-of-2-or-zero comparison based on ctpop:
4985 // (ctpop x) u< 2 -> (x & x-1) == 0
4986 // (ctpop x) u> 1 -> (x & x-1) != 0
4987 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4988 // Keep the CTPOP if it is a cheap vector op.
4989 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4990 return SDValue();
4991
4992 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4993 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4994 return SDValue();
4995 if (C1 == 0 && (Cond == ISD::SETULT))
4996 return SDValue(); // This is handled elsewhere.
4997
4998 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4999
5000 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
5001 SDValue Result = CTOp;
5002 for (unsigned i = 0; i < Passes; i++) {
5003 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
5004 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
5005 }
5007 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
5008 }
5009
5010 // Expand a power-of-2 comparison based on ctpop
5011 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
5012 // Keep the CTPOP if it is cheap.
5013 if (TLI.isCtpopFast(CTVT))
5014 return SDValue();
5015
5016 SDValue Zero = DAG.getConstant(0, dl, CTVT);
5017 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
5018 assert(CTVT.isInteger());
5019 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
5020
5021 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
5022 // check before emitting a potentially unnecessary op.
5023 if (DAG.isKnownNeverZero(CTOp)) {
5024 // (ctpop x) == 1 --> (x & x-1) == 0
5025 // (ctpop x) != 1 --> (x & x-1) != 0
5026 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
5027 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
5028 return RHS;
5029 }
5030
5031 // (ctpop x) == 1 --> (x ^ x-1) > x-1
5032 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
5033 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
5035 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
5036 }
5037
5038 return SDValue();
5039}
5040
5042 ISD::CondCode Cond, const SDLoc &dl,
5043 SelectionDAG &DAG) {
5044 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
5045 return SDValue();
5046
5047 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
5048 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
5049 return SDValue();
5050
5051 auto getRotateSource = [](SDValue X) {
5052 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
5053 return X.getOperand(0);
5054 return SDValue();
5055 };
5056
5057 // Peek through a rotated value compared against 0 or -1:
5058 // (rot X, Y) == 0/-1 --> X == 0/-1
5059 // (rot X, Y) != 0/-1 --> X != 0/-1
5060 if (SDValue R = getRotateSource(N0))
5061 return DAG.getSetCC(dl, VT, R, N1, Cond);
5062
5063 // Peek through an 'or' of a rotated value compared against 0:
5064 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
5065 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
5066 //
5067 // TODO: Add the 'and' with -1 sibling.
5068 // TODO: Recurse through a series of 'or' ops to find the rotate.
5069 EVT OpVT = N0.getValueType();
5070 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
5071 if (SDValue R = getRotateSource(N0.getOperand(0))) {
5072 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
5073 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5074 }
5075 if (SDValue R = getRotateSource(N0.getOperand(1))) {
5076 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
5077 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5078 }
5079 }
5080
5081 return SDValue();
5082}
5083
5085 ISD::CondCode Cond, const SDLoc &dl,
5086 SelectionDAG &DAG) {
5087 // If we are testing for all-bits-clear, we might be able to do that with
5088 // less shifting since bit-order does not matter.
5089 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
5090 return SDValue();
5091
5092 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
5093 if (!C1 || !C1->isZero())
5094 return SDValue();
5095
5096 if (!N0.hasOneUse() ||
5097 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
5098 return SDValue();
5099
5100 unsigned BitWidth = N0.getScalarValueSizeInBits();
5101 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
5102 if (!ShAmtC)
5103 return SDValue();
5104
5105 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
5106 if (ShAmt == 0)
5107 return SDValue();
5108
5109 // Canonicalize fshr as fshl to reduce pattern-matching.
5110 if (N0.getOpcode() == ISD::FSHR)
5111 ShAmt = BitWidth - ShAmt;
5112
5113 // Match an 'or' with a specific operand 'Other' in either commuted variant.
5114 SDValue X, Y;
5115 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
5116 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
5117 return false;
5118 if (Or.getOperand(0) == Other) {
5119 X = Or.getOperand(0);
5120 Y = Or.getOperand(1);
5121 return true;
5122 }
5123 if (Or.getOperand(1) == Other) {
5124 X = Or.getOperand(1);
5125 Y = Or.getOperand(0);
5126 return true;
5127 }
5128 return false;
5129 };
5130
5131 EVT OpVT = N0.getValueType();
5132 EVT ShAmtVT = N0.getOperand(2).getValueType();
5133 SDValue F0 = N0.getOperand(0);
5134 SDValue F1 = N0.getOperand(1);
5135 if (matchOr(F0, F1)) {
5136 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
5137 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
5138 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
5139 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
5140 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5141 }
5142 if (matchOr(F1, F0)) {
5143 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
5144 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
5145 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
5146 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
5147 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5148 }
5149
5150 return SDValue();
5151}
5152
5153/// Try to simplify a setcc built with the specified operands and cc. If it is
5154/// unable to simplify it, return a null SDValue.
5156 ISD::CondCode Cond, bool foldBooleans,
5157 DAGCombinerInfo &DCI,
5158 const SDLoc &dl) const {
5159 SelectionDAG &DAG = DCI.DAG;
5160 const DataLayout &Layout = DAG.getDataLayout();
5161 EVT OpVT = N0.getValueType();
5163
5164 // Constant fold or commute setcc.
5165 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
5166 return Fold;
5167
5168 bool N0ConstOrSplat =
5169 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5170 bool N1ConstOrSplat =
5171 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5172
5173 // Canonicalize toward having the constant on the RHS.
5174 // TODO: Handle non-splat vector constants. All undef causes trouble.
5175 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
5176 // infinite loop here when we encounter one.
5178 if (N0ConstOrSplat && !N1ConstOrSplat &&
5179 (DCI.isBeforeLegalizeOps() ||
5180 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
5181 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5182
5183 // If we have a subtract with the same 2 non-constant operands as this setcc
5184 // -- but in reverse order -- then try to commute the operands of this setcc
5185 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
5186 // instruction on some targets.
5187 if (!N0ConstOrSplat && !N1ConstOrSplat &&
5188 (DCI.isBeforeLegalizeOps() ||
5189 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
5190 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
5191 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
5192 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5193
5194 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
5195 return V;
5196
5197 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
5198 return V;
5199
5200 if (auto *N1C = isConstOrConstSplat(N1)) {
5201 const APInt &C1 = N1C->getAPIntValue();
5202
5203 // Optimize some CTPOP cases.
5204 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
5205 return V;
5206
5207 // For equality to 0 of a no-wrap multiply, decompose and test each op:
5208 // X * Y == 0 --> (X == 0) || (Y == 0)
5209 // X * Y != 0 --> (X != 0) && (Y != 0)
5210 // TODO: This bails out if minsize is set, but if the target doesn't have a
5211 // single instruction multiply for this type, it would likely be
5212 // smaller to decompose.
5213 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5214 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
5215 (N0->getFlags().hasNoUnsignedWrap() ||
5216 N0->getFlags().hasNoSignedWrap()) &&
5217 !Attr.hasFnAttr(Attribute::MinSize)) {
5218 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5219 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
5220 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
5221 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
5222 }
5223
5224 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
5225 // equality comparison, then we're just comparing whether X itself is
5226 // zero.
5227 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
5228 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
5230 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
5231 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5232 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
5233 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
5234 // (srl (ctlz x), 5) == 0 -> X != 0
5235 // (srl (ctlz x), 5) != 1 -> X != 0
5236 Cond = ISD::SETNE;
5237 } else {
5238 // (srl (ctlz x), 5) != 0 -> X == 0
5239 // (srl (ctlz x), 5) == 1 -> X == 0
5240 Cond = ISD::SETEQ;
5241 }
5242 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
5243 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
5244 Cond);
5245 }
5246 }
5247 }
5248 }
5249
5250 // setcc X, 0, setlt --> X (when X is all sign bits)
5251 // setcc X, 0, setne --> X (when X is all sign bits)
5252 //
5253 // When we know that X has 0 or -1 in each element (or scalar), this
5254 // comparison will produce X. This is only true when boolean contents are
5255 // represented via 0s and -1s.
5256 if (VT == OpVT &&
5257 // Check that the result of setcc is 0 and -1.
5259 // Match only for checks X < 0 and X != 0
5260 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
5261 // The identity holds iff we know all sign bits for all lanes.
5263 return N0;
5264
5265 // FIXME: Support vectors.
5266 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5267 const APInt &C1 = N1C->getAPIntValue();
5268
5269 // (zext x) == C --> x == (trunc C)
5270 // (sext x) == C --> x == (trunc C)
5271 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5272 DCI.isBeforeLegalize() && N0->hasOneUse()) {
5273 unsigned MinBits = N0.getValueSizeInBits();
5274 SDValue PreExt;
5275 bool Signed = false;
5276 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
5277 // ZExt
5278 MinBits = N0->getOperand(0).getValueSizeInBits();
5279 PreExt = N0->getOperand(0);
5280 } else if (N0->getOpcode() == ISD::AND) {
5281 // DAGCombine turns costly ZExts into ANDs
5282 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
5283 if ((C->getAPIntValue()+1).isPowerOf2()) {
5284 MinBits = C->getAPIntValue().countr_one();
5285 PreExt = N0->getOperand(0);
5286 }
5287 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
5288 // SExt
5289 MinBits = N0->getOperand(0).getValueSizeInBits();
5290 PreExt = N0->getOperand(0);
5291 Signed = true;
5292 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
5293 // ZEXTLOAD / SEXTLOAD
5294 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
5295 MinBits = LN0->getMemoryVT().getSizeInBits();
5296 PreExt = N0;
5297 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
5298 Signed = true;
5299 MinBits = LN0->getMemoryVT().getSizeInBits();
5300 PreExt = N0;
5301 }
5302 }
5303
5304 // Figure out how many bits we need to preserve this constant.
5305 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
5306
5307 // Make sure we're not losing bits from the constant.
5308 if (MinBits > 0 &&
5309 MinBits < C1.getBitWidth() &&
5310 MinBits >= ReqdBits) {
5311 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
5312 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
5313 // Will get folded away.
5314 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
5315 if (MinBits == 1 && C1 == 1)
5316 // Invert the condition.
5317 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
5319 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
5320 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
5321 }
5322
5323 // If truncating the setcc operands is not desirable, we can still
5324 // simplify the expression in some cases:
5325 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
5326 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
5327 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
5328 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
5329 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
5330 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
5331 SDValue TopSetCC = N0->getOperand(0);
5332 unsigned N0Opc = N0->getOpcode();
5333 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
5334 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
5335 TopSetCC.getOpcode() == ISD::SETCC &&
5336 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
5337 (isConstFalseVal(N1) ||
5338 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
5339
5340 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
5341 (!N1C->isZero() && Cond == ISD::SETNE);
5342
5343 if (!Inverse)
5344 return TopSetCC;
5345
5346 ISD::CondCode InvCond =
5348 TopSetCC.getOperand(0).getValueType());
5349 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
5350 TopSetCC.getOperand(1), InvCond);
5351 }
5352 }
5353 }
5354
5355 // If the LHS is '(and load, const)', the RHS is 0, the test is for
5356 // equality or unsigned, and all 1 bits of the const are in the same
5357 // partial word, see if we can shorten the load.
5358 if (DCI.isBeforeLegalize() &&
5360 N0.getOpcode() == ISD::AND && C1 == 0 &&
5361 N0.getNode()->hasOneUse() &&
5362 isa<LoadSDNode>(N0.getOperand(0)) &&
5363 N0.getOperand(0).getNode()->hasOneUse() &&
5365 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5366 APInt bestMask;
5367 unsigned bestWidth = 0, bestOffset = 0;
5368 if (Lod->isSimple() && Lod->isUnindexed() &&
5369 (Lod->getMemoryVT().isByteSized() ||
5370 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5371 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5372 unsigned origWidth = N0.getValueSizeInBits();
5373 unsigned maskWidth = origWidth;
5374 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5375 // 8 bits, but have to be careful...
5376 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5377 origWidth = Lod->getMemoryVT().getSizeInBits();
5378 const APInt &Mask = N0.getConstantOperandAPInt(1);
5379 // Only consider power-of-2 widths (and at least one byte) as candiates
5380 // for the narrowed load.
5381 for (unsigned width = 8; width < origWidth; width *= 2) {
5382 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5383 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5384 // Avoid accessing any padding here for now (we could use memWidth
5385 // instead of origWidth here otherwise).
5386 unsigned maxOffset = origWidth - width;
5387 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5388 if (Mask.isSubsetOf(newMask)) {
5389 unsigned ptrOffset =
5390 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5391 unsigned IsFast = 0;
5392 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5393 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5395 ptrOffset / 8) &&
5397 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5398 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5399 IsFast) {
5400 bestOffset = ptrOffset / 8;
5401 bestMask = Mask.lshr(offset);
5402 bestWidth = width;
5403 break;
5404 }
5405 }
5406 newMask <<= 8;
5407 }
5408 if (bestWidth)
5409 break;
5410 }
5411 }
5412 if (bestWidth) {
5413 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5414 SDValue Ptr = Lod->getBasePtr();
5415 if (bestOffset != 0)
5416 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5417 SDValue NewLoad =
5418 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5419 Lod->getPointerInfo().getWithOffset(bestOffset),
5420 Lod->getBaseAlign(), MachineMemOperand::MONone,
5421 Lod->getMMOMetadataForSubAccess());
5422 SDValue And =
5423 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5424 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5425 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5426 }
5427 }
5428
5429 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5430 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5431 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5432
5433 // If the comparison constant has bits in the upper part, the
5434 // zero-extended value could never match.
5435 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
5436 C1.getBitWidth() - InSize))) {
5437 switch (Cond) {
5438 case ISD::SETUGT:
5439 case ISD::SETUGE:
5440 case ISD::SETEQ:
5441 return DAG.getConstant(0, dl, VT);
5442 case ISD::SETULT:
5443 case ISD::SETULE:
5444 case ISD::SETNE:
5445 return DAG.getConstant(1, dl, VT);
5446 case ISD::SETGT:
5447 case ISD::SETGE:
5448 // True if the sign bit of C1 is set.
5449 return DAG.getConstant(C1.isNegative(), dl, VT);
5450 case ISD::SETLT:
5451 case ISD::SETLE:
5452 // True if the sign bit of C1 isn't set.
5453 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5454 default:
5455 break;
5456 }
5457 }
5458
5459 // Otherwise, we can perform the comparison with the low bits.
5460 switch (Cond) {
5461 case ISD::SETEQ:
5462 case ISD::SETNE:
5463 case ISD::SETUGT:
5464 case ISD::SETUGE:
5465 case ISD::SETULT:
5466 case ISD::SETULE: {
5467 EVT newVT = N0.getOperand(0).getValueType();
5468 // FIXME: Should use isNarrowingProfitable.
5469 if (DCI.isBeforeLegalizeOps() ||
5470 (isOperationLegal(ISD::SETCC, newVT) &&
5471 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5473 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5474 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5475
5476 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5477 NewConst, Cond);
5478 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5479 }
5480 break;
5481 }
5482 default:
5483 break; // todo, be more careful with signed comparisons
5484 }
5485 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5486 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5488 OpVT)) {
5489 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5490 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5491 EVT ExtDstTy = N0.getValueType();
5492 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5493
5494 // If the constant doesn't fit into the number of bits for the source of
5495 // the sign extension, it is impossible for both sides to be equal.
5496 if (C1.getSignificantBits() > ExtSrcTyBits)
5497 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5498
5499 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5500 ExtDstTy != ExtSrcTy && "Unexpected types!");
5501 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5502 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5503 DAG.getConstant(Imm, dl, ExtDstTy));
5504 if (!DCI.isCalledByLegalizer())
5505 DCI.AddToWorklist(ZextOp.getNode());
5506 // Otherwise, make this a use of a zext.
5507 return DAG.getSetCC(dl, VT, ZextOp,
5508 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5509 } else if ((N1C->isZero() || N1C->isOne()) &&
5510 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5511 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5512 // excluded as they are handled below whilst checking for foldBooleans.
5513 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5514 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5515 (N0.getValueType() == MVT::i1 ||
5519 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5520 if (TrueWhenTrue)
5521 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5522 // Invert the condition.
5523 if (N0.getOpcode() == ISD::SETCC) {
5526 if (DCI.isBeforeLegalizeOps() ||
5528 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5529 }
5530 }
5531
5532 if ((N0.getOpcode() == ISD::XOR ||
5533 (N0.getOpcode() == ISD::AND &&
5534 N0.getOperand(0).getOpcode() == ISD::XOR &&
5535 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5536 isOneConstant(N0.getOperand(1))) {
5537 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5538 // can only do this if the top bits are known zero.
5539 unsigned BitWidth = N0.getValueSizeInBits();
5540 if (DAG.MaskedValueIsZero(N0,
5542 BitWidth-1))) {
5543 // Okay, get the un-inverted input value.
5544 SDValue Val;
5545 if (N0.getOpcode() == ISD::XOR) {
5546 Val = N0.getOperand(0);
5547 } else {
5548 assert(N0.getOpcode() == ISD::AND &&
5549 N0.getOperand(0).getOpcode() == ISD::XOR);
5550 // ((X^1)&1)^1 -> X & 1
5551 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5552 N0.getOperand(0).getOperand(0),
5553 N0.getOperand(1));
5554 }
5555
5556 return DAG.getSetCC(dl, VT, Val, N1,
5558 }
5559 } else if (N1C->isOne()) {
5560 SDValue Op0 = N0;
5561 if (Op0.getOpcode() == ISD::TRUNCATE)
5562 Op0 = Op0.getOperand(0);
5563
5564 if ((Op0.getOpcode() == ISD::XOR) &&
5565 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5566 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5567 SDValue XorLHS = Op0.getOperand(0);
5568 SDValue XorRHS = Op0.getOperand(1);
5569 // Ensure that the input setccs return an i1 type or 0/1 value.
5570 if (Op0.getValueType() == MVT::i1 ||
5575 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5577 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5578 }
5579 }
5580 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5581 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5582 if (Op0.getValueType().bitsGT(VT))
5583 Op0 = DAG.getNode(ISD::AND, dl, VT,
5584 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5585 DAG.getConstant(1, dl, VT));
5586 else if (Op0.getValueType().bitsLT(VT))
5587 Op0 = DAG.getNode(ISD::AND, dl, VT,
5588 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5589 DAG.getConstant(1, dl, VT));
5590
5591 return DAG.getSetCC(dl, VT, Op0,
5592 DAG.getConstant(0, dl, Op0.getValueType()),
5594 }
5595 if (Op0.getOpcode() == ISD::AssertZext &&
5596 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5597 return DAG.getSetCC(dl, VT, Op0,
5598 DAG.getConstant(0, dl, Op0.getValueType()),
5600 }
5601 }
5602
5603 // Given:
5604 // icmp eq/ne (urem %x, %y), 0
5605 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5606 // icmp eq/ne %x, 0
5607 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5608 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5609 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5610 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5611 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5612 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5613 }
5614
5615 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5616 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5617 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5619 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5620 N1C->isAllOnes()) {
5621 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5622 DAG.getConstant(0, dl, OpVT),
5624 }
5625
5626 // fold (setcc (trunc x) c) -> (setcc x c)
5627 if (N0.getOpcode() == ISD::TRUNCATE &&
5629 (N0->getFlags().hasNoSignedWrap() &&
5632 EVT NewVT = N0.getOperand(0).getValueType();
5633 SDValue NewConst = DAG.getConstant(
5635 ? C1.sext(NewVT.getSizeInBits())
5636 : C1.zext(NewVT.getSizeInBits()),
5637 dl, NewVT);
5638 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5639 }
5640
5641 if (SDValue V =
5642 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5643 return V;
5644 }
5645
5646 // These simplifications apply to splat vectors as well.
5647 // TODO: Handle more splat vector cases.
5648 if (auto *N1C = isConstOrConstSplat(N1)) {
5649 const APInt &C1 = N1C->getAPIntValue();
5650
5651 APInt MinVal, MaxVal;
5652 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5654 MinVal = APInt::getSignedMinValue(OperandBitSize);
5655 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5656 } else {
5657 MinVal = APInt::getMinValue(OperandBitSize);
5658 MaxVal = APInt::getMaxValue(OperandBitSize);
5659 }
5660
5661 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5662 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5663 // X >= MIN --> true
5664 if (C1 == MinVal)
5665 return DAG.getBoolConstant(true, dl, VT, OpVT);
5666
5667 if (!VT.isVector()) { // TODO: Support this for vectors.
5668 // X >= C0 --> X > (C0 - 1)
5669 APInt C = C1 - 1;
5671 if ((DCI.isBeforeLegalizeOps() ||
5672 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5673 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5674 isLegalICmpImmediate(C.getSExtValue())))) {
5675 return DAG.getSetCC(dl, VT, N0,
5676 DAG.getConstant(C, dl, N1.getValueType()),
5677 NewCC);
5678 }
5679 }
5680 }
5681
5682 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5683 // X <= MAX --> true
5684 if (C1 == MaxVal)
5685 return DAG.getBoolConstant(true, dl, VT, OpVT);
5686
5687 // X <= C0 --> X < (C0 + 1)
5688 if (!VT.isVector()) { // TODO: Support this for vectors.
5689 APInt C = C1 + 1;
5691 if ((DCI.isBeforeLegalizeOps() ||
5692 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5693 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5694 isLegalICmpImmediate(C.getSExtValue())))) {
5695 return DAG.getSetCC(dl, VT, N0,
5696 DAG.getConstant(C, dl, N1.getValueType()),
5697 NewCC);
5698 }
5699 }
5700 }
5701
5702 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5703 if (C1 == MinVal)
5704 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5705
5706 // TODO: Support this for vectors after legalize ops.
5707 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5708 // Canonicalize setlt X, Max --> setne X, Max
5709 if (C1 == MaxVal)
5710 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5711
5712 // If we have setult X, 1, turn it into seteq X, 0
5713 if (C1 == MinVal+1)
5714 return DAG.getSetCC(dl, VT, N0,
5715 DAG.getConstant(MinVal, dl, N0.getValueType()),
5716 ISD::SETEQ);
5717 }
5718 }
5719
5720 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5721 if (C1 == MaxVal)
5722 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5723
5724 // TODO: Support this for vectors after legalize ops.
5725 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5726 // Canonicalize setgt X, Min --> setne X, Min
5727 if (C1 == MinVal)
5728 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5729
5730 // If we have setugt X, Max-1, turn it into seteq X, Max
5731 if (C1 == MaxVal-1)
5732 return DAG.getSetCC(dl, VT, N0,
5733 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5734 ISD::SETEQ);
5735 }
5736 }
5737
5738 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5739 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5740 if (C1.isZero())
5741 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5742 VT, N0, N1, Cond, DCI, dl))
5743 return CC;
5744
5745 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5746 // For example, when high 32-bits of i64 X are known clear:
5747 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5748 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5749 bool CmpZero = N1C->isZero();
5750 bool CmpNegOne = N1C->isAllOnes();
5751 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5752 // Match or(lo,shl(hi,bw/2)) pattern.
5753 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5754 unsigned EltBits = V.getScalarValueSizeInBits();
5755 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5756 return false;
5757 SDValue LHS = V.getOperand(0);
5758 SDValue RHS = V.getOperand(1);
5759 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5760 // Unshifted element must have zero upperbits.
5761 if (RHS.getOpcode() == ISD::SHL &&
5762 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5763 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5764 DAG.MaskedValueIsZero(LHS, HiBits)) {
5765 Lo = LHS;
5766 Hi = RHS.getOperand(0);
5767 return true;
5768 }
5769 if (LHS.getOpcode() == ISD::SHL &&
5770 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5771 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5772 DAG.MaskedValueIsZero(RHS, HiBits)) {
5773 Lo = RHS;
5774 Hi = LHS.getOperand(0);
5775 return true;
5776 }
5777 return false;
5778 };
5779
5780 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5781 unsigned EltBits = N0.getScalarValueSizeInBits();
5782 unsigned HalfBits = EltBits / 2;
5783 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5784 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5785 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5786 SDValue NewN0 =
5787 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5788 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5789 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5790 };
5791
5792 SDValue Lo, Hi;
5793 if (IsConcat(N0, Lo, Hi))
5794 return MergeConcat(Lo, Hi);
5795
5796 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5797 SDValue Lo0, Lo1, Hi0, Hi1;
5798 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5799 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5800 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5801 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5802 }
5803 }
5804 }
5805 }
5806
5807 // If we have "setcc X, C0", check to see if we can shrink the immediate
5808 // by changing cc.
5809 // TODO: Support this for vectors after legalize ops.
5810 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5811 // SETUGT X, SINTMAX -> SETLT X, 0
5812 // SETUGE X, SINTMIN -> SETLT X, 0
5813 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5814 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5815 return DAG.getSetCC(dl, VT, N0,
5816 DAG.getConstant(0, dl, N1.getValueType()),
5817 ISD::SETLT);
5818
5819 // SETULT X, SINTMIN -> SETGT X, -1
5820 // SETULE X, SINTMAX -> SETGT X, -1
5821 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5822 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5823 return DAG.getSetCC(dl, VT, N0,
5824 DAG.getAllOnesConstant(dl, N1.getValueType()),
5825 ISD::SETGT);
5826 }
5827 }
5828
5829 // Back to non-vector simplifications.
5830 // TODO: Can we do these for vector splats?
5831 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5832 const APInt &C1 = N1C->getAPIntValue();
5833 EVT ShValTy = N0.getValueType();
5834
5835 // Fold bit comparisons when we can. This will result in an
5836 // incorrect value when boolean false is negative one, unless
5837 // the bitsize is 1 in which case the false value is the same
5838 // in practice regardless of the representation.
5839 if ((VT.getSizeInBits() == 1 ||
5841 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5842 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5843 N0.getOpcode() == ISD::AND) {
5844 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5845 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5846 // Perform the xform if the AND RHS is a single bit.
5847 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5848 if (AndRHS->getAPIntValue().isPowerOf2() &&
5849 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5850 return DAG.getNode(
5851 ISD::TRUNCATE, dl, VT,
5852 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5853 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5854 }
5855 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5856 // (X & 8) == 8 --> (X & 8) >> 3
5857 // Perform the xform if C1 is a single bit.
5858 unsigned ShCt = C1.logBase2();
5859 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5860 return DAG.getNode(
5861 ISD::TRUNCATE, dl, VT,
5862 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5863 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5864 }
5865 }
5866 }
5867 }
5868
5869 if (C1.getSignificantBits() <= 64 &&
5870 !isLegalICmpImmediate(C1.getSExtValue())) {
5871 // (X & -256) == 256 -> (X >> 8) == 1
5872 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5873 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5874 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5875 const APInt &AndRHSC = AndRHS->getAPIntValue();
5876 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5877 unsigned ShiftBits = AndRHSC.countr_zero();
5878 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5879 // If using an unsigned shift doesn't yield a legal compare
5880 // immediate, try using sra instead.
5881 APInt NewC = C1.lshr(ShiftBits);
5882 if (NewC.getSignificantBits() <= 64 &&
5884 APInt SignedC = C1.ashr(ShiftBits);
5885 if (SignedC.getSignificantBits() <= 64 &&
5887 SDValue Shift = DAG.getNode(
5888 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5889 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5890 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5891 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5892 }
5893 }
5894 SDValue Shift = DAG.getNode(
5895 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5896 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5897 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5898 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5899 }
5900 }
5901 }
5902 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5903 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5904 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5905 // X < 0x100000000 -> (X >> 32) < 1
5906 // X >= 0x100000000 -> (X >> 32) >= 1
5907 // X <= 0x0ffffffff -> (X >> 32) < 1
5908 // X > 0x0ffffffff -> (X >> 32) >= 1
5909 unsigned ShiftBits;
5910 APInt NewC = C1;
5911 ISD::CondCode NewCond = Cond;
5912 if (AdjOne) {
5913 ShiftBits = C1.countr_one();
5914 NewC = NewC + 1;
5915 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5916 } else {
5917 ShiftBits = C1.countr_zero();
5918 }
5919 APInt RangeWidth = NewC;
5920 NewC.lshrInPlace(ShiftBits);
5921 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5923 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5924 // If this is an offset range check, try to move the offset after the
5925 // shift to avoid preserving the pre-shift add with a mask.
5926 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse()) {
5927 if (auto *AddC = isConstOrConstSplat(N0.getOperand(1))) {
5928 const APInt &AddVal = AddC->getAPIntValue();
5929 if (AddVal.countr_zero() >= ShiftBits) {
5930 APInt RangeLower = -AddVal;
5931 bool Overflow;
5932 (void)RangeLower.uadd_ov(RangeWidth, Overflow);
5933 if (!RangeWidth.isZero() && !Overflow) {
5934 SDValue Shift = DAG.getNode(
5935 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5936 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5937 APInt Offset = -RangeLower.lshr(ShiftBits);
5938 SDValue ShiftedAdd =
5939 DAG.getNode(ISD::ADD, dl, ShValTy, Shift,
5940 DAG.getConstant(Offset, dl, ShValTy));
5941 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5942 return DAG.getSetCC(dl, VT, ShiftedAdd, CmpRHS, NewCond);
5943 }
5944 }
5945 }
5946 }
5947 SDValue Shift =
5948 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5949 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5950 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5951 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5952 }
5953 }
5954 }
5955 }
5956
5958 auto *CFP = cast<ConstantFPSDNode>(N1);
5959 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5960
5961 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5962 // constant if knowing that the operand is non-nan is enough. We prefer to
5963 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5964 // materialize 0.0.
5965 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5966 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5967
5968 // setcc (fneg x), C -> setcc swap(pred) x, -C
5969 if (N0.getOpcode() == ISD::FNEG) {
5971 if (DCI.isBeforeLegalizeOps() ||
5972 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5973 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5974 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5975 }
5976 }
5977
5978 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5980 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5981 bool IsFabs = N0.getOpcode() == ISD::FABS;
5982 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5983 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5984 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5985 : (IsFabs ? fcInf : fcPosInf);
5986 if (Cond == ISD::SETUEQ)
5987 Flag |= fcNan;
5988 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5989 DAG.getTargetConstant(Flag, dl, MVT::i32));
5990 }
5991 }
5992
5993 // If the condition is not legal, see if we can find an equivalent one
5994 // which is legal.
5996 // If the comparison was an awkward floating-point == or != and one of
5997 // the comparison operands is infinity or negative infinity, convert the
5998 // condition to a less-awkward <= or >=.
5999 if (CFP->getValueAPF().isInfinity()) {
6000 bool IsNegInf = CFP->getValueAPF().isNegative();
6002 switch (Cond) {
6003 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
6004 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
6005 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
6006 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
6007 default: break;
6008 }
6009 if (NewCond != ISD::SETCC_INVALID &&
6010 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
6011 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
6012 }
6013 }
6014 }
6015
6016 if (N0 == N1) {
6017 // The sext(setcc()) => setcc() optimization relies on the appropriate
6018 // constant being emitted.
6019 assert(!N0.getValueType().isInteger() &&
6020 "Integer types should be handled by FoldSetCC");
6021
6022 bool EqTrue = ISD::isTrueWhenEqual(Cond);
6023 unsigned UOF = ISD::getUnorderedFlavor(Cond);
6024 if (UOF == 2) // FP operators that are undefined on NaNs.
6025 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
6026 if (UOF == unsigned(EqTrue))
6027 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
6028 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
6029 // if it is not already.
6030 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
6031 if (NewCond != Cond &&
6032 (DCI.isBeforeLegalizeOps() ||
6033 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
6034 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
6035 }
6036
6037 // ~X > ~Y --> Y > X
6038 // ~X < ~Y --> Y < X
6039 // ~X < C --> X > ~C
6040 // ~X > C --> X < ~C
6041 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
6042 N0.getValueType().isInteger()) {
6043 if (isBitwiseNot(N0)) {
6044 if (isBitwiseNot(N1))
6045 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
6046
6049 SDValue Not = DAG.getNOT(dl, N1, OpVT);
6050 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
6051 }
6052 }
6053 }
6054
6055 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6056 N0.getValueType().isInteger()) {
6057 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
6058 N0.getOpcode() == ISD::XOR) {
6059 // Simplify (X+Y) == (X+Z) --> Y == Z
6060 if (N0.getOpcode() == N1.getOpcode()) {
6061 if (N0.getOperand(0) == N1.getOperand(0))
6062 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
6063 if (N0.getOperand(1) == N1.getOperand(1))
6064 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6065 if (isCommutativeBinOp(N0.getOpcode())) {
6066 // If X op Y == Y op X, try other combinations.
6067 if (N0.getOperand(0) == N1.getOperand(1))
6068 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
6069 Cond);
6070 if (N0.getOperand(1) == N1.getOperand(0))
6071 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
6072 Cond);
6073 }
6074 }
6075
6076 // If RHS is a legal immediate value for a compare instruction, we need
6077 // to be careful about increasing register pressure needlessly.
6078 bool LegalRHSImm = false;
6079
6080 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
6081 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6082 // Turn (X+C1) == C2 --> X == C2-C1
6083 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
6084 return DAG.getSetCC(
6085 dl, VT, N0.getOperand(0),
6086 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
6087 dl, N0.getValueType()),
6088 Cond);
6089
6090 // Turn (X^C1) == C2 --> X == C1^C2
6091 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
6092 return DAG.getSetCC(
6093 dl, VT, N0.getOperand(0),
6094 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
6095 dl, N0.getValueType()),
6096 Cond);
6097 }
6098
6099 // Turn (C1-X) == C2 --> X == C1-C2
6100 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
6101 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
6102 return DAG.getSetCC(
6103 dl, VT, N0.getOperand(1),
6104 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
6105 dl, N0.getValueType()),
6106 Cond);
6107
6108 // Could RHSC fold directly into a compare?
6109 if (RHSC->getValueType(0).getSizeInBits() <= 64)
6110 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
6111 }
6112
6113 // (X+Y) == X --> Y == 0 and similar folds.
6114 // Don't do this if X is an immediate that can fold into a cmp
6115 // instruction and X+Y has other uses. It could be an induction variable
6116 // chain, and the transform would increase register pressure.
6117 if (!LegalRHSImm || N0.hasOneUse())
6118 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
6119 return V;
6120 }
6121
6122 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
6123 N1.getOpcode() == ISD::XOR)
6124 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
6125 return V;
6126
6127 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
6128 return V;
6129
6130 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
6131 return V;
6132 }
6133
6134 // Fold remainder of division by a constant.
6135 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
6136 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
6137 // When division is cheap or optimizing for minimum size,
6138 // fall through to DIVREM creation by skipping this fold.
6139 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
6140 if (N0.getOpcode() == ISD::UREM) {
6141 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
6142 return Folded;
6143 } else if (N0.getOpcode() == ISD::SREM) {
6144 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
6145 return Folded;
6146 }
6147 }
6148 }
6149
6150 // Fold away ALL boolean setcc's.
6151 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
6152 SDValue Temp;
6153 switch (Cond) {
6154 default: llvm_unreachable("Unknown integer setcc!");
6155 case ISD::SETEQ: // X == Y -> ~(X^Y)
6156 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
6157 N0 = DAG.getNOT(dl, Temp, OpVT);
6158 if (!DCI.isCalledByLegalizer())
6159 DCI.AddToWorklist(Temp.getNode());
6160 break;
6161 case ISD::SETNE: // X != Y --> (X^Y)
6162 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
6163 break;
6164 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
6165 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
6166 Temp = DAG.getNOT(dl, N0, OpVT);
6167 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
6168 if (!DCI.isCalledByLegalizer())
6169 DCI.AddToWorklist(Temp.getNode());
6170 break;
6171 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
6172 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
6173 Temp = DAG.getNOT(dl, N1, OpVT);
6174 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
6175 if (!DCI.isCalledByLegalizer())
6176 DCI.AddToWorklist(Temp.getNode());
6177 break;
6178 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
6179 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
6180 Temp = DAG.getNOT(dl, N0, OpVT);
6181 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
6182 if (!DCI.isCalledByLegalizer())
6183 DCI.AddToWorklist(Temp.getNode());
6184 break;
6185 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
6186 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
6187 Temp = DAG.getNOT(dl, N1, OpVT);
6188 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
6189 break;
6190 }
6191 if (VT.getScalarType() != MVT::i1) {
6192 if (!DCI.isCalledByLegalizer())
6193 DCI.AddToWorklist(N0.getNode());
6194 // FIXME: If running after legalize, we probably can't do this.
6196 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
6197 }
6198 return N0;
6199 }
6200
6201 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
6202 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
6203 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
6205 N1->getFlags().hasNoUnsignedWrap()) ||
6207 N1->getFlags().hasNoSignedWrap())) &&
6209 if (VT.getScalarType() == MVT::i1)
6210 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6211 // For (legal) non vXi1 cases - ensure we adjust the cmp and result types.
6212 EVT OldCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6213 N0.getValueType());
6214 if (VT == OldCCVT) {
6215 EVT NewCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6216 N0.getOperand(0).getValueType());
6217 return DAG.getBoolExtOrTrunc(
6218 DAG.getSetCC(dl, NewCCVT, N0.getOperand(0), N1.getOperand(0), Cond),
6219 dl, VT, N0.getOperand(0).getValueType());
6220 }
6221 }
6222
6223 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
6224 // TODO: Remove that .isVector() check
6225 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
6227 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
6228 }
6229
6230 // Could not fold it.
6231 return SDValue();
6232}
6233
6234/// Returns true (and the GlobalValue and the offset) if the node is a
6235/// GlobalAddress + offset.
6237 int64_t &Offset) const {
6238
6239 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
6240
6241 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
6242 GA = GASD->getGlobal();
6243 Offset += GASD->getOffset();
6244 return true;
6245 }
6246
6247 if (N->isAnyAdd()) {
6248 SDValue N1 = N->getOperand(0);
6249 SDValue N2 = N->getOperand(1);
6250 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
6251 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
6252 Offset += V->getSExtValue();
6253 return true;
6254 }
6255 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
6256 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
6257 Offset += V->getSExtValue();
6258 return true;
6259 }
6260 }
6261 }
6262
6263 return false;
6264}
6265
6267 DAGCombinerInfo &DCI) const {
6268 // Default implementation: no optimization.
6269 return SDValue();
6270}
6271
6272//===----------------------------------------------------------------------===//
6273// Inline Assembler Implementation Methods
6274//===----------------------------------------------------------------------===//
6275
6278 unsigned S = Constraint.size();
6279
6280 if (S == 1) {
6281 switch (Constraint[0]) {
6282 default: break;
6283 case 'r':
6284 return C_RegisterClass;
6285 case 'm': // memory
6286 case 'o': // offsetable
6287 case 'V': // not offsetable
6288 return C_Memory;
6289 case 'p': // Address.
6290 return C_Address;
6291 case 'n': // Simple Integer
6292 case 'E': // Floating Point Constant
6293 case 'F': // Floating Point Constant
6294 return C_Immediate;
6295 case 'i': // Simple Integer or Relocatable Constant
6296 case 's': // Relocatable Constant
6297 case 'X': // Allow ANY value.
6298 case 'I': // Target registers.
6299 case 'J':
6300 case 'K':
6301 case 'L':
6302 case 'M':
6303 case 'N':
6304 case 'O':
6305 case 'P':
6306 case '<':
6307 case '>':
6308 return C_Other;
6309 }
6310 }
6311
6312 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
6313 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
6314 return C_Memory;
6315 return C_Register;
6316 }
6317 return C_Unknown;
6318}
6319
6320/// Try to replace an X constraint, which matches anything, with another that
6321/// has more specific requirements based on the type of the corresponding
6322/// operand.
6323const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6324 if (ConstraintVT.isInteger())
6325 return "r";
6326 if (ConstraintVT.isFloatingPoint())
6327 return "f"; // works for many targets
6328 return nullptr;
6329}
6330
6332 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
6333 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
6334 return SDValue();
6335}
6336
6337/// Lower the specified operand into the Ops vector.
6338/// If it is invalid, don't add anything to Ops.
6340 StringRef Constraint,
6341 std::vector<SDValue> &Ops,
6342 SelectionDAG &DAG) const {
6343
6344 if (Constraint.size() > 1)
6345 return;
6346
6347 char ConstraintLetter = Constraint[0];
6348 switch (ConstraintLetter) {
6349 default: break;
6350 case 'X': // Allows any operand
6351 case 'i': // Simple Integer or Relocatable Constant
6352 case 'n': // Simple Integer
6353 case 's': { // Relocatable Constant
6354
6356 uint64_t Offset = 0;
6357
6358 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
6359 // etc., since getelementpointer is variadic. We can't use
6360 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
6361 // while in this case the GA may be furthest from the root node which is
6362 // likely an ISD::ADD.
6363 while (true) {
6364 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
6365 // gcc prints these as sign extended. Sign extend value to 64 bits
6366 // now; without this it would get ZExt'd later in
6367 // ScheduleDAGSDNodes::EmitNode, which is very generic.
6368 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
6369 BooleanContent BCont = getBooleanContents(/*isVec=*/false);
6370 ISD::NodeType ExtOpc =
6371 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
6372 int64_t ExtVal =
6373 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
6374 Ops.push_back(
6375 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
6376 return;
6377 }
6378 if (ConstraintLetter != 'n') {
6379 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6380 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6381 GA->getValueType(0),
6382 Offset + GA->getOffset()));
6383 return;
6384 }
6385 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
6386 Ops.push_back(DAG.getTargetBlockAddress(
6387 BA->getBlockAddress(), BA->getValueType(0),
6388 Offset + BA->getOffset(), BA->getTargetFlags()));
6389 return;
6390 }
6392 Ops.push_back(Op);
6393 return;
6394 }
6395 }
6396 const unsigned OpCode = Op.getOpcode();
6397 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6398 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6399 Op = Op.getOperand(1);
6400 // Subtraction is not commutative.
6401 else if (OpCode == ISD::ADD &&
6402 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6403 Op = Op.getOperand(0);
6404 else
6405 return;
6406 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6407 continue;
6408 }
6409 return;
6410 }
6411 break;
6412 }
6413 }
6414}
6415
6419
6420std::pair<unsigned, const TargetRegisterClass *>
6422 StringRef Constraint,
6423 MVT VT) const {
6424 if (!Constraint.starts_with("{"))
6425 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6426 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6427
6428 // Remove the braces from around the name.
6429 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6430
6431 std::pair<unsigned, const TargetRegisterClass *> R =
6432 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6433
6434 // Figure out which register class contains this reg.
6435 for (const TargetRegisterClass &RC : RI->regclasses()) {
6436 // If none of the value types for this register class are valid, we
6437 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6438 if (!isLegalRC(*RI, RC))
6439 continue;
6440
6441 for (const MCPhysReg &PR : RC) {
6442 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6443 std::pair<unsigned, const TargetRegisterClass *> S =
6444 std::make_pair(PR, &RC);
6445
6446 // If this register class has the requested value type, return it,
6447 // otherwise keep searching and return the first class found
6448 // if no other is found which explicitly has the requested type.
6449 if (RI->isTypeLegalForClass(RC, VT))
6450 return S;
6451 if (!R.second)
6452 R = S;
6453 }
6454 }
6455 }
6456
6457 return R;
6458}
6459
6460//===----------------------------------------------------------------------===//
6461// Constraint Selection.
6462
6463/// Return true of this is an input operand that is a matching constraint like
6464/// "4".
6466 assert(!ConstraintCode.empty() && "No known constraint!");
6467 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6468}
6469
6470/// If this is an input matching constraint, this method returns the output
6471/// operand it matches.
6473 assert(!ConstraintCode.empty() && "No known constraint!");
6474 return atoi(ConstraintCode.c_str());
6475}
6476
6477/// Split up the constraint string from the inline assembly value into the
6478/// specific constraints and their prefixes, and also tie in the associated
6479/// operand values.
6480/// If this returns an empty vector, and if the constraint string itself
6481/// isn't empty, there was an error parsing.
6484 const TargetRegisterInfo *TRI,
6485 const CallBase &Call) const {
6486 /// Information about all of the constraints.
6487 AsmOperandInfoVector ConstraintOperands;
6488 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6489 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6490
6491 // Do a prepass over the constraints, canonicalizing them, and building up the
6492 // ConstraintOperands list.
6493 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6494 unsigned ResNo = 0; // ResNo - The result number of the next output.
6495 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6496
6497 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6498 ConstraintOperands.emplace_back(std::move(CI));
6499 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6500
6501 // Update multiple alternative constraint count.
6502 if (OpInfo.multipleAlternatives.size() > maCount)
6503 maCount = OpInfo.multipleAlternatives.size();
6504
6505 OpInfo.ConstraintVT = MVT::Other;
6506
6507 // Compute the value type for each operand.
6508 switch (OpInfo.Type) {
6509 case InlineAsm::isOutput: {
6510 // Indirect outputs just consume an argument.
6511 if (OpInfo.isIndirect) {
6512 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6513 break;
6514 }
6515
6516 // The return value of the call is this value. As such, there is no
6517 // corresponding argument.
6518 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6519 EVT VT;
6520 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6521 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6522 } else {
6523 assert(ResNo == 0 && "Asm only has one result!");
6524 VT = getAsmOperandValueType(DL, Call.getType());
6525 }
6526 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6527 ++ResNo;
6528 break;
6529 }
6530 case InlineAsm::isInput:
6531 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6532 break;
6533 case InlineAsm::isLabel:
6534 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6535 ++LabelNo;
6536 continue;
6538 // Nothing to do.
6539 break;
6540 }
6541
6542 if (OpInfo.CallOperandVal) {
6543 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6544 if (OpInfo.isIndirect) {
6545 OpTy = Call.getParamElementType(ArgNo);
6546 assert(OpTy && "Indirect operand must have elementtype attribute");
6547 }
6548
6549 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6551 if (STy->getNumElements() == 1)
6552 OpTy = STy->getElementType(0);
6553
6554 // If OpTy is not a single value, it may be a struct/union that we
6555 // can tile with integers.
6556 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6557 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6558 switch (BitSize) {
6559 default: break;
6560 case 1:
6561 case 8:
6562 case 16:
6563 case 32:
6564 case 64:
6565 case 128:
6566 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6567 break;
6568 }
6569 }
6570
6571 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6572 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6573 ArgNo++;
6574 }
6575 }
6576
6577 // If we have multiple alternative constraints, select the best alternative.
6578 if (!ConstraintOperands.empty()) {
6579 if (maCount) {
6580 unsigned bestMAIndex = 0;
6581 int bestWeight = -1;
6582 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6583 int weight = -1;
6584 unsigned maIndex;
6585 // Compute the sums of the weights for each alternative, keeping track
6586 // of the best (highest weight) one so far.
6587 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6588 int weightSum = 0;
6589 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6590 cIndex != eIndex; ++cIndex) {
6591 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6592 if (OpInfo.Type == InlineAsm::isClobber)
6593 continue;
6594
6595 // If this is an output operand with a matching input operand,
6596 // look up the matching input. If their types mismatch, e.g. one
6597 // is an integer, the other is floating point, or their sizes are
6598 // different, flag it as an maCantMatch.
6599 if (OpInfo.hasMatchingInput()) {
6600 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6601 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6602 if ((OpInfo.ConstraintVT.isInteger() !=
6603 Input.ConstraintVT.isInteger()) ||
6604 (OpInfo.ConstraintVT.getSizeInBits() !=
6605 Input.ConstraintVT.getSizeInBits())) {
6606 weightSum = -1; // Can't match.
6607 break;
6608 }
6609 }
6610 }
6611 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6612 if (weight == -1) {
6613 weightSum = -1;
6614 break;
6615 }
6616 weightSum += weight;
6617 }
6618 // Update best.
6619 if (weightSum > bestWeight) {
6620 bestWeight = weightSum;
6621 bestMAIndex = maIndex;
6622 }
6623 }
6624
6625 // Now select chosen alternative in each constraint.
6626 for (AsmOperandInfo &cInfo : ConstraintOperands)
6627 if (cInfo.Type != InlineAsm::isClobber)
6628 cInfo.selectAlternative(bestMAIndex);
6629 }
6630 }
6631
6632 // Check and hook up tied operands, choose constraint code to use.
6633 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6634 cIndex != eIndex; ++cIndex) {
6635 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6636
6637 // If this is an output operand with a matching input operand, look up the
6638 // matching input. If their types mismatch, e.g. one is an integer, the
6639 // other is floating point, or their sizes are different, flag it as an
6640 // error.
6641 if (OpInfo.hasMatchingInput()) {
6642 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6643
6644 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6645 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6646 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6647 OpInfo.ConstraintVT);
6648 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6649 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6650 Input.ConstraintVT);
6651 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6652 OpInfo.ConstraintVT.isFloatingPoint();
6653 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6654 Input.ConstraintVT.isFloatingPoint();
6655 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6656 (MatchRC.second != InputRC.second)) {
6657 report_fatal_error("Unsupported asm: input constraint"
6658 " with a matching output constraint of"
6659 " incompatible type!");
6660 }
6661 }
6662 }
6663 }
6664
6665 return ConstraintOperands;
6666}
6667
6668/// Return a number indicating our preference for chosing a type of constraint
6669/// over another, for the purpose of sorting them. Immediates are almost always
6670/// preferrable (when they can be emitted). A higher return value means a
6671/// stronger preference for one constraint type relative to another.
6672/// FIXME: We should prefer registers over memory but doing so may lead to
6673/// unrecoverable register exhaustion later.
6674/// https://github.com/llvm/llvm-project/issues/20571
6676 switch (CT) {
6679 return 4;
6682 return 3;
6684 return 2;
6686 return 1;
6688 return 0;
6689 }
6690 llvm_unreachable("Invalid constraint type");
6691}
6692
6693/// Examine constraint type and operand type and determine a weight value.
6694/// This object must already have been set up with the operand type
6695/// and the current alternative constraint selected.
6698 AsmOperandInfo &info, int maIndex) const {
6700 if (maIndex >= (int)info.multipleAlternatives.size())
6701 rCodes = &info.Codes;
6702 else
6703 rCodes = &info.multipleAlternatives[maIndex].Codes;
6704 ConstraintWeight BestWeight = CW_Invalid;
6705
6706 // Loop over the options, keeping track of the most general one.
6707 for (const std::string &rCode : *rCodes) {
6709 getSingleConstraintMatchWeight(info, rCode.c_str());
6710 if (weight > BestWeight)
6711 BestWeight = weight;
6712 }
6713
6714 return BestWeight;
6715}
6716
6717/// Examine constraint type and operand type and determine a weight value.
6718/// This object must already have been set up with the operand type
6719/// and the current alternative constraint selected.
6722 AsmOperandInfo &info, const char *constraint) const {
6724 Value *CallOperandVal = info.CallOperandVal;
6725 // If we don't have a value, we can't do a match,
6726 // but allow it at the lowest weight.
6727 if (!CallOperandVal)
6728 return CW_Default;
6729 // Look at the constraint type.
6730 switch (*constraint) {
6731 case 'i': // immediate integer.
6732 case 'n': // immediate integer with a known value.
6733 if (isa<ConstantInt>(CallOperandVal))
6735 break;
6736 case 's': // non-explicit intregal immediate.
6737 if (isa<GlobalValue>(CallOperandVal))
6739 break;
6740 case 'E': // immediate float if host format.
6741 case 'F': // immediate float.
6742 if (isa<ConstantFP>(CallOperandVal))
6744 break;
6745 case '<': // memory operand with autodecrement.
6746 case '>': // memory operand with autoincrement.
6747 case 'm': // memory operand.
6748 case 'o': // offsettable memory operand
6749 case 'V': // non-offsettable memory operand
6750 weight = CW_Memory;
6751 break;
6752 case 'r': // general register.
6753 case 'g': // general register, memory operand or immediate integer.
6754 // note: Clang converts "g" to "imr".
6755 if (CallOperandVal->getType()->isIntegerTy())
6757 break;
6758 case 'X': // any operand.
6759 default:
6761 break;
6762 }
6763 return weight;
6764}
6765
6766/// If there are multiple different constraints that we could pick for this
6767/// operand (e.g. "imr") try to pick the 'best' one.
6768/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6769/// into seven classes:
6770/// Register -> one specific register
6771/// RegisterClass -> a group of regs
6772/// Memory -> memory
6773/// Address -> a symbolic memory reference
6774/// Immediate -> immediate values
6775/// Other -> magic values (such as "Flag Output Operands")
6776/// Unknown -> something we don't recognize yet and can't handle
6777/// Ideally, we would pick the most specific constraint possible: if we have
6778/// something that fits into a register, we would pick it. The problem here
6779/// is that if we have something that could either be in a register or in
6780/// memory that use of the register could cause selection of *other*
6781/// operands to fail: they might only succeed if we pick memory. Because of
6782/// this the heuristic we use is:
6783///
6784/// 1) If there is an 'other' constraint, and if the operand is valid for
6785/// that constraint, use it. This makes us take advantage of 'i'
6786/// constraints when available.
6787/// 2) Otherwise, pick the most general constraint present. This prefers
6788/// 'm' over 'r', for example.
6789///
6791 TargetLowering::AsmOperandInfo &OpInfo) const {
6792 ConstraintGroup Ret;
6793
6794 Ret.reserve(OpInfo.Codes.size());
6795 for (StringRef Code : OpInfo.Codes) {
6797
6798 // Indirect 'other' or 'immediate' constraints are not allowed.
6799 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6800 CType == TargetLowering::C_Register ||
6802 continue;
6803
6804 // Things with matching constraints can only be registers, per gcc
6805 // documentation. This mainly affects "g" constraints.
6806 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6807 continue;
6808
6809 Ret.emplace_back(Code, CType);
6810 }
6811
6813 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6814 });
6815
6816 return Ret;
6817}
6818
6819/// If we have an immediate, see if we can lower it. Return true if we can,
6820/// false otherwise.
6822 SDValue Op, SelectionDAG *DAG,
6823 const TargetLowering &TLI) {
6824
6825 assert((P.second == TargetLowering::C_Other ||
6826 P.second == TargetLowering::C_Immediate) &&
6827 "need immediate or other");
6828
6829 if (!Op.getNode())
6830 return false;
6831
6832 std::vector<SDValue> ResultOps;
6833 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6834 return !ResultOps.empty();
6835}
6836
6837/// Determines the constraint code and constraint type to use for the specific
6838/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6840 SDValue Op,
6841 SelectionDAG *DAG) const {
6842 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6843
6844 // Single-letter constraints ('r') are very common.
6845 if (OpInfo.Codes.size() == 1) {
6846 OpInfo.ConstraintCode = OpInfo.Codes[0];
6847 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6848 } else {
6850 if (G.empty())
6851 return;
6852
6853 unsigned BestIdx = 0;
6854 for (const unsigned E = G.size();
6855 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6856 G[BestIdx].second == TargetLowering::C_Immediate);
6857 ++BestIdx) {
6858 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6859 break;
6860 // If we're out of constraints, just pick the first one.
6861 if (BestIdx + 1 == E) {
6862 BestIdx = 0;
6863 break;
6864 }
6865 }
6866
6867 OpInfo.ConstraintCode = G[BestIdx].first;
6868 OpInfo.ConstraintType = G[BestIdx].second;
6869 }
6870
6871 // 'X' matches anything.
6872 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6873 // Constants are handled elsewhere. For Functions, the type here is the
6874 // type of the result, which is not what we want to look at; leave them
6875 // alone.
6876 Value *v = OpInfo.CallOperandVal;
6877 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6878 return;
6879 }
6880
6881 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6882 OpInfo.ConstraintCode = "i";
6883 return;
6884 }
6885
6886 // Otherwise, try to resolve it to something we know about by looking at
6887 // the actual operand type.
6888 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6889 OpInfo.ConstraintCode = Repl;
6890 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6891 }
6892 }
6893}
6894
6895/// Given an exact SDIV by a constant, create a multiplication
6896/// with the multiplicative inverse of the constant.
6897/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6899 const SDLoc &dl, SelectionDAG &DAG,
6900 SmallVectorImpl<SDNode *> &Created) {
6901 SDValue Op0 = N->getOperand(0);
6902 SDValue Op1 = N->getOperand(1);
6903 EVT VT = N->getValueType(0);
6904 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6905 EVT ShSVT = ShVT.getScalarType();
6906
6907 bool UseSRA = false;
6908 SmallVector<SDValue, 16> Shifts, Factors;
6909
6910 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6911 if (C->isZero())
6912 return false;
6913
6914 EVT CT = C->getValueType(0);
6915 APInt Divisor = C->getAPIntValue();
6916 unsigned Shift = Divisor.countr_zero();
6917 if (Shift) {
6918 Divisor.ashrInPlace(Shift);
6919 UseSRA = true;
6920 }
6921 APInt Factor = Divisor.multiplicativeInverse();
6922 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6923 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6924 return true;
6925 };
6926
6927 // Collect all magic values from the build vector.
6928 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6929 return SDValue();
6930
6931 SDValue Shift, Factor;
6932 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6933 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6934 Factor = DAG.getBuildVector(VT, dl, Factors);
6935 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6936 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6937 "Expected matchUnaryPredicate to return one element for scalable "
6938 "vectors");
6939 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6940 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6941 } else {
6942 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6943 Shift = Shifts[0];
6944 Factor = Factors[0];
6945 }
6946
6947 SDValue Res = Op0;
6948 if (UseSRA) {
6949 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6950 Created.push_back(Res.getNode());
6951 }
6952
6953 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6954}
6955
6956/// Given an exact UDIV by a constant, create a multiplication
6957/// with the multiplicative inverse of the constant.
6958/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6960 const SDLoc &dl, SelectionDAG &DAG,
6961 SmallVectorImpl<SDNode *> &Created) {
6962 EVT VT = N->getValueType(0);
6963 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6964 EVT ShSVT = ShVT.getScalarType();
6965
6966 bool UseSRL = false;
6967 SmallVector<SDValue, 16> Shifts, Factors;
6968
6969 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6970 if (C->isZero())
6971 return false;
6972
6973 EVT CT = C->getValueType(0);
6974 APInt Divisor = C->getAPIntValue();
6975 unsigned Shift = Divisor.countr_zero();
6976 if (Shift) {
6977 Divisor.lshrInPlace(Shift);
6978 UseSRL = true;
6979 }
6980 // Calculate the multiplicative inverse modulo BW.
6981 APInt Factor = Divisor.multiplicativeInverse();
6982 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6983 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6984 return true;
6985 };
6986
6987 SDValue Op1 = N->getOperand(1);
6988
6989 // Collect all magic values from the build vector.
6990 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6991 return SDValue();
6992
6993 SDValue Shift, Factor;
6994 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6995 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6996 Factor = DAG.getBuildVector(VT, dl, Factors);
6997 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6998 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6999 "Expected matchUnaryPredicate to return one element for scalable "
7000 "vectors");
7001 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
7002 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
7003 } else {
7004 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
7005 Shift = Shifts[0];
7006 Factor = Factors[0];
7007 }
7008
7009 SDValue Res = N->getOperand(0);
7010 if (UseSRL) {
7011 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
7012 Created.push_back(Res.getNode());
7013 }
7014
7015 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
7016}
7017
7019 SelectionDAG &DAG,
7020 SmallVectorImpl<SDNode *> &Created) const {
7022 if (isIntDivCheap(N->getValueType(0), Attr))
7023 return SDValue(N, 0); // Lower SDIV as SDIV
7024 return SDValue();
7025}
7026
7027SDValue
7029 SelectionDAG &DAG,
7030 SmallVectorImpl<SDNode *> &Created) const {
7032 if (isIntDivCheap(N->getValueType(0), Attr))
7033 return SDValue(N, 0); // Lower SREM as SREM
7034 return SDValue();
7035}
7036
7037/// Build sdiv by power-of-2 with conditional move instructions
7038/// Ref: "Hacker's Delight" by Henry Warren 10-1
7039/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
7040/// bgez x, label
7041/// add x, x, 2**k-1
7042/// label:
7043/// sra res, x, k
7044/// neg res, res (when the divisor is negative)
7046 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
7047 SmallVectorImpl<SDNode *> &Created) const {
7048 unsigned Lg2 = Divisor.countr_zero();
7049 EVT VT = N->getValueType(0);
7050
7051 SDLoc DL(N);
7052 SDValue N0 = N->getOperand(0);
7053 SDValue Zero = DAG.getConstant(0, DL, VT);
7054 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
7055 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
7056
7057 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
7058 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7059 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
7060 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7061 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
7062
7063 Created.push_back(Cmp.getNode());
7064 Created.push_back(Add.getNode());
7065 Created.push_back(CMov.getNode());
7066
7067 // Divide by pow2.
7068 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
7069 DAG.getShiftAmountConstant(Lg2, VT, DL));
7070
7071 // If we're dividing by a positive value, we're done. Otherwise, we must
7072 // negate the result.
7073 if (Divisor.isNonNegative())
7074 return SRA;
7075
7076 Created.push_back(SRA.getNode());
7077 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
7078}
7079
7080/// Given an ISD::SDIV node expressing a divide by constant,
7081/// return a DAG expression to select that will generate the same value by
7082/// multiplying by a magic number.
7083/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7085 bool IsAfterLegalization,
7086 bool IsAfterLegalTypes,
7087 SmallVectorImpl<SDNode *> &Created) const {
7088 SDLoc dl(N);
7089
7090 // If the sdiv has an 'exact' bit we can use a simpler lowering.
7091 if (N->getFlags().hasExact())
7092 return BuildExactSDIV(*this, N, dl, DAG, Created);
7093
7094 EVT VT = N->getValueType(0);
7095 EVT SVT = VT.getScalarType();
7096 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7097 EVT ShSVT = ShVT.getScalarType();
7098 unsigned EltBits = VT.getScalarSizeInBits();
7099 EVT MulVT;
7100
7101 // Check to see if we can do this.
7102 // FIXME: We should be more aggressive here.
7103 EVT QueryVT = VT;
7104 if (VT.isVector()) {
7105 // If the vector type will be legalized to a vector type with the same
7106 // element type, allow the transform before type legalization if MULHS or
7107 // SMUL_LOHI are supported.
7108 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7109 if (!QueryVT.isVector() ||
7111 return SDValue();
7112 } else if (!isTypeLegal(VT)) {
7113 // Limit this to simple scalars for now.
7114 if (!VT.isSimple())
7115 return SDValue();
7116
7117 // If this type will be promoted to a large enough type with a legal
7118 // multiply operation, we can go ahead and do this transform.
7120 return SDValue();
7121
7122 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7123 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7124 !isOperationLegal(ISD::MUL, MulVT))
7125 return SDValue();
7126 }
7127
7128 bool HasMULHS =
7129 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
7130 bool HasSMUL_LOHI =
7131 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
7132
7133 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
7134 // If type twice as wide legal, widen and use a mul plus a shift.
7135 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7136 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
7137 // custom lowered. This is very expensive so avoid it at all costs for
7138 // constant divisors.
7139 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
7142 MulVT = WideVT;
7143 }
7144
7145 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
7146 return SDValue();
7147
7148 // If we're after type legalization and SVT is not legal, use the
7149 // promoted type for creating constants to avoid creating nodes with
7150 // illegal types.
7151 if (IsAfterLegalTypes && VT.isVector()) {
7152 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7153 if (SVT.bitsLT(VT.getScalarType()))
7154 return SDValue();
7155 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7156 if (ShSVT.bitsLT(ShVT.getScalarType()))
7157 return SDValue();
7158 }
7159 const unsigned SVTBits = SVT.getSizeInBits();
7160
7161 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
7162
7163 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
7164 if (C->isZero())
7165 return false;
7166 // Truncate the divisor to the target scalar type in case it was promoted
7167 // during type legalization.
7168 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7170 int NumeratorFactor = 0;
7171 int ShiftMask = -1;
7172
7173 if (Divisor.isOne() || Divisor.isAllOnes()) {
7174 // If d is +1/-1, we just multiply the numerator by +1/-1.
7175 NumeratorFactor = Divisor.getSExtValue();
7176 magics.Magic = 0;
7177 magics.ShiftAmount = 0;
7178 ShiftMask = 0;
7179 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
7180 // If d > 0 and m < 0, add the numerator.
7181 NumeratorFactor = 1;
7182 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
7183 // If d < 0 and m > 0, subtract the numerator.
7184 NumeratorFactor = -1;
7185 }
7186
7187 MagicFactors.push_back(
7188 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
7189 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
7190 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
7191 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
7192 return true;
7193 };
7194
7195 SDValue N0 = N->getOperand(0);
7196 SDValue N1 = N->getOperand(1);
7197
7198 // Collect the shifts / magic values from each element.
7199 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
7200 /*AllowTruncation=*/true))
7201 return SDValue();
7202
7203 SDValue MagicFactor, Factor, Shift, ShiftMask;
7204 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7205 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7206 Factor = DAG.getBuildVector(VT, dl, Factors);
7207 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
7208 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
7209 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7210 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
7211 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
7212 "Expected matchUnaryPredicate to return one element for scalable "
7213 "vectors");
7214 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7215 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
7216 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
7217 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
7218 } else {
7219 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7220 MagicFactor = MagicFactors[0];
7221 Factor = Factors[0];
7222 Shift = Shifts[0];
7223 ShiftMask = ShiftMasks[0];
7224 }
7225
7226 // Multiply the numerator (operand 0) by the magic value.
7227 auto GetMULHS = [&](SDValue X, SDValue Y) {
7228 if (HasMULHS)
7229 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
7230 if (HasSMUL_LOHI) {
7231 SDValue LoHi =
7232 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7233 return LoHi.getValue(1);
7234 }
7235
7236 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
7237 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
7238 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7239 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7240 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7241 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7242 };
7243
7244 SDValue Q = GetMULHS(N0, MagicFactor);
7245 if (!Q)
7246 return SDValue();
7247
7248 Created.push_back(Q.getNode());
7249
7250 // (Optionally) Add/subtract the numerator using Factor.
7251 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
7252 Created.push_back(Factor.getNode());
7253 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
7254 Created.push_back(Q.getNode());
7255
7256 // Shift right algebraic by shift value.
7257 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
7258 Created.push_back(Q.getNode());
7259
7260 // Extract the sign bit, mask it and add it to the quotient.
7261 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
7262 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
7263 Created.push_back(T.getNode());
7264 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
7265 Created.push_back(T.getNode());
7266 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
7267}
7268
7269/// Given an ISD::UDIV node expressing a divide by constant,
7270/// return a DAG expression to select that will generate the same value by
7271/// multiplying by a magic number.
7272/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7274 bool IsAfterLegalization,
7275 bool IsAfterLegalTypes,
7276 SmallVectorImpl<SDNode *> &Created) const {
7277 SDLoc dl(N);
7278
7279 // If the udiv has an 'exact' bit we can use a simpler lowering.
7280 if (N->getFlags().hasExact())
7281 return BuildExactUDIV(*this, N, dl, DAG, Created);
7282
7283 EVT VT = N->getValueType(0);
7284 EVT SVT = VT.getScalarType();
7285 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7286 EVT ShSVT = ShVT.getScalarType();
7287 unsigned EltBits = VT.getScalarSizeInBits();
7288 EVT MulVT;
7289
7290 // Check to see if we can do this.
7291 // FIXME: We should be more aggressive here.
7292 EVT QueryVT = VT;
7293 if (VT.isVector()) {
7294 // If the vector type will be legalized to a vector type with the same
7295 // element type, allow the transform before type legalization if MULHU or
7296 // UMUL_LOHI are supported.
7297 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7298 if (!QueryVT.isVector() ||
7300 return SDValue();
7301 } else if (!isTypeLegal(VT)) {
7302 // Limit this to simple scalars for now.
7303 if (!VT.isSimple())
7304 return SDValue();
7305
7306 // If this type will be promoted to a large enough type with a legal
7307 // multiply operation, we can go ahead and do this transform.
7309 return SDValue();
7310
7311 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7312 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7313 !isOperationLegal(ISD::MUL, MulVT))
7314 return SDValue();
7315 }
7316
7317 bool HasMULHU =
7318 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
7319 bool HasUMUL_LOHI =
7320 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
7321
7322 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
7323 // If type twice as wide legal, widen and use a mul plus a shift.
7324 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7325 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
7326 // custom lowered. This is very expensive so avoid it at all costs for
7327 // constant divisors.
7328 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
7331 MulVT = WideVT;
7332 }
7333
7334 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
7335 return SDValue();
7336
7337 SDValue N0 = N->getOperand(0);
7338 SDValue N1 = N->getOperand(1);
7339
7340 // Try to use leading zeros of the dividend to reduce the multiplier and
7341 // avoid expensive fixups.
7342 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
7343
7344 // If we're after type legalization and SVT is not legal, use the
7345 // promoted type for creating constants to avoid creating nodes with
7346 // illegal types.
7347 if (IsAfterLegalTypes && VT.isVector()) {
7348 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7349 if (SVT.bitsLT(VT.getScalarType()))
7350 return SDValue();
7351 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7352 if (ShSVT.bitsLT(ShVT.getScalarType()))
7353 return SDValue();
7354 }
7355 const unsigned SVTBits = SVT.getSizeInBits();
7356
7357 // Allow scalars to be widened to twice their size for uncooperative divisors
7358 // if MULHU or UMUL_LOHI is supported for the wider type.
7359 const EVT WideSVT = EVT::getIntegerVT(*DAG.getContext(), 2 * EltBits);
7360 const bool HasWideMULHU =
7361 VT.isScalarInteger() &&
7362 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
7363 const bool HasWideUMUL_LOHI =
7364 VT.isScalarInteger() &&
7365 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
7366 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
7367
7368 // For even divisors with a 33-bit magic number, the widened high-multiply
7369 // path is only worthwhile over the even-divisor rewrite on targets that
7370 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
7371 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
7372 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
7373
7374 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
7375 bool UseWiden = false;
7376 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
7377
7378 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
7379 if (C->isZero())
7380 return false;
7381 // Truncate the divisor to the target scalar type in case it was promoted
7382 // during type legalization.
7383 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7384
7385 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
7386
7387 // Magic algorithm doesn't work for division by 1. We need to emit a select
7388 // at the end.
7389 if (Divisor.isOne()) {
7390 PreShift = PostShift = DAG.getUNDEF(ShSVT);
7391 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
7392 } else {
7395 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7396 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7397 /*AllowWidenOptimization=*/AllowWiden);
7398
7399 if (magics.Widen) {
7400 UseWiden = true;
7401 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7402 } else {
7403 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7404 }
7405
7406 assert(magics.PreShift < Divisor.getBitWidth() &&
7407 "We shouldn't generate an undefined shift!");
7408 assert(magics.PostShift < Divisor.getBitWidth() &&
7409 "We shouldn't generate an undefined shift!");
7410 assert((!magics.IsAdd || magics.PreShift == 0) &&
7411 "Unexpected pre-shift");
7412 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7413 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7414 NPQFactor = DAG.getConstant(
7415 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7416 : APInt::getZero(SVTBits),
7417 dl, SVT);
7418 UseNPQ |= magics.IsAdd;
7419 UsePreShift |= magics.PreShift != 0;
7420 UsePostShift |= magics.PostShift != 0;
7421 }
7422
7423 PreShifts.push_back(PreShift);
7424 MagicFactors.push_back(MagicFactor);
7425 NPQFactors.push_back(NPQFactor);
7426 PostShifts.push_back(PostShift);
7427 return true;
7428 };
7429
7430 // Collect the shifts/magic values from each element.
7431 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7432 /*AllowTruncation=*/true))
7433 return SDValue();
7434
7435 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7436 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7437 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7438 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7439 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7440 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7441 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7442 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7443 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7444 "Expected matchUnaryPredicate to return one for scalable vectors");
7445 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7446 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7447 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7448 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7449 } else {
7450 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7451 PreShift = PreShifts[0];
7452 MagicFactor = MagicFactors[0];
7453 PostShift = PostShifts[0];
7454 }
7455
7456 if (UseWiden) {
7457 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7458 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7459
7460 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7461 // WideSVT bits
7462 SDValue High;
7463 if (HasWideMULHU) {
7464 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7465 } else {
7466 assert(HasWideUMUL_LOHI);
7467 SDValue LoHi =
7468 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7469 WideN0, MagicFactor);
7470 High = LoHi.getValue(1);
7471 }
7472
7473 Created.push_back(High.getNode());
7474 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7475 }
7476
7477 SDValue Q = N0;
7478 if (UsePreShift) {
7479 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7480 Created.push_back(Q.getNode());
7481 }
7482
7483 auto GetMULHU = [&](SDValue X, SDValue Y) {
7484 if (HasMULHU)
7485 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7486 if (HasUMUL_LOHI) {
7487 SDValue LoHi =
7488 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7489 return LoHi.getValue(1);
7490 }
7491
7492 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7493 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7494 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7495 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7496 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7497 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7498 };
7499
7500 // Multiply the numerator (operand 0) by the magic value.
7501 Q = GetMULHU(Q, MagicFactor);
7502 if (!Q)
7503 return SDValue();
7504
7505 Created.push_back(Q.getNode());
7506
7507 if (UseNPQ) {
7508 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7509 Created.push_back(NPQ.getNode());
7510
7511 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7512 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7513 if (VT.isVector())
7514 NPQ = GetMULHU(NPQ, NPQFactor);
7515 else
7516 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7517
7518 Created.push_back(NPQ.getNode());
7519
7520 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7521 Created.push_back(Q.getNode());
7522 }
7523
7524 if (UsePostShift) {
7525 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7526 Created.push_back(Q.getNode());
7527 }
7528
7529 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7530
7531 SDValue One = DAG.getConstant(1, dl, VT);
7532 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7533 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7534}
7535
7536/// If all values in Values that *don't* match the predicate are same 'splat'
7537/// value, then replace all values with that splat value.
7538/// Else, if AlternativeReplacement was provided, then replace all values that
7539/// do match predicate with AlternativeReplacement value.
7540static void
7542 std::function<bool(SDValue)> Predicate,
7543 SDValue AlternativeReplacement = SDValue()) {
7544 SDValue Replacement;
7545 // Is there a value for which the Predicate does *NOT* match? What is it?
7546 auto SplatValue = llvm::find_if_not(Values, Predicate);
7547 if (SplatValue != Values.end()) {
7548 // Does Values consist only of SplatValue's and values matching Predicate?
7549 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7550 return Value == *SplatValue || Predicate(Value);
7551 })) // Then we shall replace values matching predicate with SplatValue.
7552 Replacement = *SplatValue;
7553 }
7554 if (!Replacement) {
7555 // Oops, we did not find the "baseline" splat value.
7556 if (!AlternativeReplacement)
7557 return; // Nothing to do.
7558 // Let's replace with provided value then.
7559 Replacement = AlternativeReplacement;
7560 }
7561 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7562}
7563
7564/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7565/// where the divisor and comparison target are constants,
7566/// return a DAG expression that will generate the same comparison result
7567/// using only multiplications, additions and shifts/rotations.
7568/// Ref: "Hacker's Delight" 10-17.
7569SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7570 SDValue CompTargetNode,
7572 DAGCombinerInfo &DCI,
7573 const SDLoc &DL) const {
7575 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7576 DCI, DL, Built)) {
7577 for (SDNode *N : Built)
7578 DCI.AddToWorklist(N);
7579 return Folded;
7580 }
7581
7582 return SDValue();
7583}
7584
7585SDValue
7586TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7587 SDValue CompTargetNode, ISD::CondCode Cond,
7588 DAGCombinerInfo &DCI, const SDLoc &DL,
7589 SmallVectorImpl<SDNode *> &Created) const {
7590 // fold (seteq/ne (urem N, D), C) ->
7591 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7592 // - D must be constant, with D = D0 * 2^K where D0 is odd
7593 // - P is the multiplicative inverse of D0 modulo 2^W
7594 // - Q = floor(((2^W) - 1) / D)
7595 // where W is the width of the common type of N and D.
7596 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7597 "Only applicable for (in)equality comparisons.");
7598
7599 SelectionDAG &DAG = DCI.DAG;
7600
7601 EVT VT = REMNode.getValueType();
7602 EVT SVT = VT.getScalarType();
7603 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7604 EVT ShSVT = ShVT.getScalarType();
7605
7606 // If MUL is unavailable, we cannot proceed in any case.
7607 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7608 return SDValue();
7609
7610 bool ComparingWithAllZeros = true;
7611 bool AllComparisonsWithNonZerosAreTautological = true;
7612 bool HadTautologicalLanes = false;
7613 bool AllLanesAreTautological = true;
7614 bool HadEvenDivisor = false;
7615 bool AllDivisorsArePowerOfTwo = true;
7616 bool HadTautologicalInvertedLanes = false;
7617 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7618
7619 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7620 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7621 if (CDiv->isZero())
7622 return false;
7623
7624 const APInt &D = CDiv->getAPIntValue();
7625 const APInt &Cmp = CCmp->getAPIntValue();
7626
7627 ComparingWithAllZeros &= Cmp.isZero();
7628
7629 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7630 // if C2 is not less than C1, the comparison is always false.
7631 // But we will only be able to produce the comparison that will give the
7632 // opposive tautological answer. So this lane would need to be fixed up.
7633 bool TautologicalInvertedLane = D.ule(Cmp);
7634 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7635
7636 // If all lanes are tautological (either all divisors are ones, or divisor
7637 // is not greater than the constant we are comparing with),
7638 // we will prefer to avoid the fold.
7639 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7640 HadTautologicalLanes |= TautologicalLane;
7641 AllLanesAreTautological &= TautologicalLane;
7642
7643 // If we are comparing with non-zero, we need'll need to subtract said
7644 // comparison value from the LHS. But there is no point in doing that if
7645 // every lane where we are comparing with non-zero is tautological..
7646 if (!Cmp.isZero())
7647 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7648
7649 // Decompose D into D0 * 2^K
7650 unsigned K = D.countr_zero();
7651 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7652 APInt D0 = D.lshr(K);
7653
7654 // D is even if it has trailing zeros.
7655 HadEvenDivisor |= (K != 0);
7656 // D is a power-of-two if D0 is one.
7657 // If all divisors are power-of-two, we will prefer to avoid the fold.
7658 AllDivisorsArePowerOfTwo &= D0.isOne();
7659
7660 // P = inv(D0, 2^W)
7661 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7662 unsigned W = D.getBitWidth();
7663 APInt P = D0.multiplicativeInverse();
7664 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7665
7666 // Q = floor((2^W - 1) u/ D)
7667 // R = ((2^W - 1) u% D)
7668 APInt Q, R;
7670
7671 // If we are comparing with zero, then that comparison constant is okay,
7672 // else it may need to be one less than that.
7673 if (Cmp.ugt(R))
7674 Q -= 1;
7675
7677 "We are expecting that K is always less than all-ones for ShSVT");
7678
7679 // If the lane is tautological the result can be constant-folded.
7680 if (TautologicalLane) {
7681 // Set P and K amount to a bogus values so we can try to splat them.
7682 P = 0;
7683 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7684 // And ensure that comparison constant is tautological,
7685 // it will always compare true/false.
7686 Q.setAllBits();
7687 } else {
7688 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7689 }
7690
7691 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7692 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7693 return true;
7694 };
7695
7696 SDValue N = REMNode.getOperand(0);
7697 SDValue D = REMNode.getOperand(1);
7698
7699 // Collect the values from each element.
7700 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7701 return SDValue();
7702
7703 // If all lanes are tautological, the result can be constant-folded.
7704 if (AllLanesAreTautological)
7705 return SDValue();
7706
7707 // If this is a urem by a powers-of-two, avoid the fold since it can be
7708 // best implemented as a bit test.
7709 if (AllDivisorsArePowerOfTwo)
7710 return SDValue();
7711
7712 SDValue PVal, KVal, QVal;
7713 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7714 if (HadTautologicalLanes) {
7715 // Try to turn PAmts into a splat, since we don't care about the values
7716 // that are currently '0'. If we can't, just keep '0'`s.
7718 // Try to turn KAmts into a splat, since we don't care about the values
7719 // that are currently '-1'. If we can't, change them to '0'`s.
7721 DAG.getConstant(0, DL, ShSVT));
7722 }
7723
7724 PVal = DAG.getBuildVector(VT, DL, PAmts);
7725 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7726 QVal = DAG.getBuildVector(VT, DL, QAmts);
7727 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7728 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7729 "Expected matchBinaryPredicate to return one element for "
7730 "SPLAT_VECTORs");
7731 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7732 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7733 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7734 } else {
7735 PVal = PAmts[0];
7736 KVal = KAmts[0];
7737 QVal = QAmts[0];
7738 }
7739
7740 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7741 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7742 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7743 assert(CompTargetNode.getValueType() == N.getValueType() &&
7744 "Expecting that the types on LHS and RHS of comparisons match.");
7745 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7746 }
7747
7748 // (mul N, P)
7749 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7750 Created.push_back(Op0.getNode());
7751
7752 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7753 // divisors as a performance improvement, since rotating by 0 is a no-op.
7754 if (HadEvenDivisor) {
7755 // We need ROTR to do this.
7756 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7757 return SDValue();
7758 // UREM: (rotr (mul N, P), K)
7759 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7760 Created.push_back(Op0.getNode());
7761 }
7762
7763 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7764 SDValue NewCC =
7765 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7767 if (!HadTautologicalInvertedLanes)
7768 return NewCC;
7769
7770 // If any lanes previously compared always-false, the NewCC will give
7771 // always-true result for them, so we need to fixup those lanes.
7772 // Or the other way around for inequality predicate.
7773 assert(VT.isVector() && "Can/should only get here for vectors.");
7774 Created.push_back(NewCC.getNode());
7775
7776 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7777 // if C2 is not less than C1, the comparison is always false.
7778 // But we have produced the comparison that will give the
7779 // opposive tautological answer. So these lanes would need to be fixed up.
7780 SDValue TautologicalInvertedChannels =
7781 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7782 Created.push_back(TautologicalInvertedChannels.getNode());
7783
7784 // NOTE: we avoid letting illegal types through even if we're before legalize
7785 // ops – legalization has a hard time producing good code for this.
7786 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7787 // If we have a vector select, let's replace the comparison results in the
7788 // affected lanes with the correct tautological result.
7789 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7790 DL, SETCCVT, SETCCVT);
7791 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7792 Replacement, NewCC);
7793 }
7794
7795 // Else, we can just invert the comparison result in the appropriate lanes.
7796 //
7797 // NOTE: see the note above VSELECT above.
7798 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7799 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7800 TautologicalInvertedChannels);
7801
7802 return SDValue(); // Don't know how to lower.
7803}
7804
7805/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7806/// where the divisor is constant and the comparison target is zero,
7807/// return a DAG expression that will generate the same comparison result
7808/// using only multiplications, additions and shifts/rotations.
7809/// Ref: "Hacker's Delight" 10-17.
7810SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7811 SDValue CompTargetNode,
7813 DAGCombinerInfo &DCI,
7814 const SDLoc &DL) const {
7816 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7817 DCI, DL, Built)) {
7818 assert(Built.size() <= 7 && "Max size prediction failed.");
7819 for (SDNode *N : Built)
7820 DCI.AddToWorklist(N);
7821 return Folded;
7822 }
7823
7824 return SDValue();
7825}
7826
7827SDValue
7828TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7829 SDValue CompTargetNode, ISD::CondCode Cond,
7830 DAGCombinerInfo &DCI, const SDLoc &DL,
7831 SmallVectorImpl<SDNode *> &Created) const {
7832 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7833 // Fold:
7834 // (seteq/ne (srem N, D), 0)
7835 // To:
7836 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7837 //
7838 // - D must be constant, with D = D0 * 2^K where D0 is odd
7839 // - P is the multiplicative inverse of D0 modulo 2^W
7840 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7841 // - Q = floor((2 * A) / (2^K))
7842 // where W is the width of the common type of N and D.
7843 //
7844 // When D is a power of two (and thus D0 is 1), the normal
7845 // formula for A and Q don't apply, because the derivation
7846 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7847 // does not apply. This specifically fails when N = INT_MIN.
7848 //
7849 // Instead, for power-of-two D, we use:
7850 // - A = 0
7851 // | -> No offset needed. We're effectively treating it the same as urem.
7852 // - Q = 2^(W-K) - 1
7853 // |-> Test that the top K bits are zero after rotation
7854 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7855 "Only applicable for (in)equality comparisons.");
7856
7857 SelectionDAG &DAG = DCI.DAG;
7858
7859 EVT VT = REMNode.getValueType();
7860 EVT SVT = VT.getScalarType();
7861 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7862 EVT ShSVT = ShVT.getScalarType();
7863
7864 // If we are after ops legalization, and MUL is unavailable, we can not
7865 // proceed.
7866 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7867 return SDValue();
7868
7869 // TODO: Could support comparing with non-zero too.
7870 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7871 if (!CompTarget || !CompTarget->isZero())
7872 return SDValue();
7873
7874 bool HadOneDivisor = false;
7875 bool AllDivisorsAreOnes = true;
7876 bool HadEvenDivisor = false;
7877 bool AllDivisorsArePowerOfTwo = true;
7878 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7879
7880 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7881 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7882 if (C->isZero())
7883 return false;
7884
7885 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7886
7887 // WARNING: this fold is only valid for positive divisors!
7888 // `rem %X, -C` is equivalent to `rem %X, C`
7889 APInt D = C->getAPIntValue().abs();
7890
7891 // If all divisors are ones, we will prefer to avoid the fold.
7892 HadOneDivisor |= D.isOne();
7893 AllDivisorsAreOnes &= D.isOne();
7894
7895 // Decompose D into D0 * 2^K
7896 unsigned K = D.countr_zero();
7897 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7898 APInt D0 = D.lshr(K);
7899
7900 // D is even if it has trailing zeros.
7901 HadEvenDivisor |= (K != 0);
7902
7903 // D is a power-of-two if D0 is one. This includes INT_MIN.
7904 // If all divisors are power-of-two, we will prefer to avoid the fold.
7905 AllDivisorsArePowerOfTwo &= D0.isOne();
7906
7907 // P = inv(D0, 2^W)
7908 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7909 unsigned W = D.getBitWidth();
7910 APInt P = D0.multiplicativeInverse();
7911 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7912
7913 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7914 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7915 A.clearLowBits(K);
7916
7917 // Q = floor((2 * A) / (2^K))
7918 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7919
7921 "We are expecting that A is always less than all-ones for SVT");
7923 "We are expecting that K is always less than all-ones for ShSVT");
7924
7925 // If D was a power of two, apply the alternate constant derivation.
7926 if (D0.isOne()) {
7927 // A = 0
7928 A = APInt(W, 0);
7929 // - Q = 2^(W-K) - 1
7930 Q = APInt::getLowBitsSet(W, W - K);
7931 }
7932
7933 // If the divisor is 1 the result can be constant-folded.
7934 if (D.isOne()) {
7935 // Set P, A and K to a bogus values so we can try to splat them.
7936 P = 0;
7937 A.setAllBits();
7938 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7939
7940 // x ?% 1 == 0 <--> true <--> x u<= -1
7941 Q.setAllBits();
7942 } else {
7943 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7944 }
7945
7946 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7947 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7948 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7949 return true;
7950 };
7951
7952 SDValue N = REMNode.getOperand(0);
7953 SDValue D = REMNode.getOperand(1);
7954
7955 // Collect the values from each element.
7956 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7957 return SDValue();
7958
7959 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7960 if (AllDivisorsAreOnes)
7961 return SDValue();
7962
7963 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7964 // since it can be best implemented as a bit test.
7965 if (AllDivisorsArePowerOfTwo)
7966 return SDValue();
7967
7968 SDValue PVal, AVal, KVal, QVal;
7969 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7970 if (HadOneDivisor) {
7971 // Try to turn PAmts into a splat, since we don't care about the values
7972 // that are currently '0'. If we can't, just keep '0'`s.
7974 // Try to turn AAmts into a splat, since we don't care about the
7975 // values that are currently '-1'. If we can't, change them to '0'`s.
7977 DAG.getConstant(0, DL, SVT));
7978 // Try to turn KAmts into a splat, since we don't care about the values
7979 // that are currently '-1'. If we can't, change them to '0'`s.
7981 DAG.getConstant(0, DL, ShSVT));
7982 }
7983
7984 PVal = DAG.getBuildVector(VT, DL, PAmts);
7985 AVal = DAG.getBuildVector(VT, DL, AAmts);
7986 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7987 QVal = DAG.getBuildVector(VT, DL, QAmts);
7988 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7989 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7990 QAmts.size() == 1 &&
7991 "Expected matchUnaryPredicate to return one element for scalable "
7992 "vectors");
7993 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7994 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7995 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7996 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7997 } else {
7998 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7999 PVal = PAmts[0];
8000 AVal = AAmts[0];
8001 KVal = KAmts[0];
8002 QVal = QAmts[0];
8003 }
8004
8005 // (mul N, P)
8006 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
8007 Created.push_back(Op0.getNode());
8008
8009 // We need ADD to do this.
8010 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
8011 return SDValue();
8012
8013 // (add (mul N, P), A)
8014 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
8015 Created.push_back(Op0.getNode());
8016
8017 // Rotate right only if any divisor was even. We avoid rotates for all-odd
8018 // divisors as a performance improvement, since rotating by 0 is a no-op.
8019 if (HadEvenDivisor) {
8020 // We need ROTR to do this.
8021 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
8022 return SDValue();
8023 // SREM: (rotr (add (mul N, P), A), K)
8024 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
8025 Created.push_back(Op0.getNode());
8026 }
8027
8028 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
8029 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
8031}
8032
8034 const DenormalMode &Mode,
8035 SDNodeFlags Flags) const {
8036 SDLoc DL(Op);
8037 EVT VT = Op.getValueType();
8038 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8039 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
8040
8041 // This is specifically a check for the handling of denormal inputs, not the
8042 // result.
8043 if (Mode.Input == DenormalMode::PreserveSign ||
8044 Mode.Input == DenormalMode::PositiveZero) {
8045 // Test = X == 0.0
8046 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
8047 /*Signaling=*/false, Flags);
8048 }
8049
8050 // Testing it with denormal inputs to avoid wrong estimate.
8051 //
8052 // Test = fabs(X) < SmallestNormal
8053 const fltSemantics &FltSem = VT.getFltSemantics();
8054 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
8055 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
8056 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
8057 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
8058 /*Signaling=*/false, Flags);
8059}
8060
8062 bool LegalOps, bool OptForSize,
8064 unsigned Depth) const {
8065 // fneg is removable even if it has multiple uses.
8066 if (Op.getOpcode() == ISD::FNEG) {
8068 return Op.getOperand(0);
8069 }
8070
8071 // Don't recurse exponentially.
8073 return SDValue();
8074
8075 // Pre-increment recursion depth for use in recursive calls.
8076 ++Depth;
8077 const SDNodeFlags Flags = Op->getFlags();
8078 EVT VT = Op.getValueType();
8079 unsigned Opcode = Op.getOpcode();
8080
8081 // Don't allow anything with multiple uses unless we know it is free.
8082 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
8083 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
8084 isFPExtFree(VT, Op.getOperand(0).getValueType());
8085 if (!IsFreeExtend)
8086 return SDValue();
8087 }
8088
8089 auto RemoveDeadNode = [&](SDValue N) {
8090 if (N && N.getNode()->use_empty())
8091 DAG.RemoveDeadNode(N.getNode());
8092 };
8093
8094 SDLoc DL(Op);
8095
8096 // Because getNegatedExpression can delete nodes we need a handle to keep
8097 // temporary nodes alive in case the recursion manages to create an identical
8098 // node.
8099 std::list<HandleSDNode> Handles;
8100
8101 switch (Opcode) {
8102 case ISD::ConstantFP: {
8103 // Don't invert constant FP values after legalization unless the target says
8104 // the negated constant is legal.
8105 bool IsOpLegal =
8107 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
8108 OptForSize);
8109
8110 if (LegalOps && !IsOpLegal)
8111 break;
8112
8113 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
8114 V.changeSign();
8115 SDValue CFP = DAG.getConstantFP(V, DL, VT);
8116
8117 // If we already have the use of the negated floating constant, it is free
8118 // to negate it even it has multiple uses.
8119 if (!Op.hasOneUse() && CFP.use_empty())
8120 break;
8122 return CFP;
8123 }
8124 case ISD::SPLAT_VECTOR: {
8125 // fold splat_vector(fneg(X)) -> splat_vector(-X)
8126 SDValue X = Op.getOperand(0);
8128 break;
8129
8130 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
8131 if (!NegX)
8132 break;
8134 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
8135 }
8136 case ISD::BUILD_VECTOR: {
8137 // Only permit BUILD_VECTOR of constants.
8138 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
8139 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
8140 }))
8141 break;
8142
8143 bool IsOpLegal =
8146 llvm::all_of(Op->op_values(), [&](SDValue N) {
8147 return N.isUndef() ||
8148 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
8149 OptForSize);
8150 });
8151
8152 if (LegalOps && !IsOpLegal)
8153 break;
8154
8156 for (SDValue C : Op->op_values()) {
8157 if (C.isUndef()) {
8158 Ops.push_back(C);
8159 continue;
8160 }
8161 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
8162 V.changeSign();
8163 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
8164 }
8166 return DAG.getBuildVector(VT, DL, Ops);
8167 }
8168 case ISD::FADD: {
8169 if (!Flags.hasNoSignedZeros())
8170 break;
8171
8172 // After operation legalization, it might not be legal to create new FSUBs.
8173 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
8174 break;
8175 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8176
8177 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
8179 SDValue NegX =
8180 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8181 // Prevent this node from being deleted by the next call.
8182 if (NegX)
8183 Handles.emplace_back(NegX);
8184
8185 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
8187 SDValue NegY =
8188 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8189
8190 // We're done with the handles.
8191 Handles.clear();
8192
8193 // Negate the X if its cost is less or equal than Y.
8194 if (NegX && (CostX <= CostY)) {
8195 Cost = CostX;
8196 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
8197 if (NegY != N)
8198 RemoveDeadNode(NegY);
8199 return N;
8200 }
8201
8202 // Negate the Y if it is not expensive.
8203 if (NegY) {
8204 Cost = CostY;
8205 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
8206 if (NegX != N)
8207 RemoveDeadNode(NegX);
8208 return N;
8209 }
8210 break;
8211 }
8212 case ISD::FSUB: {
8213 // We can't turn -(A-B) into B-A when we honor signed zeros.
8214 if (!Flags.hasNoSignedZeros())
8215 break;
8216
8217 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8218 // fold (fneg (fsub 0, Y)) -> Y
8219 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
8220 if (C->isZero()) {
8222 return Y;
8223 }
8224
8225 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
8227 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
8228 }
8229 case ISD::FMUL:
8230 case ISD::FDIV: {
8231 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8232
8233 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
8235 SDValue NegX =
8236 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8237 // Prevent this node from being deleted by the next call.
8238 if (NegX)
8239 Handles.emplace_back(NegX);
8240
8241 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
8243 SDValue NegY =
8244 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8245
8246 // We're done with the handles.
8247 Handles.clear();
8248
8249 // Negate the X if its cost is less or equal than Y.
8250 if (NegX && (CostX <= CostY)) {
8251 Cost = CostX;
8252 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
8253 if (NegY != N)
8254 RemoveDeadNode(NegY);
8255 return N;
8256 }
8257
8258 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
8259 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
8260 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
8261 break;
8262
8263 // Negate the Y if it is not expensive.
8264 if (NegY) {
8265 Cost = CostY;
8266 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
8267 if (NegX != N)
8268 RemoveDeadNode(NegX);
8269 return N;
8270 }
8271 break;
8272 }
8273 case ISD::FMA:
8274 case ISD::FMULADD:
8275 case ISD::FMAD: {
8276 if (!Flags.hasNoSignedZeros())
8277 break;
8278
8279 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
8281 SDValue NegZ =
8282 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
8283 // Give up if fail to negate the Z.
8284 if (!NegZ)
8285 break;
8286
8287 // Prevent this node from being deleted by the next two calls.
8288 Handles.emplace_back(NegZ);
8289
8290 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
8292 SDValue NegX =
8293 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8294 // Prevent this node from being deleted by the next call.
8295 if (NegX)
8296 Handles.emplace_back(NegX);
8297
8298 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
8300 SDValue NegY =
8301 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8302
8303 // We're done with the handles.
8304 Handles.clear();
8305
8306 // Negate the X if its cost is less or equal than Y.
8307 if (NegX && (CostX <= CostY)) {
8308 Cost = std::min(CostX, CostZ);
8309 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
8310 if (NegY != N)
8311 RemoveDeadNode(NegY);
8312 return N;
8313 }
8314
8315 // Negate the Y if it is not expensive.
8316 if (NegY) {
8317 Cost = std::min(CostY, CostZ);
8318 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
8319 if (NegX != N)
8320 RemoveDeadNode(NegX);
8321 return N;
8322 }
8323 break;
8324 }
8325
8326 case ISD::FP_EXTEND:
8327 case ISD::FSIN:
8328 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8329 OptForSize, Cost, Depth))
8330 return DAG.getNode(Opcode, DL, VT, NegV);
8331 break;
8332 case ISD::FP_ROUND:
8333 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8334 OptForSize, Cost, Depth))
8335 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
8336 break;
8337 case ISD::SELECT:
8338 case ISD::VSELECT: {
8339 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
8340 // iff at least one cost is cheaper and the other is neutral/cheaper
8341 SDValue LHS = Op.getOperand(1);
8343 SDValue NegLHS =
8344 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
8345 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
8346 RemoveDeadNode(NegLHS);
8347 break;
8348 }
8349
8350 // Prevent this node from being deleted by the next call.
8351 Handles.emplace_back(NegLHS);
8352
8353 SDValue RHS = Op.getOperand(2);
8355 SDValue NegRHS =
8356 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
8357
8358 // We're done with the handles.
8359 Handles.clear();
8360
8361 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
8362 (CostLHS != NegatibleCost::Cheaper &&
8363 CostRHS != NegatibleCost::Cheaper)) {
8364 RemoveDeadNode(NegLHS);
8365 RemoveDeadNode(NegRHS);
8366 break;
8367 }
8368
8369 Cost = std::min(CostLHS, CostRHS);
8370 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
8371 }
8372 }
8373
8374 return SDValue();
8375}
8376
8377//===----------------------------------------------------------------------===//
8378// Legalization Utilities
8379//===----------------------------------------------------------------------===//
8380
8381bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
8382 SDValue LHS, SDValue RHS,
8384 EVT HiLoVT, SelectionDAG &DAG,
8385 MulExpansionKind Kind, SDValue LL,
8386 SDValue LH, SDValue RL, SDValue RH) const {
8387 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
8388 Opcode == ISD::SMUL_LOHI);
8389
8390 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
8392 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8394 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8396 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8398
8399 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8400 return false;
8401
8402 unsigned OuterBitSize = VT.getScalarSizeInBits();
8403 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8404
8405 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8406 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8407 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8408
8409 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8410 bool Signed) -> bool {
8411 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8412 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8413 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8414 Hi = Lo.getValue(1);
8415 return true;
8416 }
8417 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8418 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8419 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8420 return true;
8421 }
8422 return false;
8423 };
8424
8425 SDValue Lo, Hi;
8426
8427 if (!LL.getNode() && !RL.getNode() &&
8429 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8430 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8431 }
8432
8433 if (!LL.getNode())
8434 return false;
8435
8436 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8437 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8438 DAG.MaskedValueIsZero(RHS, HighMask)) {
8439 // The inputs are both zero-extended.
8440 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8441 Result.push_back(Lo);
8442 Result.push_back(Hi);
8443 if (Opcode != ISD::MUL) {
8444 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8445 Result.push_back(Zero);
8446 Result.push_back(Zero);
8447 }
8448 return true;
8449 }
8450 }
8451
8452 if (!VT.isVector() && Opcode == ISD::MUL &&
8453 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8454 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8455 // The input values are both sign-extended.
8456 // TODO non-MUL case?
8457 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8458 Result.push_back(Lo);
8459 Result.push_back(Hi);
8460 return true;
8461 }
8462 }
8463
8464 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8465 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8466
8467 if (!LH.getNode() && !RH.getNode() &&
8470 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8471 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8472 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8473 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8474 }
8475
8476 if (!LH.getNode())
8477 return false;
8478
8479 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8480 return false;
8481
8482 Result.push_back(Lo);
8483
8484 if (Opcode == ISD::MUL) {
8485 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8486 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8487 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8488 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8489 Result.push_back(Hi);
8490 return true;
8491 }
8492
8493 // Compute the full width result.
8494 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8495 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8496 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8497 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8498 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8499 };
8500
8501 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8502 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8503 return false;
8504
8505 // This is effectively the add part of a multiply-add of half-sized operands,
8506 // so it cannot overflow.
8507 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8508
8509 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8510 return false;
8511
8512 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8513 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8514
8515 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8517 if (UseGlue)
8518 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8519 Merge(Lo, Hi));
8520 else
8521 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8522 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8523
8524 SDValue Carry = Next.getValue(1);
8525 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8526 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8527
8528 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8529 return false;
8530
8531 if (UseGlue)
8532 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8533 Carry);
8534 else
8535 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8536 Zero, Carry);
8537
8538 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8539
8540 if (Opcode == ISD::SMUL_LOHI) {
8541 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8542 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8543 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8544
8545 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8546 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8547 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8548 }
8549
8550 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8551 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8552 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8553 return true;
8554}
8555
8557 SelectionDAG &DAG, MulExpansionKind Kind,
8558 SDValue LL, SDValue LH, SDValue RL,
8559 SDValue RH) const {
8561 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8562 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8563 DAG, Kind, LL, LH, RL, RH);
8564 if (Ok) {
8565 assert(Result.size() == 2);
8566 Lo = Result[0];
8567 Hi = Result[1];
8568 }
8569 return Ok;
8570}
8571
8572// Optimize unsigned division or remainder by constants for types twice as large
8573// as a legal VT.
8574//
8575// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8576// can be computed
8577// as:
8578// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8579// Remainder = Sum % Constant;
8580//
8581// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8582// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8583// High:Low into 3 chunks of W bits and compute remainder as
8584// Sum = Chunk0 + Chunk1 + Chunk2;
8585// Remainder = Sum % Constant;
8586//
8587// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8588//
8589// For division, we can compute the remainder using the algorithm described
8590// above, subtract it from the dividend to get an exact multiple of Constant.
8591// Then multiply that exact multiply by the multiplicative inverse modulo
8592// (1 << (BitWidth / 2)) to get the quotient.
8593
8594// If Constant is even, we can shift right the dividend and the divisor by the
8595// number of trailing zeros in Constant before applying the remainder algorithm.
8596// If we're after the quotient, we can subtract this value from the shifted
8597// dividend and multiply by the multiplicative inverse of the shifted divisor.
8598// If we want the remainder, we shift the value left by the number of trailing
8599// zeros and add the bits that were shifted out of the dividend.
8600bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8601 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8602 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8603 unsigned Opcode = N->getOpcode();
8604 EVT VT = N->getValueType(0);
8605
8606 unsigned BitWidth = Divisor.getBitWidth();
8607 unsigned HBitWidth = BitWidth / 2;
8609 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8610
8611 // If the divisor is even, shift it until it becomes odd.
8612 unsigned TrailingZeros = 0;
8613 if (!Divisor[0]) {
8614 TrailingZeros = Divisor.countr_zero();
8615 Divisor.lshrInPlace(TrailingZeros);
8616 }
8617
8618 // After removing trailing zeros, the divisor needs to be less than
8619 // (1 << HBitWidth).
8620 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8621 if (Divisor.uge(HalfMaxPlus1))
8622 return false;
8623
8624 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8625 // (1 << W) % Divisor == -1.
8626 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8627 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8628 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8629 if (I == HBitWidth - 1)
8630 continue;
8631
8632 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8633
8634 if (Mod.isOne()) {
8635 BestChunkWidth = I;
8636 break;
8637 }
8638
8639 // We have an alternate strategy for Remainder == Divisor - 1.
8640 // FIXME: Support HBitWidth.
8641 if (I != HBitWidth && Mod == Divisor - 1)
8642 AltChunkWidth = I;
8643 }
8644
8645 bool Alternate = false;
8646 if (!BestChunkWidth) {
8647 if (!AltChunkWidth)
8648 return false;
8649 Alternate = true;
8650 BestChunkWidth = AltChunkWidth;
8651 }
8652
8653 SDLoc dl(N);
8654
8655 assert(!LL == !LH && "Expected both input halves or no input halves!");
8656 if (!LL)
8657 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8658
8659 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8660
8661 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8662 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8663 if (HasFSHR)
8664 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8665 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8666 return DAG.getNode(
8667 ISD::OR, dl, HiLoVT,
8668 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8669 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8670 DAG.getNode(
8671 ISD::SHL, dl, HiLoVT, Hi,
8672 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8673 };
8674
8675 // Helper to perform a right shift on a 128-bit value split into two halves.
8676 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8677 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8678 if (ShiftAmt == 0)
8679 return;
8680 if (ShiftAmt < HBitWidth) {
8681 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8682 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8683 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8684 } else if (ShiftAmt == HBitWidth) {
8685 Lo = Hi;
8686 Hi = DAG.getConstant(0, dl, HiLoVT);
8687 } else {
8688 Lo = DAG.getNode(
8689 ISD::SRL, dl, HiLoVT, Hi,
8690 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8691 Hi = DAG.getConstant(0, dl, HiLoVT);
8692 }
8693 };
8694
8695 // Shift the input by the number of TrailingZeros in the divisor. The
8696 // shifted out bits will be added to the remainder later.
8697 SDValue PartialRemL, PartialRemH;
8698 if (TrailingZeros && Opcode != ISD::UDIV) {
8699 // Save the shifted off bits if we need the remainder.
8700 if (TrailingZeros < HBitWidth) {
8701 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8702 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8703 DAG.getConstant(Mask, dl, HiLoVT));
8704 } else if (TrailingZeros == HBitWidth) {
8705 // All of LL is part of the remainder.
8706 PartialRemL = LL;
8707 } else {
8708 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8709 PartialRemL = LL;
8710 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8711 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8712 DAG.getConstant(Mask, dl, HiLoVT));
8713 }
8714 }
8715
8716 SDValue Sum;
8717 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8718 // out, add that to the final sum.
8719 if (BestChunkWidth == HBitWidth) {
8720 assert(!Alternate);
8721 // Shift LH:LL right if there were trailing zeros in the divisor.
8722 ShiftRight(LL, LH, TrailingZeros);
8723
8724 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8725 EVT SetCCType =
8726 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8728 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8729 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8730 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8731 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8732 } else {
8733 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8734 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8735 // If the boolean for the target is 0 or 1, we can add the setcc result
8736 // directly.
8737 if (getBooleanContents(HiLoVT) ==
8739 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8740 else
8741 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8742 DAG.getConstant(0, dl, HiLoVT));
8743 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8744 }
8745 } else {
8746 // Otherwise split into multple chunks and add them together. We chose
8747 // BestChunkWidth so that the sum will not overflow.
8748 SDValue Mask = DAG.getConstant(
8749 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8750
8751 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8752 // If there were trailing zeros in the divisor, increase the shift amount.
8753 unsigned Shift = I + TrailingZeros;
8754 SDValue Chunk;
8755 if (Shift == 0)
8756 Chunk = LL;
8757 else if (Shift >= HBitWidth)
8758 Chunk = DAG.getNode(
8759 ISD::SRL, dl, HiLoVT, LH,
8760 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8761 else
8762 Chunk = GetFSHR(LL, LH, Shift);
8763 // If we're on the last chunk, we don't need an AND.
8764 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8765 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8766 if (!Sum) {
8767 Sum = Chunk;
8768 } else {
8769 // For Alternate, we need to subtract odd chunks.
8770 unsigned ChunkNum = I / BestChunkWidth;
8771 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8772 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8773 }
8774 }
8775
8776 // For Alternate, the sum may be negative, but we need a positive sum. We
8777 // can increase it by a multiple of the divisor to make it positive. For 3
8778 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8779 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8780 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8781 // positive.
8782 if (Alternate) {
8783 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8784 assert(NumChunks <= 4);
8785
8786 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8787 Adjust.setBit(0);
8788 // If there are 4 chunks, we need to adjust twice.
8789 if (NumChunks == 4)
8790 Adjust <<= 1;
8791 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8792 DAG.getConstant(Adjust, dl, HiLoVT));
8793 }
8794 }
8795
8796 // Perform a HiLoVT urem on the Sum using truncated divisor.
8797 SDValue RemL =
8798 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8799 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8800 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8801
8802 if (Opcode != ISD::UREM) {
8803 // If we didn't shift LH/LR earlier, do it now.
8804 if (BestChunkWidth != HBitWidth)
8805 ShiftRight(LL, LH, TrailingZeros);
8806
8807 // Subtract the remainder from the shifted dividend.
8808 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8809 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8810
8811 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8812
8813 // Multiply by the multiplicative inverse of the divisor modulo
8814 // (1 << BitWidth).
8815 APInt MulFactor = Divisor.multiplicativeInverse();
8816
8817 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8818 DAG.getConstant(MulFactor, dl, VT));
8819
8820 // Split the quotient into low and high parts.
8821 SDValue QuotL, QuotH;
8822 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8823 Result.push_back(QuotL);
8824 Result.push_back(QuotH);
8825 }
8826
8827 if (Opcode != ISD::UDIV) {
8828 // If we shifted the input, shift the remainder left and add the bits we
8829 // shifted off the input.
8830 if (TrailingZeros) {
8831 if (TrailingZeros < HBitWidth) {
8832 // Shift RemH:RemL left by TrailingZeros.
8833 // RemH gets the high bits shifted out of RemL.
8834 RemH = DAG.getNode(
8835 ISD::SRL, dl, HiLoVT, RemL,
8836 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8837 RemL =
8838 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8839 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8840 // OR in the partial remainder.
8841 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8843 } else if (TrailingZeros == HBitWidth) {
8844 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8845 // PartialRemL.
8846 RemH = RemL;
8847 RemL = PartialRemL;
8848 } else {
8849 // Shift left by more than HBitWidth.
8850 RemH = DAG.getNode(
8851 ISD::SHL, dl, HiLoVT, RemL,
8852 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8853 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8855 RemL = PartialRemL;
8856 }
8857 }
8858 Result.push_back(RemL);
8859 Result.push_back(RemH);
8860 }
8861
8862 return true;
8863}
8864
8865bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8866 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8867 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8868
8869 SDValue N0 = N->getOperand(0);
8870 EVT VT = N0->getValueType(0);
8871 SDLoc DL{N};
8872
8873 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8874
8875 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8876 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8877 const APInt &Const,
8878 SmallVectorImpl<SDValue> &Result) {
8879 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8880 SDValue RHS = DAG.getConstant(Const, DL, VT);
8881 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8882 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8884 LL, LH, RL, RH);
8885 };
8886
8887 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8888 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8889 SDValue RH) {
8890 SDValue AddSubNode =
8892 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8893 SDValue OutL = AddSubNode.getValue(0);
8894 SDValue Overflow = AddSubNode.getValue(1);
8895 SDValue AddSubWithOverflow =
8897 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8898 SDValue OutH = AddSubWithOverflow.getValue(0);
8899 return std::make_pair(OutL, OutH);
8900 };
8901
8902 // This helper creates a SRL of the pair (LL, LH) by Shift.
8903 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8904 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8905 if (Shift < HBitWidth) {
8906 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8907 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8908 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8909 return std::make_pair(ResL, ResH);
8910 }
8911 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8912 if (Shift == HBitWidth)
8913 return std::make_pair(LH, Zero);
8914 assert(Shift - HBitWidth < HBitWidth &&
8915 "We shouldn't generate an undefined shift");
8916 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8917 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8918 };
8919
8920 // Knowledge of leading zeros may help to reduce the multiplier.
8921 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8922
8923 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8924 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8925
8926 assert(!LL == !LH && "Expected both input halves or no input halves!");
8927 if (!LL)
8928 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8929 SDValue QL = LL;
8930 SDValue QH = LH;
8931 if (Magics.PreShift != 0)
8932 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8933
8934 SmallVector<SDValue, 4> UMulResult;
8935 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8936 return false;
8937
8938 QL = UMulResult[2];
8939 QH = UMulResult[3];
8940
8941 if (Magics.IsAdd) {
8942 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8943 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8944 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8945 }
8946
8947 if (Magics.PostShift != 0)
8948 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8949
8950 unsigned Opcode = N->getOpcode();
8951 if (Opcode != ISD::UREM) {
8952 Result.push_back(QL);
8953 Result.push_back(QH);
8954 }
8955
8956 if (Opcode != ISD::UDIV) {
8957 SmallVector<SDValue, 2> MulResult;
8958 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8959 return false;
8960
8961 assert(MulResult.size() == 2);
8962
8963 auto [RemL, RemH] =
8964 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8965
8966 Result.push_back(RemL);
8967 Result.push_back(RemH);
8968 }
8969
8970 return true;
8971}
8972
8975 EVT HiLoVT, SelectionDAG &DAG,
8976 SDValue LL, SDValue LH) const {
8977 unsigned Opcode = N->getOpcode();
8978
8979 // TODO: Support signed division/remainder.
8980 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8981 return false;
8982 assert(
8983 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8984 "Unexpected opcode");
8985
8986 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8987 if (!CN)
8988 return false;
8989
8990 APInt Divisor = CN->getAPIntValue();
8991
8992 // The generated half-width UREM is normally optimized using high multiply.
8993 // If the wide UREM libcall is unavailable, a legal or custom half-width
8994 // UDIVREM can lower it instead.
8995 bool CanDecomposeUREMWithoutMulHi =
8996 Opcode == ISD::UREM &&
8997 DAG.getLibcalls().getLibcallImpl(RTLIB::getUREM(N->getValueType(0))) ==
8998 RTLIB::Unsupported &&
9000 if (!CanDecomposeUREMWithoutMulHi &&
9003 return false;
9004
9005 // Prefer the smaller libcall when one is available.
9006 if (DAG.shouldOptForSize() && !CanDecomposeUREMWithoutMulHi)
9007 return false;
9008
9009 // Early out for 0 or 1 divisors.
9010 if (Divisor.ule(1))
9011 return false;
9012
9013 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
9014 DAG, LL, LH))
9015 return true;
9016
9017 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
9018 LH))
9019 return true;
9020
9021 return false;
9022}
9023
9024// Check that (every element of) Z is undef or not an exact multiple of BW.
9025static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
9027 Z,
9028 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
9029 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
9030}
9031
9033 SelectionDAG &DAG) const {
9034 EVT VT = Node->getValueType(0);
9035
9036 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
9040 return SDValue();
9041
9042 SDValue X = Node->getOperand(0);
9043 SDValue Y = Node->getOperand(1);
9044 SDValue Z = Node->getOperand(2);
9045
9046 unsigned BW = VT.getScalarSizeInBits();
9047 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
9048 SDLoc DL(SDValue(Node, 0));
9049
9050 EVT ShVT = Z.getValueType();
9051
9052 // If a funnel shift in the other direction is more supported, use it.
9053 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
9054 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
9055 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
9056 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
9057 // fshl X, Y, Z -> fshr X, Y, -Z
9058 // fshr X, Y, Z -> fshl X, Y, -Z
9059 Z = DAG.getNegative(Z, DL, ShVT);
9060 } else {
9061 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
9062 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
9063 SDValue One = DAG.getConstant(1, DL, ShVT);
9064 if (IsFSHL) {
9065 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
9066 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
9067 } else {
9068 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
9069 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
9070 }
9071 Z = DAG.getNOT(DL, Z, ShVT);
9072 }
9073 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
9074 }
9075
9076 SDValue ShX, ShY;
9077 SDValue ShAmt, InvShAmt;
9078 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
9079 // fshl: X << C | Y >> (BW - C)
9080 // fshr: X << (BW - C) | Y >> C
9081 // where C = Z % BW is not zero
9082 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
9083 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
9084 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
9085 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
9086 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
9087 } else {
9088 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
9089 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
9090 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
9091 if (isPowerOf2_32(BW)) {
9092 // Z % BW -> Z & (BW - 1)
9093 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
9094 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
9095 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
9096 } else {
9097 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
9098 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
9099 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
9100 }
9101
9102 SDValue One = DAG.getConstant(1, DL, ShVT);
9103 if (IsFSHL) {
9104 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
9105 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
9106 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
9107 } else {
9108 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
9109 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
9110 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
9111 }
9112 }
9113 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
9114}
9115
9116// TODO: Merge with expandFunnelShift.
9118 SelectionDAG &DAG) const {
9119 EVT VT = Node->getValueType(0);
9120 unsigned EltSizeInBits = VT.getScalarSizeInBits();
9121 bool IsLeft = Node->getOpcode() == ISD::ROTL;
9122 SDValue Op0 = Node->getOperand(0);
9123 SDValue Op1 = Node->getOperand(1);
9124 SDLoc DL(SDValue(Node, 0));
9125
9126 EVT ShVT = Op1.getValueType();
9127 SDValue Zero = DAG.getConstant(0, DL, ShVT);
9128
9129 // If a rotate in the other direction is more supported, use it.
9130 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
9131 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
9132 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
9133 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
9134 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
9135 }
9136
9137 if (!AllowVectorOps && VT.isVector() &&
9143 return SDValue();
9144
9145 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
9146 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
9147 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
9148 SDValue ShVal;
9149 SDValue HsVal;
9150 if (isPowerOf2_32(EltSizeInBits)) {
9151 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
9152 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
9153 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
9154 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
9155 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
9156 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
9157 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
9158 } else {
9159 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
9160 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
9161 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
9162 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
9163 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
9164 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
9165 SDValue One = DAG.getConstant(1, DL, ShVT);
9166 HsVal =
9167 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
9168 }
9169 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
9170}
9171
9172/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
9173/// a chain of halving decompositions (halving element width) and/or vector
9174/// widening (doubling element count). This guides expansion strategy selection:
9175/// if true, the halving/widening path produces better code than bit-by-bit.
9176///
9177/// HalveDepth tracks halving steps only (each creates ~4x more operations).
9178/// Widening steps are cheap (O(1) pad/extract) and don't count.
9179/// Limiting halvings to 2 prevents exponential blowup:
9180/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
9181/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
9182/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
9184 EVT VT, unsigned HalveDepth = 0,
9185 unsigned TotalDepth = 0) {
9186 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
9187 return false;
9188 if (TLI.isOperationLegalOrCustom(ISD::CLMUL, VT))
9189 return true;
9190 if (!TLI.isTypeLegal(VT))
9191 return false;
9192
9193 unsigned BW = VT.getScalarSizeInBits();
9194
9195 // Halve: halve element width, same element count.
9196 // This is the expensive step -- each halving creates ~4x more operations.
9197 if (BW % 2 == 0) {
9198 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
9199 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
9200 if (TLI.isTypeLegal(HalfVT) &&
9201 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
9202 return true;
9203 }
9204
9205 // Widen: double element count (fixed-width vectors only).
9206 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
9207 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
9208 if (TLI.isTypeLegal(WideVT) &&
9209 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
9210 return true;
9211
9212 return false;
9213}
9214
9216 SDLoc DL(Node);
9217 EVT VT = Node->getValueType(0);
9218 SDValue X = Node->getOperand(0);
9219 SDValue Y = Node->getOperand(1);
9220 unsigned BW = VT.getScalarSizeInBits();
9221 unsigned Opcode = Node->getOpcode();
9222 LLVMContext &Ctx = *DAG.getContext();
9223
9224 switch (Opcode) {
9225 case ISD::CLMUL: {
9226 // For vector types, try decomposition strategies that leverage legal
9227 // CLMUL on narrower or wider element types, avoiding the expensive
9228 // bit-by-bit expansion.
9229 if (VT.isVector()) {
9230 // Strategy 1: Halving decomposition to half-element-width CLMUL.
9231 // Applies ExpandIntRes_CLMUL's identity element-wise:
9232 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
9233 // where:
9234 // Lo = CLMUL(XLo, YLo)
9235 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9236 unsigned HalfBW = BW / 2;
9237 if (BW % 2 == 0) {
9238 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
9239 EVT HalfVT =
9240 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
9241 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
9242 /*HalveDepth=*/1)) {
9243 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
9244
9245 // Extract low and high halves of each element.
9246 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
9247 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9248 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
9249 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
9250 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9251 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
9252
9253 // Lo = CLMUL(XLo, YLo)
9254 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
9255
9256 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9257 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
9258 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
9259 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
9260 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
9261 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
9262
9263 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
9264 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
9265 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
9266 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
9267 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
9268 }
9269 }
9270
9271 // Strategy 2: Promote to double-element-width CLMUL.
9272 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
9273 {
9274 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9275 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
9276 // If CLMUL on ExtVT is Custom (not Legal), the target may
9277 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
9278 // fallback costs O(BW) vectorized iterations. Only widen when
9279 // element count is small enough that scalarization is cheaper.
9280 unsigned NumElts = VT.getVectorMinNumElements();
9281 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
9282 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
9283 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
9284 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9285 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
9286 }
9287 }
9288 }
9289
9290 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
9291 // vector, extract lower result). CLMUL is element-wise, so upper
9292 // (undef) lanes don't affect the lower results.
9293 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
9294 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
9295 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
9296 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
9297 SDValue Undef = DAG.getUNDEF(WideVT);
9298 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9299 X, DAG.getVectorIdxConstant(0, DL));
9300 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9301 Y, DAG.getVectorIdxConstant(0, DL));
9302 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
9303 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
9304 DAG.getVectorIdxConstant(0, DL));
9305 }
9306 }
9307 }
9308
9309 // Special case: clmul(X, Y) where Y is a known constant (splat) that forms
9310 // a contiguous block of trailing ones whose length N is a power of two
9311 // (e.g. i8 0xFF, i8 0x0F, ...) or equal to the operand width. In this
9312 // special case, clmul(X, Y) is equivalent to a "parallel prefix XOR" or
9313 // "bitwise parity" operation on X.
9314 //
9315 // Note: This special currently dose NOT apply when the mask is neither a
9316 // power of two nor equal to the operand width because the loop inside
9317 // behaves as if the mask was bit-ceiled, and "undoing" the XOR with parts
9318 // of that CLMUL is a recursive problem (e.g. CLMUL with a 20-bit mask
9319 // requires correction XOR with CLMUL with 12-bit mask).
9320 if (auto *C = isConstOrConstSplat(Y, /*AllowUndefs=*/true)) {
9321 const APInt &YVal = C->getAPIntValue();
9322 unsigned N = YVal.countr_one();
9323 if (YVal.isAllOnes() || (YVal.isMask() && isPowerOf2_32(N))) {
9324 SDValue R = X;
9325 for (unsigned I = 1; I < N; I <<= 1) {
9326 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
9327 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
9328 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
9329 }
9330 return R;
9331 }
9332 }
9333
9334 // NOTE: If you change this expansion, please update the cost model
9335 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
9336 // Intrinsic::clmul.
9337
9338 // Strategy 4: multiplication with holes.
9339 //
9340 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
9341 // do occur, they wind up in a "hole" and are subsequently masked out of the
9342 // result.
9343 //
9344 // https://www.bearssl.org/constanttime.html#ghash-for-gcm describes this
9345 // approach.
9346
9347 // Stride S handles operands up to S·2^S bits using S² multiplies.
9348 //
9349 // * BW <= 8 uses S = 2 (holes of 1 bit)
9350 // * BW <= 24 uses S = 3 (holes of 2 bits)
9351 // * BW <= 64 uses S = 4 (holes of 3 bits)
9352 // * BW <= 160 uses S = 5 (holes of 4 bits)
9353 // * BW <= 384 uses S = 6 (holes of 5 bits)
9354 //
9355 // We distribute the BW bits over S phases:
9356 //
9357 // phase 0 keeps bits: 0, S, 2S, ...
9358 // phase 1 keeps bits: 1, S + 1, 2S + 1, ...
9359 // ...
9360 //
9361 // Each phase has up to n = ceil(BW / S) bits set, and the holes are S-1
9362 // bits wide.
9363 //
9364 // Take BW = 4, S = 2, n = 2. The worst case is a fully populated phase (all
9365 // non-hole bits are set to 1) multiplied by itself, 0b0101 * 0b0101. Each
9366 // set bit of one operand shifts a copy of the other, and we add the copies:
9367 //
9368 // col: 4 3 2 1 0
9369 // 0b0101 << 0: 0 0 1 0 1
9370 // 0b0101 << 2: 1 0 1 0 0
9371 // ----------------- +
9372 // count: 1 0 2 0 1
9373 //
9374 // Counting the number of one-bits in each column gives a triangle: the
9375 // counts climb 1, 2, ..., n and back down (here 1, 2, 1 across the data
9376 // columns). So a column holds at most n one-bits, and that maximum n is
9377 // reached in only one column: the peak. Every other column holds at most n
9378 // - 1 one-bits.
9379 //
9380 // A stack of one-bits in a column turns into carries: column 2 above really
9381 // stores the value 1 + 1 = 2 = n. A column spans S bits, its kept bit
9382 // plus S-1 hole bits, and the count is written from the kept bit upward,
9383 // so any count <= 2^S - 1 stays within the column and never interferes with
9384 // the next data bit S positions up. Every non-peak column holds at most n -
9385 // 1, so they all fit as soon as n - 1 <= 2^S - 1.
9386 //
9387 // That leaves only the peak column. Because both operands set all data
9388 // bits, the triangle peaks at the top of the word at the highest data bit
9389 // still inside BW. Here the count reaches exactly n = 2^S and overflows.
9390 // But its carry lands at bit n*S >= BW, off the top, where it (and the
9391 // whole descending half of the triangle) is truncated.
9392 //
9393 // Hence the holes suffice exactly when n = ceil(BW / S) <= 2^S, i.e. BW <=
9394 // S*2^S.
9395 //
9396 // Here we find the smallest S that satisfies this inequality.
9397 unsigned S = 1;
9398 while (S < 32 && divideCeil(BW, S) > (1u << S))
9399 ++S;
9400
9401 // The "multiplication with holes" expansion emits S*S MULs, 3*S ANDs,
9402 // S*(S-1) XORs and S-1 ORs.
9403 unsigned HolesCost = S * S + 3 * S + S * (S - 1) + (S - 1);
9404
9405 // Estimate the cost of the naive algorithm.
9406 KnownBits KnownY = DAG.computeKnownBits(Y);
9407 unsigned NaiveCost = 0;
9408 for (unsigned I = 0; I < BW; ++I) {
9409 // The iteration folds away entirely and is free.
9410 if (KnownY.Zero[I])
9411 continue;
9412
9413 // On targets with a fast bit test instruction more instructions are used
9414 // to not need a (potentially expensive) multiplication. See also below.
9415 if (hasBitTest(Y, DAG.getShiftAmountConstant(I, VT, DL))) {
9416 // AND + SETCC + SHL + SELECT + XOR.
9417 NaiveCost += 5;
9418 } else {
9419 // AND + MUL + XOR.
9420 NaiveCost += 3;
9421 }
9422 }
9423
9424 // Only use multiplication with holes when it is cheaper, else use the naive
9425 // fallback below.
9426 if (HolesCost < NaiveCost &&
9428
9429 // Set a bit every S positions, e.g. for S = 4 this is equivalent to
9430 // 0b...00010001...0001.
9431 APInt MaskVal = APInt::getSplat(BW, APInt(S, 1));
9432
9433 // Create versions of X and Y that keep only the I-th bit of each S-bit
9434 // slice.
9435 SmallVector<SDValue, 4> M(S), Xp(S), Yp(S);
9436 for (unsigned I = 0; I < S; ++I) {
9437 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9438 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9439 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9440 }
9441
9442 // Codegens these expressions (S*S multiplications), e.g. for S=4:
9443 //
9444 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9445 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9446 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9447 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9448 SDValue Res = DAG.getConstant(0, DL, VT);
9449 for (unsigned I = 0; I < S; ++I) {
9450 SDValue Zi = DAG.getConstant(0, DL, VT);
9451 for (unsigned J = 0; J < S; ++J) {
9452 unsigned K = (I + S - J) % S;
9453 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9454 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9455 }
9456
9457 // Keep only the bits belonging to this iteration, and bitwise or it all
9458 // together.
9459 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9460 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9461 }
9462 return Res;
9463 }
9464
9465 // Strategy 5: the naive fallback.
9466 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9467
9468 SDValue Res = DAG.getConstant(0, DL, VT);
9469 for (unsigned I = 0; I < BW; ++I) {
9470 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9471 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9472 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9473
9474 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9475 // multiply, use a shift-based expansion to avoid expensive MUL
9476 // instructions.
9477 SDValue Part;
9478 if (!hasBitTest(Y, ShiftAmt) &&
9481 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9482 } else {
9483 // Canonical bit test: (Y & (1 << I)) != 0
9484 SDValue Zero = DAG.getConstant(0, DL, VT);
9485 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9486 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9487 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9488 }
9489 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9490 }
9491 return Res;
9492 }
9493 case ISD::CLMULR:
9494 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9497 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9498 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9499 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9500 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9501 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9502 DAG.getShiftAmountConstant(1, VT, DL));
9503 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9504 }
9505 [[fallthrough]];
9506 case ISD::CLMULH: {
9507 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9508 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9509 // when any of these hold:
9510 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9511 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9512 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9513 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9514 // path creates CLMUL(VT) which will be expanded efficiently. The
9515 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9516 // causing a cycle.
9517 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9518 // => trunc path is preferred over the bitreverse path, as it avoids the
9519 // cost of 3 bitreverse operations.
9524 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9525 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9526 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9527 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9528 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9529 if (Opcode == ISD::CLMULH)
9530 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9531 DAG.getShiftAmountConstant(1, VT, DL));
9532 return Res;
9533 }
9534 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9535 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9536 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9537 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9538 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9539 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9540 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9541 }
9542 }
9543 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9544}
9545
9548 SDLoc dl(Node);
9549 SDValue Val = Node->getOperand(0);
9550 EVT VT = Val.getValueType();
9551 SDNodeFlags Flags = Node->getFlags();
9552
9553 SDValue IntPart = DAG.getNode(ISD::FTRUNC, dl, VT, Val, Flags);
9554 SDValue FracPart = DAG.getNode(ISD::FSUB, dl, VT, Val, IntPart, Flags);
9555
9556 SDValue FracToUse = FracPart;
9557 if (!Flags.hasNoInfs()) {
9558 SDValue Abs = DAG.getNode(ISD::FABS, dl, VT, Val, Flags);
9559 SDValue Inf =
9561 EVT SetCCVT =
9562 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9563 SDValue IsInf = DAG.getSetCC(dl, SetCCVT, Abs, Inf, ISD::SETOEQ);
9564 SDValue Zero = DAG.getConstantFP(0.0, dl, VT);
9565 FracToUse = DAG.getSelect(dl, VT, IsInf, Zero, FracPart);
9566 }
9567
9568 SDValue ResultFrac =
9569 DAG.getNode(ISD::FCOPYSIGN, dl, VT, FracToUse, Val, Flags);
9570 Results.push_back(ResultFrac);
9571 Results.push_back(IntPart);
9572 return true;
9573}
9574
9576 SDLoc DL(Node);
9577 EVT VT = Node->getValueType(0);
9578 SDValue Val = Node->getOperand(0);
9579 SDValue Msk = Node->getOperand(1);
9580 unsigned BW = VT.getScalarSizeInBits();
9581
9582 // Just scalarize if scalar PEXT is legal
9584 return DAG.UnrollVectorOp(Node);
9585
9586 // Hacker's Delight §7-4: Compress, or Generalized Extract
9587 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9588 SDValue M = Msk;
9589 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9590 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9591
9592 // Repeatedly compute which bits would shift to the right by an odd amount,
9593 // shift all such bits in parallel using a mask, and double the shift amount.
9594 for (unsigned I = 1; I < BW; I *= 2) {
9595 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9596 SDValue Mp =
9597 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9598 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9599 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9600 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9601 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9603 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9604 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9605 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9607 if (I * 2 < BW)
9608 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9609 }
9610
9611 return X;
9612}
9613
9615 SDLoc DL(Node);
9616 EVT VT = Node->getValueType(0);
9617 SDValue Val = Node->getOperand(0);
9618 SDValue Msk = Node->getOperand(1);
9619 unsigned BW = VT.getScalarSizeInBits();
9620
9621 // Just scalarize if scalar PDEP is legal
9623 return DAG.UnrollVectorOp(Node);
9624
9625 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9626 unsigned LogBW = Log2_32_Ceil(BW);
9627 SmallVector<SDValue, 8> MvArray(LogBW);
9628 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9629 SDValue Mc = Msk;
9630 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9631
9632 // First pass: compute move masks for each power of two that a bit moves by.
9633 for (unsigned S = 0; S < LogBW; ++S) {
9634 unsigned ShiftS = 1u << S;
9635 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9636 SDValue Mp =
9637 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9638 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9639 MvArray[S] = Mv;
9640 if (S + 1 < LogBW) {
9641 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9642 SDValue MvShifted = DAG.getNode(
9643 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9644 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9646 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9647 }
9648 }
9649
9650 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9651 // Each pass handles half the shift amount of the previous pass.
9652 SDValue X = Val;
9653 for (int S = (int)LogBW - 1; S >= 0; --S) {
9654 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9655 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9656 SDValue UnshiftedBits =
9657 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9658 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9659 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9661 }
9662
9663 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9664}
9665
9667 SelectionDAG &DAG) const {
9668 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9669 EVT VT = Node->getValueType(0);
9670 unsigned VTBits = VT.getScalarSizeInBits();
9671 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9672
9673 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9674 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9675 SDValue ShOpLo = Node->getOperand(0);
9676 SDValue ShOpHi = Node->getOperand(1);
9677 SDValue ShAmt = Node->getOperand(2);
9678 EVT ShAmtVT = ShAmt.getValueType();
9679 EVT ShAmtCCVT =
9680 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9681 SDLoc dl(Node);
9682
9683 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9684 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9685 // away during isel.
9686 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9687 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9688 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9689 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9690 : DAG.getConstant(0, dl, VT);
9691
9692 SDValue Tmp2, Tmp3;
9693 if (IsSHL) {
9694 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9695 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9696 } else {
9697 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9698 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9699 }
9700
9701 // If the shift amount is larger or equal than the width of a part we don't
9702 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9703 // values for large shift amounts.
9704 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9705 DAG.getConstant(VTBits, dl, ShAmtVT));
9706 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9707 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9708
9709 if (IsSHL) {
9710 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9711 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9712 } else {
9713 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9714 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9715 }
9716}
9717
9719 SelectionDAG &DAG) const {
9720 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9721 // suggested in
9722 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9723 // It uses strict_fp operations even outside a strict_fp context in order
9724 // to guarantee that the canonicalization is not optimized away by later
9725 // passes. The result chain introduced by that is intentionally ignored
9726 // since no ordering requirement is intended here.
9727 EVT VT = Node->getValueType(0);
9728 SDLoc DL(Node);
9729 SDNodeFlags Flags = Node->getFlags();
9730 Flags.setNoFPExcept(true);
9731 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9732 SDValue Mul =
9733 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9734 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9735 return Mul;
9736}
9737
9739 SelectionDAG &DAG) const {
9740 // Expand conversion from a native IEEE float type to an arbitrary FP format
9741 // returning the result as an integer using bit manipulation.
9742 EVT ResVT = Node->getValueType(0);
9743 SDLoc dl(Node);
9744
9745 SDValue FloatVal = Node->getOperand(0);
9746 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9747 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9748 const auto RoundMode =
9749 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9750 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9751
9752 // Supported destination formats.
9753 switch (Sem) {
9760 break;
9761 default:
9762 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9763 "destination format (semantics enum " +
9764 Twine(SemEnum) + ")");
9765 return SDValue();
9766 }
9767
9768 // Supported rounding modes.
9769 switch (RoundMode) {
9775 break;
9776 default:
9777 DAG.getContext()->emitError(
9778 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9779 Twine(static_cast<int>(RoundMode)) + ")");
9780 return SDValue();
9781 }
9782
9783 // Destination format parameters.
9784 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9785 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9786 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9787 const unsigned DstMant = DstPrecision - 1;
9788 // Unsigned formats spend no bit on the sign.
9789 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9790 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9791 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9792 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9793 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9794 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9795 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9796
9797 // Compute the maximum normal exponent for the destination format.
9798 const unsigned DstExpMaxNormal =
9799 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9800 : DstExpMax;
9801
9802 // For NanOnly formats the max exponent field for finite values
9803 // is DstExpMax, but the encoding with exp = DstExpMax and
9804 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9805 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9806 // avoid the NaN encoding.
9807 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9808 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9809 DstNanEnc == fltNanEncoding::AllOnes)
9810 DstMaxMantAtMaxExp = DstMantMask - 1;
9811
9812 // Source format parameters.
9813 EVT SrcVT = FloatVal.getValueType();
9814 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9815 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9816 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9817 const unsigned SrcMant = SrcPrecision - 1;
9818 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9819
9820 // Work in the source integer type. Match the destination shape so the
9821 // expansion stays vector when ResVT is a vector.
9822 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9823 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9824 EVT SetCCVT =
9825 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9826 EVT FPSetCCVT =
9827 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9828
9829 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9830 SDValue One = DAG.getConstant(1, dl, IntVT);
9831
9832 // Bitcast source float to integer to extract the sign bit.
9833 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9834 SDValue SignBit =
9835 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9836 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9837
9838 // Classify the input.
9839 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9840 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9841 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9842 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9843 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9844 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9845
9846 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9847 // source denormals automatically. The result is unspecified for Inf/NaN, but
9848 // those inputs are detected above and override the final result.
9849 EVT FrexpExpScalarVT =
9851 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9852 SDValue Frexp =
9853 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9854 SDValue FrexpFrac = Frexp.getValue(0);
9855 SDValue FrexpExp = Frexp.getValue(1);
9856
9857 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9858 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9859 DAG.getConstant(SrcMantMask, dl, IntVT));
9860
9861 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9862 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9863 DAG.getConstant(DstBias - 1, dl, IntVT));
9864
9865 // Compute rounding increment given the round bit, sticky bits, and LSB
9866 // of the truncated mantissa.
9867 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9868 SDValue LSB) -> SDValue {
9869 switch (RoundMode) {
9871 // Round up if round_bit && (sticky || lsb)
9872 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9873 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9874 }
9876 return Zero;
9878 // Round up if positive and any truncated bits are set.
9879 SDValue AnyTruncBits =
9880 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9881 SDValue HasTruncBits =
9882 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9883 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9884 SDValue DoRound =
9885 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9886 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9887 }
9889 // Round up if negative and any truncated bits are set (to -Inf).
9890 SDValue AnyTruncBits =
9891 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9892 SDValue HasTruncBits =
9893 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9894 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9895 SDValue DoRound =
9896 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9897 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9898 }
9900 return RoundBit;
9901 default:
9902 llvm_unreachable("unsupported rounding mode");
9903 }
9904 };
9905
9906 // Round mantissa from SrcMant bits to DstMant bits.
9907 SDValue TruncMant;
9908 SDValue RoundUp;
9909 if (SrcMant > DstMant) {
9910 const unsigned Shift = SrcMant - DstMant;
9911 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9912 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9913
9914 // Check bit at position Shift - 1 aka the round bit.
9915 SDValue RoundBit;
9916 if (Shift >= 1) {
9917 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9918 SDValue ShiftedMant =
9919 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9920 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9921 } else {
9922 RoundBit = Zero;
9923 }
9924
9925 // OR of all bits below the round bit to get sticky bits.
9926 SDValue StickyBits;
9927 if (Shift >= 2) {
9928 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9929 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9930 DAG.getConstant(StickyMask, dl, IntVT));
9931 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9932 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9933 } else {
9934 StickyBits = Zero;
9935 }
9936
9937 // LSB of truncated mantissa.
9938 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9939
9940 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9941 } else {
9942 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9943 SDValue MantShift =
9944 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9945 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9946 RoundUp = Zero;
9947 }
9948
9949 // Apply rounding.
9950 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9951
9952 // Handle mantissa overflow from rounding.
9953 // If rounded_mant > DstMantMask, carry into exponent.
9954 SDValue MantOverflow =
9955 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9956 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9957 // On overflow: mant = 0, exp += 1.
9958 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9959 SDValue AdjExp =
9960 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9961 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9962
9963 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9964 // sign bit to merge in.
9965 SDValue SignShifted =
9966 DstHasSign
9967 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9968 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9969 : Zero;
9970
9971 // Destination denormal conversion (when new_exp <= 0).
9972 // Shift the mantissa right by 1 - new_exp additional bits and set the
9973 // exponent field to 0.
9974 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9975 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9976
9977 SDValue DenormResult;
9978 {
9979 // denorm_shift = 1 - NewExp.
9980 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9981
9982 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9983 SDValue ImplicitOne =
9984 DAG.getNode(ISD::SHL, dl, IntVT, One,
9985 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9986 SDValue FullSrcMant =
9987 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9988
9989 // Total right shift = DenormShift + (SrcMant - DstMant).
9990 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9991 SDValue TotalShift =
9992 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9993 DAG.getSignedConstant(MantDelta, dl, IntVT));
9994
9995 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9996 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9997 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9998 SDValue ClampedShift =
9999 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
10000 SDValue DenormTruncMant =
10001 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
10002 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
10003
10004 // Rounding for denorm path.
10005 SDValue DenormRoundUp;
10006 {
10007 // Round bit is at position TotalShift - 1 of FullSrcMant.
10008 // Clamp to at least 1 so the subtraction doesn't underflow and create
10009 // shift nodes with invalid shift amounts.
10010 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
10011 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
10012 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
10013 SDValue DenormRoundBit = DAG.getNode(
10014 ISD::AND, dl, IntVT,
10015 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
10016
10017 // Sticky: all bits below round bit.
10018 // sticky_mask = (1 << RoundBitPos) - 1
10019 SDValue StickyMask = DAG.getNode(
10020 ISD::SUB, dl, IntVT,
10021 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
10022 SDValue DenormStickyBits =
10023 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
10024 SDValue HasSticky = DAG.getNode(
10025 ISD::ZERO_EXTEND, dl, IntVT,
10026 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
10027
10028 SDValue DenormLSB =
10029 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
10030
10031 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
10032
10033 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
10034 SDValue ShiftGEOne =
10035 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
10036 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
10037 }
10038
10039 SDValue DenormRoundedMant =
10040 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
10041
10042 // If rounding caused overflow into the normal range, then we get the
10043 // smallest normal number.
10044 SDValue DenormMantOF =
10045 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
10046 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
10047 SDValue DenormFinalMant =
10048 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
10049 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
10050
10051 // Assemble: sign | (exp << DstMant) | mant
10052 SDValue DenormExpShifted =
10053 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
10054 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
10055 DenormResult = DAG.getNode(
10056 ISD::OR, dl, IntVT,
10057 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10058 DenormFinalMant);
10059 }
10060
10061 // Exponent overflow detection.
10062 SDValue ExpOF =
10063 DAG.getSetCC(dl, SetCCVT, AdjExp,
10064 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
10065
10066 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
10067 // a value that exceeds the max allowed mantissa at that exponent.
10068 SDValue ExpAtMax =
10069 DAG.getSetCC(dl, SetCCVT, AdjExp,
10070 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
10071 SDValue MantExceedsMax =
10072 DAG.getSetCC(dl, SetCCVT, AdjMant,
10073 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
10074 SDValue ExpMantOF =
10075 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
10076 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
10077
10078 // Build overflow result.
10080
10081 if (Saturate) {
10082 // Clamp to max finite value:
10083 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
10084 uint64_t MaxFinite =
10085 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
10086 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10087 DAG.getConstant(MaxFinite, dl, IntVT));
10088 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10089 // Produce infinity.
10090 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
10091 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10092 DAG.getConstant(InfBits, dl, IntVT));
10093 } else {
10094 // Emit poison if no Inf in format and not saturating.
10095 OverflowResult = DAG.getPOISON(IntVT);
10096 }
10097
10098 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
10099 SDValue NormExpShifted =
10100 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
10101 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
10102 SDValue NormResult = DAG.getNode(
10103 ISD::OR, dl, IntVT,
10104 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
10105
10106 // Build special-value results.
10107 SDValue NaNResult;
10108 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10109 // Produce canonical NaN.
10110 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10111 NaNResult =
10112 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
10113 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
10114 DstNanEnc == fltNanEncoding::AllOnes) {
10115 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
10116 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
10117 dl, IntVT);
10118 } else {
10119 // NaN -> poison for finite only values.
10120 NaNResult = DAG.getPOISON(IntVT);
10121 }
10122
10123 // Inf handling.
10124 SDValue InfResult;
10125 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10126 // Produce signed infinity.
10127 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
10128 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10129 DAG.getConstant(InfBits, dl, IntVT));
10130 } else if (Saturate) {
10131 // Inf saturates to max finite.
10132 uint64_t MaxFinite =
10133 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
10134 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10135 DAG.getConstant(MaxFinite, dl, IntVT));
10136 } else {
10137 // No Inf and not saturating -> poison.
10138 InfResult = DAG.getPOISON(IntVT);
10139 }
10140
10141 SDValue ZeroResult = SignShifted;
10142
10143 // Final selection in an order: NaN takes priority, then Inf, then Zero.
10144 SDValue FiniteResult =
10145 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
10146 FiniteResult =
10147 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
10148
10149 SDValue Result = FiniteResult;
10150 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10151 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10152
10153 // Negative values are unrepresentable in an unsigned format: clamp to zero
10154 // when saturating, poison otherwise so no select is needed. -0.0 is handled
10155 // by IsZero above. Run before the NaN case so a negative NaN still yields
10156 // NaN.
10157 if (!DstHasSign && Saturate) {
10158 SDValue IsNegative =
10159 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
10160 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
10161 }
10162
10163 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10164
10165 // Truncate to destination integer type.
10166 return DAG.getZExtOrTrunc(Result, dl, ResVT);
10167}
10168
10169SDValue
10171 SelectionDAG &DAG) const {
10172 SDLoc dl(Node);
10173 EVT DstVT = Node->getValueType(0);
10174 EVT DstScalarVT = DstVT.getScalarType();
10175
10176 SDValue IntVal = Node->getOperand(0);
10177 const uint64_t SemEnum = Node->getConstantOperandVal(1);
10178 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
10179
10180 // Supported source formats.
10181 switch (Sem) {
10188 break;
10189 default:
10190 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
10191 "source format (semantics enum " +
10192 Twine(SemEnum) + ")");
10193 return SDValue();
10194 }
10195
10196 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
10197 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
10198 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
10199 const unsigned SrcMant = SrcPrecision - 1;
10200 // Unsigned formats spend no bit on the sign.
10201 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
10202 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
10203 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
10204 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
10205
10206 // Destination format parameters.
10207 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
10208 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
10209 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
10210 const unsigned DstExpBits = DstBits - DstMant - 1;
10211 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
10212 const int DstBias = 1 - DstMinExp;
10213 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
10214
10215 // Work in an integer type matching the destination float width.
10216 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
10217 EVT IntVT = IntScalarVT;
10218 if (DstVT.isVector()) {
10219 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
10220 DstVT.getVectorElementCount());
10221 } else if (!isTypeLegal(IntScalarVT)) {
10222 // Avoid generating illegal type as there is no other places that'll
10223 // legalize it. Vector types don't have this problem because they
10224 // are subject to LegalizeVectorOps and another type legalization phase
10225 // will follow.
10226 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
10227 // We only know how to handle situations where the legal type is wider.
10228 DAG.getContext()->emitError(
10229 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
10230 "legalization is not supported");
10231 return SDValue();
10232 }
10233 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
10234 }
10235
10236 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
10237
10238 EVT SetCCVT =
10239 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
10240
10241 SDValue Zero = DAG.getConstant(0, dl, IntVT);
10242 SDValue One = DAG.getConstant(1, dl, IntVT);
10243
10244 // Extract bit fields.
10245 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
10246 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
10247
10248 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
10249 DAG.getConstant(MantMask, dl, IntVT));
10250
10251 SDValue ExpField =
10252 DAG.getNode(ISD::AND, dl, IntVT,
10253 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10254 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
10255 DAG.getConstant(ExpMask, dl, IntVT));
10256
10257 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
10258 // exponent.
10259 SDValue SignShifted =
10260 SrcHasSign
10261 ? DAG.getNode(
10262 ISD::SHL, dl, IntVT,
10263 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10264 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
10265 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
10266 : Zero;
10267
10268 // Classify the input.
10269 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
10270 SDValue IsExpAllOnes =
10271 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
10272 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
10273 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
10274 SDValue IsMantNonZero =
10275 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
10276
10277 SDValue IsNaN;
10278 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
10279 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10280 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
10281 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
10282 } else {
10284 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
10285 SDValue IsMantAllOnes =
10286 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
10287 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
10288 }
10289
10290 SDValue IsInf;
10291 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
10292 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
10293 else
10294 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10295
10296 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
10297 SDValue IsDenorm =
10298 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
10299
10300 // Normal value conversion.
10301 const int BiasAdjust = DstBias - SrcBias;
10302 SDValue NormDstExp = DAG.getNode(
10303 ISD::ADD, dl, IntVT, ExpField,
10304 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
10305 IntVT));
10306
10307 SDValue NormDstMant;
10308 if (DstMant > SrcMant) {
10309 SDValue NormDstMantShift =
10310 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
10311 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
10312 } else {
10313 NormDstMant = MantField;
10314 }
10315
10316 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
10317 SDValue NormExpShifted =
10318 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
10319 SDValue NormResult =
10320 DAG.getNode(ISD::OR, dl, IntVT,
10321 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
10322 NormDstMant);
10323
10324 // With identical exponent biases, denormal values remain denormal and the
10325 // normal conversion's mantissa shift is sufficient.
10326 SDValue DenormResult = NormResult;
10327 if (BiasAdjust != 0) {
10328 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
10329 SDValue LeadingZeros =
10330 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
10331
10332 const int DenormExpConst =
10333 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
10334 SDValue DenormDstExp = DAG.getNode(
10335 ISD::SUB, dl, IntVT,
10336 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
10337 LeadingZeros);
10338
10339 SDValue MantMSB =
10340 DAG.getNode(ISD::SUB, dl, IntVT,
10341 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
10342
10343 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
10344 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
10345
10346 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
10347 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
10348 DAG.getConstant(ShiftSub, dl, IntVT));
10349
10350 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
10351
10352 SDValue DenormExpShifted =
10353 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
10354 DenormResult = DAG.getNode(
10355 ISD::OR, dl, IntVT,
10356 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10357 DenormDstMant);
10358 }
10359
10360 SDValue FiniteResult =
10361 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
10362
10363 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10364 SDValue NaNResult =
10365 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
10366
10367 SDValue InfResult =
10368 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10369 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
10370
10371 // A source format may have a larger finite exponent range despite having
10372 // fewer bits, as with Float8E5M3FNU converted to half. Its overflowing finite
10373 // values become infinity. The NaN selection below still takes precedence.
10374 if (APFloat::semanticsMaxExponent(SrcSem) >
10376 SDValue IsOverflow =
10377 DAG.getSetCC(dl, SetCCVT, NormDstExp,
10378 DAG.getConstant(DstExpAllOnes, dl, IntVT), ISD::SETUGE);
10379 FiniteResult =
10380 DAG.getSelect(dl, IntVT, IsOverflow, InfResult, FiniteResult);
10381 }
10382
10383 SDValue ZeroResult = SignShifted;
10384
10385 SDValue Result = FiniteResult;
10386 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10387 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10388 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10389
10390 if (!DstVT.bitsEq(IntVT)) {
10391 // Store to stack before loading it back.
10392 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
10393 // IntScalarVT is the original type that has the same width as DstVT.
10394 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
10395 SDValue StackPtr =
10396 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
10397 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10399 MachinePointerInfo PtrInfo =
10400 MachinePointerInfo::getFixedStack(MF, FrameIndex);
10401 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
10402 PtrInfo, IntScalarVT, Alignment);
10403
10404 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
10405 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
10406 }
10407
10408 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
10409}
10410
10412 SelectionDAG &DAG) const {
10413 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10414 SDValue Src = Node->getOperand(OpNo);
10415 EVT SrcVT = Src.getValueType();
10416 EVT DstVT = Node->getValueType(0);
10417 SDLoc dl(SDValue(Node, 0));
10418
10419 // FIXME: Only f32 to i64 conversions are supported.
10420 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
10421 return false;
10422
10423 if (Node->isStrictFPOpcode())
10424 // When a NaN is converted to an integer a trap is allowed. We can't
10425 // use this expansion here because it would eliminate that trap. Other
10426 // traps are also allowed and cannot be eliminated. See
10427 // IEEE 754-2008 sec 5.8.
10428 return false;
10429
10430 // Expand f32 -> i64 conversion
10431 // This algorithm comes from compiler-rt's implementation of fixsfdi:
10432 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
10433 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
10434 EVT IntVT = SrcVT.changeTypeToInteger();
10435 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
10436
10437 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
10438 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
10439 SDValue Bias = DAG.getConstant(127, dl, IntVT);
10440 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
10441 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
10442 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
10443
10444 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
10445
10446 SDValue ExponentBits = DAG.getNode(
10447 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
10448 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
10449 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
10450
10451 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
10452 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
10453 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
10454 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10455
10456 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10457 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10458 DAG.getConstant(0x00800000, dl, IntVT));
10459
10460 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10461
10462 R = DAG.getSelectCC(
10463 dl, Exponent, ExponentLoBit,
10464 DAG.getNode(ISD::SHL, dl, DstVT, R,
10465 DAG.getZExtOrTrunc(
10466 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10467 dl, IntShVT)),
10468 DAG.getNode(ISD::SRL, dl, DstVT, R,
10469 DAG.getZExtOrTrunc(
10470 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10471 dl, IntShVT)),
10472 ISD::SETGT);
10473
10474 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10475 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10476
10477 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10478 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10479 return true;
10480}
10481
10483 SDValue &Chain,
10484 SelectionDAG &DAG) const {
10485 SDLoc dl(SDValue(Node, 0));
10486 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10487 SDValue Src = Node->getOperand(OpNo);
10488
10489 EVT SrcVT = Src.getValueType();
10490 EVT DstVT = Node->getValueType(0);
10491 EVT SetCCVT =
10492 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10493 EVT DstSetCCVT =
10494 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10495
10496 // Only expand vector types if we have the appropriate vector bit operations.
10497 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10499 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10501 return false;
10502
10503 // If the maximum float value is smaller then the signed integer range,
10504 // the destination signmask can't be represented by the float, so we can
10505 // just use FP_TO_SINT directly.
10506 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10507 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10508 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10510 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10511 if (Node->isStrictFPOpcode()) {
10512 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10513 { Node->getOperand(0), Src });
10514 Chain = Result.getValue(1);
10515 } else
10516 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10517 return true;
10518 }
10519
10520 // Don't expand it if there isn't cheap fsub instruction.
10522 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10523 return false;
10524
10525 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10526 SDValue Sel;
10527
10528 if (Node->isStrictFPOpcode()) {
10529 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10530 Node->getOperand(0), /*IsSignaling*/ true);
10531 Chain = Sel.getValue(1);
10532 } else {
10533 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10534 }
10535
10536 bool Strict = Node->isStrictFPOpcode() ||
10537 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10538
10539 if (Strict) {
10540 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10541 // signmask then offset (the result of which should be fully representable).
10542 // Sel = Src < 0x8000000000000000
10543 // FltOfs = select Sel, 0, 0x8000000000000000
10544 // IntOfs = select Sel, 0, 0x8000000000000000
10545 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10546
10547 // TODO: Should any fast-math-flags be set for the FSUB?
10548 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10549 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10550 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10551 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10552 DAG.getConstant(0, dl, DstVT),
10553 DAG.getConstant(SignMask, dl, DstVT));
10554 SDValue SInt;
10555 if (Node->isStrictFPOpcode()) {
10556 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10557 { Chain, Src, FltOfs });
10558 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10559 { Val.getValue(1), Val });
10560 Chain = SInt.getValue(1);
10561 } else {
10562 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10563 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10564 }
10565 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10566 } else {
10567 // Expand based on maximum range of FP_TO_SINT:
10568 // True = fp_to_sint(Src)
10569 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10570 // Result = select (Src < 0x8000000000000000), True, False
10571
10572 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10573 // TODO: Should any fast-math-flags be set for the FSUB?
10574 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10575 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10576 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10577 DAG.getConstant(SignMask, dl, DstVT));
10578 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10579 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10580 }
10581 return true;
10582}
10583
10585 SDValue &Chain, SelectionDAG &DAG) const {
10586 // This transform is not correct for converting 0 when rounding mode is set
10587 // to round toward negative infinity which will produce -0.0. So disable
10588 // under strictfp.
10589 if (Node->isStrictFPOpcode())
10590 return false;
10591
10592 SDValue Src = Node->getOperand(0);
10593 EVT SrcVT = Src.getValueType();
10594 EVT DstVT = Node->getValueType(0);
10595
10596 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10597 // it.
10598 if (Node->getFlags().hasNonNeg() &&
10600 Result =
10601 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10602 return true;
10603 }
10604
10605 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10606 return false;
10607
10608 // Only expand vector types if we have the appropriate vector bit
10609 // operations.
10610 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10615 return false;
10616
10617 SDLoc dl(SDValue(Node, 0));
10618
10619 // Implementation of unsigned i64 to f64 following the algorithm in
10620 // __floatundidf in compiler_rt. This implementation performs rounding
10621 // correctly in all rounding modes with the exception of converting 0
10622 // when rounding toward negative infinity. In that case the fsub will
10623 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10624 // incorrect.
10625 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10626 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10627 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10628 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10629 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10630 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10631
10632 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10633 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10634 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10635 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10636 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10637 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10638 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10639 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10640 return true;
10641}
10642
10643SDValue
10645 SelectionDAG &DAG) const {
10646 unsigned Opcode = Node->getOpcode();
10647 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10648 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10649 "Wrong opcode");
10650
10651 if (Node->getFlags().hasNoNaNs()) {
10652 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10653 EVT VT = Node->getValueType(0);
10654 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10656 VT.isVector())
10657 return SDValue();
10658 SDValue Op1 = Node->getOperand(0);
10659 SDValue Op2 = Node->getOperand(1);
10660 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10661 Node->getFlags());
10662 }
10663
10664 return SDValue();
10665}
10666
10668 SelectionDAG &DAG) const {
10669 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10670 return Expanded;
10671
10672 EVT VT = Node->getValueType(0);
10673 if (VT.isScalableVector())
10675 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10676
10677 SDLoc dl(Node);
10678 unsigned NewOp =
10680
10681 if (isOperationLegalOrCustom(NewOp, VT)) {
10682 SDValue Quiet0 = Node->getOperand(0);
10683 SDValue Quiet1 = Node->getOperand(1);
10684
10685 if (!Node->getFlags().hasNoNaNs()) {
10686 // Insert canonicalizes if it's possible we need to quiet to get correct
10687 // sNaN behavior.
10688 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10689 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10690 Node->getFlags());
10691 }
10692 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10693 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10694 Node->getFlags());
10695 }
10696 }
10697
10698 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10699 }
10700
10701 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10702 // instead if there are no NaNs.
10703 if (Node->getFlags().hasNoNaNs() ||
10704 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10705 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10706 unsigned IEEE2018Op =
10707 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10708 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10709 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10710 Node->getOperand(1), Node->getFlags());
10711 }
10712
10714 return SelCC;
10715
10716 return SDValue();
10717}
10718
10720 const TargetLowering &TLI,
10721 const SDLoc &DL, SDValue Val,
10722 FPClassTest FPClass) {
10723 EVT VT = Val.getValueType();
10724 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10725 EVT IntVT = VT.changeTypeToInteger();
10726 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10727 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10728 if (!TLI.isTypeLegal(IntVT) &&
10729 !TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, VT))
10730 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10731 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10732 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10733}
10734
10736 SelectionDAG &DAG) const {
10737 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10738 return Expanded;
10739
10740 SDLoc DL(N);
10741 SDValue LHS = N->getOperand(0);
10742 SDValue RHS = N->getOperand(1);
10743 unsigned Opc = N->getOpcode();
10744 EVT VT = N->getValueType(0);
10745 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10746 bool IsMax = Opc == ISD::FMAXIMUM;
10747 SDNodeFlags Flags = N->getFlags();
10748
10749 // First, implement comparison not propagating NaN. If no native fmin or fmax
10750 // available, use plain select with setcc instead.
10752 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10753 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10754
10755 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10756 // signed zero behavior.
10757 bool MinMaxMustRespectOrderedZero = false;
10758
10759 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10760 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10761 MinMaxMustRespectOrderedZero = true;
10762 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10763 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10764 } else {
10766 return DAG.UnrollVectorOp(N);
10767
10768 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10769 SDValue Compare =
10770 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10771 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10772 }
10773
10774 // Propagate any NaN of both operands
10775 if (!N->getFlags().hasNoNaNs() &&
10776 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10777 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10779 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10780 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10781 }
10782
10783 // fminimum/fmaximum requires -0.0 less than +0.0
10784 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10785 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10786 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10788 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10789 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10790 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10791 }
10792
10793 return MinMax;
10794}
10795
10797 SelectionDAG &DAG) const {
10798 SDLoc DL(Node);
10799 SDValue LHS = Node->getOperand(0);
10800 SDValue RHS = Node->getOperand(1);
10801 unsigned Opc = Node->getOpcode();
10802 EVT VT = Node->getValueType(0);
10803 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10804 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10805 SDNodeFlags Flags = Node->getFlags();
10806
10807 unsigned NewOp =
10809
10810 if (isOperationLegalOrCustom(NewOp, VT)) {
10811 if (!Flags.hasNoNaNs()) {
10812 // Insert canonicalizes if it's possible we need to quiet to get correct
10813 // sNaN behavior.
10814 if (!DAG.isKnownNeverSNaN(LHS)) {
10815 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10816 }
10817 if (!DAG.isKnownNeverSNaN(RHS)) {
10818 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10819 }
10820 }
10821
10822 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10823 }
10824
10825 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10826 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10827 if (Flags.hasNoNaNs() ||
10828 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10829 unsigned IEEE2019Op =
10831 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10832 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10833 }
10834
10835 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10836 // either one for +0.0 vs -0.0.
10837 if ((Flags.hasNoNaNs() ||
10838 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10839 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10840 DAG.isKnownNeverLogicalZero(RHS))) {
10841 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10842 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10843 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10844 }
10845
10846 if (VT.isVector() &&
10849 return DAG.UnrollVectorOp(Node);
10850
10851 // If only one operand is NaN, override it with another operand.
10852 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10853 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10854 }
10855 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10856 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10857 }
10858
10859 // Always prefer RHS if equal.
10860 SDValue MinMax =
10861 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10862
10863 // TODO: We need quiet sNaN if strictfp.
10864
10865 // Fixup signed zero behavior.
10866 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10867 DAG.isKnownNeverLogicalZero(RHS)) {
10868 return MinMax;
10869 }
10870 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10871 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10873 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10874 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10875 // we preferred RHS when generate MinMax, if the operands are equal.
10876 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10877 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10878}
10879
10880/// Returns a true value if if this FPClassTest can be performed with an ordered
10881/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10882/// std::nullopt if it cannot be performed as a compare with 0.
10883static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10884 const fltSemantics &Semantics,
10885 const MachineFunction &MF) {
10886 FPClassTest OrderedMask = Test & ~fcNan;
10887 FPClassTest NanTest = Test & fcNan;
10888 bool IsOrdered = NanTest == fcNone;
10889 bool IsUnordered = NanTest == fcNan;
10890
10891 // Skip cases that are testing for only a qnan or snan.
10892 if (!IsOrdered && !IsUnordered)
10893 return std::nullopt;
10894
10895 if (OrderedMask == fcZero &&
10896 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10897 return IsOrdered;
10898 if (OrderedMask == (fcZero | fcSubnormal) &&
10899 MF.getDenormalMode(Semantics).inputsAreZero())
10900 return IsOrdered;
10901 return std::nullopt;
10902}
10903
10905 const FPClassTest OrigTestMask,
10906 SDNodeFlags Flags, const SDLoc &DL,
10907 SelectionDAG &DAG) const {
10908 EVT OperandVT = Op.getValueType();
10909 assert(OperandVT.isFloatingPoint());
10910 FPClassTest Test = OrigTestMask;
10911
10912 // Degenerated cases.
10913 if (Test == fcNone)
10914 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10915 if (Test == fcAllFlags)
10916 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10917
10918 // PPC double double is a pair of doubles, of which the higher part determines
10919 // the value class.
10920 if (OperandVT == MVT::ppcf128) {
10921 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10922 DAG.getConstant(1, DL, MVT::i32));
10923 OperandVT = MVT::f64;
10924 }
10925
10926 // Floating-point type properties.
10927 EVT ScalarFloatVT = OperandVT.getScalarType();
10928 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10929 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10930 bool IsF80 = (ScalarFloatVT == MVT::f80);
10931
10932 // Some checks can be implemented using float comparisons, if floating point
10933 // exceptions are ignored.
10934 if (Flags.hasNoFPExcept() &&
10936 FPClassTest FPTestMask = Test;
10937 bool IsInvertedFP = false;
10938
10939 if (FPClassTest InvertedFPCheck =
10940 invertFPClassTestIfSimpler(FPTestMask, true)) {
10941 FPTestMask = InvertedFPCheck;
10942 IsInvertedFP = true;
10943 }
10944
10945 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10946 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10947
10948 // See if we can fold an | fcNan into an unordered compare.
10949 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10950
10951 // Can't fold the ordered check if we're only testing for snan or qnan
10952 // individually.
10953 if ((FPTestMask & fcNan) != fcNan)
10954 OrderedFPTestMask = FPTestMask;
10955
10956 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10957
10958 if (std::optional<bool> IsCmp0 =
10959 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10960 IsCmp0 && (isCondCodeLegalOrCustom(
10961 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10962 OperandVT.getScalarType().getSimpleVT()))) {
10963
10964 // If denormals could be implicitly treated as 0, this is not equivalent
10965 // to a compare with 0 since it will also be true for denormals.
10966 return DAG.getSetCC(DL, ResultVT, Op,
10967 DAG.getConstantFP(0.0, DL, OperandVT),
10968 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10969 }
10970
10971 if (FPTestMask == fcNan &&
10973 OperandVT.getScalarType().getSimpleVT()))
10974 return DAG.getSetCC(DL, ResultVT, Op, Op,
10975 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10976
10977 bool IsOrderedInf = FPTestMask == fcInf;
10978 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10979 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10980 : UnorderedCmpOpcode,
10981 OperandVT.getScalarType().getSimpleVT()) &&
10984 (OperandVT.isVector() &&
10986 // isinf(x) --> fabs(x) == inf
10987 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10988 SDValue Inf =
10989 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10990 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10991 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10992 }
10993
10994 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10995 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10996 : UnorderedCmpOpcode,
10997 OperandVT.getSimpleVT())) {
10998 // isposinf(x) --> x == inf
10999 // isneginf(x) --> x == -inf
11000 // isposinf(x) || nan --> x u== inf
11001 // isneginf(x) || nan --> x u== -inf
11002
11003 SDValue Inf = DAG.getConstantFP(
11004 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
11005 OperandVT);
11006 return DAG.getSetCC(DL, ResultVT, Op, Inf,
11007 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
11008 }
11009
11010 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
11011 // TODO: Could handle ordered case, but it produces worse code for
11012 // x86. Maybe handle ordered if fabs is free?
11013
11014 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
11015 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
11016
11017 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
11018 OperandVT.getScalarType().getSimpleVT())) {
11019 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
11020
11021 // TODO: Maybe only makes sense if fabs is free. Integer test of
11022 // exponent bits seems better for x86.
11023 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
11024 SDValue SmallestNormal = DAG.getConstantFP(
11025 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
11026 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
11027 IsOrdered ? OrderedOp : UnorderedOp);
11028 }
11029 }
11030
11031 if (FPTestMask == fcNormal) {
11032 // TODO: Handle unordered
11033 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
11034 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
11035
11036 if (isCondCodeLegalOrCustom(IsFiniteOp,
11037 OperandVT.getScalarType().getSimpleVT()) &&
11038 isCondCodeLegalOrCustom(IsNormalOp,
11039 OperandVT.getScalarType().getSimpleVT()) &&
11040 isFAbsFree(OperandVT)) {
11041 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
11042 SDValue Inf =
11043 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
11044 SDValue SmallestNormal = DAG.getConstantFP(
11045 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
11046
11047 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
11048 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
11049 SDValue IsNormal =
11050 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
11051 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
11052 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
11053 }
11054 }
11055 }
11056
11057 // Some checks may be represented as inversion of simpler check, for example
11058 // "inf|normal|subnormal|zero" => !"nan".
11059 bool IsInverted = false;
11060
11061 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
11062 Test = InvertedCheck;
11063 IsInverted = true;
11064 }
11065
11066 // In the general case use integer operations.
11067 unsigned BitSize = OperandVT.getScalarSizeInBits();
11068 EVT IntVT = OperandVT.changeElementType(
11069 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
11070 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
11071
11072 // Various masks.
11073 APInt SignBit = APInt::getSignMask(BitSize);
11074 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
11075 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
11076 const unsigned ExplicitIntBitInF80 = 63;
11077 APInt ExpMask = Inf;
11078 if (IsF80)
11079 ExpMask.clearBit(ExplicitIntBitInF80);
11080 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
11081 APInt QNaNBitMask =
11082 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
11083 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
11084
11085 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
11086 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
11087 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
11088 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
11089 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
11090 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
11091
11092 SDValue Res;
11093 const auto appendResult = [&](SDValue PartialRes) {
11094 if (PartialRes) {
11095 if (Res)
11096 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
11097 else
11098 Res = PartialRes;
11099 }
11100 };
11101
11102 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
11103 const auto getIntBitIsSet = [&]() -> SDValue {
11104 if (!IntBitIsSetV) {
11105 APInt IntBitMask(BitSize, 0);
11106 IntBitMask.setBit(ExplicitIntBitInF80);
11107 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
11108 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
11109 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
11110 }
11111 return IntBitIsSetV;
11112 };
11113
11114 // Split the value into sign bit and absolute value.
11115 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
11116 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
11117 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
11118
11119 // Tests that involve more than one class should be processed first.
11120 SDValue PartialRes;
11121
11122 if (IsF80)
11123 ; // Detect finite numbers of f80 by checking individual classes because
11124 // they have different settings of the explicit integer bit.
11125 else if ((Test & fcFinite) == fcFinite) {
11126 // finite(V) ==> (a << 1) < (inf << 1)
11127 //
11128 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
11129 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
11130
11132 "finite check requires IEEE-like FP");
11133
11134 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
11135 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
11136 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
11137
11138 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
11139 Test &= ~fcFinite;
11140 } else if ((Test & fcFinite) == fcPosFinite) {
11141 // finite(V) && V > 0 ==> V < exp_mask
11142 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
11143 Test &= ~fcPosFinite;
11144 } else if ((Test & fcFinite) == fcNegFinite) {
11145 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
11146 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
11147 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11148 Test &= ~fcNegFinite;
11149 }
11150 appendResult(PartialRes);
11151
11152 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
11153 // fcZero | fcSubnormal => test all exponent bits are 0
11154 // TODO: Handle sign bit specific cases
11155 if (PartialCheck == (fcZero | fcSubnormal)) {
11156 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
11157 SDValue ExpIsZero =
11158 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11159 appendResult(ExpIsZero);
11160 Test &= ~PartialCheck & fcAllFlags;
11161 }
11162 }
11163
11164 // Check for individual classes.
11165
11166 if (unsigned PartialCheck = Test & fcZero) {
11167 if (PartialCheck == fcPosZero)
11168 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
11169 else if (PartialCheck == fcZero)
11170 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
11171 else // ISD::fcNegZero
11172 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
11173 appendResult(PartialRes);
11174 }
11175
11176 if (unsigned PartialCheck = Test & fcSubnormal) {
11177 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
11178 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
11179 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
11180 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
11181 SDValue VMinusOneV =
11182 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
11183 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
11184 if (PartialCheck == fcNegSubnormal)
11185 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11186 appendResult(PartialRes);
11187 }
11188
11189 if (unsigned PartialCheck = Test & fcInf) {
11190 if (PartialCheck == fcPosInf)
11191 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
11192 else if (PartialCheck == fcInf)
11193 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
11194 else { // ISD::fcNegInf
11195 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
11196 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
11197 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
11198 }
11199 appendResult(PartialRes);
11200 }
11201
11202 if (unsigned PartialCheck = Test & fcNan) {
11203 APInt InfWithQnanBit = Inf | QNaNBitMask;
11204 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
11205 if (PartialCheck == fcNan) {
11206 // isnan(V) ==> abs(V) > int(inf)
11207 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11208 if (IsF80) {
11209 // Recognize unsupported values as NaNs for compatibility with glibc.
11210 // In them (exp(V)==0) == int_bit.
11211 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
11212 SDValue ExpIsZero =
11213 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11214 SDValue IsPseudo =
11215 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
11216 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
11217 }
11218 } else if (PartialCheck == fcQNan) {
11219 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
11220 PartialRes =
11221 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
11222 } else { // ISD::fcSNan
11223 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
11224 // abs(V) < (unsigned(Inf) | quiet_bit)
11225 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11226 SDValue IsNotQnan =
11227 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
11228 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
11229 }
11230 appendResult(PartialRes);
11231 }
11232
11233 if (unsigned PartialCheck = Test & fcNormal) {
11234 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
11235 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
11236 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
11237 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
11238 APInt ExpLimit = ExpMask - ExpLSB;
11239 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
11240 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
11241 if (PartialCheck == fcNegNormal)
11242 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11243 else if (PartialCheck == fcPosNormal) {
11244 SDValue PosSignV =
11245 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
11246 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
11247 }
11248 if (IsF80)
11249 PartialRes =
11250 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
11251 appendResult(PartialRes);
11252 }
11253
11254 if (!Res)
11255 return DAG.getConstant(IsInverted, DL, ResultVT);
11256 if (IsInverted)
11257 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
11258 return Res;
11259}
11260
11261// Only expand vector types if we have the appropriate vector bit operations.
11263 assert(VT.isVector() && "Expected vector type");
11264 unsigned Len = VT.getScalarSizeInBits();
11265 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
11266 TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
11267 TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
11268 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
11269 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
11270}
11271
11273 SDLoc dl(Node);
11274 EVT VT = Node->getValueType(0);
11275 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11276 SDValue Op = Node->getOperand(0);
11277 unsigned Len = VT.getScalarSizeInBits();
11278
11279 // Compute effective bit width from known bits, allowing us to shift the
11280 // active bits down if necessary to fit into smaller specialized expansions.
11282 unsigned LZ = Known.countMinLeadingZeros();
11283 unsigned TZ = Known.countMinTrailingZeros();
11284 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
11285
11286 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
11287 unsigned EffectiveLen = Len;
11288 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
11289 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
11290
11291 assert(VT.isInteger() && "CTPOP not implemented for this type.");
11292
11293 // TODO: Add support for irregular type lengths.
11294 if (!(Len <= 128 && Len % 8 == 0))
11295 return SDValue();
11296
11297 // Only expand vector types if we have the appropriate vector bit operations.
11298 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
11299 return SDValue();
11300
11301 // If the active bits are not at the low end, shift them down
11302 if (EffectiveLen < Len && TZ > 0) {
11303 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
11304 DAG.getShiftAmountConstant(TZ, VT, dl));
11305 }
11306
11307 // This is the "best" algorithm from
11308 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
11309 SDValue Mask55 =
11310 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
11311 SDValue Mask33 =
11312 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
11313 SDValue Mask0F =
11314 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
11315
11316 // v = v - ((v >> 1) & 0x55555555...)
11317 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
11318 DAG.getNode(ISD::AND, dl, VT,
11319 DAG.getNode(ISD::SRL, dl, VT, Op,
11320 DAG.getConstant(1, dl, ShVT)),
11321 Mask55));
11322 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
11323 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
11324 DAG.getNode(ISD::AND, dl, VT,
11325 DAG.getNode(ISD::SRL, dl, VT, Op,
11326 DAG.getConstant(2, dl, ShVT)),
11327 Mask33));
11328 // v = (v + (v >> 4)) & 0x0F0F0F0F...
11329 Op = DAG.getNode(ISD::AND, dl, VT,
11330 DAG.getNode(ISD::ADD, dl, VT, Op,
11331 DAG.getNode(ISD::SRL, dl, VT, Op,
11332 DAG.getConstant(4, dl, ShVT))),
11333 Mask0F);
11334
11335 if (EffectiveLen <= 8)
11336 return Op;
11337
11338 // Avoid the multiply if we only have 2 bytes to add.
11339 // TODO: Only doing this for scalars because vectors weren't as obviously
11340 // improved.
11341 if (EffectiveLen == 16 && !VT.isVector()) {
11342 // v = (v + (v >> 8)) & 0x00FF;
11343 return DAG.getNode(ISD::AND, dl, VT,
11344 DAG.getNode(ISD::ADD, dl, VT, Op,
11345 DAG.getNode(ISD::SRL, dl, VT, Op,
11346 DAG.getConstant(8, dl, ShVT))),
11347 DAG.getConstant(0xFF, dl, VT));
11348 }
11349
11350 // v = (v * 0x01010101...) >> (Len - 8)
11351 SDValue V;
11354 SDValue Mask01 =
11355 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
11356 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
11357 } else {
11358 V = Op;
11359 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
11360 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
11361 V = DAG.getNode(ISD::ADD, dl, VT, V,
11362 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
11363 }
11364 }
11365 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
11366}
11367
11369 SDLoc dl(Node);
11370 EVT VT = Node->getValueType(0);
11371 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11372 SDValue Op = Node->getOperand(0);
11373 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11374
11375 // If the non-ZERO_POISON version is supported we can use that instead.
11376 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
11378 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
11379
11380 // If the ZERO_POISON version is supported use that and handle the zero case.
11382 EVT SetCCVT =
11383 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11384 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
11385 SDValue Zero = DAG.getConstant(0, dl, VT);
11386 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11387 return DAG.getSelect(dl, VT, SrcIsZero,
11388 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
11389 }
11390
11391 // Only expand vector types if we have the appropriate vector bit operations.
11392 // This includes the operations needed to expand CTPOP if it isn't supported.
11393 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11395 !canExpandVectorCTPOP(*this, VT)) ||
11398 return SDValue();
11399
11400 // for now, we do this:
11401 // x = x | (x >> 1);
11402 // x = x | (x >> 2);
11403 // ...
11404 // x = x | (x >>16);
11405 // x = x | (x >>32); // for 64-bit input
11406 // return popcount(~x);
11407 //
11408 // Ref: "Hacker's Delight" by Henry Warren
11409 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
11410 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
11411 Op = DAG.getNode(ISD::OR, dl, VT, Op,
11412 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
11413 }
11414 Op = DAG.getNOT(dl, Op, VT);
11415 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
11416}
11417
11419 SDLoc dl(Node);
11420 EVT VT = Node->getValueType(0);
11421 SDValue Op = DAG.getFreeze(Node->getOperand(0));
11422 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11423
11424 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
11425 // This transforms the sign bits into leading zeros that can be counted.
11426 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
11427 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
11428 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
11429 SDValue Shl =
11430 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11431 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
11432 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
11433}
11434
11436 const SDLoc &DL, EVT VT, SDValue Op,
11437 unsigned BitWidth) const {
11438 if (BitWidth != 32 && BitWidth != 64)
11439 return SDValue();
11440
11441 const DataLayout &TD = DAG.getDataLayout();
11443 return SDValue();
11444
11445 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
11446 : APInt(64, 0x0218A392CD3D5DBFULL);
11447 MachinePointerInfo PtrInfo =
11449 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
11450 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11451 SDValue Lookup = DAG.getNode(
11452 ISD::SRL, DL, VT,
11453 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
11454 DAG.getConstant(DeBruijn, DL, VT)),
11455 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11457
11459 for (unsigned i = 0; i < BitWidth; i++) {
11460 APInt Shl = DeBruijn.shl(i);
11461 APInt Lshr = Shl.lshr(ShiftAmt);
11462 Table[Lshr.getZExtValue()] = i;
11463 }
11464
11465 // Create a ConstantArray in Constant Pool
11466 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11467 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11468 TD.getPrefTypeAlign(CA->getType()));
11469 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11470 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11471 PtrInfo, MVT::i8);
11472 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11473 return ExtLoad;
11474
11475 EVT SetCCVT =
11476 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11477 SDValue Zero = DAG.getConstant(0, DL, VT);
11478 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11479 return DAG.getSelect(DL, VT, SrcIsZero,
11480 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11481}
11482
11484 SDLoc dl(Node);
11485 EVT VT = Node->getValueType(0);
11486 SDValue Op = Node->getOperand(0);
11487 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11488
11489 // If the non-ZERO_POISON version is supported we can use that instead.
11490 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11492 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11493
11494 // If the ZERO_POISON version is supported use that and handle the zero case.
11496 EVT SetCCVT =
11497 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11498 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11499 SDValue Zero = DAG.getConstant(0, dl, VT);
11500 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11501 return DAG.getSelect(dl, VT, SrcIsZero,
11502 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11503 }
11504
11505 // Only expand vector types if we have the appropriate vector bit operations.
11506 // This includes the operations needed to expand CTPOP if it isn't supported.
11507 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11510 !canExpandVectorCTPOP(*this, VT)) ||
11514 return SDValue();
11515
11516 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11517 // to be expanded or converted to a libcall.
11520 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11521 return V;
11522
11523 bool UseCTLZ =
11525
11526 // When only ctlz is available and the operand is nonzero we can use:
11527 // { return nlz(x & -x) ^ 31; }
11528 // which is more efficient than:
11529 // { return 32 - nlz(~x & (x - 1)); }.
11530 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11531 SDValue LowestBit =
11532 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11533 return DAG.getNode(ISD::XOR, dl, VT,
11534 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11535 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11536 }
11537
11538 // If ctpop is available, we use:
11539 // { return popcount(~x & (x-1)); }
11540 // If the target has ctlz but not ctpop, we use:
11541 // { return 32 - nlz(~x & (x-1)); }
11542 // Ref: "Hacker's Delight" by Henry Warren
11543 SDValue Tmp = DAG.getNode(
11544 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11545 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11546
11547 if (UseCTLZ)
11548 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11549 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11550
11551 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11552}
11553
11555 SelectionDAG &DAG) const {
11556 // %cond = to_bool_vec %source
11557 // %splat = splat /*val=*/VL
11558 // %tz = step_vector
11559 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11560 // %r = vp.reduce.umin %v
11561 SDLoc DL(N);
11562 SDValue Source = N->getOperand(0);
11563 SDValue Mask = N->getOperand(1);
11564 SDValue EVL = N->getOperand(2);
11565 EVT SrcVT = Source.getValueType();
11566 EVT ResVT = N->getValueType(0);
11567 EVT ResVecVT =
11568 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11569
11570 // Convert to boolean vector.
11571 if (SrcVT.getScalarType() != MVT::i1) {
11572 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11573 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11574 SrcVT.getVectorElementCount());
11575 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11576 }
11577
11578 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11579 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11580 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11581 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11582 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11583}
11584
11585/// Returns a type-legalized version of \p Mask as the first item in the
11586/// pair. The second item contains a type-legalized step vector that's
11587/// guaranteed to fit the number of elements in \p Mask.
11588/// If the stepvector would require splitting, returns an empty SDValue
11589/// as the second item to signal that the operation should be split instead.
11590static std::pair<SDValue, SDValue>
11592 SelectionDAG &DAG) {
11593 EVT MaskVT = Mask.getValueType();
11594 EVT BoolVT = MaskVT.getScalarType();
11595
11596 // Find a suitable type for a stepvector.
11597 // If zero is poison, we can assume the upper limit of the result is VF-1.
11598 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11599 if (MaskVT.isScalableVector())
11600 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11602 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11603 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11604 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11605 // If the step vector element type is smaller than the mask element type,
11606 // use the mask type directly to avoid widening issues.
11607 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11608 EVT StepVT = MVT::getIntegerVT(EltWidth);
11609 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11610
11611 // If promotion or widening is required to make the type legal, do it here.
11612 // Promotion of integers within LegalizeVectorOps is looking for types of
11613 // the same size but with a smaller number of larger elements, not the usual
11614 // larger size with the same number of larger elements.
11616 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11617 SDValue StepVec;
11618 if (TypeAction == TargetLowering::TypePromoteInteger) {
11619 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11620 StepVec = DAG.getStepVector(DL, StepVecVT);
11621 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11622 // For widening, the element count changes. Create a step vector with only
11623 // the original elements valid and zeros for padding. Also widen the mask.
11624 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11625 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11626
11627 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11628 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11629 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11630 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11631
11632 // Widen mask: pad with zeros.
11633 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11634 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11635 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11636 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11637 // The stepvector type would require splitting. Signal to the caller
11638 // that the operation should be split instead of expanded.
11639 return {Mask, SDValue()};
11640 } else {
11641 StepVec = DAG.getStepVector(DL, StepVecVT);
11642 }
11643
11644 return {Mask, StepVec};
11645}
11646
11648 SelectionDAG &DAG) const {
11649 SDLoc DL(N);
11650 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11651 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11652
11653 // If StepVec is empty, the stepvector would require splitting.
11654 // Split the operation instead and let it be recursively legalized.
11655 if (!StepVec) {
11656 EVT MaskVT = N->getOperand(0).getValueType();
11657 EVT ResVT = N->getValueType(0);
11658
11659 // Split the mask
11660 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11661 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11662
11663 // Create split VECTOR_FIND_LAST_ACTIVE operations
11664 SDValue LoResult =
11665 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11666 SDValue HiResult =
11667 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11668
11669 // Check if any lane is active in the high mask.
11670 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11672 AnyHiActive, DL,
11673 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11674 MVT::i1);
11675
11676 // Adjust HiResult by adding the number of elements in Lo
11677 SDValue LoNumElts =
11678 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11679 SDValue AdjustedHiResult =
11680 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11681
11682 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11683 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11684 LoResult);
11685 }
11686
11687 EVT StepVecVT = StepVec.getValueType();
11688 EVT StepVT = StepVec.getValueType().getVectorElementType();
11689
11690 // Zero out lanes with inactive elements, then find the highest remaining
11691 // value from the stepvector.
11692 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11693 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11694 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11695 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11696}
11697
11699 SelectionDAG &DAG) const {
11700 SDLoc DL(N);
11701
11702 SDValue Start = N->getOperand(0);
11703 SDValue End = N->getOperand(1);
11704 EVT VT = N->getValueType(0);
11705 EVT OpVT = Start.getValueType();
11706
11707 auto [Mask, StepVector] = getLegalMaskAndStepVector(
11708 DAG.getPOISON(VT), /*ZeroIsPoison=*/false, DL, DAG);
11709
11710 // No legal step vector: split the mask in half and recombine the results.
11711 // Lo = get_active_lane_mask Start, End
11712 // Hi = get_active_lane_mask (uaddsat Start, LoNumElts), End
11713 if (!StepVector) {
11714 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
11715 SDValue Lo = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, LoVT, Start, End);
11716 SDValue LoNumElts =
11717 DAG.getElementCount(DL, OpVT, LoVT.getVectorElementCount());
11718 SDValue HiStart = DAG.getNode(ISD::UADDSAT, DL, OpVT, Start, LoNumElts);
11719 SDValue Hi = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, HiVT, HiStart, End);
11720 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
11721 }
11722
11723 // Rebase and saturate the termination value.
11724 SDValue Max =
11725 DAG.getConstant(maxUIntN(std::min(StepVector.getScalarValueSizeInBits(),
11726 OpVT.getScalarSizeInBits())),
11727 DL, OpVT);
11728 End = DAG.getNode(ISD::USUBSAT, DL, OpVT, End, Start);
11729 End = DAG.getNode(ISD::UMIN, DL, OpVT, End, Max);
11730 End = DAG.getZExtOrTrunc(End, DL, StepVector.getValueType().getScalarType());
11731
11732 // cmp <0, 1, 2, 3...>, End
11733 SDValue EndV = DAG.getSplat(StepVector.getValueType(), DL, End);
11734 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11735 StepVector.getValueType());
11736 SDValue Cmp = DAG.getSetCC(DL, CCVT, StepVector, EndV, ISD::SETULT);
11737 SDValue Res = DAG.getBoolExtOrTrunc(Cmp, DL, Mask.getValueType(),
11738 StepVector.getValueType());
11739 if (Mask.getValueType() != VT)
11740 Res = DAG.getExtractSubvector(DL, VT, Res, 0);
11741 return Res;
11742}
11743
11745 SelectionDAG &DAG) const {
11746 SDLoc DL(N);
11747 EVT VT = N->getValueType(0);
11748 SDValue SourceValue = N->getOperand(0);
11749 SDValue SinkValue = N->getOperand(1);
11750 SDValue EltSizeInBytes = N->getOperand(2);
11751
11752 // Note: The lane offset is scalable if the mask is scalable.
11753 ElementCount LaneOffsetEC =
11754 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11755
11756 EVT AddrVT = SourceValue->getValueType(0);
11757 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11758
11759 EVT CmpVT =
11760 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11761
11762 // Unsigned compare: Source >= Sink.
11763 SDValue SourceAheadOfOrEqualToSink =
11764 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11765
11766 // Take the difference between the pointers and divided by the element size,
11767 // to see how many lanes separate them.
11768 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11769
11770 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11771 if (IsReadAfterWrite)
11772 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11773 DAG.getNegative(Diff, DL, AddrVT), Diff);
11774
11775 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11776
11777 // The pointers do not alias if:
11778 // - Source >= Sink (WAR_MASK)
11779 // - Source == Sink (RAW_MASK)
11780 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11781 if (IsReadAfterWrite)
11782 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11783
11784 // The pointers do not alias if:
11785 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11786 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11787 SDValue MaskN = DAG.getSelect(
11788 DL, AddrVT, NoAlias,
11790 AddrVT),
11791 Diff);
11792
11793 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11794}
11795
11797 bool IsNegative) const {
11798 SDLoc dl(N);
11799 EVT VT = N->getValueType(0);
11800 SDValue Op = N->getOperand(0);
11801
11802 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11803 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11805 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11806 if (IsNegative)
11807 return DAG.getNegative(AbsVal, dl, VT);
11808 return AbsVal;
11809 }
11810
11811 // abs(x) -> smax(x,sub(0,x))
11812 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11814 SDValue Zero = DAG.getConstant(0, dl, VT);
11815 Op = DAG.getFreeze(Op);
11816 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11817 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11818 }
11819
11820 // abs(x) -> umin(x,sub(0,x))
11821 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11823 SDValue Zero = DAG.getConstant(0, dl, VT);
11824 Op = DAG.getFreeze(Op);
11825 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11826 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11827 }
11828
11829 // 0 - abs(x) -> smin(x, sub(0,x))
11830 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11832 SDValue Zero = DAG.getConstant(0, dl, VT);
11833 Op = DAG.getFreeze(Op);
11834 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11835 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11836 }
11837
11838 // Only expand vector types if we have the appropriate vector operations.
11839 if (VT.isVector() &&
11841 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11842 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11844 return SDValue();
11845
11846 Op = DAG.getFreeze(Op);
11847 SDValue Shift = DAG.getNode(
11848 ISD::SRA, dl, VT, Op,
11849 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11850 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11851
11852 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11853 if (!IsNegative)
11854 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11855
11856 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11857 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11858}
11859
11861 SDLoc dl(N);
11862 EVT VT = N->getValueType(0);
11863 SDValue LHS = N->getOperand(0);
11864 SDValue RHS = N->getOperand(1);
11865 bool IsSigned = N->getOpcode() == ISD::ABDS;
11866
11867 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11868 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11869 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11870 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11871 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11872 LHS = DAG.getFreeze(LHS);
11873 RHS = DAG.getFreeze(RHS);
11874 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11875 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11876 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11877 }
11878
11879 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11880 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11881 LHS = DAG.getFreeze(LHS);
11882 RHS = DAG.getFreeze(RHS);
11883 return DAG.getNode(ISD::OR, dl, VT,
11884 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11885 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11886 }
11887
11888 // abds: if the sub is nsw -> abs(sub)
11889 // abdu with non-negative operands -> abs(sub)
11890 // The abdu case where the sub is nuw is handled in DAGCombine.
11891 if (IsSigned) {
11892 if (DAG.willNotOverflowSub(/*IsSigned=*/true, LHS, RHS))
11893 return DAG.getNode(ISD::ABS, dl, VT,
11894 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11895
11896 if (DAG.willNotOverflowSub(/*IsSigned=*/true, RHS, LHS))
11897 return DAG.getNode(ISD::ABS, dl, VT,
11898 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11899 } else if (DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS)) {
11900 return DAG.getNode(ISD::ABS, dl, VT,
11901 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11902 }
11903
11904 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11906 LHS = DAG.getFreeze(LHS);
11907 RHS = DAG.getFreeze(RHS);
11908 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11909
11910 // Branchless expansion iff cmp result is allbits:
11911 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11912 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11913 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11914 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11915 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11916 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11917 }
11918
11919 // Similar to the branchless expansion, if we don't prefer selects, use the
11920 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11921 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11922 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11923 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11925 SDValue USubO =
11926 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11927 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11928 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11929 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11930 }
11931
11932 // FIXME: Should really try to split the vector in case it's legal on a
11933 // subvector.
11935 return DAG.UnrollVectorOp(N);
11936
11937 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11938 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11939 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11940 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11941}
11942
11944 SDLoc dl(N);
11945 EVT VT = N->getValueType(0);
11946 SDValue LHS = N->getOperand(0);
11947 SDValue RHS = N->getOperand(1);
11948
11949 unsigned Opc = N->getOpcode();
11950 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11951 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11952 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11953 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11954 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11955 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11957 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11958 "Unknown AVG node");
11959
11960 // If the operands are already extended, we can add+shift.
11961 bool IsExt =
11962 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11963 DAG.ComputeNumSignBits(RHS) >= 2) ||
11964 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11965 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11966 if (IsExt) {
11967 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11968 if (!IsFloor)
11969 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11970 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11971 DAG.getShiftAmountConstant(1, VT, dl));
11972 }
11973
11974 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11975 if (VT.isScalarInteger()) {
11976 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11977 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11978 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11979 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11980 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11981 if (!IsFloor)
11982 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11983 DAG.getConstant(1, dl, ExtVT));
11984 // Just use SRL as we will be truncating away the extended sign bits.
11985 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11986 DAG.getShiftAmountConstant(1, ExtVT, dl));
11987 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11988 }
11989 }
11990
11991 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11992 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11995 SDValue UAddWithOverflow =
11996 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11997
11998 SDValue Sum = UAddWithOverflow.getValue(0);
11999 SDValue Overflow = UAddWithOverflow.getValue(1);
12000
12001 // Right shift the sum by 1
12002 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
12003 DAG.getShiftAmountConstant(1, VT, dl));
12004
12005 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
12006 SDValue OverflowShl = DAG.getNode(
12007 ISD::SHL, dl, VT, ZeroExtOverflow,
12008 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
12009
12010 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
12011 }
12012
12013 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
12014 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
12015 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
12016 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
12017 LHS = DAG.getFreeze(LHS);
12018 RHS = DAG.getFreeze(RHS);
12019 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
12020 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
12021 SDValue Shift =
12022 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
12023 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
12024}
12025
12027 SDLoc dl(N);
12028 EVT VT = N->getValueType(0);
12029 SDValue Op = N->getOperand(0);
12030
12031 if (!VT.isSimple())
12032 return SDValue();
12033
12034 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
12035 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
12036 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
12037 default:
12038 return SDValue();
12039 case MVT::i16:
12040 // Use a rotate by 8. This can be further expanded if necessary.
12041 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12042 case MVT::i32:
12043 // This is meant for ARM specifically, which has ROTR but no ROTL.
12044 // t = x ^ rotr(x, 16)
12045 // t = bic(t, 0x00ff0000)
12046 // t = lshr(t, 8)
12047 // x = t ^ rotr(x, 8)
12049 SDValue Rotr16 =
12050 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
12051 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
12052 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
12053 DAG.getConstant(0xFF00FFFF, dl, VT));
12054 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
12055 SDValue Rotr8 =
12056 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12057 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
12058 }
12059 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12060 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
12061 DAG.getConstant(0xFF00, dl, VT));
12062 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
12063 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12064 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
12065 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12066 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
12067 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
12068 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
12069 case MVT::i64:
12070 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
12071 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
12072 DAG.getConstant(255ULL<<8, dl, VT));
12073 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
12074 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
12075 DAG.getConstant(255ULL<<16, dl, VT));
12076 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
12077 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
12078 DAG.getConstant(255ULL<<24, dl, VT));
12079 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
12080 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12081 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
12082 DAG.getConstant(255ULL<<24, dl, VT));
12083 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12084 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
12085 DAG.getConstant(255ULL<<16, dl, VT));
12086 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
12087 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
12088 DAG.getConstant(255ULL<<8, dl, VT));
12089 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
12090 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
12091 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
12092 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
12093 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
12094 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
12095 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
12096 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
12097 }
12098}
12099
12101 SDLoc dl(N);
12102 EVT VT = N->getValueType(0);
12103 SDValue Op = N->getOperand(0);
12104 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
12105 unsigned Sz = VT.getScalarSizeInBits();
12106
12107 SDValue Tmp, Tmp2, Tmp3;
12108
12109 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
12110 // and finally the i1 pairs.
12111 // TODO: We can easily support i4/i2 legal types if any target ever does.
12112 if (Sz >= 8 && isPowerOf2_32(Sz)) {
12113 // Create the masks - repeating the pattern every byte.
12114 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
12115 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
12116 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
12117
12118 // BSWAP if the type is wider than a single byte.
12119 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
12120
12121 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
12122 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
12123 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
12124 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
12125 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
12126 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12127
12128 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
12129 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
12130 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
12131 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
12132 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
12133 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12134
12135 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
12136 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
12137 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
12138 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
12139 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
12140 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12141 return Tmp;
12142 }
12143
12144 Tmp = DAG.getConstant(0, dl, VT);
12145 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
12146 if (I < J)
12147 Tmp2 =
12148 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
12149 else
12150 Tmp2 =
12151 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
12152
12153 APInt Shift = APInt::getOneBitSet(Sz, J);
12154 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
12155 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
12156 }
12157
12158 return Tmp;
12159}
12160
12161std::pair<SDValue, SDValue>
12163 SelectionDAG &DAG) const {
12164 SDLoc SL(LD);
12165 SDValue Chain = LD->getChain();
12166 SDValue BasePTR = LD->getBasePtr();
12167 EVT SrcVT = LD->getMemoryVT();
12168 EVT DstVT = LD->getValueType(0);
12169 ISD::LoadExtType ExtType = LD->getExtensionType();
12170
12171 if (SrcVT.isScalableVector())
12172 report_fatal_error("Cannot scalarize scalable vector loads");
12173
12174 unsigned NumElem = SrcVT.getVectorNumElements();
12175
12176 EVT SrcEltVT = SrcVT.getScalarType();
12177 EVT DstEltVT = DstVT.getScalarType();
12178
12179 // A vector must always be stored in memory as-is, i.e. without any padding
12180 // between the elements, since various code depend on it, e.g. in the
12181 // handling of a bitcast of a vector type to int, which may be done with a
12182 // vector store followed by an integer load. A vector that does not have
12183 // elements that are byte-sized must therefore be stored as an integer
12184 // built out of the extracted vector elements.
12185 if (!SrcEltVT.isByteSized()) {
12186 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
12187 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
12188
12189 unsigned NumSrcBits = SrcVT.getSizeInBits();
12190 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
12191
12192 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
12193 SDValue SrcEltBitMask = DAG.getConstant(
12194 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
12195
12196 // Load the whole vector and avoid masking off the top bits as it makes
12197 // the codegen worse.
12198 SDValue Load = DAG.getExtLoad(
12199 ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, LD->getPointerInfo(),
12200 SrcIntVT, LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12201 LD->getMMOMetadataForSubAccess());
12202
12204 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12205 unsigned ShiftIntoIdx =
12206 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12207 SDValue ShiftAmount = DAG.getShiftAmountConstant(
12208 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
12209 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
12210 SDValue Elt =
12211 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
12212 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
12213
12214 if (ExtType != ISD::NON_EXTLOAD) {
12215 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
12216 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
12217 }
12218
12219 Vals.push_back(Scalar);
12220 }
12221
12222 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12223 return std::make_pair(Value, Load.getValue(1));
12224 }
12225
12226 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
12227 assert(SrcEltVT.isByteSized());
12228
12230 SmallVector<SDValue, 8> LoadChains;
12231
12232 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12233 SDValue ScalarLoad = DAG.getExtLoad(
12234 ExtType, SL, DstEltVT, Chain, BasePTR,
12235 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
12236 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12237 LD->getMMOMetadataForSubAccess());
12238
12239 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
12240
12241 Vals.push_back(ScalarLoad.getValue(0));
12242 LoadChains.push_back(ScalarLoad.getValue(1));
12243 }
12244
12245 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
12246 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12247
12248 return std::make_pair(Value, NewChain);
12249}
12250
12252 SelectionDAG &DAG) const {
12253 SDLoc SL(ST);
12254
12255 SDValue Chain = ST->getChain();
12256 SDValue BasePtr = ST->getBasePtr();
12257 SDValue Value = ST->getValue();
12258 EVT StVT = ST->getMemoryVT();
12259
12260 if (StVT.isScalableVector())
12261 report_fatal_error("Cannot scalarize scalable vector stores");
12262
12263 // The type of the data we want to save
12264 EVT RegVT = Value.getValueType();
12265 EVT RegSclVT = RegVT.getScalarType();
12266
12267 // The type of data as saved in memory.
12268 EVT MemSclVT = StVT.getScalarType();
12269
12270 unsigned NumElem = StVT.getVectorNumElements();
12271
12272 // A vector must always be stored in memory as-is, i.e. without any padding
12273 // between the elements, since various code depend on it, e.g. in the
12274 // handling of a bitcast of a vector type to int, which may be done with a
12275 // vector store followed by an integer load. A vector that does not have
12276 // elements that are byte-sized must therefore be stored as an integer
12277 // built out of the extracted vector elements.
12278 if (!MemSclVT.isByteSized()) {
12279 unsigned NumBits = StVT.getSizeInBits();
12280 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
12281
12282 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
12283
12284 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12285 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12286 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
12287 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
12288 unsigned ShiftIntoIdx =
12289 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12290 SDValue ShiftAmount =
12291 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
12292 SDValue ShiftedElt =
12293 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
12294 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
12295 }
12296
12297 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
12298 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12299 ST->getMMOMetadataForSubAccess());
12300 }
12301
12302 // Store Stride in bytes
12303 unsigned Stride = MemSclVT.getSizeInBits() / 8;
12304 assert(Stride && "Zero stride!");
12305 // Extract each of the elements from the original vector and save them into
12306 // memory individually.
12308 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12309 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12310
12311 SDValue Ptr =
12312 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
12313
12314 // This scalar TruncStore may be illegal, but we legalize it later.
12316 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
12317 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12318 ST->getMMOMetadataForSubAccess());
12319
12320 Stores.push_back(Store);
12321 }
12322
12323 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
12324}
12325
12326std::pair<SDValue, SDValue>
12328 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
12329 "unaligned indexed loads not implemented!");
12330 SDValue Chain = LD->getChain();
12331 SDValue Ptr = LD->getBasePtr();
12332 EVT VT = LD->getValueType(0);
12333 EVT LoadedVT = LD->getMemoryVT();
12334 SDLoc dl(LD);
12335 auto &MF = DAG.getMachineFunction();
12336
12337 if (VT.isFloatingPoint() || VT.isVector()) {
12338 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
12339 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
12340 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
12341 LoadedVT.isVector()) {
12342 // Scalarize the load and let the individual components be handled.
12343 return scalarizeVectorLoad(LD, DAG);
12344 }
12345
12346 // Expand to a (misaligned) integer load of the same size,
12347 // then bitconvert to floating point or vector.
12348 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
12349 LD->getMemOperand());
12350 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
12351 if (LoadedVT != VT)
12352 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
12353 ISD::ANY_EXTEND, dl, VT, Result);
12354
12355 return std::make_pair(Result, newLoad.getValue(1));
12356 }
12357
12358 // Copy the value to a (aligned) stack slot using (unaligned) integer
12359 // loads and stores, then do a (aligned) load from the stack slot.
12360 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
12361 unsigned LoadedBytes = LoadedVT.getStoreSize();
12362 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12363 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
12364
12365 // Make sure the stack slot is also aligned for the register type.
12366 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
12367 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
12369 SDValue StackPtr = StackBase;
12370 unsigned Offset = 0;
12371
12372 EVT PtrVT = Ptr.getValueType();
12373 EVT StackPtrVT = StackPtr.getValueType();
12374
12375 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12376 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12377
12378 // Do all but one copies using the full register width.
12379 for (unsigned i = 1; i < NumRegs; i++) {
12380 // Load one integer register's worth from the original location.
12381 SDValue Load = DAG.getLoad(
12382 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12383 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12384 LD->getMMOMetadataForSubAccess());
12385 // Follow the load with a store to the stack slot. Remember the store.
12386 Stores.push_back(DAG.getStore(
12387 Load.getValue(1), dl, Load, StackPtr,
12388 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12389 // Increment the pointers.
12390 Offset += RegBytes;
12391
12392 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12393 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12394 }
12395
12396 // The last copy may be partial. Do an extending load.
12397 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12398 8 * (LoadedBytes - Offset));
12399 SDValue Load = DAG.getExtLoad(
12400 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12401 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12402 LD->getMemOperand()->getFlags(), LD->getMMOMetadataForSubAccess());
12403 // Follow the load with a store to the stack slot. Remember the store.
12404 // On big-endian machines this requires a truncating store to ensure
12405 // that the bits end up in the right place.
12406 Stores.push_back(DAG.getTruncStore(
12407 Load.getValue(1), dl, Load, StackPtr,
12408 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12409
12410 // The order of the stores doesn't matter - say it with a TokenFactor.
12411 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12412
12413 // Finally, perform the original load only redirected to the stack slot.
12414 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12415 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12416 LoadedVT);
12417
12418 // Callers expect a MERGE_VALUES node.
12419 return std::make_pair(Load, TF);
12420 }
12421
12422 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12423 "Unaligned load of unsupported type.");
12424
12425 // Compute the new VT that is half the size of the old one. This is an
12426 // integer MVT.
12427 unsigned NumBits = LoadedVT.getSizeInBits();
12428 EVT NewLoadedVT;
12429 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12430 NumBits >>= 1;
12431
12432 Align Alignment = LD->getBaseAlign();
12433 unsigned IncrementSize = NumBits / 8;
12434 ISD::LoadExtType HiExtType = LD->getExtensionType();
12435
12436 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12437 if (HiExtType == ISD::NON_EXTLOAD)
12438 HiExtType = ISD::ZEXTLOAD;
12439
12440 // Load the value in two parts
12441 SDValue Lo, Hi;
12442 if (DAG.getDataLayout().isLittleEndian()) {
12443 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12444 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12445 LD->getMMOMetadataForSubAccess());
12446
12447 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12448 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12449 LD->getPointerInfo().getWithOffset(IncrementSize),
12450 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12451 LD->getMMOMetadataForSubAccess());
12452 } else {
12453 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12454 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12455 LD->getMMOMetadataForSubAccess());
12456
12457 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12458 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12459 LD->getPointerInfo().getWithOffset(IncrementSize),
12460 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12461 LD->getMMOMetadataForSubAccess());
12462 }
12463
12464 // aggregate the two parts
12465 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12466 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12467 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12468
12469 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12470 Hi.getValue(1));
12471
12472 return std::make_pair(Result, TF);
12473}
12474
12476 SelectionDAG &DAG) const {
12477 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12478 "unaligned indexed stores not implemented!");
12479 SDValue Chain = ST->getChain();
12480 SDValue Ptr = ST->getBasePtr();
12481 SDValue Val = ST->getValue();
12482 EVT VT = Val.getValueType();
12483 Align Alignment = ST->getBaseAlign();
12484 auto &MF = DAG.getMachineFunction();
12485 EVT StoreMemVT = ST->getMemoryVT();
12486
12487 SDLoc dl(ST);
12488 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12489 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12490 if (isTypeLegal(intVT)) {
12491 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12492 StoreMemVT.isVector()) {
12493 // Scalarize the store and let the individual components be handled.
12494 SDValue Result = scalarizeVectorStore(ST, DAG);
12495 return Result;
12496 }
12497 // Expand to a bitconvert of the value to the integer type of the
12498 // same size, then a (misaligned) int store.
12499 // FIXME: Does not handle truncating floating point stores!
12500 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12501 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12502 Alignment, ST->getMemOperand()->getFlags(),
12503 ST->getMMOMetadataForSubAccess());
12504 return Result;
12505 }
12506 // Do a (aligned) store to a stack slot, then copy from the stack slot
12507 // to the final destination using (unaligned) integer loads and stores.
12508 MVT RegVT = getRegisterType(
12509 *DAG.getContext(),
12510 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12511 EVT PtrVT = Ptr.getValueType();
12512 unsigned StoredBytes = StoreMemVT.getStoreSize();
12513 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12514 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12515
12516 // Make sure the stack slot is also aligned for the register type.
12517 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12518 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12519
12520 // Perform the original store, only redirected to the stack slot.
12522 Chain, dl, Val, StackPtr,
12523 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12524
12525 EVT StackPtrVT = StackPtr.getValueType();
12526
12527 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12528 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12530 unsigned Offset = 0;
12531
12532 // Do all but one copies using the full register width.
12533 for (unsigned i = 1; i < NumRegs; i++) {
12534 // Load one integer register's worth from the stack slot.
12535 SDValue Load = DAG.getLoad(
12536 RegVT, dl, Store, StackPtr,
12537 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12538 // Store it to the final location. Remember the store.
12539 Stores.push_back(DAG.getStore(
12540 Load.getValue(1), dl, Load, Ptr,
12541 ST->getPointerInfo().getWithOffset(Offset), ST->getBaseAlign(),
12542 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess()));
12543 // Increment the pointers.
12544 Offset += RegBytes;
12545 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12546 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12547 }
12548
12549 // The last store may be partial. Do a truncating store. On big-endian
12550 // machines this requires an extending load from the stack slot to ensure
12551 // that the bits are in the right place.
12552 EVT LoadMemVT =
12553 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12554
12555 // Load from the stack slot.
12556 SDValue Load = DAG.getExtLoad(
12557 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12558 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12559
12560 Stores.push_back(
12561 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
12562 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12563 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12564 ST->getMMOMetadataForSubAccess()));
12565 // The order of the stores doesn't matter - say it with a TokenFactor.
12566 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12567 return Result;
12568 }
12569
12570 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12571 "Unaligned store of unknown type.");
12572 // Get the half-size VT
12573 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12574 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12575 unsigned IncrementSize = NumBits / 8;
12576
12577 // Divide the stored value in two parts.
12578 SDValue ShiftAmount =
12579 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12580 SDValue Lo = Val;
12581 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12582 // fold and not use the upper bits. A smaller constant may be easier to
12583 // materialize.
12584 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12585 Lo = DAG.getNode(
12586 ISD::AND, dl, VT, Lo,
12587 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12588 VT));
12589 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12590
12591 // Store the two parts
12592 SDValue Store1, Store2;
12593 Store1 = DAG.getTruncStore(
12594 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Lo : Hi, Ptr,
12595 ST->getPointerInfo(), NewStoredVT, Alignment,
12596 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12597
12598 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12599 Store2 = DAG.getTruncStore(
12600 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12601 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12602 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12603
12604 SDValue Result =
12605 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12606 return Result;
12607}
12608
12609SDValue
12611 const SDLoc &DL, EVT DataVT,
12612 SelectionDAG &DAG,
12613 bool IsCompressedMemory) const {
12615 EVT AddrVT = Addr.getValueType();
12616 EVT MaskVT = Mask.getValueType();
12617 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12618 "Incompatible types of Data and Mask");
12619 if (IsCompressedMemory) {
12620 // Incrementing the pointer according to number of '1's in the mask.
12621 if (DataVT.isScalableVector()) {
12622 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12623 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12624 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12625 } else {
12626 EVT MaskIntVT =
12627 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12628 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12629 if (MaskIntVT.getSizeInBits() < 32) {
12630 MaskInIntReg =
12631 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12632 MaskIntVT = MVT::i32;
12633 }
12634 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12635 }
12636 // Scale is an element size in bytes.
12637 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12638 AddrVT);
12639 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12640 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12641 } else
12642 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12643
12644 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12645}
12646
12648 EVT VecVT, const SDLoc &DL,
12649 ElementCount SubEC) {
12650 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12651 "Cannot index a scalable vector within a fixed-width vector");
12652 ElementCount NElts = VecVT.getVectorElementCount();
12653 EVT IdxVT = Idx.getValueType();
12654
12655 // Attempt to prove all accessed lanes sit within VecVT.
12656 ElementCount IdxAsEC;
12657 if (sd_match(Idx, m_ElementCount(IdxAsEC))) {
12658 if (SubEC.isScalar() && ElementCount::isKnownLT(IdxAsEC, NElts))
12659 return Idx;
12660 // Calculate end index as TypeSize to remove possibility of overflow.
12661 if (IdxAsEC.isScalable() == SubEC.isScalable() &&
12662 TypeSize::isKnownLE(TypeSize(IdxAsEC) + TypeSize(SubEC),
12663 TypeSize(NElts)))
12664 return Idx;
12665 }
12666
12667 // Can we mask Idx rather than clamp it.
12668 if (SubEC.isScalar() && NElts.isPowerOf2()) {
12669 SDValue EC = DAG.getElementCount(DL, IdxVT, NElts);
12670 SDValue Mask =
12671 DAG.getNode(ISD::SUB, DL, IdxVT, EC, DAG.getConstant(1, DL, IdxVT));
12672 return DAG.getNode(ISD::AND, DL, IdxVT, Idx, Mask);
12673 }
12674
12675 unsigned SubOpcode =
12677 SDValue MaxSafeIndex =
12678 DAG.getNode(SubOpcode, DL, IdxVT, DAG.getElementCount(DL, IdxVT, NElts),
12679 DAG.getElementCount(DL, IdxVT, SubEC));
12680 return DAG.getNode(ISD::UMIN, DL, IdxVT, Idx, MaxSafeIndex);
12681}
12682
12683SDValue
12685 EVT VecVT, SDValue Index,
12686 const SDNodeFlags PtrArithFlags) const {
12688 DAG, VecPtr, VecVT,
12690 Index, PtrArithFlags);
12691}
12692
12693SDValue
12695 EVT VecVT, EVT SubVecVT, SDValue Index,
12696 const SDNodeFlags PtrArithFlags) const {
12697 SDLoc dl(Index);
12698 // Make sure the index type is big enough to compute in.
12699 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12700
12701 EVT EltVT = VecVT.getVectorElementType();
12702
12703 // Calculate the element offset and add it to the pointer.
12704 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12705 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12706 "Converting bits to bytes lost precision");
12707 assert(SubVecVT.getVectorElementType() == EltVT &&
12708 "Sub-vector must be a vector with matching element type");
12709 assert((SubVecVT.getVectorElementCount().isScalar() ||
12710 isa<ConstantSDNode>(Index)) &&
12711 "Subvector Index must be constant!");
12712
12713 // An out-of-range index only makes the vector operation return poison, but
12714 // a load/store through the pointer computed below would be immediate UB, so
12715 // freeze the index before clamping it into range.
12716 Index = DAG.getFreeze(Index, UndefPoisonKind::PoisonOnly);
12717
12718 EVT IdxVT = Index.getValueType();
12719 if (SubVecVT.isScalableVector())
12720 Index =
12721 DAG.getVScale(dl, IdxVT, cast<ConstantSDNode>(Index)->getAPIntValue());
12722
12723 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12724 SubVecVT.getVectorElementCount());
12725 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12726 DAG.getConstant(EltSize, dl, IdxVT));
12727 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12728}
12729
12730//===----------------------------------------------------------------------===//
12731// Implementation of Emulated TLS Model
12732//===----------------------------------------------------------------------===//
12733
12735 SelectionDAG &DAG) const {
12736 // Access to address of TLS varialbe xyz is lowered to a function call:
12737 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12738 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12739 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12740 SDLoc dl(GA);
12741
12742 ArgListTy Args;
12743 const GlobalValue *GV =
12745 SmallString<32> NameString("__emutls_v.");
12746 NameString += GV->getName();
12747 StringRef EmuTlsVarName(NameString);
12748 const GlobalVariable *EmuTlsVar =
12749 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12750 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12751 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12752
12753 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12754
12756 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12757 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12758 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12759
12760 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12761 // At last for X86 targets, maybe good for other targets too?
12763 MFI.setAdjustsStack(true); // Is this only for X86 target?
12764 MFI.setHasCalls(true);
12765
12766 assert((GA->getOffset() == 0) &&
12767 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12768 return CallResult.first;
12769}
12770
12772 SelectionDAG &DAG) const {
12773 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12774 if (!isCtlzFast())
12775 return SDValue();
12776 ISD::CondCode CC = Op.getOperandCondCode(2);
12777 SDLoc dl(Op);
12778 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12779 EVT VT = Op.getOperand(0).getValueType();
12780 SDValue Zext = Op.getOperand(0);
12781 if (VT.bitsLT(MVT::i32)) {
12782 VT = MVT::i32;
12783 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12784 }
12785 unsigned Log2b = Log2_32(VT.getSizeInBits());
12786 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12787 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12788 DAG.getConstant(Log2b, dl, MVT::i32));
12789 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12790 }
12791 return SDValue();
12792}
12793
12795 SDValue Op0 = Node->getOperand(0);
12796 SDValue Op1 = Node->getOperand(1);
12797 EVT VT = Op0.getValueType();
12798 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12799 unsigned Opcode = Node->getOpcode();
12800 SDLoc DL(Node);
12801
12802 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12803 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12804 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12805 DAG.SignBitIsZero(Op1))
12806 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12807
12808 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12809 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12811 Op0 = DAG.getFreeze(Op0);
12812 SDValue Zero = DAG.getConstant(0, DL, VT);
12813 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12814 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12815 }
12816
12817 // umin(x,y) -> sub(x,usubsat(x,y))
12818 // TODO: Missing freeze(Op0)?
12819 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12821 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12822 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12823 }
12824
12825 // umax(x,y) -> add(x,usubsat(y,x))
12826 // TODO: Missing freeze(Op0)?
12827 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12829 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12830 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12831 }
12832
12833 // FIXME: Should really try to split the vector in case it's legal on a
12834 // subvector.
12836 return DAG.UnrollVectorOp(Node);
12837
12838 // Attempt to find an existing SETCC node that we can reuse.
12839 // TODO: Do we need a generic doesSETCCNodeExist?
12840 // TODO: Missing freeze(Op0)/freeze(Op1)?
12841 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12842 ISD::CondCode PrefCommuteCC,
12843 ISD::CondCode AltCommuteCC) {
12844 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12845 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12846 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12847 {Op0, Op1, DAG.getCondCode(CC)})) {
12848 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12849 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12850 }
12851 }
12852 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12853 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12854 {Op0, Op1, DAG.getCondCode(CC)})) {
12855 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12856 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12857 }
12858 }
12859 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12860 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12861 };
12862
12863 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12864 // -> Y = (A < B) ? B : A
12865 // -> Y = (A >= B) ? A : B
12866 // -> Y = (A <= B) ? B : A
12867 switch (Opcode) {
12868 case ISD::SMAX:
12869 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12870 case ISD::SMIN:
12871 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12872 case ISD::UMAX:
12873 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12874 case ISD::UMIN:
12875 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12876 }
12877
12878 llvm_unreachable("How did we get here?");
12879}
12880
12882 unsigned Opcode = Node->getOpcode();
12883 SDValue LHS = Node->getOperand(0);
12884 SDValue RHS = Node->getOperand(1);
12885 EVT VT = LHS.getValueType();
12886 SDLoc dl(Node);
12887
12888 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12889 assert(VT.isInteger() && "Expected operands to be integers");
12890
12891 // usub.sat(a, b) -> umax(a, b) - b
12892 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12893 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12894 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12895 }
12896
12897 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12898 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12899 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12901 LHS = DAG.getFreeze(LHS);
12902 SDValue Zero = DAG.getConstant(0, dl, VT);
12903 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12904 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12905 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12906 Subtrahend =
12907 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12908 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12909 }
12910
12911 // uadd.sat(a, b) -> umin(a, ~b) + b
12912 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12913 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12914 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12915 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12916 }
12917
12918 unsigned OverflowOp;
12919 switch (Opcode) {
12920 case ISD::SADDSAT:
12921 OverflowOp = ISD::SADDO;
12922 break;
12923 case ISD::UADDSAT:
12924 OverflowOp = ISD::UADDO;
12925 break;
12926 case ISD::SSUBSAT:
12927 OverflowOp = ISD::SSUBO;
12928 break;
12929 case ISD::USUBSAT:
12930 OverflowOp = ISD::USUBO;
12931 break;
12932 default:
12933 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12934 "addition or subtraction node.");
12935 }
12936
12937 // FIXME: Should really try to split the vector in case it's legal on a
12938 // subvector.
12940 return DAG.UnrollVectorOp(Node);
12941
12942 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12943 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12944 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12945 SDValue SumDiff = Result.getValue(0);
12946 SDValue Overflow = Result.getValue(1);
12947 SDValue Zero = DAG.getConstant(0, dl, VT);
12948 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12949
12950 if (Opcode == ISD::UADDSAT) {
12952 // (LHS + RHS) | OverflowMask
12953 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12954 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12955 }
12956 // Overflow ? 0xffff.... : (LHS + RHS)
12957 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12958 }
12959
12960 if (Opcode == ISD::USUBSAT) {
12962 // (LHS - RHS) & ~OverflowMask
12963 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12964 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12965 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12966 }
12967 // Overflow ? 0 : (LHS - RHS)
12968 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12969 }
12970
12971 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12972 "Expected signed saturating add/sub opcode");
12973
12974 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12975 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12976
12977 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12978 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12979
12980 // If either of the operand signs are known, then they are guaranteed to
12981 // only saturate in one direction. If non-negative they will saturate
12982 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12983 //
12984 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12985 // sign of 'y' has to be flipped.
12986
12987 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12988 bool RHSIsNonNegative =
12989 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12990 if (LHSIsNonNegative || RHSIsNonNegative) {
12991 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12992 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12993 }
12994
12995 bool LHSIsNegative = KnownLHS.isNegative();
12996 bool RHSIsNegative =
12997 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12998 if (LHSIsNegative || RHSIsNegative) {
12999 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13000 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
13001 }
13002
13003 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
13004 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13005 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
13006 DAG.getConstant(BitWidth - 1, dl, VT));
13007 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
13008 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
13009}
13010
13012 unsigned Opcode = Node->getOpcode();
13013 SDValue LHS = Node->getOperand(0);
13014 SDValue RHS = Node->getOperand(1);
13015 EVT VT = LHS.getValueType();
13016 EVT ResVT = Node->getValueType(0);
13017 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13018 SDLoc dl(Node);
13019
13020 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
13021 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
13022 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
13023 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
13024
13025 // We can't perform arithmetic on i1 values. Extending them would
13026 // probably result in worse codegen, so let's just use two selects instead.
13027 // Some targets are also just better off using selects rather than subtraction
13028 // because one of the conditions can be merged with one of the selects.
13029 // And finally, if we don't know the contents of high bits of a boolean value
13030 // we can't perform any arithmetic either.
13032 BoolVT.getScalarSizeInBits() == 1 ||
13034 SDValue SelectZeroOrOne =
13035 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
13036 DAG.getConstant(0, dl, ResVT));
13037 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
13038 SelectZeroOrOne);
13039 }
13040
13042 std::swap(IsGT, IsLT);
13043 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
13044 ResVT);
13045}
13046
13048 unsigned Opcode = Node->getOpcode();
13049 bool IsSigned = Opcode == ISD::SSHLSAT;
13050 SDValue LHS = Node->getOperand(0);
13051 SDValue RHS = Node->getOperand(1);
13052 EVT VT = LHS.getValueType();
13053 SDLoc dl(Node);
13054
13055 assert((Node->getOpcode() == ISD::SSHLSAT ||
13056 Node->getOpcode() == ISD::USHLSAT) &&
13057 "Expected a SHLSAT opcode");
13058 assert(VT.isInteger() && "Expected operands to be integers");
13059
13061 return DAG.UnrollVectorOp(Node);
13062
13063 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
13064
13065 unsigned BW = VT.getScalarSizeInBits();
13066 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13067 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
13068 SDValue Orig =
13069 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
13070
13071 SDValue SatVal;
13072 if (IsSigned) {
13073 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
13074 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
13075 SDValue Cond =
13076 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
13077 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
13078 } else {
13079 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
13080 }
13081 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
13082 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
13083}
13084
13086 bool Signed, SDValue &Lo, SDValue &Hi,
13087 SDValue LHS, SDValue RHS,
13088 SDValue HiLHS, SDValue HiRHS) const {
13089 EVT VT = LHS.getValueType();
13090 assert(RHS.getValueType() == VT && "Mismatching operand types");
13091
13092 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
13093 assert((!Signed || !HiLHS) &&
13094 "Signed flag should only be set when HiLHS and RiRHS are null");
13095
13096 // We'll expand the multiplication by brute force because we have no other
13097 // options. This is a trivially-generalized version of the code from
13098 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
13099 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
13100 // sign bits while calculating the Hi half.
13101 unsigned Bits = VT.getScalarSizeInBits();
13102 unsigned HalfBits = Bits / 2;
13103 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
13104 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
13105 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
13106
13107 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
13108 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
13109
13110 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
13111 // This is always an unsigned shift.
13112 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
13113
13114 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
13115 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
13116 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
13117
13118 SDValue U =
13119 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
13120 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
13121 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
13122
13123 SDValue V =
13124 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
13125 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
13126
13127 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
13128 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
13129
13130 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
13131 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
13132
13133 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
13134 // the products to Hi.
13135 if (HiLHS) {
13136 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
13137 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
13138 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
13139 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
13140 }
13141}
13142
13144 bool Signed, const SDValue LHS,
13145 const SDValue RHS, SDValue &Lo,
13146 SDValue &Hi) const {
13147 EVT VT = LHS.getValueType();
13148 assert(RHS.getValueType() == VT && "Mismatching operand types");
13149 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13150 // We can fall back to a libcall with an illegal type for the MUL if we
13151 // have a libcall big enough.
13152 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
13153 if (WideVT == MVT::i16)
13154 LC = RTLIB::MUL_I16;
13155 else if (WideVT == MVT::i32)
13156 LC = RTLIB::MUL_I32;
13157 else if (WideVT == MVT::i64)
13158 LC = RTLIB::MUL_I64;
13159 else if (WideVT == MVT::i128)
13160 LC = RTLIB::MUL_I128;
13161
13162 RTLIB::LibcallImpl LibcallImpl = DAG.getLibcalls().getLibcallImpl(LC);
13163 if (LibcallImpl == RTLIB::Unsupported) {
13164 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
13165 return;
13166 }
13167
13168 // The libcall takes and returns WideVT values as packed VT halves. This only
13169 // works if VT is legal and WideVT isn't. Otherwise, emit a wide multiply and
13170 // let it legalise normally, possibly into a wider libcall.
13171 if (isTypeLegal(WideVT) || !isTypeLegal(VT)) {
13172 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT,
13173 DAG.getExtOrTrunc(Signed, LHS, dl, WideVT),
13174 DAG.getExtOrTrunc(Signed, RHS, dl, WideVT));
13175 SDValue Shift =
13176 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13177 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13178 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT,
13179 DAG.getNode(ISD::SRL, dl, WideVT, Mul, Shift));
13180 return;
13181 }
13182
13183 SDValue HiLHS, HiRHS;
13184 if (Signed) {
13185 // The high part is obtained by SRA'ing all but one of the bits of low
13186 // part.
13187 unsigned LoSize = VT.getFixedSizeInBits();
13188 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
13189 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
13190 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
13191 } else {
13192 HiLHS = DAG.getConstant(0, dl, VT);
13193 HiRHS = DAG.getConstant(0, dl, VT);
13194 }
13195
13196 // Attempt a libcall.
13197 SDValue Ret;
13199 CallOptions.setIsSigned(Signed);
13200 CallOptions.setIsPostTypeLegalization(true);
13202 // Halves of WideVT are packed into registers in different order
13203 // depending on platform endianness. This is usually handled by
13204 // the C calling convention, but we can't defer to it in
13205 // the legalizer.
13206 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
13207 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13208 } else {
13209 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
13210 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13211 }
13213 "Ret value is a collection of constituent nodes holding result.");
13214 if (DAG.getDataLayout().isLittleEndian()) {
13215 // Same as above.
13216 Lo = Ret.getOperand(0);
13217 Hi = Ret.getOperand(1);
13218 } else {
13219 Lo = Ret.getOperand(1);
13220 Hi = Ret.getOperand(0);
13221 }
13222}
13223
13224SDValue
13226 assert((Node->getOpcode() == ISD::SMULFIX ||
13227 Node->getOpcode() == ISD::UMULFIX ||
13228 Node->getOpcode() == ISD::SMULFIXSAT ||
13229 Node->getOpcode() == ISD::UMULFIXSAT) &&
13230 "Expected a fixed point multiplication opcode");
13231
13232 SDLoc dl(Node);
13233 SDValue LHS = Node->getOperand(0);
13234 SDValue RHS = Node->getOperand(1);
13235 EVT VT = LHS.getValueType();
13236 unsigned Scale = Node->getConstantOperandVal(2);
13237 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
13238 Node->getOpcode() == ISD::UMULFIXSAT);
13239 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
13240 Node->getOpcode() == ISD::SMULFIXSAT);
13241 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13242 unsigned VTSize = VT.getScalarSizeInBits();
13243
13244 if (!Scale) {
13245 // [us]mul.fix(a, b, 0) -> mul(a, b)
13246 if (!Saturating) {
13248 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13249 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
13250 SDValue Result =
13251 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13252 SDValue Product = Result.getValue(0);
13253 SDValue Overflow = Result.getValue(1);
13254 SDValue Zero = DAG.getConstant(0, dl, VT);
13255
13256 APInt MinVal = APInt::getSignedMinValue(VTSize);
13257 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
13258 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13259 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13260 // Xor the inputs, if resulting sign bit is 0 the product will be
13261 // positive, else negative.
13262 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
13263 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
13264 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
13265 return DAG.getSelect(dl, VT, Overflow, Result, Product);
13266 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
13267 SDValue Result =
13268 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13269 SDValue Product = Result.getValue(0);
13270 SDValue Overflow = Result.getValue(1);
13271
13272 APInt MaxVal = APInt::getMaxValue(VTSize);
13273 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13274 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
13275 }
13276 }
13277
13278 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
13279 "Expected scale to be less than the number of bits if signed or at "
13280 "most the number of bits if unsigned.");
13281 assert(LHS.getValueType() == RHS.getValueType() &&
13282 "Expected both operands to be the same type");
13283
13284 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
13285 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
13286 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
13287 SDValue Val, ISD::CondCode CC) {
13288 if (VT.isVector())
13289 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
13290 Sat, Val);
13291 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
13292 };
13293
13294 // Get the upper and lower bits of the result.
13295 SDValue Lo, Hi;
13296 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13297 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
13298 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13299 if (isOperationLegalOrCustom(LoHiOp, VT)) {
13300 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
13301 Lo = Result.getValue(0);
13302 Hi = Result.getValue(1);
13303 } else if (isOperationLegalOrCustom(HiOp, VT)) {
13304 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13305 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
13306 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13307 // Try for a multiplication using a wider type.
13308 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13309 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
13310 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
13311 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
13312 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
13313 SDValue Shifted =
13314 DAG.getNode(ISD::SRA, dl, WideVT, Res,
13315 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
13316 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
13317 } else if (VT.isVector()) {
13318 return SDValue();
13319 } else {
13320 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
13321 }
13322
13323 if (Scale == VTSize)
13324 // Result is just the top half since we'd be shifting by the width of the
13325 // operand. Overflow impossible so this works for both UMULFIX and
13326 // UMULFIXSAT.
13327 return Hi;
13328
13329 // The result will need to be shifted right by the scale since both operands
13330 // are scaled. The result is given to us in 2 halves, so we only want part of
13331 // both in the result.
13332 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
13333 DAG.getShiftAmountConstant(Scale, VT, dl));
13334 if (!Saturating)
13335 return Result;
13336
13337 if (!Signed) {
13338 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
13339 // widened multiplication) aren't all zeroes.
13340
13341 // Saturate to max if ((Hi >> Scale) != 0),
13342 // which is the same as if (Hi > ((1 << Scale) - 1))
13343 APInt MaxVal = APInt::getMaxValue(VTSize);
13344 SDValue LowMask =
13345 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
13346 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
13347 Result, ISD::SETUGT);
13348 }
13349
13350 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
13351 // widened multiplication) aren't all ones or all zeroes.
13352
13353 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
13354 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
13355
13356 if (Scale == 0) {
13357 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
13358 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
13359 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
13360 // Saturated to SatMin if wide product is negative, and SatMax if wide
13361 // product is positive ...
13362 SDValue Zero = DAG.getConstant(0, dl, VT);
13363 SDValue ResultIfOverflow =
13364 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
13365 // ... but only if we overflowed.
13366 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
13367 }
13368
13369 // We handled Scale==0 above so all the bits to examine is in Hi.
13370
13371 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
13372 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
13373 SDValue LowMask =
13374 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
13375 // Saturate to min if (Hi >> (Scale - 1)) < -1),
13376 // which is the same as if (HI < (-1 << (Scale - 1))
13377 SDValue HighMask = DAG.getConstant(
13378 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
13379 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
13380 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
13381 return Result;
13382}
13383
13384SDValue
13386 SDValue LHS, SDValue RHS,
13387 unsigned Scale, SelectionDAG &DAG) const {
13388 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
13389 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
13390 "Expected a fixed point division opcode");
13391
13392 EVT VT = LHS.getValueType();
13393 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
13394 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
13395 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13396
13397 // If there is enough room in the type to upscale the LHS or downscale the
13398 // RHS before the division, we can perform it in this type without having to
13399 // resize. For signed operations, the LHS headroom is the number of
13400 // redundant sign bits, and for unsigned ones it is the number of zeroes.
13401 // The headroom for the RHS is the number of trailing zeroes.
13402 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
13404 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
13405
13406 // For signed saturating operations, we need to be able to detect true integer
13407 // division overflow; that is, when you have MIN / -EPS. However, this
13408 // is undefined behavior and if we emit divisions that could take such
13409 // values it may cause undesired behavior (arithmetic exceptions on x86, for
13410 // example).
13411 // Avoid this by requiring an extra bit so that we never get this case.
13412 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13413 // signed saturating division, we need to emit a whopping 32-bit division.
13414 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13415 return SDValue();
13416
13417 unsigned LHSShift = std::min(LHSLead, Scale);
13418 unsigned RHSShift = Scale - LHSShift;
13419
13420 // At this point, we know that if we shift the LHS up by LHSShift and the
13421 // RHS down by RHSShift, we can emit a regular division with a final scaling
13422 // factor of Scale.
13423
13424 if (LHSShift)
13425 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13426 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13427 if (RHSShift)
13428 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13429 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13430
13431 SDValue Quot;
13432 if (Signed) {
13433 // For signed operations, if the resulting quotient is negative and the
13434 // remainder is nonzero, subtract 1 from the quotient to round towards
13435 // negative infinity.
13436 SDValue Rem;
13437 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13438 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13439 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13440 if (isTypeLegal(VT) &&
13442 Quot = DAG.getNode(ISD::SDIVREM, dl,
13443 DAG.getVTList(VT, VT),
13444 LHS, RHS);
13445 Rem = Quot.getValue(1);
13446 Quot = Quot.getValue(0);
13447 } else {
13448 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13449 LHS, RHS);
13450 Rem = DAG.getNode(ISD::SREM, dl, VT,
13451 LHS, RHS);
13452 }
13453 SDValue Zero = DAG.getConstant(0, dl, VT);
13454 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13455 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13456 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13457 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13458 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13459 DAG.getConstant(1, dl, VT));
13460 Quot = DAG.getSelect(dl, VT,
13461 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13462 Sub1, Quot);
13463 } else
13464 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13465 LHS, RHS);
13466
13467 return Quot;
13468}
13469
13471 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13472 SDLoc dl(Node);
13473 SDValue LHS = Node->getOperand(0);
13474 SDValue RHS = Node->getOperand(1);
13475 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13476
13477 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13478 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13479 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13480 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13481 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13482 { LHS, RHS, CarryIn });
13483 Result = SDValue(NodeCarry.getNode(), 0);
13484 Overflow = SDValue(NodeCarry.getNode(), 1);
13485 return;
13486 }
13487
13488 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13489 LHS.getValueType(), LHS, RHS);
13490
13491 EVT ResultType = Node->getValueType(1);
13492 EVT SetCCType = getSetCCResultType(
13493 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13494 SDValue SetCC;
13495 if (IsAdd && isOneConstant(RHS)) {
13496 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13497 // the live range of X. We assume comparing with 0 is cheap.
13498 // The general case (X + C) < C is not necessarily beneficial. Although we
13499 // reduce the live range of X, we may introduce the materialization of
13500 // constant C.
13501 SetCC =
13502 DAG.getSetCC(dl, SetCCType, Result,
13503 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13504 } else if (IsAdd && isAllOnesConstant(RHS)) {
13505 // Special case: uaddo X, -1 overflows if X != 0.
13506 SetCC =
13507 DAG.getSetCC(dl, SetCCType, LHS,
13508 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13509 } else {
13511 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13512 }
13513 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13514}
13515
13517 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13518 SDLoc dl(Node);
13519 SDValue LHS = Node->getOperand(0);
13520 SDValue RHS = Node->getOperand(1);
13521 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13522
13523 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13524 LHS.getValueType(), LHS, RHS);
13525
13526 EVT ResultType = Node->getValueType(1);
13527 EVT OType = getSetCCResultType(
13528 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13529
13530 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13531 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13532 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13533 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13534 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13535 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13536 return;
13537 }
13538
13539 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13540
13541 if (IsAdd) {
13542 // For an addition, the result should be less than one of the operands (LHS)
13543 // if and only if the other operand (RHS) is negative, otherwise there will
13544 // be overflow.
13545 SDValue ResultLowerThanLHS =
13546 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13547 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13548 Overflow = DAG.getBoolExtOrTrunc(
13549 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13550 ResultType, ResultType);
13551 } else {
13552 // For subtraction, overflow occurs when the signed comparison of operands
13553 // doesn't match the sign of the result.
13554 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13555 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13556 Overflow = DAG.getBoolExtOrTrunc(
13557 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13558 ResultType, ResultType);
13559 }
13560}
13561
13563 SDValue &Overflow, SelectionDAG &DAG) const {
13564 SDLoc dl(Node);
13565 EVT VT = Node->getValueType(0);
13566 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13567 SDValue LHS = Node->getOperand(0);
13568 SDValue RHS = Node->getOperand(1);
13569 bool isSigned = Node->getOpcode() == ISD::SMULO;
13570
13571 // For power-of-two multiplications we can use a simpler shift expansion.
13572 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13573 const APInt &C = RHSC->getAPIntValue();
13574 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13575 if (C.isPowerOf2()) {
13576 // smulo(x, signed_min) is same as umulo(x, signed_min).
13577 bool UseArithShift = isSigned && !C.isMinSignedValue();
13578 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13579 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13580 Overflow = DAG.getSetCC(dl, SetCCVT,
13581 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13582 dl, VT, Result, ShiftAmt),
13583 LHS, ISD::SETNE);
13584 return true;
13585 }
13586 }
13587
13588 SDValue BottomHalf;
13589 SDValue TopHalf;
13590 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13591
13592 static const unsigned Ops[2][3] =
13595 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13596 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13597 RHS);
13598 TopHalf = BottomHalf.getValue(1);
13599 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13600 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13601 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13602 } else if (isTypeLegal(WideVT)) {
13603 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13604 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13605 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13606 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13607 SDValue ShiftAmt =
13608 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13609 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13610 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13611 } else {
13612 if (VT.isVector())
13613 return false;
13614
13615 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13616 }
13617
13618 Result = BottomHalf;
13619 if (isSigned) {
13620 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13621 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13622 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13623 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13624 } else {
13625 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13626 DAG.getConstant(0, dl, VT), ISD::SETNE);
13627 }
13628
13629 // Truncate the result if SetCC returns a larger type than needed.
13630 EVT RType = Node->getValueType(1);
13631 if (RType.bitsLT(Overflow.getValueType()))
13632 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13633
13634 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13635 "Unexpected result type for S/UMULO legalization");
13636 return true;
13637}
13638
13640 SDLoc dl(Node);
13641 EVT VT = Node->getValueType(0);
13642 SDValue LHS = Node->getOperand(0);
13643 SDValue RHS = Node->getOperand(1);
13644 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13645
13646 // Use MUL_LOHI if legal/custom for the original type.
13647 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13648 if (isOperationLegalOrCustom(LoHiOp, VT))
13649 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13650
13651 // Use a wide multiply if available.
13652 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13653 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13654 unsigned BW = VT.getScalarSizeInBits();
13655 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13656 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13657 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13658 DAG.getNode(ISD::SRL, dl, WideVT,
13659 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13660 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13661 }
13662
13663 // Let fixed-length vectors be scalarised by the caller.
13664 // Expand everything else with a wide multiply.
13665 if (!VT.isFixedLengthVector()) {
13666 SDValue Lo, Hi;
13667 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13668 return Hi;
13669 }
13670
13671 return SDValue();
13672}
13673
13675 SDLoc dl(Node);
13676 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13677 SDValue Op = Node->getOperand(0);
13678 SDNodeFlags Flags = Node->getFlags();
13679 EVT VT = Op.getValueType();
13680
13681 // Try to use a shuffle reduction for power of two vectors.
13682 if (VT.isPow2VectorType()) {
13683 // See if the reduction opcode is safe to use with widened types.
13684 bool WidenSrc = false;
13685 switch (Node->getOpcode()) {
13688 case ISD::VECREDUCE_ADD:
13689 case ISD::VECREDUCE_MUL:
13690 case ISD::VECREDUCE_AND:
13691 case ISD::VECREDUCE_OR:
13692 case ISD::VECREDUCE_XOR:
13697 WidenSrc = VT.isFixedLengthVector();
13698 break;
13699 }
13700
13702 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13703 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13704 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13705 // Attempt to widen the source vectors to a legal op.
13706 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13707 if (WideVT.isVector() &&
13708 WideVT.getScalarType() == HalfVT.getScalarType() &&
13709 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13710 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13711 SDValue Lo, Hi;
13712 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13713 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13714 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13715 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13716 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13717 VT = HalfVT;
13718 continue;
13719 }
13720 }
13721 break;
13722 }
13723
13724 SDValue Lo, Hi;
13725 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13726 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13727 VT = HalfVT;
13728
13729 // Stop if splitting is enough to make the reduction legal.
13730 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13731 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13732 Flags);
13733 }
13734 }
13735
13736 if (VT.isScalableVector())
13738 "Expanding reductions for scalable vectors is undefined.");
13739
13740 EVT EltVT = VT.getVectorElementType();
13741 unsigned NumElts = VT.getVectorNumElements();
13742
13744 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13745
13746 SDValue Res = Ops[0];
13747 for (unsigned i = 1; i < NumElts; i++)
13748 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13749
13750 // Result type may be wider than element type.
13751 if (EltVT != Node->getValueType(0))
13752 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13753 return Res;
13754}
13755
13757 SDLoc dl(Node);
13758 SDValue AccOp = Node->getOperand(0);
13759 SDValue VecOp = Node->getOperand(1);
13760 SDNodeFlags Flags = Node->getFlags();
13761
13762 EVT VT = VecOp.getValueType();
13763 EVT EltVT = VT.getVectorElementType();
13764
13765 if (VT.isScalableVector())
13767 "Expanding reductions for scalable vectors is undefined.");
13768
13769 unsigned NumElts = VT.getVectorNumElements();
13770
13772 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13773
13774 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13775
13776 SDValue Res = AccOp;
13777 for (unsigned i = 0; i < NumElts; i++)
13778 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13779
13780 return Res;
13781}
13782
13784 SelectionDAG &DAG) const {
13785 EVT VT = Node->getValueType(0);
13786 SDLoc dl(Node);
13787 bool isSigned = Node->getOpcode() == ISD::SREM;
13788 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13789 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13790 SDValue Dividend = Node->getOperand(0);
13791 SDValue Divisor = Node->getOperand(1);
13792 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13793 SDVTList VTs = DAG.getVTList(VT, VT);
13794 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13795 return true;
13796 }
13797 if (isOperationLegalOrCustom(DivOpc, VT)) {
13798 // X % Y -> X-X/Y*Y
13799 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13800 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13801 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13802 return true;
13803 }
13804 return false;
13805}
13806
13808 SelectionDAG &DAG) const {
13809 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13810 SDLoc dl(SDValue(Node, 0));
13811 SDValue Src = Node->getOperand(0);
13812
13813 // DstVT is the result type, while SatVT is the size to which we saturate
13814 EVT SrcVT = Src.getValueType();
13815 EVT DstVT = Node->getValueType(0);
13816
13817 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13818 unsigned SatWidth = SatVT.getScalarSizeInBits();
13819 unsigned DstWidth = DstVT.getScalarSizeInBits();
13820 assert(SatWidth <= DstWidth &&
13821 "Expected saturation width smaller than result width");
13822
13823 // Determine minimum and maximum integer values and their corresponding
13824 // floating-point values.
13825 APInt MinInt, MaxInt;
13826 if (IsSigned) {
13827 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13828 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13829 } else {
13830 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13831 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13832 }
13833
13834 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13835 // libcall emission cannot handle this. Large result types will fail.
13836 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13837 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13838 SrcVT = Src.getValueType();
13839 }
13840
13841 const fltSemantics &Sem = SrcVT.getFltSemantics();
13842 APFloat MinFloat(Sem);
13843 APFloat MaxFloat(Sem);
13844
13845 APFloat::opStatus MinStatus =
13846 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13847 APFloat::opStatus MaxStatus =
13848 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13849 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13850 !(MaxStatus & APFloat::opStatus::opInexact);
13851
13852 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13853 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13854
13855 // If the integer bounds are exactly representable as floats and min/max are
13856 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13857 // of comparisons and selects.
13858 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13859 bool MayPropagateNaN) {
13860 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13861 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13862 if (!MinMaxLegal)
13863 return SDValue();
13864
13865 SDValue Clamped = Src;
13866
13867 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13868 // then the result is MinFloat.
13869 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13870 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13871 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13872 // Convert clamped value to integer.
13873 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13874 dl, DstVT, Clamped);
13875
13876 // If !MayPropagateNan and the conversion is unsigned case we're done,
13877 // because we mapped NaN to MinFloat, which will cast to zero.
13878 if (!MayPropagateNaN && !IsSigned)
13879 return FpToInt;
13880
13881 // Otherwise, select 0 if Src is NaN.
13882 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13883 EVT SetCCVT =
13884 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13885 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13886 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13887 };
13888 if (AreExactFloatBounds) {
13889 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13890 /*MayPropagateNaN=*/false))
13891 return Res;
13892 // These may propagate NaN for sNaN operands.
13893 if (SDValue Res =
13894 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13895 return Res;
13896 // These always propagate NaN.
13897 if (SDValue Res =
13898 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13899 return Res;
13900 }
13901
13902 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13903 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13904
13905 // Result of direct conversion. The assumption here is that the operation is
13906 // non-trapping and it's fine to apply it to an out-of-range value if we
13907 // select it away later.
13908 SDValue FpToInt =
13909 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13910
13911 SDValue Select = FpToInt;
13912
13913 EVT SetCCVT =
13914 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13915
13916 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13917 // MinInt if Src is NaN.
13918 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13919 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13920 // If Src OGT MaxFloat, select MaxInt.
13921 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13922 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13923
13924 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13925 // is already zero.
13926 if (!IsSigned)
13927 return Select;
13928
13929 // Otherwise, select 0 if Src is NaN.
13930 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13931 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13932 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13933}
13934
13936 const SDLoc &dl,
13937 SelectionDAG &DAG) const {
13938 EVT OperandVT = Op.getValueType();
13939 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13940 return Op;
13941 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13942 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13943 // can induce double-rounding which may alter the results. We can
13944 // correct for this using a trick explained in: Boldo, Sylvie, and
13945 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13946 // World Congress. 2005.
13947 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13948 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13949
13950 // We can keep the narrow value as-is if narrowing was exact (no
13951 // rounding error), the wide value was NaN (the narrow value is also
13952 // NaN and should be preserved) or if we rounded to the odd value.
13953 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13954 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13955 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13956 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13957 EVT ResultIntVTCCVT = getSetCCResultType(
13958 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13959 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13960 // The result is already odd so we don't need to do anything.
13961 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13962
13963 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13964 Op.getValueType());
13965 // We keep results which are exact, odd or NaN.
13966 SDValue KeepNarrow =
13967 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13968 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13969 // We morally performed a round-down if AbsNarrow is smaller than
13970 // AbsWide.
13971 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13972 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13973 SDValue NarrowIsRd =
13974 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13975 // If the narrow value is odd or exact, pick it.
13976 // Otherwise, narrow is even and corresponds to either the rounded-up
13977 // or rounded-down value. If narrow is the rounded-down value, we want
13978 // the rounded-up value as it will be odd.
13979 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13980 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13981 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13982 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13983}
13984
13986 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13987 SDValue Op = Node->getOperand(0);
13988 EVT VT = Node->getValueType(0);
13989 SDLoc dl(Node);
13990 if (VT.getScalarType() == MVT::bf16) {
13991 if (Node->getConstantOperandVal(1) == 1) {
13992 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13993 }
13994 EVT OperandVT = Op.getValueType();
13995
13996 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13997 // can induce double-rounding which may alter the results. We can
13998 // correct for this using a trick explained in: Boldo, Sylvie, and
13999 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
14000 // World Congress. 2005.
14001 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
14002 EVT I32 = F32.changeTypeToInteger();
14003 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
14004 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
14005
14006 // Factor in the contribution of the low 16 bits.
14007 SDValue One = DAG.getConstant(1, dl, I32);
14008 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
14009 DAG.getShiftAmountConstant(16, I32, dl));
14010 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
14011 SDValue RoundingBias =
14012 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
14013 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
14014
14015 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
14016 // 0x80000000.
14017 if (!Node->getFlags().hasNoNaNs() &&
14018 !DAG.isKnownNeverNaN(Node->getOperand(0))) {
14019 // Conversions should set NaN's quiet bit. This also prevents NaNs from
14020 // turning into infinities.
14021 SDValue NaN =
14022 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
14023
14024 SDValue IsNaN = DAG.getSetCC(
14025 dl,
14026 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
14027 Node->getOperand(0), Node->getOperand(0), ISD::SETUO);
14028 Add = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
14029 }
14030
14031 // Now that we have rounded, shift the bits into position.
14032 Op = DAG.getNode(ISD::SRL, dl, I32, Add,
14033 DAG.getShiftAmountConstant(16, I32, dl));
14034 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
14035 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
14036 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14037 }
14038 return SDValue();
14039}
14040
14043 SelectionDAG &DAG) const {
14044 assert(Node->getOpcode() == ISD::VECTOR_INTERLEAVE && "Unexpected opcode");
14045 EVT VT = Node->getValueType(0);
14046 unsigned Factor = Node->getNumOperands();
14047 SDLoc DL(Node);
14048
14049 if (Factor > 2 && Factor % 2 == 0) {
14050 SmallVector<EVT> HalfVTs(Factor / 2, VT);
14051 SmallVector<SDValue, 8> LOps, ROps;
14052 // Interleave so we have 2 factors per result:
14053 // a0a1 b0b1 c0c1 d0d1 -> [a0c0 b0d0] [a1c1 b1d1]
14054 for (unsigned I = 0; I < Factor / 2; I++) {
14055 SDValue Interleave =
14056 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, {VT, VT},
14057 {Node->getOperand(I), Node->getOperand(I + Factor / 2)});
14058 LOps.push_back(Interleave.getValue(0));
14059 ROps.push_back(Interleave.getValue(1));
14060 }
14061 // Interleave at Factor/2:
14062 // [a0c0 b0d0] [a1c1 b1d1] -> a0b0 c0d0 a1b1 c1d1
14063 SDValue L = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, LOps);
14064 SDValue R = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, ROps);
14065 for (unsigned I = 0; I < Factor / 2; I++)
14066 Results.push_back(L.getValue(I));
14067 for (unsigned I = 0; I < Factor / 2; I++)
14068 Results.push_back(R.getValue(I));
14069 return;
14070 }
14071
14072 if (!VT.isFixedLengthVector())
14073 return;
14074
14075 unsigned NumElts = VT.getVectorNumElements();
14076 EVT EltVT = VT.getVectorElementType();
14077
14078 // A factor of two needs only same-width, two-input shuffles.
14079 if (Factor == 2) {
14080 SmallVector<int, 8> Mask = createInterleaveMask(NumElts, Factor);
14081 for (unsigned I = 0; I != Factor; ++I)
14082 Results.push_back(DAG.getVectorShuffle(
14083 VT, DL, Node->getOperand(0), Node->getOperand(1),
14084 ArrayRef<int>(Mask).slice(I * NumElts, NumElts)));
14085 return;
14086 }
14087
14088 SmallVector<SDValue> InterleavedElts;
14089 InterleavedElts.reserve(Factor * NumElts);
14090 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14091 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
14092 InterleavedElts.push_back(DAG.getExtractVectorElt(
14093 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
14094
14095 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx)
14096 Results.push_back(DAG.getBuildVector(
14097 VT, DL, ArrayRef(InterleavedElts).slice(ResultIdx * NumElts, NumElts)));
14098}
14099
14102 SelectionDAG &DAG) const {
14103 assert(Node->getOpcode() == ISD::VECTOR_DEINTERLEAVE && "Unexpected opcode");
14104 EVT VT = Node->getValueType(0);
14105 unsigned Factor = Node->getNumOperands();
14106 SDLoc DL(Node);
14107
14108 if (Factor > 2 && Factor % 2 == 0) {
14110 SmallVector<EVT> HalfVTs(Factor / 2, VT);
14111 // Deinterleave at Factor/2 so each result contains two factors interleaved:
14112 // a0b0 c0d0 a1b1 c1d1 -> [a0c0 b0d0] [a1c1 b1d1]
14113 SDValue L = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
14114 ArrayRef(Ops).take_front(Factor / 2));
14115 SDValue R = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
14116 ArrayRef(Ops).take_back(Factor / 2));
14117 Results.resize(Factor);
14118 // Deinterleave the 2 factors out:
14119 // [a0c0 a1c1] [b0d0 b1d1] -> a0a1 b0b1 c0c1 d0d1
14120 for (unsigned I = 0; I < Factor / 2; ++I) {
14122 {L.getValue(I), R.getValue(I)});
14123 Results[I] = Deinterleave.getValue(0);
14124 Results[I + Factor / 2] = Deinterleave.getValue(1);
14125 }
14126 return;
14127 }
14128
14129 if (!VT.isFixedLengthVector())
14130 return;
14131
14132 unsigned NumElts = VT.getVectorNumElements();
14133 EVT EltVT = VT.getVectorElementType();
14134
14135 // A factor of two needs only same-width, two-input shuffles.
14136 if (Factor == 2) {
14137 for (unsigned I = 0; I != Factor; ++I)
14138 Results.push_back(
14139 DAG.getVectorShuffle(VT, DL, Node->getOperand(0), Node->getOperand(1),
14140 createStrideMask(I, Factor, NumElts)));
14141 return;
14142 }
14143
14144 SmallVector<SDValue> ConcatElts;
14145 ConcatElts.reserve(Factor * NumElts);
14146 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
14147 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14148 ConcatElts.push_back(DAG.getExtractVectorElt(
14149 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
14150
14151 SmallVector<SDValue> DeinterleavedElts;
14152 DeinterleavedElts.reserve(Factor * NumElts);
14153 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx) {
14154 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14155 DeinterleavedElts.push_back(ConcatElts[ResultIdx + EltIdx * Factor]);
14156 Results.push_back(DAG.getBuildVector(
14157 VT, DL,
14158 ArrayRef(DeinterleavedElts).slice(ResultIdx * NumElts, NumElts)));
14159 }
14160}
14161
14163 SelectionDAG &DAG) const {
14164 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
14165 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
14166 "Unexpected opcode!");
14167 assert((Node->getValueType(0).isScalableVector() ||
14168 !isa<ConstantSDNode>(Node->getOperand(2))) &&
14169 "Fixed length vector types with constant offsets expected to use "
14170 "SHUFFLE_VECTOR!");
14171
14172 EVT VT = Node->getValueType(0);
14173 SDValue V1 = Node->getOperand(0);
14174 SDValue V2 = Node->getOperand(1);
14175 SDValue Offset = Node->getOperand(2);
14176 SDLoc DL(Node);
14177
14178 // Expand through memory thusly:
14179 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
14180 // Store V1, Ptr
14181 // Store V2, Ptr + sizeof(V1)
14182 // if (VECTOR_SPLICE_LEFT)
14183 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
14184 // else
14185 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
14186 // Res = Load Ptr
14187
14188 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
14189
14191 VT.getVectorElementCount() * 2);
14192 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
14193 EVT PtrVT = StackPtr.getValueType();
14194 auto &MF = DAG.getMachineFunction();
14195 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14196 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
14197
14198 // Store the lo part of CONCAT_VECTORS(V1, V2)
14199 SDValue StoreV1 =
14200 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
14201 // Store the hi part of CONCAT_VECTORS(V1, V2)
14202 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
14203 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
14204 SDValue StoreV2 =
14205 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
14206
14207 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
14208 SDValue EltByteSize =
14209 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
14210 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
14211 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
14212
14213 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
14214
14215 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
14216 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
14217 else
14218 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
14219
14220 // Load the spliced result
14221 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
14223}
14224
14226 SelectionDAG &DAG) const {
14227 SDLoc DL(Node);
14228 SDValue Vec = Node->getOperand(0);
14229 SDValue Mask = Node->getOperand(1);
14230 SDValue Passthru = Node->getOperand(2);
14231
14232 EVT VecVT = Vec.getValueType();
14233 EVT ScalarVT = VecVT.getScalarType();
14234 EVT MaskVT = Mask.getValueType();
14235 EVT MaskScalarVT = MaskVT.getScalarType();
14236
14237 // Needs to be handled by targets that have scalable vector types.
14238 if (VecVT.isScalableVector())
14239 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
14240
14241 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
14242 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
14243 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14244 MachinePointerInfo PtrInfo =
14246
14247 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
14248 SDValue Chain = DAG.getEntryNode();
14249 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
14250
14251 bool HasPassthru = !Passthru.isUndef();
14252
14253 // If we have a passthru vector, store it on the stack, overwrite the matching
14254 // positions and then re-write the last element that was potentially
14255 // overwritten even though mask[i] = false.
14256 if (HasPassthru)
14257 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
14258
14259 SDValue LastWriteVal;
14260 APInt PassthruSplatVal;
14261 bool IsSplatPassthru = ISD::isConstantSplatVector(Passthru, PassthruSplatVal);
14262
14263 if (IsSplatPassthru) {
14264 // As we do not know which position we wrote to last, we cannot simply
14265 // access that index from the passthru vector. So we first check if passthru
14266 // is a splat vector, to use any element ...
14267 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
14268 } else if (HasPassthru) {
14269 // ... if it is not a splat vector, we need to get the passthru value at
14270 // position = popcount(mask) and re-load it from the stack before it is
14271 // overwritten in the loop below.
14272 EVT PopcountVT = ScalarVT.changeTypeToInteger();
14273 SDValue Popcount = DAG.getNode(
14275 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
14276 Popcount = DAG.getNode(
14278 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
14279 Popcount);
14280 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
14281 SDValue LastElmtPtr =
14282 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
14283 LastWriteVal = DAG.getLoad(
14284 ScalarVT, DL, Chain, LastElmtPtr,
14286 Chain = LastWriteVal.getValue(1);
14287 }
14288
14289 unsigned NumElms = VecVT.getVectorNumElements();
14290 for (unsigned I = 0; I < NumElms; I++) {
14291 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
14292 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14293 Chain = DAG.getStore(
14294 Chain, DL, ValI, OutPtr,
14296
14297 // Get the mask value and add it to the current output position. This
14298 // either increments by 1 if MaskI is true or adds 0 otherwise.
14299 // Freeze in case we have poison/undef mask entries.
14300 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
14301 MaskI = DAG.getFreeze(MaskI);
14302 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
14303 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
14304 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
14305
14306 if (HasPassthru && I == NumElms - 1) {
14307 SDValue EndOfVector =
14308 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
14309 SDValue AllLanesSelected =
14310 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
14311 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
14312 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14313
14314 // Re-write the last ValI if all lanes were selected. Otherwise,
14315 // overwrite the last write it with the passthru value.
14316 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
14317 LastWriteVal, SDNodeFlags::Unpredictable);
14318 Chain = DAG.getStore(
14319 Chain, DL, LastWriteVal, OutPtr,
14321 }
14322 }
14323
14324 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
14325}
14326
14328 SelectionDAG &DAG) const {
14329 SDLoc DL(Node);
14330 SDValue V = Node->getOperand(0);
14331 SDValue Mask = Node->getOperand(1);
14332
14333 EVT VecVT = Node->getValueType(0);
14334 EVT ScalarVT = VecVT.getScalarType();
14335
14336 // Needs to be handled by targets that have scalable vector types.
14337 if (VecVT.isScalableVector())
14339 "Cannot expand vector_shuffle_var for scalable vectors.");
14340
14341 if (VecVT.getVectorNumElements() == 2) {
14342 // Select between V and V with its lanes swapped.
14343 EVT IdxVT = VecVT.changeVectorElementTypeToInteger();
14344 SDValue Idx = DAG.getZExtOrTrunc(Mask, DL, IdxVT);
14345 EVT CCVT =
14346 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IdxVT);
14347 SDValue Keep =
14348 DAG.getSetCC(DL, CCVT, Idx, DAG.getStepVector(DL, IdxVT), ISD::SETEQ);
14349 SDValue Swapped = DAG.getVectorShuffle(VecVT, DL, V, V, {1, 0});
14350 return DAG.getNode(ISD::VSELECT, DL, VecVT, Keep, V, Swapped);
14351 }
14352
14353 // Res[i] = V[Mask[i]]. Out-of-range extracts are undefined, as required.
14354 MVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
14356 DAG.ExtractVectorElements(Mask, Elts);
14357 for (SDValue &Elt : Elts) {
14358 SDValue Idx = DAG.getZExtOrTrunc(Elt, DL, IdxVT);
14359 Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, V, Idx);
14360 }
14361 return DAG.getBuildVector(VecVT, DL, Elts);
14362}
14363
14365 SDLoc DL(Node);
14366 EVT VT = Node->getValueType(0);
14367 SDValue Op = Node->getOperand(0);
14368 ElementCount EC = Op.getValueType().getVectorElementCount();
14369
14370 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
14371 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
14372
14373 // No legal step vector: split mask in half and recombine results.
14374 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
14375 // (== LoNumElts when no active lane), allowing the SETNE comparison.
14376 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
14377 if (!StepVec) {
14378 EVT ResVT = Node->getValueType(0);
14379 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
14380 SDValue LoNumElts = DAG.getElementCount(
14381 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
14382 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
14383 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
14384 SDValue ResLoNotNumElts = DAG.getSetCC(
14385 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
14386 ResLo, LoNumElts, ISD::SETNE);
14387 // Per LangRef, ResVT must be wide enough to hold the total element count,
14388 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
14389 // the count is only required to fit unsigned.
14390 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
14392 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
14393 }
14394
14395 EVT StepVecVT = StepVec.getValueType();
14396 EVT StepVT = StepVecVT.getVectorElementType();
14397
14398 // Promote the scalar result type early to avoid redundant zexts.
14400 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
14401
14402 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
14403 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
14404 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
14405 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
14406 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
14408 StepVecVT.getVectorElementType(), Select);
14409 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
14410 DAG.getZExtOrTrunc(Max, DL, StepVT));
14411
14412 return DAG.getZExtOrTrunc(Sub, DL, VT);
14413}
14414
14416 SDLoc DL(N);
14417 SDValue Source = N->getOperand(0);
14418 SDValue Needle = N->getOperand(1);
14419 SDValue Mask = N->getOperand(2);
14420 EVT SourceVT = Source.getValueType();
14421 EVT NeedleVT = Needle.getValueType();
14422 EVT ResVT = N->getValueType(0);
14423 EVT CmpVT =
14424 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
14425
14426 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
14427
14428 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
14429 EVT NeedleEltVT = NeedleVT.getVectorElementType();
14430 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
14431 SDValue Splat;
14432 if (NeedleVT == SourceVT) {
14433 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
14434 Splat = DAG.getVectorShuffle(
14435 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
14437 } else {
14438 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
14439 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
14440 }
14441 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
14442 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
14443 }
14444
14445 EVT UseVT = ResVT;
14446 // If the result is immediately truncated, only extend to that type (to avoid
14447 // unnecessary sign/zero extends).
14448 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
14449 UseVT = N->user_begin()->getValueType(0);
14450
14451 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
14452 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
14453
14454 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
14455 if (UseVT != ResVT)
14456 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
14457 return Ret;
14458}
14459
14461 SelectionDAG &DAG) const {
14462 SDLoc DL(N);
14463 SDValue Acc = N->getOperand(0);
14464 SDValue MulLHS = N->getOperand(1);
14465 SDValue MulRHS = N->getOperand(2);
14466 EVT AccVT = Acc.getValueType();
14467 EVT MulOpVT = MulLHS.getValueType();
14468
14469 EVT ExtMulOpVT =
14471 MulOpVT.getVectorElementCount());
14472
14473 unsigned ExtOpcLHS, ExtOpcRHS;
14474 switch (N->getOpcode()) {
14475 default:
14476 llvm_unreachable("Unexpected opcode");
14478 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
14479 break;
14481 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
14482 break;
14484 ExtOpcLHS = ISD::SIGN_EXTEND;
14485 ExtOpcRHS = ISD::ZERO_EXTEND;
14486 break;
14488 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
14489 break;
14490 }
14491
14492 // A wide partial reduction is built from a ladder of narrower ones, a rung
14493 // at a time, each halving the element count and doubling the width.
14494 unsigned Opc = N->getOpcode();
14495 ElementCount MulEC = MulOpVT.getVectorElementCount();
14496 ElementCount AccEC = AccVT.getVectorElementCount();
14497 unsigned CountRatio =
14498 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
14499 unsigned WidthRatio =
14500 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
14501 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
14502 LLVMContext &Ctx = *DAG.getContext();
14503 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
14504
14505 // A pure reduction peels one rung and re-enters.
14506 if (llvm::isOneOrOneSplat(MulRHS)) {
14507 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
14508 return DAG.getNode(Opc, DL, AccVT, Acc,
14509 DAG.getNode(Opc, DL, RungVT,
14510 DAG.getConstant(0, DL, RungVT), MulLHS,
14511 MulRHS),
14512 DAG.getConstant(1, DL, RungVT));
14513 }
14514
14515 // A multiply widens the products by one rung, which legalizes back into a
14516 // widening multiply per half, and the ladder re-enters as a plain sum.
14517 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
14518 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
14519 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
14520 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
14521 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
14522
14523 // The halves meet at the narrowest rung, so the accumulator is added once.
14524 EVT MidVT = Lo.getValueType()
14525 .widenIntegerVectorElementType(Ctx)
14526 .getHalfNumVectorElementsVT(Ctx);
14528 return DAG.getNode(Opc, DL, AccVT,
14529 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
14530 SDValue Mid =
14531 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
14532 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
14533 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
14534 }
14535
14536 if (ExtMulOpVT != MulOpVT) {
14537 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
14538 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
14539 }
14540 SDValue Input = MulLHS;
14541 // Maintain the FP flags (if any).
14542 SDNodeFlags Flags = N->getFlags();
14543 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
14544 if (!llvm::isOneOrOneSplatFP(MulRHS))
14545 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS, Flags);
14546 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
14547 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14548 }
14549
14550 unsigned Stride = AccVT.getVectorMinNumElements();
14551 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
14552
14553 // Collect all of the subvectors
14554 std::deque<SDValue> Subvectors = {Acc};
14555 for (unsigned I = 0; I < ScaleFactor; I++)
14556 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
14557
14558 unsigned FlatNode =
14559 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
14560
14561 // Flatten the subvector tree
14562 while (Subvectors.size() > 1) {
14563 Subvectors.push_back(DAG.getNode(FlatNode, DL, AccVT,
14564 {Subvectors[0], Subvectors[1]}, Flags));
14565 Subvectors.pop_front();
14566 Subvectors.pop_front();
14567 }
14568
14569 assert(Subvectors.size() == 1 &&
14570 "There should only be one subvector after tree flattening");
14571
14572 return Subvectors[0];
14573}
14574
14575/// Given a store node \p StoreNode, return true if it is safe to fold that node
14576/// into \p FPNode, which expands to a library call with output pointers.
14578 SDNode *FPNode,
14579 unsigned MaxSteps) {
14581 SmallVector<const SDNode *, 8> DeferredNodes;
14583
14584 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
14585 for (SDValue Op : StoreNode->ops())
14586 if (Op.getNode() != FPNode)
14587 Worklist.push_back(Op.getNode());
14588
14589 while (!Worklist.empty()) {
14590 const SDNode *Node = Worklist.pop_back_val();
14591 auto [_, Inserted] = Visited.insert(Node);
14592 if (!Inserted)
14593 continue;
14594
14595 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
14596 return false;
14597
14598 // Reached the FPNode (would result in a cycle).
14599 // OR Reached CALLSEQ_START (would result in nested call sequences).
14600 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
14601 return false;
14602
14603 if (Node->getOpcode() == ISD::CALLSEQ_END) {
14604 // Defer looking into call sequences (so we can check we're outside one).
14605 // We still need to look through these for the predecessor check.
14606 DeferredNodes.push_back(Node);
14607 continue;
14608 }
14609
14610 for (SDValue Op : Node->ops())
14611 Worklist.push_back(Op.getNode());
14612 }
14613
14614 // True if we're outside a call sequence and don't have the FPNode as a
14615 // predecessor. No cycles or nested call sequences possible.
14616 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
14617 MaxSteps);
14618}
14619
14621 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
14623 std::optional<unsigned> CallRetResNo) const {
14624 if (LC == RTLIB::UNKNOWN_LIBCALL)
14625 return false;
14626
14627 RTLIB::LibcallImpl LibcallImpl =
14629 if (LibcallImpl == RTLIB::Unsupported)
14630 return false;
14631
14632 LLVMContext &Ctx = *DAG.getContext();
14633 EVT VT = Node->getValueType(0);
14634 unsigned NumResults = Node->getNumValues();
14635 unsigned MaxSteps = DAG.getHasPredecessorMaxSteps();
14636
14637 // Find users of the node that store the results (and share input chains). The
14638 // destination pointers can be used instead of creating stack allocations.
14639 SDValue StoresInChain;
14640 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
14641 for (SDNode *User : Node->users()) {
14643 continue;
14644 auto *ST = cast<StoreSDNode>(User);
14645 SDValue StoreValue = ST->getValue();
14646 unsigned ResNo = StoreValue.getResNo();
14647 // Ensure the store corresponds to an output pointer.
14648 if (CallRetResNo == ResNo)
14649 continue;
14650 // Ensure the store to the default address space and not atomic or volatile.
14651 if (!ST->isSimple() || ST->getAddressSpace() != 0)
14652 continue;
14653 // Ensure all store chains are the same (so they don't alias).
14654 if (StoresInChain && ST->getChain() != StoresInChain)
14655 continue;
14656 // Ensure the store is properly aligned.
14657 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
14658 if (ST->getAlign() <
14659 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
14660 continue;
14661 // Avoid:
14662 // 1. Creating cyclic dependencies.
14663 // 2. Expanding the node to a call within a call sequence.
14664 if (!canFoldStoreIntoLibCallOutputPointers(ST, Node, MaxSteps))
14665 continue;
14666 ResultStores[ResNo] = ST;
14667 StoresInChain = ST->getChain();
14668 }
14669
14670 ArgListTy Args;
14671
14672 // Pass the arguments.
14673 for (const SDValue &Op : Node->op_values()) {
14674 EVT ArgVT = Op.getValueType();
14675 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
14676 Args.emplace_back(Op, ArgTy);
14677 }
14678
14679 // Pass the output pointers.
14680 SmallVector<SDValue, 2> ResultPtrs(NumResults);
14682 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
14683 if (ResNo == CallRetResNo)
14684 continue;
14685 EVT ResVT = Node->getValueType(ResNo);
14686 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
14687 ResultPtrs[ResNo] = ResultPtr;
14688 Args.emplace_back(ResultPtr, PointerTy);
14689 }
14690
14691 SDLoc DL(Node);
14692
14694 // Pass the vector mask (if required).
14695 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
14696 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
14697 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14698 }
14699
14700 Type *RetType = CallRetResNo.has_value()
14701 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14702 : Type::getVoidTy(Ctx);
14703 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14704 SDValue Callee =
14705 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14707 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14708 DAG.getLibcalls().getLibcallImplCallingConv(LibcallImpl), RetType, Callee,
14709 std::move(Args));
14710
14711 auto [Call, CallChain] = LowerCallTo(CLI);
14712
14713 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14714 if (ResNo == CallRetResNo) {
14715 Results.push_back(Call);
14716 continue;
14717 }
14718 MachinePointerInfo PtrInfo;
14719 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14720 ResultPtr, PtrInfo);
14721 SDValue OutChain = LoadResult.getValue(1);
14722
14723 if (StoreSDNode *ST = ResultStores[ResNo]) {
14724 // Replace store with the library call.
14725 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14726 PtrInfo = ST->getPointerInfo();
14727 } else {
14729 DAG.getMachineFunction(),
14730 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14731 }
14732
14733 Results.push_back(LoadResult);
14734 }
14735
14736 return true;
14737}
14738
14740 SDValue &LHS, SDValue &RHS,
14741 SDValue &CC, bool &NeedInvert,
14742 const SDLoc &dl, SDValue &Chain,
14743 bool IsSignaling) const {
14744 MVT OpVT = LHS.getSimpleValueType();
14745 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14746 NeedInvert = false;
14747 switch (getCondCodeAction(CCCode, OpVT)) {
14748 default:
14749 llvm_unreachable("Unknown condition code action!");
14751 // Nothing to do.
14752 break;
14755 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14756 std::swap(LHS, RHS);
14757 CC = DAG.getCondCode(InvCC);
14758 return true;
14759 }
14760 // Swapping operands didn't work. Try inverting the condition.
14761 bool NeedSwap = false;
14762 InvCC = getSetCCInverse(CCCode, OpVT);
14763 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14764 // If inverting the condition is not enough, try swapping operands
14765 // on top of it.
14766 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14767 NeedSwap = true;
14768 }
14769 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14770 CC = DAG.getCondCode(InvCC);
14771 NeedInvert = true;
14772 if (NeedSwap)
14773 std::swap(LHS, RHS);
14774 return true;
14775 }
14776
14777 // Special case: expand i1 comparisons using logical operations.
14778 if (OpVT == MVT::i1) {
14779 SDValue Ret;
14780 switch (CCCode) {
14781 default:
14782 llvm_unreachable("Unknown integer setcc!");
14783 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14784 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14785 MVT::i1);
14786 break;
14787 case ISD::SETNE: // X != Y --> (X ^ Y)
14788 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14789 break;
14790 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14791 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14792 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14793 DAG.getNOT(dl, LHS, MVT::i1));
14794 break;
14795 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14796 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14797 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14798 DAG.getNOT(dl, RHS, MVT::i1));
14799 break;
14800 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14801 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14802 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14803 DAG.getNOT(dl, LHS, MVT::i1));
14804 break;
14805 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14806 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14807 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14808 DAG.getNOT(dl, RHS, MVT::i1));
14809 break;
14810 }
14811
14812 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14813 RHS = SDValue();
14814 CC = SDValue();
14815 return true;
14816 }
14817
14819 unsigned Opc = 0;
14820 switch (CCCode) {
14821 default:
14822 llvm_unreachable("Don't know how to expand this condition!");
14823 case ISD::SETUO:
14824 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14825 CC1 = ISD::SETUNE;
14826 CC2 = ISD::SETUNE;
14827 Opc = ISD::OR;
14828 break;
14829 }
14831 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14832 NeedInvert = true;
14833 [[fallthrough]];
14834 case ISD::SETO:
14836 "If SETO is expanded, SETOEQ must be legal!");
14837 CC1 = ISD::SETOEQ;
14838 CC2 = ISD::SETOEQ;
14839 Opc = ISD::AND;
14840 break;
14841 case ISD::SETONE:
14842 case ISD::SETUEQ:
14843 // If the SETUO or SETO CC isn't legal, we might be able to use
14844 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14845 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14846 // the operands.
14847 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14848 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14849 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14850 CC1 = ISD::SETOGT;
14851 CC2 = ISD::SETOLT;
14852 Opc = ISD::OR;
14853 NeedInvert = ((unsigned)CCCode & 0x8U);
14854 break;
14855 }
14856 [[fallthrough]];
14857 case ISD::SETOEQ:
14858 case ISD::SETOGT:
14859 case ISD::SETOGE:
14860 case ISD::SETOLT:
14861 case ISD::SETOLE:
14862 case ISD::SETUNE:
14863 case ISD::SETUGT:
14864 case ISD::SETUGE:
14865 case ISD::SETULT:
14866 case ISD::SETULE:
14867 // If we are floating point, assign and break, otherwise fall through.
14868 if (!OpVT.isInteger()) {
14869 // We can use the 4th bit to tell if we are the unordered
14870 // or ordered version of the opcode.
14871 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14872 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14873 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14874 break;
14875 }
14876 // Fallthrough if we are unsigned integer.
14877 [[fallthrough]];
14878 case ISD::SETLE:
14879 case ISD::SETGT:
14880 case ISD::SETGE:
14881 case ISD::SETLT:
14882 case ISD::SETNE:
14883 case ISD::SETEQ:
14884 // If all combinations of inverting the condition and swapping operands
14885 // didn't work then we have no means to expand the condition.
14886 llvm_unreachable("Don't know how to expand this condition!");
14887 }
14888
14889 SDValue SetCC1, SetCC2;
14890 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14891 // If we aren't the ordered or unorder operation,
14892 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14893 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14894 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14895 } else {
14896 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14897 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14898 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14899 }
14900 if (Chain)
14901 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14902 SetCC2.getValue(1));
14903 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14904 RHS = SDValue();
14905 CC = SDValue();
14906 return true;
14907 }
14908 }
14909 return false;
14910}
14911
14913 SelectionDAG &DAG) const {
14914 EVT VT = Node->getValueType(0);
14915 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14916 // split into two equal parts.
14917 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14918 return SDValue();
14919
14920 // Restrict expansion to cases where both parts can be concatenated.
14921 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14922 if (LoVT != HiVT || !isTypeLegal(LoVT))
14923 return SDValue();
14924
14925 SDLoc DL(Node);
14926 unsigned Opcode = Node->getOpcode();
14927
14928 // Don't expand if the result is likely to be unrolled anyway.
14929 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14930 return SDValue();
14931
14932 SmallVector<SDValue, 4> LoOps, HiOps;
14933 for (const SDValue &V : Node->op_values()) {
14934 if (!V.getValueType().isVector()) {
14935 // Scalar operands pass through to both halves unchanged.
14936 LoOps.push_back(V);
14937 HiOps.push_back(V);
14938 continue;
14939 }
14940 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14941 LoOps.push_back(Lo);
14942 HiOps.push_back(Hi);
14943 }
14944
14945 bool IsStrict = Node->isStrictFPOpcode();
14946 SDVTList LoVTs =
14947 IsStrict ? DAG.getVTList(LoVT, MVT::Other) : DAG.getVTList(LoVT);
14948 SDVTList HiVTs =
14949 IsStrict ? DAG.getVTList(HiVT, MVT::Other) : DAG.getVTList(HiVT);
14950 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVTs, LoOps, Node->getFlags());
14951 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVTs, HiOps, Node->getFlags());
14952 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14953
14954 if (!IsStrict)
14955 return Res;
14956
14957 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14958 SplitOpLo.getValue(1), SplitOpHi.getValue(1));
14959 return DAG.getMergeValues({Res, Chain}, DL);
14960}
14961
14963 const SDLoc &DL,
14964 EVT InVecVT, SDValue EltNo,
14965 LoadSDNode *OriginalLoad,
14966 SelectionDAG &DAG) const {
14967 assert(OriginalLoad->isSimple());
14968
14969 EVT VecEltVT = InVecVT.getVectorElementType();
14970
14971 // If the vector element type is not a multiple of a byte then we are unable
14972 // to correctly compute an address to load only the extracted element as a
14973 // scalar.
14974 if (!VecEltVT.isByteSized())
14975 return SDValue();
14976
14977 ISD::LoadExtType ExtTy =
14978 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14979 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14980 return SDValue();
14981
14982 std::optional<unsigned> ByteOffset;
14983 Align Alignment = OriginalLoad->getAlign();
14985 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14986 int Elt = ConstEltNo->getZExtValue();
14987 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14988 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14989 Alignment = commonAlignment(Alignment, *ByteOffset);
14990 } else {
14991 // Discard the pointer info except the address space because the memory
14992 // operand can't represent this new access since the offset is variable.
14993 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14994 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14995 }
14996
14997 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14998 return SDValue();
14999
15000 unsigned IsFast = 0;
15001 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
15002 OriginalLoad->getAddressSpace(), Alignment,
15003 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
15004 !IsFast)
15005 return SDValue();
15006
15007 // The original DAG loaded the entire vector from memory, so arithmetic
15008 // within it must be inbounds.
15010 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
15011
15012 // We are replacing a vector load with a scalar load. The new load must have
15013 // identical memory op ordering to the original.
15014 SDValue Load;
15015 if (ResultVT.bitsGT(VecEltVT)) {
15016 // If the result type of vextract is wider than the load, then issue an
15017 // extending load instead.
15018 ISD::LoadExtType ExtType =
15019 isLoadLegal(ResultVT, VecEltVT, Alignment,
15020 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
15022 : ISD::EXTLOAD;
15023 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
15024 NewPtr, MPI, VecEltVT, Alignment,
15025 OriginalLoad->getMemOperand()->getFlags(),
15026 OriginalLoad->getMMOMetadataForSubAccess());
15027 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
15028 } else {
15029 // The result type is narrower or the same width as the vector element
15030 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
15031 Alignment, OriginalLoad->getMemOperand()->getFlags(),
15032 OriginalLoad->getMMOMetadataForSubAccess());
15033 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
15034 if (ResultVT.bitsLT(VecEltVT))
15035 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
15036 else
15037 Load = DAG.getBitcast(ResultVT, Load);
15038 }
15039
15040 return Load;
15041}
15042
15043// Set type id for call site info and metadata 'call_target'.
15044// We are filtering for:
15045// a) The call-graph-section use case that wants to know about indirect
15046// calls, or
15047// b) We want to annotate indirect calls.
15049 const CallBase *CB, MachineFunction &MF,
15050 MachineFunction::CallSiteInfo &CSInfo) const {
15051 if (CB && CB->isIndirectCall() &&
15054 CSInfo = MachineFunction::CallSiteInfo(*CB);
15055}
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
#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
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
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:452
static constexpr roundingMode rmTowardZero
Definition APFloat.h:384
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:618
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:639
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:674
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:380
static LLVM_ABI bool hasSignBitInMSB(const fltSemantics &)
Definition APFloat.cpp:656
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:614
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:610
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:651
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:396
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1480
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1291
APInt bitcastToAPInt() const
Definition APFloat.h:1504
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1271
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1231
void changeSign()
Definition APFloat.h:1430
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1242
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:126
@ None
No attributes have been set.
Definition Attributes.h:128
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:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:220
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:34
iterator_range< regclass_iterator > regclasses() const
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
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:872
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
LLVM_ABI bool isConstantSplatVector(SDValue V, APInt &SplatValue)
Node predicates.
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:1717
@ 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:1699
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:967
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:1771
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:991
@ 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:1065
fltNanEncoding nanEncoding
Definition APFloat.h:1067