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 APInt SignMask = APInt::getSignMask(BitWidth);
3360
3361 if (!DemandedBits.intersects(SignMask))
3362 return TLO.CombineTo(Op, Op0);
3363
3364 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3365 Depth + 1))
3366 return true;
3367
3368 if (Known.isNonNegative())
3369 return TLO.CombineTo(Op, Op0);
3370 if (Known.isNegative())
3371 return TLO.CombineTo(
3372 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT, Op0, Op->getFlags()));
3373
3374 Known.Zero |= SignMask;
3375 Known.One &= ~SignMask;
3376
3377 break;
3378 }
3379 case ISD::FCOPYSIGN: {
3380 SDValue Op0 = Op.getOperand(0);
3381 SDValue Op1 = Op.getOperand(1);
3382
3383 unsigned BitWidth0 = Op0.getScalarValueSizeInBits();
3384 unsigned BitWidth1 = Op1.getScalarValueSizeInBits();
3385 APInt SignMask0 = APInt::getSignMask(BitWidth0);
3386 APInt SignMask1 = APInt::getSignMask(BitWidth1);
3387
3388 if (!DemandedBits.intersects(SignMask0))
3389 return TLO.CombineTo(Op, Op0);
3390
3391 if (SimplifyDemandedBits(Op0, ~SignMask0 & DemandedBits, DemandedElts,
3392 Known, TLO, Depth + 1) ||
3393 SimplifyDemandedBits(Op1, SignMask1, DemandedElts, Known2, TLO,
3394 Depth + 1))
3395 return true;
3396
3397 if (Known2.isNonNegative())
3398 return TLO.CombineTo(
3399 Op, TLO.DAG.getNode(ISD::FABS, dl, VT, Op0, Op->getFlags()));
3400
3401 if (Known2.isNegative())
3402 return TLO.CombineTo(
3403 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT,
3404 TLO.DAG.getNode(ISD::FABS, SDLoc(Op0), VT, Op0)));
3405
3406 Known.Zero &= ~SignMask0;
3407 Known.One &= ~SignMask0;
3408 break;
3409 }
3410 case ISD::FNEG: {
3411 SDValue Op0 = Op.getOperand(0);
3412 APInt SignMask = APInt::getSignMask(BitWidth);
3413
3414 if (!DemandedBits.intersects(SignMask))
3415 return TLO.CombineTo(Op, Op0);
3416
3417 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3418 Depth + 1))
3419 return true;
3420
3421 if (!Known.isSignUnknown()) {
3422 Known.Zero ^= SignMask;
3423 Known.One ^= SignMask;
3424 }
3425
3426 break;
3427 }
3428 default:
3429 // We also ask the target about intrinsics (which could be specific to it).
3430 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3431 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
3432 // TODO: Probably okay to remove after audit; here to reduce change size
3433 // in initial enablement patch for scalable vectors
3434 if (Op.getValueType().isScalableVector())
3435 break;
3437 Known, TLO, Depth))
3438 return true;
3439 break;
3440 }
3441
3442 // Just use computeKnownBits to compute output bits.
3443 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3444 break;
3445 }
3446
3447 // If we know the value of all of the demanded bits, return this as a
3448 // constant.
3450 DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
3451 // Avoid folding to a constant if any OpaqueConstant is involved.
3452 if (llvm::any_of(Op->ops(), [](SDValue V) {
3453 auto *C = dyn_cast<ConstantSDNode>(V);
3454 return C && C->isOpaque();
3455 }))
3456 return false;
3457 if (VT.isInteger())
3458 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
3459 if (VT.isFloatingPoint())
3460 return TLO.CombineTo(
3462 dl, VT));
3463 }
3464
3465 // A multi use 'all demanded elts' simplify failed to find any knownbits.
3466 // Try again just for the original demanded elts.
3467 // Ensure we do this AFTER constant folding above.
3468 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
3469 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
3470
3471 return false;
3472}
3473
3475 const APInt &DemandedElts,
3476 DAGCombinerInfo &DCI) const {
3477 SelectionDAG &DAG = DCI.DAG;
3478 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3479 !DCI.isBeforeLegalizeOps());
3480
3481 APInt KnownUndef, KnownZero;
3482 bool Simplified =
3483 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
3484 if (Simplified) {
3485 DCI.AddToWorklist(Op.getNode());
3486 DCI.CommitTargetLoweringOpt(TLO);
3487 }
3488
3489 return Simplified;
3490}
3491
3492/// Given a vector binary operation and known undefined elements for each input
3493/// operand, compute whether each element of the output is undefined.
3495 const APInt &UndefOp0,
3496 const APInt &UndefOp1) {
3497 EVT VT = BO.getValueType();
3499 "Vector binop only");
3500
3501 EVT EltVT = VT.getVectorElementType();
3502 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
3503 assert(UndefOp0.getBitWidth() == NumElts &&
3504 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
3505
3506 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
3507 const APInt &UndefVals) {
3508 if (UndefVals[Index])
3509 return DAG.getUNDEF(EltVT);
3510
3511 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
3512 // Try hard to make sure that the getNode() call is not creating temporary
3513 // nodes. Ignore opaque integers because they do not constant fold.
3514 SDValue Elt = BV->getOperand(Index);
3515 auto *C = dyn_cast<ConstantSDNode>(Elt);
3516 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
3517 return Elt;
3518 }
3519
3520 return SDValue();
3521 };
3522
3523 APInt KnownUndef = APInt::getZero(NumElts);
3524 for (unsigned i = 0; i != NumElts; ++i) {
3525 // If both inputs for this element are either constant or undef and match
3526 // the element type, compute the constant/undef result for this element of
3527 // the vector.
3528 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
3529 // not handle FP constants. The code within getNode() should be refactored
3530 // to avoid the danger of creating a bogus temporary node here.
3531 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
3532 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
3533 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
3534 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
3535 KnownUndef.setBit(i);
3536 }
3537 return KnownUndef;
3538}
3539
3541 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3542 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3543 bool AssumeSingleUse) const {
3544 EVT VT = Op.getValueType();
3545 unsigned Opcode = Op.getOpcode();
3546 APInt DemandedElts = OriginalDemandedElts;
3547 unsigned NumElts = DemandedElts.getBitWidth();
3548 assert(VT.isVector() && "Expected vector op");
3549
3550 KnownUndef = KnownZero = APInt::getZero(NumElts);
3551
3553 return false;
3554
3555 // TODO: For now we assume we know nothing about scalable vectors.
3556 if (VT.isScalableVector())
3557 return false;
3558
3559 assert(VT.getVectorNumElements() == NumElts &&
3560 "Mask size mismatches value type element count!");
3561
3562 // Undef operand.
3563 if (Op.isUndef()) {
3564 KnownUndef.setAllBits();
3565 return false;
3566 }
3567
3568 // If Op has other users, assume that all elements are needed.
3569 if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3570 DemandedElts.setAllBits();
3571
3572 // Not demanding any elements from Op.
3573 if (DemandedElts == 0) {
3574 KnownUndef.setAllBits();
3575 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3576 }
3577
3578 // Limit search depth.
3580 return false;
3581
3582 SDLoc DL(Op);
3583 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3584 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3585
3586 auto TryShrinkBinOp = [&](SDValue Op0, SDValue Op1) {
3587 unsigned ShrunkSize = getPreferredShrunkVectorSizeInBits(Op, DemandedElts);
3588 if (!ShrunkSize)
3589 return false;
3590
3591 assert(ShrunkSize % EltSizeInBits == 0 &&
3592 "Shrunk size not a multiple of element size");
3593 assert(ShrunkSize < VT.getSizeInBits() &&
3594 "Shrunk size must be < original vector size");
3595 assert(ShrunkSize >= EltSizeInBits * DemandedElts.getActiveBits() &&
3596 "Shrunk size must be >= demanded size");
3597
3598 EVT ShrunkVT = VT.changeVectorElementCount(
3599 *TLO.DAG.getContext(),
3600 ElementCount::getFixed(ShrunkSize / EltSizeInBits));
3601 Op0 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op0, 0);
3602 Op1 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op1, 0);
3603 SDValue NewOp =
3604 TLO.DAG.getNode(Opcode, DL, ShrunkVT, Op0, Op1, Op->getFlags());
3605 return TLO.CombineTo(
3606 Op, TLO.DAG.getInsertSubvector(DL, TLO.DAG.getUNDEF(VT), NewOp, 0));
3607 };
3608
3609 // Helper for demanding the specified elements and all the bits of both binary
3610 // operands.
3611 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3612 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3613 TLO.DAG, Depth + 1);
3614 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3615 TLO.DAG, Depth + 1);
3616 if (NewOp0 || NewOp1) {
3617 SDValue NewOp =
3618 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3619 NewOp1 ? NewOp1 : Op1, Op->getFlags());
3620 return TLO.CombineTo(Op, NewOp);
3621 }
3622
3623 if (TryShrinkBinOp(Op0, Op1))
3624 return true;
3625
3626 return false;
3627 };
3628
3629 switch (Opcode) {
3630 case ISD::SCALAR_TO_VECTOR: {
3631 if (!DemandedElts[0])
3632 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
3633 // Upper elements are poison, not undef - don't mark them as KnownUndef.
3634 break;
3635 }
3636 case ISD::BITCAST: {
3637 SDValue Src = Op.getOperand(0);
3638 EVT SrcVT = Src.getValueType();
3639
3640 if (!SrcVT.isVector()) {
3641 // TODO - bigendian once we have test coverage.
3642 if (IsLE) {
3643 APInt DemandedSrcBits = APInt::getZero(SrcVT.getSizeInBits());
3644 unsigned EltSize = VT.getScalarSizeInBits();
3645 for (unsigned I = 0; I != NumElts; ++I) {
3646 if (DemandedElts[I]) {
3647 unsigned Offset = I * EltSize;
3648 DemandedSrcBits.setBits(Offset, Offset + EltSize);
3649 }
3650 }
3652 if (SimplifyDemandedBits(Src, DemandedSrcBits, Known, TLO, Depth + 1))
3653 return true;
3654 }
3655 break;
3656 }
3657
3658 // Fast handling of 'identity' bitcasts.
3659 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3660 if (NumSrcElts == NumElts)
3661 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3662 KnownZero, TLO, Depth + 1);
3663
3664 APInt SrcDemandedElts, SrcZero, SrcUndef;
3665
3666 // Bitcast from 'large element' src vector to 'small element' vector, we
3667 // must demand a source element if any DemandedElt maps to it.
3668 if ((NumElts % NumSrcElts) == 0) {
3669 unsigned Scale = NumElts / NumSrcElts;
3670 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3671 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3672 TLO, Depth + 1))
3673 return true;
3674
3675 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3676 // of the large element.
3677 // TODO - bigendian once we have test coverage.
3678 if (IsLE) {
3679 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3680 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3681 for (unsigned i = 0; i != NumElts; ++i)
3682 if (DemandedElts[i]) {
3683 unsigned Ofs = (i % Scale) * EltSizeInBits;
3684 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3685 }
3686
3688 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3689 TLO, Depth + 1))
3690 return true;
3691
3692 // The bitcast has split each wide element into a number of
3693 // narrow subelements. We have just computed the Known bits
3694 // for wide elements. See if element splitting results in
3695 // some subelements being zero. Only for demanded elements!
3696 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3697 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3698 .isAllOnes())
3699 continue;
3700 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3701 unsigned Elt = Scale * SrcElt + SubElt;
3702 // A wholly-undef source lane is reported as undef below; don't also
3703 // flag it as zero, keeping the undef and zero sets disjoint.
3704 if (DemandedElts[Elt] && !SrcUndef[SrcElt])
3705 KnownZero.setBit(Elt);
3706 }
3707 }
3708 }
3709
3710 // If the src element is zero/undef then all the output elements will be -
3711 // only demanded elements are guaranteed to be correct.
3712 for (unsigned i = 0; i != NumSrcElts; ++i) {
3713 if (SrcDemandedElts[i]) {
3714 if (SrcZero[i])
3715 KnownZero.setBits(i * Scale, (i + 1) * Scale);
3716 if (SrcUndef[i])
3717 KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3718 }
3719 }
3720 }
3721
3722 // Bitcast from 'small element' src vector to 'large element' vector, we
3723 // demand all smaller source elements covered by the larger demanded element
3724 // of this vector.
3725 if ((NumSrcElts % NumElts) == 0) {
3726 unsigned Scale = NumSrcElts / NumElts;
3727 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3728 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3729 TLO, Depth + 1))
3730 return true;
3731
3732 // If all the src elements covering an output element are zero/undef, then
3733 // the output element will be as well, assuming it was demanded.
3734 for (unsigned i = 0; i != NumElts; ++i) {
3735 if (DemandedElts[i]) {
3736 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3737 KnownZero.setBit(i);
3738 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3739 KnownUndef.setBit(i);
3740 }
3741 }
3742 }
3743 break;
3744 }
3745 case ISD::FREEZE: {
3746 SDValue N0 = Op.getOperand(0);
3748 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
3749 return TLO.CombineTo(Op, N0);
3750
3751 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE
3752 // freeze(op(x, ...)) -> op(freeze(x), ...).
3753 // Don't sink the freeze below SCALAR_TO_VECTOR when the scalar is a load
3754 // of a promoted (wider than the element) type: freeze(load) can never be
3755 // folded away (the loaded value may be poison in memory), and the extra
3756 // freeze node then blocks ISel patterns matching scalar_to_vector of a
3757 // load, e.g. the AArch64 scalar_to_vector(extload) -> ldr b/h forms.
3758 // freeze(scalar_to_vector(load)) is equivalent for the demanded element
3759 // zero, and ISel selects the freeze as a plain copy.
3760 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) {
3761 SDValue Scalar = N0.getOperand(0);
3762 bool IsPromotedLoad = Scalar.getOpcode() == ISD::LOAD &&
3763 Scalar.getValueType() != VT.getVectorElementType();
3764 if (!IsPromotedLoad)
3765 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
3766 TLO.DAG.getFreeze(Scalar)));
3767 }
3768 break;
3769 }
3770 case ISD::BUILD_VECTOR: {
3771 // Check all elements and simplify any unused elements with UNDEF.
3772 if (!DemandedElts.isAllOnes()) {
3773 // Don't simplify BROADCASTS.
3774 if (llvm::any_of(Op->op_values(),
3775 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3777 bool Updated = false;
3778 for (unsigned i = 0; i != NumElts; ++i) {
3779 if (!DemandedElts[i] && !Ops[i].isUndef()) {
3780 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3781 KnownUndef.setBit(i);
3782 Updated = true;
3783 }
3784 }
3785 if (Updated)
3786 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3787 }
3788 }
3789 for (unsigned i = 0; i != NumElts; ++i) {
3790 SDValue SrcOp = Op.getOperand(i);
3791 if (SrcOp.isUndef()) {
3792 KnownUndef.setBit(i);
3793 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3795 KnownZero.setBit(i);
3796 }
3797 }
3798 break;
3799 }
3800 case ISD::CONCAT_VECTORS: {
3801 EVT SubVT = Op.getOperand(0).getValueType();
3802 unsigned NumSubVecs = Op.getNumOperands();
3803 unsigned NumSubElts = SubVT.getVectorNumElements();
3804 for (unsigned i = 0; i != NumSubVecs; ++i) {
3805 SDValue SubOp = Op.getOperand(i);
3806 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3807 APInt SubUndef, SubZero;
3808 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3809 Depth + 1))
3810 return true;
3811 KnownUndef.insertBits(SubUndef, i * NumSubElts);
3812 KnownZero.insertBits(SubZero, i * NumSubElts);
3813 }
3814
3815 // Attempt to avoid multi-use ops if we don't need anything from them.
3816 if (!DemandedElts.isAllOnes()) {
3817 bool FoundNewSub = false;
3818 SmallVector<SDValue, 2> DemandedSubOps;
3819 for (unsigned i = 0; i != NumSubVecs; ++i) {
3820 SDValue SubOp = Op.getOperand(i);
3821 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3823 SubOp, SubElts, TLO.DAG, Depth + 1);
3824 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3825 FoundNewSub = NewSubOp ? true : FoundNewSub;
3826 }
3827 if (FoundNewSub) {
3828 SDValue NewOp =
3829 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3830 return TLO.CombineTo(Op, NewOp);
3831 }
3832 }
3833 break;
3834 }
3835 case ISD::INSERT_SUBVECTOR: {
3836 // Demand any elements from the subvector and the remainder from the src it
3837 // is inserted into.
3838 SDValue Src = Op.getOperand(0);
3839 SDValue Sub = Op.getOperand(1);
3840 uint64_t Idx = Op.getConstantOperandVal(2);
3841 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3842 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3843 APInt DemandedSrcElts = DemandedElts;
3844 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3845
3846 // If none of the sub operand elements are demanded, bypass the insert.
3847 if (!DemandedSubElts)
3848 return TLO.CombineTo(Op, Src);
3849
3850 APInt SubUndef, SubZero;
3851 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3852 Depth + 1))
3853 return true;
3854
3855 // If none of the src operand elements are demanded, replace it with undef.
3856 if (!DemandedSrcElts && !Src.isUndef())
3857 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3858 TLO.DAG.getUNDEF(VT), Sub,
3859 Op.getOperand(2)));
3860
3861 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3862 TLO, Depth + 1))
3863 return true;
3864 KnownUndef.insertBits(SubUndef, Idx);
3865 KnownZero.insertBits(SubZero, Idx);
3866
3867 // Attempt to avoid multi-use ops if we don't need anything from them.
3868 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3870 Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3872 Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3873 if (NewSrc || NewSub) {
3874 NewSrc = NewSrc ? NewSrc : Src;
3875 NewSub = NewSub ? NewSub : Sub;
3876 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3877 NewSub, Op.getOperand(2));
3878 return TLO.CombineTo(Op, NewOp);
3879 }
3880 }
3881 break;
3882 }
3884 // Offset the demanded elts by the subvector index.
3885 SDValue Src = Op.getOperand(0);
3886 if (Src.getValueType().isScalableVector())
3887 break;
3888 uint64_t Idx = Op.getConstantOperandVal(1);
3889 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3890 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3891
3892 APInt SrcUndef, SrcZero;
3893 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3894 Depth + 1))
3895 return true;
3896 KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3897 KnownZero = SrcZero.extractBits(NumElts, Idx);
3898
3899 // Attempt to avoid multi-use ops if we don't need anything from them.
3900 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(Src, DemandedSrcElts,
3901 TLO.DAG, Depth + 1);
3902 if (NewSrc) {
3903 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3904 Op.getOperand(1));
3905 return TLO.CombineTo(Op, NewOp);
3906 }
3907 break;
3908 }
3910 SDValue Vec = Op.getOperand(0);
3911 SDValue Scl = Op.getOperand(1);
3912 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3913
3914 // For a legal, constant insertion index, if we don't need this insertion
3915 // then strip it, else remove it from the demanded elts.
3916 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3917 unsigned Idx = CIdx->getZExtValue();
3918 if (!DemandedElts[Idx])
3919 return TLO.CombineTo(Op, Vec);
3920
3921 APInt DemandedVecElts(DemandedElts);
3922 DemandedVecElts.clearBit(Idx);
3923 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3924 KnownZero, TLO, Depth + 1))
3925 return true;
3926
3927 KnownUndef.setBitVal(Idx, Scl.isUndef());
3928
3929 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3930 break;
3931 }
3932
3933 APInt VecUndef, VecZero;
3934 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3935 Depth + 1))
3936 return true;
3937 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3938 break;
3939 }
3940 case ISD::VSELECT: {
3941 SDValue Sel = Op.getOperand(0);
3942 SDValue LHS = Op.getOperand(1);
3943 SDValue RHS = Op.getOperand(2);
3944
3945 // Try to transform the select condition based on the current demanded
3946 // elements.
3947 APInt UndefSel, ZeroSel;
3948 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3949 Depth + 1))
3950 return true;
3951
3952 // See if we can simplify either vselect operand.
3953 APInt DemandedLHS(DemandedElts);
3954 APInt DemandedRHS(DemandedElts);
3955 APInt UndefLHS, ZeroLHS;
3956 APInt UndefRHS, ZeroRHS;
3957 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3958 Depth + 1))
3959 return true;
3960 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3961 Depth + 1))
3962 return true;
3963
3964 KnownUndef = UndefLHS & UndefRHS;
3965 KnownZero = ZeroLHS & ZeroRHS;
3966
3967 // If we know that the selected element is always zero, we don't need the
3968 // select value element.
3969 APInt DemandedSel = DemandedElts & ~KnownZero;
3970 if (DemandedSel != DemandedElts)
3971 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3972 Depth + 1))
3973 return true;
3974
3975 break;
3976 }
3977 case ISD::VECTOR_SHUFFLE: {
3978 SDValue LHS = Op.getOperand(0);
3979 SDValue RHS = Op.getOperand(1);
3980 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3981
3982 // Collect demanded elements from shuffle operands..
3983 APInt DemandedLHS(NumElts, 0);
3984 APInt DemandedRHS(NumElts, 0);
3985 for (unsigned i = 0; i != NumElts; ++i) {
3986 int M = ShuffleMask[i];
3987 if (M < 0 || !DemandedElts[i])
3988 continue;
3989 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3990 if (M < (int)NumElts)
3991 DemandedLHS.setBit(M);
3992 else
3993 DemandedRHS.setBit(M - NumElts);
3994 }
3995
3996 // If either side isn't demanded, replace it by UNDEF. We handle this
3997 // explicitly here to also simplify in case of multiple uses (on the
3998 // contrary to the SimplifyDemandedVectorElts calls below).
3999 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
4000 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
4001 if (FoldLHS || FoldRHS) {
4002 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
4003 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
4004 SDValue NewOp =
4005 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
4006 return TLO.CombineTo(Op, NewOp);
4007 }
4008
4009 // See if we can simplify either shuffle operand.
4010 APInt UndefLHS, ZeroLHS;
4011 APInt UndefRHS, ZeroRHS;
4012 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
4013 Depth + 1))
4014 return true;
4015 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
4016 Depth + 1))
4017 return true;
4018
4019 // Simplify mask using undef elements from LHS/RHS.
4020 bool Updated = false;
4021 bool IdentityLHS = true, IdentityRHS = true;
4022 SmallVector<int, 32> NewMask(ShuffleMask);
4023 for (unsigned i = 0; i != NumElts; ++i) {
4024 int &M = NewMask[i];
4025 if (M < 0)
4026 continue;
4027 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
4028 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
4029 Updated = true;
4030 M = -1;
4031 }
4032 IdentityLHS &= (M < 0) || (M == (int)i);
4033 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
4034 }
4035
4036 // Update legal shuffle masks based on demanded elements if it won't reduce
4037 // to Identity which can cause premature removal of the shuffle mask.
4038 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
4039 SDValue LegalShuffle =
4040 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
4041 if (LegalShuffle)
4042 return TLO.CombineTo(Op, LegalShuffle);
4043 }
4044
4045 // Propagate undef/zero elements from LHS/RHS.
4046 for (unsigned i = 0; i != NumElts; ++i) {
4047 int M = ShuffleMask[i];
4048 if (M < 0) {
4049 KnownUndef.setBit(i);
4050 } else if (M < (int)NumElts) {
4051 if (UndefLHS[M])
4052 KnownUndef.setBit(i);
4053 if (ZeroLHS[M])
4054 KnownZero.setBit(i);
4055 } else {
4056 if (UndefRHS[M - NumElts])
4057 KnownUndef.setBit(i);
4058 if (ZeroRHS[M - NumElts])
4059 KnownZero.setBit(i);
4060 }
4061 }
4062 break;
4063 }
4067 APInt SrcUndef, SrcZero;
4068 SDValue Src = Op.getOperand(0);
4069 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4070 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
4071 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
4072 Depth + 1))
4073 return true;
4074 KnownZero = SrcZero.zextOrTrunc(NumElts);
4075 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
4076
4077 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
4078 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
4079 DemandedSrcElts == 1) {
4080 // aext - if we just need the bottom element then we can bitcast.
4081 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
4082 }
4083
4084 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
4085 // zext(undef) upper bits are guaranteed to be zero.
4086 if (DemandedElts.isSubsetOf(KnownUndef))
4087 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4088 KnownUndef.clearAllBits();
4089
4090 // zext - if we just need the bottom element then we can mask:
4091 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
4092 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
4093 Op->isOnlyUserOf(Src.getNode()) &&
4094 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
4095 SDLoc DL(Op);
4096 EVT SrcVT = Src.getValueType();
4097 EVT SrcSVT = SrcVT.getScalarType();
4098
4099 // If we're after type legalization and SrcSVT is not legal, use the
4100 // promoted type for creating constants to avoid creating nodes with
4101 // illegal types.
4102 if (TLO.LegalTypes())
4103 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
4104
4105 SmallVector<SDValue> MaskElts;
4106 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
4107 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
4108 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
4109 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
4110 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
4111 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
4112 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
4113 }
4114 }
4115 }
4116 break;
4117 }
4118
4119 // TODO: There are more binop opcodes that could be handled here - MIN,
4120 // MAX, saturated math, etc.
4121 case ISD::ADD: {
4122 SDValue Op0 = Op.getOperand(0);
4123 SDValue Op1 = Op.getOperand(1);
4124 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
4125 APInt UndefLHS, ZeroLHS;
4126 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4127 Depth + 1, /*AssumeSingleUse*/ true))
4128 return true;
4129 }
4130 [[fallthrough]];
4131 }
4132 case ISD::AVGCEILS:
4133 case ISD::AVGCEILU:
4134 case ISD::AVGFLOORS:
4135 case ISD::AVGFLOORU:
4136 case ISD::AVGSUBFLOORS:
4137 case ISD::AVGSUBFLOORU:
4138 case ISD::OR:
4139 case ISD::XOR:
4140 case ISD::SUB:
4141 case ISD::FADD:
4142 case ISD::FSUB:
4143 case ISD::FMUL:
4144 case ISD::FDIV:
4145 case ISD::FREM:
4146 case ISD::PSEUDO_FMIN:
4147 case ISD::PSEUDO_FMAX: {
4148 SDValue Op0 = Op.getOperand(0);
4149 SDValue Op1 = Op.getOperand(1);
4150
4151 APInt UndefRHS, ZeroRHS;
4152 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4153 Depth + 1))
4154 return true;
4155 APInt UndefLHS, ZeroLHS;
4156 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4157 Depth + 1))
4158 return true;
4159
4160 KnownZero = ZeroLHS & ZeroRHS;
4161 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
4162
4163 // Attempt to avoid multi-use ops if we don't need anything from them.
4164 // TODO - use KnownUndef to relax the demandedelts?
4165 if (!DemandedElts.isAllOnes())
4166 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4167 return true;
4168 break;
4169 }
4170 case ISD::SHL:
4171 case ISD::SRL:
4172 case ISD::SRA:
4173 case ISD::ROTL:
4174 case ISD::ROTR: {
4175 SDValue Op0 = Op.getOperand(0);
4176 SDValue Op1 = Op.getOperand(1);
4177
4178 APInt UndefRHS, ZeroRHS;
4179 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4180 Depth + 1))
4181 return true;
4182 APInt UndefLHS, ZeroLHS;
4183 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4184 Depth + 1))
4185 return true;
4186
4187 KnownZero = ZeroLHS & ~UndefRHS;
4188 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
4189
4190 // Attempt to avoid multi-use ops if we don't need anything from them.
4191 // TODO - use KnownUndef to relax the demandedelts?
4192 if (!DemandedElts.isAllOnes())
4193 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4194 return true;
4195 break;
4196 }
4197 case ISD::MUL:
4198 case ISD::MULHU:
4199 case ISD::MULHS:
4200 case ISD::AND: {
4201 SDValue Op0 = Op.getOperand(0);
4202 SDValue Op1 = Op.getOperand(1);
4203
4204 APInt SrcUndef, SrcZero;
4205 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
4206 Depth + 1))
4207 return true;
4208 // FIXME: If we know that a demanded element was zero in Op1 we don't need
4209 // to demand it in Op0 - its guaranteed to be zero. There is however a
4210 // restriction, as we must not make any of the originally demanded elements
4211 // more poisonous. We could reduce amount of elements demanded, but then we
4212 // also need a to inform SimplifyDemandedVectorElts that some elements must
4213 // not be made more poisonous.
4214 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
4215 TLO, Depth + 1))
4216 return true;
4217
4218 KnownUndef &= DemandedElts;
4219 KnownZero &= DemandedElts;
4220
4221 // If every element pair has a zero/undef/poison then just fold to zero.
4222 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
4223 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
4224 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
4225 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4226
4227 // If either side has a zero element, then the result element is zero, even
4228 // if the other is an UNDEF.
4229 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
4230 // and then handle 'and' nodes with the rest of the binop opcodes.
4231 KnownZero |= SrcZero;
4232 KnownUndef &= SrcUndef;
4233 KnownUndef &= ~KnownZero;
4234
4235 // Attempt to avoid multi-use ops if we don't need anything from them.
4236 if (!DemandedElts.isAllOnes())
4237 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4238 return true;
4239 break;
4240 }
4241 case ISD::TRUNCATE:
4242 case ISD::SIGN_EXTEND:
4243 case ISD::ZERO_EXTEND:
4244 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4245 KnownZero, TLO, Depth + 1))
4246 return true;
4247
4248 if (!DemandedElts.isAllOnes())
4250 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
4251 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
4252
4253 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
4254 // zext(undef) upper bits are guaranteed to be zero.
4255 if (DemandedElts.isSubsetOf(KnownUndef))
4256 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4257 KnownUndef.clearAllBits();
4258 }
4259 break;
4260 case ISD::SINT_TO_FP:
4261 case ISD::UINT_TO_FP:
4262 case ISD::FP_TO_SINT:
4263 case ISD::FP_TO_UINT:
4264 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4265 KnownZero, TLO, Depth + 1))
4266 return true;
4267 // Don't fall through to generic undef -> undef handling.
4268 return false;
4269 default: {
4270 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
4271 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
4272 KnownZero, TLO, Depth))
4273 return true;
4274 } else {
4276 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
4277 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
4278 TLO, Depth, AssumeSingleUse))
4279 return true;
4280 }
4281 break;
4282 }
4283 }
4284
4285 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
4286
4287 // Constant fold all undef cases.
4288 // TODO: Handle zero cases as well.
4289 if (DemandedElts.isSubsetOf(KnownUndef))
4290 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
4291
4292 return false;
4293}
4294
4295/// Determine which of the bits specified in Mask are known to be either zero or
4296/// one and return them in the Known.
4299 const APInt &DemandedElts,
4300 const SelectionDAG &DAG,
4301 unsigned Depth) const {
4302 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4303 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4304 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4305 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4306 "Should use MaskedValueIsZero if you don't know whether Op"
4307 " is a target node!");
4308 Known.resetAll();
4309}
4310
4313 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4314 unsigned Depth) const {
4315 Known.resetAll();
4316}
4317
4320 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4321 unsigned Depth) const {
4322 Known.resetAll();
4323}
4324
4326 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4327 // The low bits are known zero if the pointer is aligned.
4328 Known.Zero.setLowBits(Log2(Alignment));
4329}
4330
4332 SelectionDAG &DAG,
4333 const SDLoc &DL,
4334 Align Alignment) const {
4335 // Materialize leading-zero stack object pointer facts as AssertZext.
4336 // Alignment-derived low zero bits are not represented on the returned DAG
4337 // value here.
4338 EVT PtrVT = Ptr.getValueType();
4339
4340 unsigned RegSize = PtrVT.getScalarSizeInBits();
4343 Alignment);
4344
4345 unsigned NumZeroBits = Known.countMinLeadingZeros();
4346 if (!NumZeroBits)
4347 return Ptr;
4348
4349 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4350 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4351}
4352
4358
4359/// This method can be implemented by targets that want to expose additional
4360/// information about sign bits to the DAG Combiner.
4362 const APInt &,
4363 const SelectionDAG &,
4364 unsigned Depth) const {
4365 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4366 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4367 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4368 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4369 "Should use ComputeNumSignBits if you don't know whether Op"
4370 " is a target node!");
4371 return 1;
4372}
4373
4375 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4376 const MachineRegisterInfo &MRI, unsigned Depth) const {
4377 return 1;
4378}
4379
4381 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4382 TargetLoweringOpt &TLO, unsigned Depth) const {
4383 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4384 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4385 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4386 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4387 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4388 " is a target node!");
4389 return false;
4390}
4391
4393 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4394 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4395 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4396 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4397 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4398 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4399 "Should use SimplifyDemandedBits if you don't know whether Op"
4400 " is a target node!");
4401 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4402 return false;
4403}
4404
4406 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4407 SelectionDAG &DAG, unsigned Depth) const {
4408 assert(
4409 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4410 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4411 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4412 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4413 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4414 " is a target node!");
4415 return SDValue();
4416}
4417
4418SDValue
4421 SelectionDAG &DAG) const {
4422 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4423 if (!LegalMask) {
4424 std::swap(N0, N1);
4426 LegalMask = isShuffleMaskLegal(Mask, VT);
4427 }
4428
4429 if (!LegalMask)
4430 return SDValue();
4431
4432 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4433}
4434
4436 return nullptr;
4437}
4438
4440 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4441 UndefPoisonKind Kind, unsigned Depth) const {
4442 assert(
4443 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4444 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4445 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4446 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4447 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4448 " is a target node!");
4449
4450 // If Op can't create undef/poison and none of its operands are undef/poison
4451 // then Op is never undef/poison.
4452 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4453 /*ConsiderFlags*/ true, Depth) &&
4454 all_of(Op->ops(), [&](SDValue V) {
4455 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4456 });
4457}
4458
4460 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4461 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4462 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4463 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4464 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4465 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4466 "Should use canCreateUndefOrPoison if you don't know whether Op"
4467 " is a target node!");
4468 // Be conservative and return true.
4469 return true;
4470}
4471
4474 const APInt &DemandedElts,
4475 const SelectionDAG &DAG,
4476 unsigned Depth) const {
4477 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4478 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4479 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4480 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4481 "Should use computeKnownFPClass if you don't know whether Op"
4482 " is a target node!");
4483}
4484
4486 const APInt &DemandedElts,
4487 const SelectionDAG &DAG,
4488 bool SNaN,
4489 unsigned Depth) const {
4490 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4491 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4492 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4493 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4494 "Should use isKnownNeverNaN if you don't know whether Op"
4495 " is a target node!");
4496 return false;
4497}
4498
4500 const APInt &DemandedElts,
4501 APInt &UndefElts,
4502 const SelectionDAG &DAG,
4503 unsigned Depth) const {
4504 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4505 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4506 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4507 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4508 "Should use isSplatValue if you don't know whether Op"
4509 " is a target node!");
4510 return false;
4511}
4512
4513// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4514// work with truncating build vectors and vectors with elements of less than
4515// 8 bits.
4517 if (!N)
4518 return false;
4519
4520 unsigned EltWidth;
4521 APInt CVal;
4522 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4523 /*AllowTruncation=*/true)) {
4524 CVal = CN->getAPIntValue();
4525 EltWidth = N.getValueType().getScalarSizeInBits();
4526 } else
4527 return false;
4528
4529 // If this is a truncating splat, truncate the splat value.
4530 // Otherwise, we may fail to match the expected values below.
4531 if (EltWidth < CVal.getBitWidth())
4532 CVal = CVal.trunc(EltWidth);
4533
4534 switch (getBooleanContents(N.getValueType())) {
4536 return CVal[0];
4538 return CVal.isOne();
4540 return CVal.isAllOnes();
4541 }
4542
4543 llvm_unreachable("Invalid boolean contents");
4544}
4545
4547 if (!N)
4548 return false;
4549
4551 if (!CN) {
4553 if (!BV)
4554 return false;
4555
4556 // Only interested in constant splats, we don't care about undef
4557 // elements in identifying boolean constants and getConstantSplatNode
4558 // returns NULL if all ops are undef;
4559 CN = BV->getConstantSplatNode();
4560 if (!CN)
4561 return false;
4562 }
4563
4564 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4565 return !CN->getAPIntValue()[0];
4566
4567 return CN->isZero();
4568}
4569
4571 bool SExt) const {
4572 if (VT == MVT::i1)
4573 return N->isOne();
4574
4576 switch (Cnt) {
4578 // An extended value of 1 is always true, unless its original type is i1,
4579 // in which case it will be sign extended to -1.
4580 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4583 return N->isAllOnes() && SExt;
4584 }
4585 llvm_unreachable("Unexpected enumeration.");
4586}
4587
4588/// This helper function of SimplifySetCC tries to optimize the comparison when
4589/// either operand of the SetCC node is a bitwise-and instruction.
4590SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4591 ISD::CondCode Cond, const SDLoc &DL,
4592 DAGCombinerInfo &DCI) const {
4593 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4594 std::swap(N0, N1);
4595
4596 SelectionDAG &DAG = DCI.DAG;
4597 EVT OpVT = N0.getValueType();
4598 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4599 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4600 return SDValue();
4601
4602 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4603 // iff everything but LSB is known zero:
4604 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4607 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4608 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4609 if (DAG.MaskedValueIsZero(N0, UpperBits))
4610 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4611 }
4612
4613 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4614 // test in a narrow type that we can truncate to with no cost. Examples:
4615 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4616 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4617 // TODO: This conservatively checks for type legality on the source and
4618 // destination types. That may inhibit optimizations, but it also
4619 // allows setcc->shift transforms that may be more beneficial.
4620 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4621 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4622 isTypeLegal(OpVT) && N0.hasOneUse()) {
4623 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4624 AndC->getAPIntValue().getActiveBits());
4625 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4626 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4627 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4628 return DAG.getSetCC(DL, VT, Trunc, Zero,
4630 }
4631 }
4632
4633 // Match these patterns in any of their permutations:
4634 // (X & Y) == Y
4635 // (X & Y) != Y
4636 SDValue X, Y;
4637 if (N0.getOperand(0) == N1) {
4638 X = N0.getOperand(1);
4639 Y = N0.getOperand(0);
4640 } else if (N0.getOperand(1) == N1) {
4641 X = N0.getOperand(0);
4642 Y = N0.getOperand(1);
4643 } else {
4644 return SDValue();
4645 }
4646
4647 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4648 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4649 // its liable to create and infinite loop.
4650 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4651 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4653 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4654 // Note that where Y is variable and is known to have at most one bit set
4655 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4656 // equivalent when Y == 0.
4657 assert(OpVT.isInteger());
4659 if (DCI.isBeforeLegalizeOps() ||
4661 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4662 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4663 // If the target supports an 'and-not' or 'and-complement' logic operation,
4664 // try to use that to make a comparison operation more efficient.
4665 // But don't do this transform if the mask is a single bit because there are
4666 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4667 // 'rlwinm' on PPC).
4668
4669 // Bail out if the compare operand that we want to turn into a zero is
4670 // already a zero (otherwise, infinite loop).
4671 if (isNullConstant(Y))
4672 return SDValue();
4673
4674 // Transform this into: ~X & Y == 0.
4675 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4676 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4677 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4678 }
4679
4680 return SDValue();
4681}
4682
4683/// This helper function of SimplifySetCC tries to optimize the comparison when
4684/// either operand of the SetCC node is a bitwise-or instruction.
4685/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4686SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4687 ISD::CondCode Cond, const SDLoc &DL,
4688 DAGCombinerInfo &DCI) const {
4689 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4690 std::swap(N0, N1);
4691
4692 SelectionDAG &DAG = DCI.DAG;
4693 EVT OpVT = N0.getValueType();
4694 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4695 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4696 return SDValue();
4697
4698 // (X | Y) == Y
4699 // (X | Y) != Y
4700 SDValue X;
4701 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4702 // If the target supports an 'and-not' or 'and-complement' logic operation,
4703 // try to use that to make a comparison operation more efficient.
4704
4705 // Bail out if the compare operand that we want to turn into a zero is
4706 // already a zero (otherwise, infinite loop).
4707 if (isNullConstant(N1))
4708 return SDValue();
4709
4710 // Transform this into: X & ~Y ==/!= 0.
4711 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4712 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4713 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4714 }
4715
4716 return SDValue();
4717}
4718
4719/// There are multiple IR patterns that could be checking whether certain
4720/// truncation of a signed number would be lossy or not. The pattern which is
4721/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4722/// We are looking for the following pattern: (KeptBits is a constant)
4723/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4724/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4725/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4726/// We will unfold it into the natural trunc+sext pattern:
4727/// ((%x << C) a>> C) dstcond %x
4728/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4729SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4730 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4731 const SDLoc &DL) const {
4732 // We must be comparing with a constant.
4733 ConstantSDNode *C1;
4734 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4735 return SDValue();
4736
4737 // N0 should be: add %x, (1 << (KeptBits-1))
4738 if (N0->getOpcode() != ISD::ADD)
4739 return SDValue();
4740
4741 // And we must be 'add'ing a constant.
4742 ConstantSDNode *C01;
4743 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4744 return SDValue();
4745
4746 SDValue X = N0->getOperand(0);
4747 EVT XVT = X.getValueType();
4748
4749 // Validate constants ...
4750
4751 APInt I1 = C1->getAPIntValue();
4752
4753 ISD::CondCode NewCond;
4754 if (Cond == ISD::CondCode::SETULT) {
4755 NewCond = ISD::CondCode::SETEQ;
4756 } else if (Cond == ISD::CondCode::SETULE) {
4757 NewCond = ISD::CondCode::SETEQ;
4758 // But need to 'canonicalize' the constant.
4759 I1 += 1;
4760 } else if (Cond == ISD::CondCode::SETUGT) {
4761 NewCond = ISD::CondCode::SETNE;
4762 // But need to 'canonicalize' the constant.
4763 I1 += 1;
4764 } else if (Cond == ISD::CondCode::SETUGE) {
4765 NewCond = ISD::CondCode::SETNE;
4766 } else
4767 return SDValue();
4768
4769 APInt I01 = C01->getAPIntValue();
4770
4771 auto checkConstants = [&I1, &I01]() -> bool {
4772 // Both of them must be power-of-two, and the constant from setcc is bigger.
4773 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4774 };
4775
4776 if (checkConstants()) {
4777 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4778 } else {
4779 // What if we invert constants? (and the target predicate)
4780 I1.negate();
4781 I01.negate();
4782 assert(XVT.isInteger());
4783 NewCond = getSetCCInverse(NewCond, XVT);
4784 if (!checkConstants())
4785 return SDValue();
4786 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4787 }
4788
4789 // They are power-of-two, so which bit is set?
4790 const unsigned KeptBits = I1.logBase2();
4791 const unsigned KeptBitsMinusOne = I01.logBase2();
4792
4793 // Magic!
4794 if (KeptBits != (KeptBitsMinusOne + 1))
4795 return SDValue();
4796 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4797
4798 // We don't want to do this in every single case.
4799 SelectionDAG &DAG = DCI.DAG;
4800 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4801 return SDValue();
4802
4803 // Unfold into: sext_inreg(%x) cond %x
4804 // Where 'cond' will be either 'eq' or 'ne'.
4805 SDValue SExtInReg = DAG.getNode(
4807 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4808 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4809}
4810
4811// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4812SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4813 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4814 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4816 "Should be a comparison with 0.");
4817 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4818 "Valid only for [in]equality comparisons.");
4819
4820 unsigned NewShiftOpcode;
4821 SDValue X, C, Y;
4822
4823 SelectionDAG &DAG = DCI.DAG;
4824
4825 // Look for '(C l>>/<< Y)'.
4826 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4827 // The shift should be one-use.
4828 if (!V.hasOneUse())
4829 return false;
4830 unsigned OldShiftOpcode = V.getOpcode();
4831 switch (OldShiftOpcode) {
4832 case ISD::SHL:
4833 NewShiftOpcode = ISD::SRL;
4834 break;
4835 case ISD::SRL:
4836 NewShiftOpcode = ISD::SHL;
4837 break;
4838 default:
4839 return false; // must be a logical shift.
4840 }
4841 // We should be shifting a constant.
4842 // FIXME: best to use isConstantOrConstantVector().
4843 C = V.getOperand(0);
4844 ConstantSDNode *CC =
4845 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4846 if (!CC)
4847 return false;
4848 Y = V.getOperand(1);
4849
4850 ConstantSDNode *XC =
4851 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4853 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4854 };
4855
4856 // LHS of comparison should be an one-use 'and'.
4857 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4858 return SDValue();
4859
4860 X = N0.getOperand(0);
4861 SDValue Mask = N0.getOperand(1);
4862
4863 // 'and' is commutative!
4864 if (!Match(Mask)) {
4865 std::swap(X, Mask);
4866 if (!Match(Mask))
4867 return SDValue();
4868 }
4869
4870 EVT VT = X.getValueType();
4871
4872 // Produce:
4873 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4874 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4875 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4876 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4877 return T2;
4878}
4879
4880/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4881/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4882/// handle the commuted versions of these patterns.
4883SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4884 ISD::CondCode Cond, const SDLoc &DL,
4885 DAGCombinerInfo &DCI) const {
4886 unsigned BOpcode = N0.getOpcode();
4887 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4888 "Unexpected binop");
4889 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4890
4891 // (X + Y) == X --> Y == 0
4892 // (X - Y) == X --> Y == 0
4893 // (X ^ Y) == X --> Y == 0
4894 SelectionDAG &DAG = DCI.DAG;
4895 EVT OpVT = N0.getValueType();
4896 SDValue X = N0.getOperand(0);
4897 SDValue Y = N0.getOperand(1);
4898 if (X == N1)
4899 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4900
4901 if (Y != N1)
4902 return SDValue();
4903
4904 // (X + Y) == Y --> X == 0
4905 // (X ^ Y) == Y --> X == 0
4906 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4907 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4908
4909 // The shift would not be valid if the operands are boolean (i1).
4910 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4911 return SDValue();
4912
4913 // (X - Y) == Y --> X == Y << 1
4914 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4915 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4916 if (!DCI.isCalledByLegalizer())
4917 DCI.AddToWorklist(YShl1.getNode());
4918 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4919}
4920
4922 SDValue N0, const APInt &C1,
4923 ISD::CondCode Cond, const SDLoc &dl,
4924 SelectionDAG &DAG) {
4925 // Look through truncs that don't change the value of a ctpop.
4926 // FIXME: Add vector support? Need to be careful with setcc result type below.
4927 SDValue CTPOP = N0;
4928 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4930 CTPOP = N0.getOperand(0);
4931
4932 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4933 return SDValue();
4934
4935 EVT CTVT = CTPOP.getValueType();
4936 SDValue CTOp = CTPOP.getOperand(0);
4937
4938 // Expand a power-of-2-or-zero comparison based on ctpop:
4939 // (ctpop x) u< 2 -> (x & x-1) == 0
4940 // (ctpop x) u> 1 -> (x & x-1) != 0
4941 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4942 // Keep the CTPOP if it is a cheap vector op.
4943 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4944 return SDValue();
4945
4946 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4947 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4948 return SDValue();
4949 if (C1 == 0 && (Cond == ISD::SETULT))
4950 return SDValue(); // This is handled elsewhere.
4951
4952 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4953
4954 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4955 SDValue Result = CTOp;
4956 for (unsigned i = 0; i < Passes; i++) {
4957 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4958 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4959 }
4961 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4962 }
4963
4964 // Expand a power-of-2 comparison based on ctpop
4965 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4966 // Keep the CTPOP if it is cheap.
4967 if (TLI.isCtpopFast(CTVT))
4968 return SDValue();
4969
4970 SDValue Zero = DAG.getConstant(0, dl, CTVT);
4971 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4972 assert(CTVT.isInteger());
4973 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4974
4975 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4976 // check before emitting a potentially unnecessary op.
4977 if (DAG.isKnownNeverZero(CTOp)) {
4978 // (ctpop x) == 1 --> (x & x-1) == 0
4979 // (ctpop x) != 1 --> (x & x-1) != 0
4980 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4981 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4982 return RHS;
4983 }
4984
4985 // (ctpop x) == 1 --> (x ^ x-1) > x-1
4986 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4987 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4989 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4990 }
4991
4992 return SDValue();
4993}
4994
4996 ISD::CondCode Cond, const SDLoc &dl,
4997 SelectionDAG &DAG) {
4998 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4999 return SDValue();
5000
5001 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
5002 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
5003 return SDValue();
5004
5005 auto getRotateSource = [](SDValue X) {
5006 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
5007 return X.getOperand(0);
5008 return SDValue();
5009 };
5010
5011 // Peek through a rotated value compared against 0 or -1:
5012 // (rot X, Y) == 0/-1 --> X == 0/-1
5013 // (rot X, Y) != 0/-1 --> X != 0/-1
5014 if (SDValue R = getRotateSource(N0))
5015 return DAG.getSetCC(dl, VT, R, N1, Cond);
5016
5017 // Peek through an 'or' of a rotated value compared against 0:
5018 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
5019 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
5020 //
5021 // TODO: Add the 'and' with -1 sibling.
5022 // TODO: Recurse through a series of 'or' ops to find the rotate.
5023 EVT OpVT = N0.getValueType();
5024 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
5025 if (SDValue R = getRotateSource(N0.getOperand(0))) {
5026 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
5027 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5028 }
5029 if (SDValue R = getRotateSource(N0.getOperand(1))) {
5030 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
5031 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5032 }
5033 }
5034
5035 return SDValue();
5036}
5037
5039 ISD::CondCode Cond, const SDLoc &dl,
5040 SelectionDAG &DAG) {
5041 // If we are testing for all-bits-clear, we might be able to do that with
5042 // less shifting since bit-order does not matter.
5043 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
5044 return SDValue();
5045
5046 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
5047 if (!C1 || !C1->isZero())
5048 return SDValue();
5049
5050 if (!N0.hasOneUse() ||
5051 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
5052 return SDValue();
5053
5054 unsigned BitWidth = N0.getScalarValueSizeInBits();
5055 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
5056 if (!ShAmtC)
5057 return SDValue();
5058
5059 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
5060 if (ShAmt == 0)
5061 return SDValue();
5062
5063 // Canonicalize fshr as fshl to reduce pattern-matching.
5064 if (N0.getOpcode() == ISD::FSHR)
5065 ShAmt = BitWidth - ShAmt;
5066
5067 // Match an 'or' with a specific operand 'Other' in either commuted variant.
5068 SDValue X, Y;
5069 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
5070 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
5071 return false;
5072 if (Or.getOperand(0) == Other) {
5073 X = Or.getOperand(0);
5074 Y = Or.getOperand(1);
5075 return true;
5076 }
5077 if (Or.getOperand(1) == Other) {
5078 X = Or.getOperand(1);
5079 Y = Or.getOperand(0);
5080 return true;
5081 }
5082 return false;
5083 };
5084
5085 EVT OpVT = N0.getValueType();
5086 EVT ShAmtVT = N0.getOperand(2).getValueType();
5087 SDValue F0 = N0.getOperand(0);
5088 SDValue F1 = N0.getOperand(1);
5089 if (matchOr(F0, F1)) {
5090 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
5091 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
5092 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
5093 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
5094 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5095 }
5096 if (matchOr(F1, F0)) {
5097 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
5098 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
5099 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
5100 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
5101 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5102 }
5103
5104 return SDValue();
5105}
5106
5107/// Try to simplify a setcc built with the specified operands and cc. If it is
5108/// unable to simplify it, return a null SDValue.
5110 ISD::CondCode Cond, bool foldBooleans,
5111 DAGCombinerInfo &DCI,
5112 const SDLoc &dl) const {
5113 SelectionDAG &DAG = DCI.DAG;
5114 const DataLayout &Layout = DAG.getDataLayout();
5115 EVT OpVT = N0.getValueType();
5117
5118 // Constant fold or commute setcc.
5119 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
5120 return Fold;
5121
5122 bool N0ConstOrSplat =
5123 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5124 bool N1ConstOrSplat =
5125 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5126
5127 // Canonicalize toward having the constant on the RHS.
5128 // TODO: Handle non-splat vector constants. All undef causes trouble.
5129 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
5130 // infinite loop here when we encounter one.
5132 if (N0ConstOrSplat && !N1ConstOrSplat &&
5133 (DCI.isBeforeLegalizeOps() ||
5134 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
5135 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5136
5137 // If we have a subtract with the same 2 non-constant operands as this setcc
5138 // -- but in reverse order -- then try to commute the operands of this setcc
5139 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
5140 // instruction on some targets.
5141 if (!N0ConstOrSplat && !N1ConstOrSplat &&
5142 (DCI.isBeforeLegalizeOps() ||
5143 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
5144 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
5145 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
5146 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5147
5148 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
5149 return V;
5150
5151 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
5152 return V;
5153
5154 if (auto *N1C = isConstOrConstSplat(N1)) {
5155 const APInt &C1 = N1C->getAPIntValue();
5156
5157 // Optimize some CTPOP cases.
5158 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
5159 return V;
5160
5161 // For equality to 0 of a no-wrap multiply, decompose and test each op:
5162 // X * Y == 0 --> (X == 0) || (Y == 0)
5163 // X * Y != 0 --> (X != 0) && (Y != 0)
5164 // TODO: This bails out if minsize is set, but if the target doesn't have a
5165 // single instruction multiply for this type, it would likely be
5166 // smaller to decompose.
5167 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5168 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
5169 (N0->getFlags().hasNoUnsignedWrap() ||
5170 N0->getFlags().hasNoSignedWrap()) &&
5171 !Attr.hasFnAttr(Attribute::MinSize)) {
5172 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5173 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
5174 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
5175 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
5176 }
5177
5178 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
5179 // equality comparison, then we're just comparing whether X itself is
5180 // zero.
5181 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
5182 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
5184 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
5185 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5186 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
5187 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
5188 // (srl (ctlz x), 5) == 0 -> X != 0
5189 // (srl (ctlz x), 5) != 1 -> X != 0
5190 Cond = ISD::SETNE;
5191 } else {
5192 // (srl (ctlz x), 5) != 0 -> X == 0
5193 // (srl (ctlz x), 5) == 1 -> X == 0
5194 Cond = ISD::SETEQ;
5195 }
5196 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
5197 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
5198 Cond);
5199 }
5200 }
5201 }
5202 }
5203
5204 // setcc X, 0, setlt --> X (when X is all sign bits)
5205 // setcc X, 0, setne --> X (when X is all sign bits)
5206 //
5207 // When we know that X has 0 or -1 in each element (or scalar), this
5208 // comparison will produce X. This is only true when boolean contents are
5209 // represented via 0s and -1s.
5210 if (VT == OpVT &&
5211 // Check that the result of setcc is 0 and -1.
5213 // Match only for checks X < 0 and X != 0
5214 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
5215 // The identity holds iff we know all sign bits for all lanes.
5217 return N0;
5218
5219 // FIXME: Support vectors.
5220 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5221 const APInt &C1 = N1C->getAPIntValue();
5222
5223 // (zext x) == C --> x == (trunc C)
5224 // (sext x) == C --> x == (trunc C)
5225 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5226 DCI.isBeforeLegalize() && N0->hasOneUse()) {
5227 unsigned MinBits = N0.getValueSizeInBits();
5228 SDValue PreExt;
5229 bool Signed = false;
5230 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
5231 // ZExt
5232 MinBits = N0->getOperand(0).getValueSizeInBits();
5233 PreExt = N0->getOperand(0);
5234 } else if (N0->getOpcode() == ISD::AND) {
5235 // DAGCombine turns costly ZExts into ANDs
5236 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
5237 if ((C->getAPIntValue()+1).isPowerOf2()) {
5238 MinBits = C->getAPIntValue().countr_one();
5239 PreExt = N0->getOperand(0);
5240 }
5241 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
5242 // SExt
5243 MinBits = N0->getOperand(0).getValueSizeInBits();
5244 PreExt = N0->getOperand(0);
5245 Signed = true;
5246 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
5247 // ZEXTLOAD / SEXTLOAD
5248 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
5249 MinBits = LN0->getMemoryVT().getSizeInBits();
5250 PreExt = N0;
5251 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
5252 Signed = true;
5253 MinBits = LN0->getMemoryVT().getSizeInBits();
5254 PreExt = N0;
5255 }
5256 }
5257
5258 // Figure out how many bits we need to preserve this constant.
5259 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
5260
5261 // Make sure we're not losing bits from the constant.
5262 if (MinBits > 0 &&
5263 MinBits < C1.getBitWidth() &&
5264 MinBits >= ReqdBits) {
5265 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
5266 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
5267 // Will get folded away.
5268 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
5269 if (MinBits == 1 && C1 == 1)
5270 // Invert the condition.
5271 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
5273 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
5274 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
5275 }
5276
5277 // If truncating the setcc operands is not desirable, we can still
5278 // simplify the expression in some cases:
5279 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
5280 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
5281 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
5282 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
5283 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
5284 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
5285 SDValue TopSetCC = N0->getOperand(0);
5286 unsigned N0Opc = N0->getOpcode();
5287 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
5288 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
5289 TopSetCC.getOpcode() == ISD::SETCC &&
5290 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
5291 (isConstFalseVal(N1) ||
5292 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
5293
5294 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
5295 (!N1C->isZero() && Cond == ISD::SETNE);
5296
5297 if (!Inverse)
5298 return TopSetCC;
5299
5300 ISD::CondCode InvCond =
5302 TopSetCC.getOperand(0).getValueType());
5303 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
5304 TopSetCC.getOperand(1), InvCond);
5305 }
5306 }
5307 }
5308
5309 // If the LHS is '(and load, const)', the RHS is 0, the test is for
5310 // equality or unsigned, and all 1 bits of the const are in the same
5311 // partial word, see if we can shorten the load.
5312 if (DCI.isBeforeLegalize() &&
5314 N0.getOpcode() == ISD::AND && C1 == 0 &&
5315 N0.getNode()->hasOneUse() &&
5316 isa<LoadSDNode>(N0.getOperand(0)) &&
5317 N0.getOperand(0).getNode()->hasOneUse() &&
5319 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5320 APInt bestMask;
5321 unsigned bestWidth = 0, bestOffset = 0;
5322 if (Lod->isSimple() && Lod->isUnindexed() &&
5323 (Lod->getMemoryVT().isByteSized() ||
5324 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5325 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5326 unsigned origWidth = N0.getValueSizeInBits();
5327 unsigned maskWidth = origWidth;
5328 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5329 // 8 bits, but have to be careful...
5330 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5331 origWidth = Lod->getMemoryVT().getSizeInBits();
5332 const APInt &Mask = N0.getConstantOperandAPInt(1);
5333 // Only consider power-of-2 widths (and at least one byte) as candiates
5334 // for the narrowed load.
5335 for (unsigned width = 8; width < origWidth; width *= 2) {
5336 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5337 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5338 // Avoid accessing any padding here for now (we could use memWidth
5339 // instead of origWidth here otherwise).
5340 unsigned maxOffset = origWidth - width;
5341 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5342 if (Mask.isSubsetOf(newMask)) {
5343 unsigned ptrOffset =
5344 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5345 unsigned IsFast = 0;
5346 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5347 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5349 ptrOffset / 8) &&
5351 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5352 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5353 IsFast) {
5354 bestOffset = ptrOffset / 8;
5355 bestMask = Mask.lshr(offset);
5356 bestWidth = width;
5357 break;
5358 }
5359 }
5360 newMask <<= 8;
5361 }
5362 if (bestWidth)
5363 break;
5364 }
5365 }
5366 if (bestWidth) {
5367 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5368 SDValue Ptr = Lod->getBasePtr();
5369 if (bestOffset != 0)
5370 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5371 SDValue NewLoad =
5372 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5373 Lod->getPointerInfo().getWithOffset(bestOffset),
5374 Lod->getBaseAlign(), MachineMemOperand::MONone,
5375 Lod->getMMOMetadataForSubAccess());
5376 SDValue And =
5377 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5378 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5379 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5380 }
5381 }
5382
5383 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5384 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5385 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5386
5387 // If the comparison constant has bits in the upper part, the
5388 // zero-extended value could never match.
5389 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
5390 C1.getBitWidth() - InSize))) {
5391 switch (Cond) {
5392 case ISD::SETUGT:
5393 case ISD::SETUGE:
5394 case ISD::SETEQ:
5395 return DAG.getConstant(0, dl, VT);
5396 case ISD::SETULT:
5397 case ISD::SETULE:
5398 case ISD::SETNE:
5399 return DAG.getConstant(1, dl, VT);
5400 case ISD::SETGT:
5401 case ISD::SETGE:
5402 // True if the sign bit of C1 is set.
5403 return DAG.getConstant(C1.isNegative(), dl, VT);
5404 case ISD::SETLT:
5405 case ISD::SETLE:
5406 // True if the sign bit of C1 isn't set.
5407 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5408 default:
5409 break;
5410 }
5411 }
5412
5413 // Otherwise, we can perform the comparison with the low bits.
5414 switch (Cond) {
5415 case ISD::SETEQ:
5416 case ISD::SETNE:
5417 case ISD::SETUGT:
5418 case ISD::SETUGE:
5419 case ISD::SETULT:
5420 case ISD::SETULE: {
5421 EVT newVT = N0.getOperand(0).getValueType();
5422 // FIXME: Should use isNarrowingProfitable.
5423 if (DCI.isBeforeLegalizeOps() ||
5424 (isOperationLegal(ISD::SETCC, newVT) &&
5425 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5427 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5428 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5429
5430 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5431 NewConst, Cond);
5432 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5433 }
5434 break;
5435 }
5436 default:
5437 break; // todo, be more careful with signed comparisons
5438 }
5439 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5440 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5442 OpVT)) {
5443 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5444 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5445 EVT ExtDstTy = N0.getValueType();
5446 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5447
5448 // If the constant doesn't fit into the number of bits for the source of
5449 // the sign extension, it is impossible for both sides to be equal.
5450 if (C1.getSignificantBits() > ExtSrcTyBits)
5451 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5452
5453 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5454 ExtDstTy != ExtSrcTy && "Unexpected types!");
5455 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5456 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5457 DAG.getConstant(Imm, dl, ExtDstTy));
5458 if (!DCI.isCalledByLegalizer())
5459 DCI.AddToWorklist(ZextOp.getNode());
5460 // Otherwise, make this a use of a zext.
5461 return DAG.getSetCC(dl, VT, ZextOp,
5462 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5463 } else if ((N1C->isZero() || N1C->isOne()) &&
5464 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5465 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5466 // excluded as they are handled below whilst checking for foldBooleans.
5467 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5468 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5469 (N0.getValueType() == MVT::i1 ||
5473 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5474 if (TrueWhenTrue)
5475 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5476 // Invert the condition.
5477 if (N0.getOpcode() == ISD::SETCC) {
5480 if (DCI.isBeforeLegalizeOps() ||
5482 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5483 }
5484 }
5485
5486 if ((N0.getOpcode() == ISD::XOR ||
5487 (N0.getOpcode() == ISD::AND &&
5488 N0.getOperand(0).getOpcode() == ISD::XOR &&
5489 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5490 isOneConstant(N0.getOperand(1))) {
5491 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5492 // can only do this if the top bits are known zero.
5493 unsigned BitWidth = N0.getValueSizeInBits();
5494 if (DAG.MaskedValueIsZero(N0,
5496 BitWidth-1))) {
5497 // Okay, get the un-inverted input value.
5498 SDValue Val;
5499 if (N0.getOpcode() == ISD::XOR) {
5500 Val = N0.getOperand(0);
5501 } else {
5502 assert(N0.getOpcode() == ISD::AND &&
5503 N0.getOperand(0).getOpcode() == ISD::XOR);
5504 // ((X^1)&1)^1 -> X & 1
5505 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5506 N0.getOperand(0).getOperand(0),
5507 N0.getOperand(1));
5508 }
5509
5510 return DAG.getSetCC(dl, VT, Val, N1,
5512 }
5513 } else if (N1C->isOne()) {
5514 SDValue Op0 = N0;
5515 if (Op0.getOpcode() == ISD::TRUNCATE)
5516 Op0 = Op0.getOperand(0);
5517
5518 if ((Op0.getOpcode() == ISD::XOR) &&
5519 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5520 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5521 SDValue XorLHS = Op0.getOperand(0);
5522 SDValue XorRHS = Op0.getOperand(1);
5523 // Ensure that the input setccs return an i1 type or 0/1 value.
5524 if (Op0.getValueType() == MVT::i1 ||
5529 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5531 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5532 }
5533 }
5534 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5535 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5536 if (Op0.getValueType().bitsGT(VT))
5537 Op0 = DAG.getNode(ISD::AND, dl, VT,
5538 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5539 DAG.getConstant(1, dl, VT));
5540 else if (Op0.getValueType().bitsLT(VT))
5541 Op0 = DAG.getNode(ISD::AND, dl, VT,
5542 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5543 DAG.getConstant(1, dl, VT));
5544
5545 return DAG.getSetCC(dl, VT, Op0,
5546 DAG.getConstant(0, dl, Op0.getValueType()),
5548 }
5549 if (Op0.getOpcode() == ISD::AssertZext &&
5550 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5551 return DAG.getSetCC(dl, VT, Op0,
5552 DAG.getConstant(0, dl, Op0.getValueType()),
5554 }
5555 }
5556
5557 // Given:
5558 // icmp eq/ne (urem %x, %y), 0
5559 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5560 // icmp eq/ne %x, 0
5561 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5562 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5563 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5564 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5565 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5566 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5567 }
5568
5569 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5570 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5571 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5573 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5574 N1C->isAllOnes()) {
5575 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5576 DAG.getConstant(0, dl, OpVT),
5578 }
5579
5580 // fold (setcc (trunc x) c) -> (setcc x c)
5581 if (N0.getOpcode() == ISD::TRUNCATE &&
5583 (N0->getFlags().hasNoSignedWrap() &&
5586 EVT NewVT = N0.getOperand(0).getValueType();
5587 SDValue NewConst = DAG.getConstant(
5589 ? C1.sext(NewVT.getSizeInBits())
5590 : C1.zext(NewVT.getSizeInBits()),
5591 dl, NewVT);
5592 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5593 }
5594
5595 if (SDValue V =
5596 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5597 return V;
5598 }
5599
5600 // These simplifications apply to splat vectors as well.
5601 // TODO: Handle more splat vector cases.
5602 if (auto *N1C = isConstOrConstSplat(N1)) {
5603 const APInt &C1 = N1C->getAPIntValue();
5604
5605 APInt MinVal, MaxVal;
5606 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5608 MinVal = APInt::getSignedMinValue(OperandBitSize);
5609 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5610 } else {
5611 MinVal = APInt::getMinValue(OperandBitSize);
5612 MaxVal = APInt::getMaxValue(OperandBitSize);
5613 }
5614
5615 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5616 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5617 // X >= MIN --> true
5618 if (C1 == MinVal)
5619 return DAG.getBoolConstant(true, dl, VT, OpVT);
5620
5621 if (!VT.isVector()) { // TODO: Support this for vectors.
5622 // X >= C0 --> X > (C0 - 1)
5623 APInt C = C1 - 1;
5625 if ((DCI.isBeforeLegalizeOps() ||
5626 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5627 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5628 isLegalICmpImmediate(C.getSExtValue())))) {
5629 return DAG.getSetCC(dl, VT, N0,
5630 DAG.getConstant(C, dl, N1.getValueType()),
5631 NewCC);
5632 }
5633 }
5634 }
5635
5636 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5637 // X <= MAX --> true
5638 if (C1 == MaxVal)
5639 return DAG.getBoolConstant(true, dl, VT, OpVT);
5640
5641 // X <= C0 --> X < (C0 + 1)
5642 if (!VT.isVector()) { // TODO: Support this for vectors.
5643 APInt C = C1 + 1;
5645 if ((DCI.isBeforeLegalizeOps() ||
5646 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5647 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5648 isLegalICmpImmediate(C.getSExtValue())))) {
5649 return DAG.getSetCC(dl, VT, N0,
5650 DAG.getConstant(C, dl, N1.getValueType()),
5651 NewCC);
5652 }
5653 }
5654 }
5655
5656 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5657 if (C1 == MinVal)
5658 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5659
5660 // TODO: Support this for vectors after legalize ops.
5661 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5662 // Canonicalize setlt X, Max --> setne X, Max
5663 if (C1 == MaxVal)
5664 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5665
5666 // If we have setult X, 1, turn it into seteq X, 0
5667 if (C1 == MinVal+1)
5668 return DAG.getSetCC(dl, VT, N0,
5669 DAG.getConstant(MinVal, dl, N0.getValueType()),
5670 ISD::SETEQ);
5671 }
5672 }
5673
5674 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5675 if (C1 == MaxVal)
5676 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5677
5678 // TODO: Support this for vectors after legalize ops.
5679 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5680 // Canonicalize setgt X, Min --> setne X, Min
5681 if (C1 == MinVal)
5682 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5683
5684 // If we have setugt X, Max-1, turn it into seteq X, Max
5685 if (C1 == MaxVal-1)
5686 return DAG.getSetCC(dl, VT, N0,
5687 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5688 ISD::SETEQ);
5689 }
5690 }
5691
5692 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5693 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5694 if (C1.isZero())
5695 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5696 VT, N0, N1, Cond, DCI, dl))
5697 return CC;
5698
5699 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5700 // For example, when high 32-bits of i64 X are known clear:
5701 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5702 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5703 bool CmpZero = N1C->isZero();
5704 bool CmpNegOne = N1C->isAllOnes();
5705 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5706 // Match or(lo,shl(hi,bw/2)) pattern.
5707 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5708 unsigned EltBits = V.getScalarValueSizeInBits();
5709 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5710 return false;
5711 SDValue LHS = V.getOperand(0);
5712 SDValue RHS = V.getOperand(1);
5713 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5714 // Unshifted element must have zero upperbits.
5715 if (RHS.getOpcode() == ISD::SHL &&
5716 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5717 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5718 DAG.MaskedValueIsZero(LHS, HiBits)) {
5719 Lo = LHS;
5720 Hi = RHS.getOperand(0);
5721 return true;
5722 }
5723 if (LHS.getOpcode() == ISD::SHL &&
5724 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5725 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5726 DAG.MaskedValueIsZero(RHS, HiBits)) {
5727 Lo = RHS;
5728 Hi = LHS.getOperand(0);
5729 return true;
5730 }
5731 return false;
5732 };
5733
5734 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5735 unsigned EltBits = N0.getScalarValueSizeInBits();
5736 unsigned HalfBits = EltBits / 2;
5737 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5738 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5739 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5740 SDValue NewN0 =
5741 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5742 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5743 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5744 };
5745
5746 SDValue Lo, Hi;
5747 if (IsConcat(N0, Lo, Hi))
5748 return MergeConcat(Lo, Hi);
5749
5750 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5751 SDValue Lo0, Lo1, Hi0, Hi1;
5752 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5753 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5754 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5755 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5756 }
5757 }
5758 }
5759 }
5760
5761 // If we have "setcc X, C0", check to see if we can shrink the immediate
5762 // by changing cc.
5763 // TODO: Support this for vectors after legalize ops.
5764 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5765 // SETUGT X, SINTMAX -> SETLT X, 0
5766 // SETUGE X, SINTMIN -> SETLT X, 0
5767 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5768 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5769 return DAG.getSetCC(dl, VT, N0,
5770 DAG.getConstant(0, dl, N1.getValueType()),
5771 ISD::SETLT);
5772
5773 // SETULT X, SINTMIN -> SETGT X, -1
5774 // SETULE X, SINTMAX -> SETGT X, -1
5775 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5776 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5777 return DAG.getSetCC(dl, VT, N0,
5778 DAG.getAllOnesConstant(dl, N1.getValueType()),
5779 ISD::SETGT);
5780 }
5781 }
5782
5783 // Back to non-vector simplifications.
5784 // TODO: Can we do these for vector splats?
5785 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5786 const APInt &C1 = N1C->getAPIntValue();
5787 EVT ShValTy = N0.getValueType();
5788
5789 // Fold bit comparisons when we can. This will result in an
5790 // incorrect value when boolean false is negative one, unless
5791 // the bitsize is 1 in which case the false value is the same
5792 // in practice regardless of the representation.
5793 if ((VT.getSizeInBits() == 1 ||
5795 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5796 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5797 N0.getOpcode() == ISD::AND) {
5798 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5799 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5800 // Perform the xform if the AND RHS is a single bit.
5801 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5802 if (AndRHS->getAPIntValue().isPowerOf2() &&
5803 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5804 return DAG.getNode(
5805 ISD::TRUNCATE, dl, VT,
5806 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5807 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5808 }
5809 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5810 // (X & 8) == 8 --> (X & 8) >> 3
5811 // Perform the xform if C1 is a single bit.
5812 unsigned ShCt = C1.logBase2();
5813 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5814 return DAG.getNode(
5815 ISD::TRUNCATE, dl, VT,
5816 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5817 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5818 }
5819 }
5820 }
5821 }
5822
5823 if (C1.getSignificantBits() <= 64 &&
5824 !isLegalICmpImmediate(C1.getSExtValue())) {
5825 // (X & -256) == 256 -> (X >> 8) == 1
5826 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5827 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5828 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5829 const APInt &AndRHSC = AndRHS->getAPIntValue();
5830 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5831 unsigned ShiftBits = AndRHSC.countr_zero();
5832 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5833 // If using an unsigned shift doesn't yield a legal compare
5834 // immediate, try using sra instead.
5835 APInt NewC = C1.lshr(ShiftBits);
5836 if (NewC.getSignificantBits() <= 64 &&
5838 APInt SignedC = C1.ashr(ShiftBits);
5839 if (SignedC.getSignificantBits() <= 64 &&
5841 SDValue Shift = DAG.getNode(
5842 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5843 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5844 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5845 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5846 }
5847 }
5848 SDValue Shift = DAG.getNode(
5849 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5850 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5851 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5852 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5853 }
5854 }
5855 }
5856 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5857 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5858 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5859 // X < 0x100000000 -> (X >> 32) < 1
5860 // X >= 0x100000000 -> (X >> 32) >= 1
5861 // X <= 0x0ffffffff -> (X >> 32) < 1
5862 // X > 0x0ffffffff -> (X >> 32) >= 1
5863 unsigned ShiftBits;
5864 APInt NewC = C1;
5865 ISD::CondCode NewCond = Cond;
5866 if (AdjOne) {
5867 ShiftBits = C1.countr_one();
5868 NewC = NewC + 1;
5869 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5870 } else {
5871 ShiftBits = C1.countr_zero();
5872 }
5873 APInt RangeWidth = NewC;
5874 NewC.lshrInPlace(ShiftBits);
5875 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5877 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5878 // If this is an offset range check, try to move the offset after the
5879 // shift to avoid preserving the pre-shift add with a mask.
5880 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse()) {
5881 if (auto *AddC = isConstOrConstSplat(N0.getOperand(1))) {
5882 const APInt &AddVal = AddC->getAPIntValue();
5883 if (AddVal.countr_zero() >= ShiftBits) {
5884 APInt RangeLower = -AddVal;
5885 bool Overflow;
5886 (void)RangeLower.uadd_ov(RangeWidth, Overflow);
5887 if (!RangeWidth.isZero() && !Overflow) {
5888 SDValue Shift = DAG.getNode(
5889 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5890 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5891 APInt Offset = -RangeLower.lshr(ShiftBits);
5892 SDValue ShiftedAdd =
5893 DAG.getNode(ISD::ADD, dl, ShValTy, Shift,
5894 DAG.getConstant(Offset, dl, ShValTy));
5895 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5896 return DAG.getSetCC(dl, VT, ShiftedAdd, CmpRHS, NewCond);
5897 }
5898 }
5899 }
5900 }
5901 SDValue Shift =
5902 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5903 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5904 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5905 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5906 }
5907 }
5908 }
5909 }
5910
5912 auto *CFP = cast<ConstantFPSDNode>(N1);
5913 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5914
5915 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5916 // constant if knowing that the operand is non-nan is enough. We prefer to
5917 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5918 // materialize 0.0.
5919 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5920 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5921
5922 // setcc (fneg x), C -> setcc swap(pred) x, -C
5923 if (N0.getOpcode() == ISD::FNEG) {
5925 if (DCI.isBeforeLegalizeOps() ||
5926 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5927 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5928 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5929 }
5930 }
5931
5932 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5934 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5935 bool IsFabs = N0.getOpcode() == ISD::FABS;
5936 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5937 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5938 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5939 : (IsFabs ? fcInf : fcPosInf);
5940 if (Cond == ISD::SETUEQ)
5941 Flag |= fcNan;
5942 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5943 DAG.getTargetConstant(Flag, dl, MVT::i32));
5944 }
5945 }
5946
5947 // If the condition is not legal, see if we can find an equivalent one
5948 // which is legal.
5950 // If the comparison was an awkward floating-point == or != and one of
5951 // the comparison operands is infinity or negative infinity, convert the
5952 // condition to a less-awkward <= or >=.
5953 if (CFP->getValueAPF().isInfinity()) {
5954 bool IsNegInf = CFP->getValueAPF().isNegative();
5956 switch (Cond) {
5957 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5958 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5959 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5960 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5961 default: break;
5962 }
5963 if (NewCond != ISD::SETCC_INVALID &&
5964 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5965 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5966 }
5967 }
5968 }
5969
5970 if (N0 == N1) {
5971 // The sext(setcc()) => setcc() optimization relies on the appropriate
5972 // constant being emitted.
5973 assert(!N0.getValueType().isInteger() &&
5974 "Integer types should be handled by FoldSetCC");
5975
5976 bool EqTrue = ISD::isTrueWhenEqual(Cond);
5977 unsigned UOF = ISD::getUnorderedFlavor(Cond);
5978 if (UOF == 2) // FP operators that are undefined on NaNs.
5979 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5980 if (UOF == unsigned(EqTrue))
5981 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5982 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
5983 // if it is not already.
5984 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5985 if (NewCond != Cond &&
5986 (DCI.isBeforeLegalizeOps() ||
5987 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5988 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5989 }
5990
5991 // ~X > ~Y --> Y > X
5992 // ~X < ~Y --> Y < X
5993 // ~X < C --> X > ~C
5994 // ~X > C --> X < ~C
5995 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5996 N0.getValueType().isInteger()) {
5997 if (isBitwiseNot(N0)) {
5998 if (isBitwiseNot(N1))
5999 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
6000
6003 SDValue Not = DAG.getNOT(dl, N1, OpVT);
6004 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
6005 }
6006 }
6007 }
6008
6009 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6010 N0.getValueType().isInteger()) {
6011 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
6012 N0.getOpcode() == ISD::XOR) {
6013 // Simplify (X+Y) == (X+Z) --> Y == Z
6014 if (N0.getOpcode() == N1.getOpcode()) {
6015 if (N0.getOperand(0) == N1.getOperand(0))
6016 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
6017 if (N0.getOperand(1) == N1.getOperand(1))
6018 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6019 if (isCommutativeBinOp(N0.getOpcode())) {
6020 // If X op Y == Y op X, try other combinations.
6021 if (N0.getOperand(0) == N1.getOperand(1))
6022 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
6023 Cond);
6024 if (N0.getOperand(1) == N1.getOperand(0))
6025 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
6026 Cond);
6027 }
6028 }
6029
6030 // If RHS is a legal immediate value for a compare instruction, we need
6031 // to be careful about increasing register pressure needlessly.
6032 bool LegalRHSImm = false;
6033
6034 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
6035 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6036 // Turn (X+C1) == C2 --> X == C2-C1
6037 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
6038 return DAG.getSetCC(
6039 dl, VT, N0.getOperand(0),
6040 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
6041 dl, N0.getValueType()),
6042 Cond);
6043
6044 // Turn (X^C1) == C2 --> X == C1^C2
6045 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
6046 return DAG.getSetCC(
6047 dl, VT, N0.getOperand(0),
6048 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
6049 dl, N0.getValueType()),
6050 Cond);
6051 }
6052
6053 // Turn (C1-X) == C2 --> X == C1-C2
6054 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
6055 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
6056 return DAG.getSetCC(
6057 dl, VT, N0.getOperand(1),
6058 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
6059 dl, N0.getValueType()),
6060 Cond);
6061
6062 // Could RHSC fold directly into a compare?
6063 if (RHSC->getValueType(0).getSizeInBits() <= 64)
6064 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
6065 }
6066
6067 // (X+Y) == X --> Y == 0 and similar folds.
6068 // Don't do this if X is an immediate that can fold into a cmp
6069 // instruction and X+Y has other uses. It could be an induction variable
6070 // chain, and the transform would increase register pressure.
6071 if (!LegalRHSImm || N0.hasOneUse())
6072 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
6073 return V;
6074 }
6075
6076 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
6077 N1.getOpcode() == ISD::XOR)
6078 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
6079 return V;
6080
6081 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
6082 return V;
6083
6084 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
6085 return V;
6086 }
6087
6088 // Fold remainder of division by a constant.
6089 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
6090 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
6091 // When division is cheap or optimizing for minimum size,
6092 // fall through to DIVREM creation by skipping this fold.
6093 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
6094 if (N0.getOpcode() == ISD::UREM) {
6095 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
6096 return Folded;
6097 } else if (N0.getOpcode() == ISD::SREM) {
6098 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
6099 return Folded;
6100 }
6101 }
6102 }
6103
6104 // Fold away ALL boolean setcc's.
6105 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
6106 SDValue Temp;
6107 switch (Cond) {
6108 default: llvm_unreachable("Unknown integer setcc!");
6109 case ISD::SETEQ: // X == Y -> ~(X^Y)
6110 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
6111 N0 = DAG.getNOT(dl, Temp, OpVT);
6112 if (!DCI.isCalledByLegalizer())
6113 DCI.AddToWorklist(Temp.getNode());
6114 break;
6115 case ISD::SETNE: // X != Y --> (X^Y)
6116 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
6117 break;
6118 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
6119 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
6120 Temp = DAG.getNOT(dl, N0, OpVT);
6121 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
6122 if (!DCI.isCalledByLegalizer())
6123 DCI.AddToWorklist(Temp.getNode());
6124 break;
6125 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
6126 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
6127 Temp = DAG.getNOT(dl, N1, OpVT);
6128 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
6129 if (!DCI.isCalledByLegalizer())
6130 DCI.AddToWorklist(Temp.getNode());
6131 break;
6132 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
6133 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
6134 Temp = DAG.getNOT(dl, N0, OpVT);
6135 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
6136 if (!DCI.isCalledByLegalizer())
6137 DCI.AddToWorklist(Temp.getNode());
6138 break;
6139 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
6140 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
6141 Temp = DAG.getNOT(dl, N1, OpVT);
6142 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
6143 break;
6144 }
6145 if (VT.getScalarType() != MVT::i1) {
6146 if (!DCI.isCalledByLegalizer())
6147 DCI.AddToWorklist(N0.getNode());
6148 // FIXME: If running after legalize, we probably can't do this.
6150 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
6151 }
6152 return N0;
6153 }
6154
6155 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
6156 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
6157 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
6159 N1->getFlags().hasNoUnsignedWrap()) ||
6161 N1->getFlags().hasNoSignedWrap())) &&
6163 if (VT.getScalarType() == MVT::i1)
6164 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6165 // For (legal) non vXi1 cases - ensure we adjust the cmp and result types.
6166 EVT OldCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6167 N0.getValueType());
6168 if (VT == OldCCVT) {
6169 EVT NewCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6170 N0.getOperand(0).getValueType());
6171 return DAG.getBoolExtOrTrunc(
6172 DAG.getSetCC(dl, NewCCVT, N0.getOperand(0), N1.getOperand(0), Cond),
6173 dl, VT, N0.getOperand(0).getValueType());
6174 }
6175 }
6176
6177 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
6178 // TODO: Remove that .isVector() check
6179 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
6181 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
6182 }
6183
6184 // Could not fold it.
6185 return SDValue();
6186}
6187
6188/// Returns true (and the GlobalValue and the offset) if the node is a
6189/// GlobalAddress + offset.
6191 int64_t &Offset) const {
6192
6193 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
6194
6195 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
6196 GA = GASD->getGlobal();
6197 Offset += GASD->getOffset();
6198 return true;
6199 }
6200
6201 if (N->isAnyAdd()) {
6202 SDValue N1 = N->getOperand(0);
6203 SDValue N2 = N->getOperand(1);
6204 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
6205 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
6206 Offset += V->getSExtValue();
6207 return true;
6208 }
6209 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
6210 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
6211 Offset += V->getSExtValue();
6212 return true;
6213 }
6214 }
6215 }
6216
6217 return false;
6218}
6219
6221 DAGCombinerInfo &DCI) const {
6222 // Default implementation: no optimization.
6223 return SDValue();
6224}
6225
6226//===----------------------------------------------------------------------===//
6227// Inline Assembler Implementation Methods
6228//===----------------------------------------------------------------------===//
6229
6232 unsigned S = Constraint.size();
6233
6234 if (S == 1) {
6235 switch (Constraint[0]) {
6236 default: break;
6237 case 'r':
6238 return C_RegisterClass;
6239 case 'm': // memory
6240 case 'o': // offsetable
6241 case 'V': // not offsetable
6242 return C_Memory;
6243 case 'p': // Address.
6244 return C_Address;
6245 case 'n': // Simple Integer
6246 case 'E': // Floating Point Constant
6247 case 'F': // Floating Point Constant
6248 return C_Immediate;
6249 case 'i': // Simple Integer or Relocatable Constant
6250 case 's': // Relocatable Constant
6251 case 'X': // Allow ANY value.
6252 case 'I': // Target registers.
6253 case 'J':
6254 case 'K':
6255 case 'L':
6256 case 'M':
6257 case 'N':
6258 case 'O':
6259 case 'P':
6260 case '<':
6261 case '>':
6262 return C_Other;
6263 }
6264 }
6265
6266 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
6267 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
6268 return C_Memory;
6269 return C_Register;
6270 }
6271 return C_Unknown;
6272}
6273
6274/// Try to replace an X constraint, which matches anything, with another that
6275/// has more specific requirements based on the type of the corresponding
6276/// operand.
6277const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6278 if (ConstraintVT.isInteger())
6279 return "r";
6280 if (ConstraintVT.isFloatingPoint())
6281 return "f"; // works for many targets
6282 return nullptr;
6283}
6284
6286 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
6287 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
6288 return SDValue();
6289}
6290
6291/// Lower the specified operand into the Ops vector.
6292/// If it is invalid, don't add anything to Ops.
6294 StringRef Constraint,
6295 std::vector<SDValue> &Ops,
6296 SelectionDAG &DAG) const {
6297
6298 if (Constraint.size() > 1)
6299 return;
6300
6301 char ConstraintLetter = Constraint[0];
6302 switch (ConstraintLetter) {
6303 default: break;
6304 case 'X': // Allows any operand
6305 case 'i': // Simple Integer or Relocatable Constant
6306 case 'n': // Simple Integer
6307 case 's': { // Relocatable Constant
6308
6310 uint64_t Offset = 0;
6311
6312 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
6313 // etc., since getelementpointer is variadic. We can't use
6314 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
6315 // while in this case the GA may be furthest from the root node which is
6316 // likely an ISD::ADD.
6317 while (true) {
6318 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
6319 // gcc prints these as sign extended. Sign extend value to 64 bits
6320 // now; without this it would get ZExt'd later in
6321 // ScheduleDAGSDNodes::EmitNode, which is very generic.
6322 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
6323 BooleanContent BCont = getBooleanContents(MVT::i64);
6324 ISD::NodeType ExtOpc =
6325 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
6326 int64_t ExtVal =
6327 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
6328 Ops.push_back(
6329 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
6330 return;
6331 }
6332 if (ConstraintLetter != 'n') {
6333 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6334 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6335 GA->getValueType(0),
6336 Offset + GA->getOffset()));
6337 return;
6338 }
6339 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
6340 Ops.push_back(DAG.getTargetBlockAddress(
6341 BA->getBlockAddress(), BA->getValueType(0),
6342 Offset + BA->getOffset(), BA->getTargetFlags()));
6343 return;
6344 }
6346 Ops.push_back(Op);
6347 return;
6348 }
6349 }
6350 const unsigned OpCode = Op.getOpcode();
6351 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6352 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6353 Op = Op.getOperand(1);
6354 // Subtraction is not commutative.
6355 else if (OpCode == ISD::ADD &&
6356 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6357 Op = Op.getOperand(0);
6358 else
6359 return;
6360 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6361 continue;
6362 }
6363 return;
6364 }
6365 break;
6366 }
6367 }
6368}
6369
6373
6374std::pair<unsigned, const TargetRegisterClass *>
6376 StringRef Constraint,
6377 MVT VT) const {
6378 if (!Constraint.starts_with("{"))
6379 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6380 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6381
6382 // Remove the braces from around the name.
6383 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6384
6385 std::pair<unsigned, const TargetRegisterClass *> R =
6386 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6387
6388 // Figure out which register class contains this reg.
6389 for (const TargetRegisterClass &RC : RI->regclasses()) {
6390 // If none of the value types for this register class are valid, we
6391 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6392 if (!isLegalRC(*RI, RC))
6393 continue;
6394
6395 for (const MCPhysReg &PR : RC) {
6396 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6397 std::pair<unsigned, const TargetRegisterClass *> S =
6398 std::make_pair(PR, &RC);
6399
6400 // If this register class has the requested value type, return it,
6401 // otherwise keep searching and return the first class found
6402 // if no other is found which explicitly has the requested type.
6403 if (RI->isTypeLegalForClass(RC, VT))
6404 return S;
6405 if (!R.second)
6406 R = S;
6407 }
6408 }
6409 }
6410
6411 return R;
6412}
6413
6414//===----------------------------------------------------------------------===//
6415// Constraint Selection.
6416
6417/// Return true of this is an input operand that is a matching constraint like
6418/// "4".
6420 assert(!ConstraintCode.empty() && "No known constraint!");
6421 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6422}
6423
6424/// If this is an input matching constraint, this method returns the output
6425/// operand it matches.
6427 assert(!ConstraintCode.empty() && "No known constraint!");
6428 return atoi(ConstraintCode.c_str());
6429}
6430
6431/// Split up the constraint string from the inline assembly value into the
6432/// specific constraints and their prefixes, and also tie in the associated
6433/// operand values.
6434/// If this returns an empty vector, and if the constraint string itself
6435/// isn't empty, there was an error parsing.
6438 const TargetRegisterInfo *TRI,
6439 const CallBase &Call) const {
6440 /// Information about all of the constraints.
6441 AsmOperandInfoVector ConstraintOperands;
6442 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6443 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6444
6445 // Do a prepass over the constraints, canonicalizing them, and building up the
6446 // ConstraintOperands list.
6447 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6448 unsigned ResNo = 0; // ResNo - The result number of the next output.
6449 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6450
6451 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6452 ConstraintOperands.emplace_back(std::move(CI));
6453 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6454
6455 // Update multiple alternative constraint count.
6456 if (OpInfo.multipleAlternatives.size() > maCount)
6457 maCount = OpInfo.multipleAlternatives.size();
6458
6459 OpInfo.ConstraintVT = MVT::Other;
6460
6461 // Compute the value type for each operand.
6462 switch (OpInfo.Type) {
6463 case InlineAsm::isOutput: {
6464 // Indirect outputs just consume an argument.
6465 if (OpInfo.isIndirect) {
6466 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6467 break;
6468 }
6469
6470 // The return value of the call is this value. As such, there is no
6471 // corresponding argument.
6472 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6473 EVT VT;
6474 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6475 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6476 } else {
6477 assert(ResNo == 0 && "Asm only has one result!");
6478 VT = getAsmOperandValueType(DL, Call.getType());
6479 }
6480 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6481 ++ResNo;
6482 break;
6483 }
6484 case InlineAsm::isInput:
6485 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6486 break;
6487 case InlineAsm::isLabel:
6488 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6489 ++LabelNo;
6490 continue;
6492 // Nothing to do.
6493 break;
6494 }
6495
6496 if (OpInfo.CallOperandVal) {
6497 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6498 if (OpInfo.isIndirect) {
6499 OpTy = Call.getParamElementType(ArgNo);
6500 assert(OpTy && "Indirect operand must have elementtype attribute");
6501 }
6502
6503 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6505 if (STy->getNumElements() == 1)
6506 OpTy = STy->getElementType(0);
6507
6508 // If OpTy is not a single value, it may be a struct/union that we
6509 // can tile with integers.
6510 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6511 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6512 switch (BitSize) {
6513 default: break;
6514 case 1:
6515 case 8:
6516 case 16:
6517 case 32:
6518 case 64:
6519 case 128:
6520 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6521 break;
6522 }
6523 }
6524
6525 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6526 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6527 ArgNo++;
6528 }
6529 }
6530
6531 // If we have multiple alternative constraints, select the best alternative.
6532 if (!ConstraintOperands.empty()) {
6533 if (maCount) {
6534 unsigned bestMAIndex = 0;
6535 int bestWeight = -1;
6536 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6537 int weight = -1;
6538 unsigned maIndex;
6539 // Compute the sums of the weights for each alternative, keeping track
6540 // of the best (highest weight) one so far.
6541 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6542 int weightSum = 0;
6543 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6544 cIndex != eIndex; ++cIndex) {
6545 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6546 if (OpInfo.Type == InlineAsm::isClobber)
6547 continue;
6548
6549 // If this is an output operand with a matching input operand,
6550 // look up the matching input. If their types mismatch, e.g. one
6551 // is an integer, the other is floating point, or their sizes are
6552 // different, flag it as an maCantMatch.
6553 if (OpInfo.hasMatchingInput()) {
6554 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6555 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6556 if ((OpInfo.ConstraintVT.isInteger() !=
6557 Input.ConstraintVT.isInteger()) ||
6558 (OpInfo.ConstraintVT.getSizeInBits() !=
6559 Input.ConstraintVT.getSizeInBits())) {
6560 weightSum = -1; // Can't match.
6561 break;
6562 }
6563 }
6564 }
6565 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6566 if (weight == -1) {
6567 weightSum = -1;
6568 break;
6569 }
6570 weightSum += weight;
6571 }
6572 // Update best.
6573 if (weightSum > bestWeight) {
6574 bestWeight = weightSum;
6575 bestMAIndex = maIndex;
6576 }
6577 }
6578
6579 // Now select chosen alternative in each constraint.
6580 for (AsmOperandInfo &cInfo : ConstraintOperands)
6581 if (cInfo.Type != InlineAsm::isClobber)
6582 cInfo.selectAlternative(bestMAIndex);
6583 }
6584 }
6585
6586 // Check and hook up tied operands, choose constraint code to use.
6587 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6588 cIndex != eIndex; ++cIndex) {
6589 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6590
6591 // If this is an output operand with a matching input operand, look up the
6592 // matching input. If their types mismatch, e.g. one is an integer, the
6593 // other is floating point, or their sizes are different, flag it as an
6594 // error.
6595 if (OpInfo.hasMatchingInput()) {
6596 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6597
6598 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6599 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6600 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6601 OpInfo.ConstraintVT);
6602 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6603 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6604 Input.ConstraintVT);
6605 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6606 OpInfo.ConstraintVT.isFloatingPoint();
6607 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6608 Input.ConstraintVT.isFloatingPoint();
6609 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6610 (MatchRC.second != InputRC.second)) {
6611 report_fatal_error("Unsupported asm: input constraint"
6612 " with a matching output constraint of"
6613 " incompatible type!");
6614 }
6615 }
6616 }
6617 }
6618
6619 return ConstraintOperands;
6620}
6621
6622/// Return a number indicating our preference for chosing a type of constraint
6623/// over another, for the purpose of sorting them. Immediates are almost always
6624/// preferrable (when they can be emitted). A higher return value means a
6625/// stronger preference for one constraint type relative to another.
6626/// FIXME: We should prefer registers over memory but doing so may lead to
6627/// unrecoverable register exhaustion later.
6628/// https://github.com/llvm/llvm-project/issues/20571
6630 switch (CT) {
6633 return 4;
6636 return 3;
6638 return 2;
6640 return 1;
6642 return 0;
6643 }
6644 llvm_unreachable("Invalid constraint type");
6645}
6646
6647/// Examine constraint type and operand type and determine a weight value.
6648/// This object must already have been set up with the operand type
6649/// and the current alternative constraint selected.
6652 AsmOperandInfo &info, int maIndex) const {
6654 if (maIndex >= (int)info.multipleAlternatives.size())
6655 rCodes = &info.Codes;
6656 else
6657 rCodes = &info.multipleAlternatives[maIndex].Codes;
6658 ConstraintWeight BestWeight = CW_Invalid;
6659
6660 // Loop over the options, keeping track of the most general one.
6661 for (const std::string &rCode : *rCodes) {
6662 ConstraintWeight weight =
6663 getSingleConstraintMatchWeight(info, rCode.c_str());
6664 if (weight > BestWeight)
6665 BestWeight = weight;
6666 }
6667
6668 return BestWeight;
6669}
6670
6671/// Examine constraint type and operand type and determine a weight value.
6672/// This object must already have been set up with the operand type
6673/// and the current alternative constraint selected.
6676 AsmOperandInfo &info, const char *constraint) const {
6678 Value *CallOperandVal = info.CallOperandVal;
6679 // If we don't have a value, we can't do a match,
6680 // but allow it at the lowest weight.
6681 if (!CallOperandVal)
6682 return CW_Default;
6683 // Look at the constraint type.
6684 switch (*constraint) {
6685 case 'i': // immediate integer.
6686 case 'n': // immediate integer with a known value.
6687 if (isa<ConstantInt>(CallOperandVal))
6688 weight = CW_Constant;
6689 break;
6690 case 's': // non-explicit intregal immediate.
6691 if (isa<GlobalValue>(CallOperandVal))
6692 weight = CW_Constant;
6693 break;
6694 case 'E': // immediate float if host format.
6695 case 'F': // immediate float.
6696 if (isa<ConstantFP>(CallOperandVal))
6697 weight = CW_Constant;
6698 break;
6699 case '<': // memory operand with autodecrement.
6700 case '>': // memory operand with autoincrement.
6701 case 'm': // memory operand.
6702 case 'o': // offsettable memory operand
6703 case 'V': // non-offsettable memory operand
6704 weight = CW_Memory;
6705 break;
6706 case 'r': // general register.
6707 case 'g': // general register, memory operand or immediate integer.
6708 // note: Clang converts "g" to "imr".
6709 if (CallOperandVal->getType()->isIntegerTy())
6710 weight = CW_Register;
6711 break;
6712 case 'X': // any operand.
6713 default:
6714 weight = CW_Default;
6715 break;
6716 }
6717 return weight;
6718}
6719
6720/// If there are multiple different constraints that we could pick for this
6721/// operand (e.g. "imr") try to pick the 'best' one.
6722/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6723/// into seven classes:
6724/// Register -> one specific register
6725/// RegisterClass -> a group of regs
6726/// Memory -> memory
6727/// Address -> a symbolic memory reference
6728/// Immediate -> immediate values
6729/// Other -> magic values (such as "Flag Output Operands")
6730/// Unknown -> something we don't recognize yet and can't handle
6731/// Ideally, we would pick the most specific constraint possible: if we have
6732/// something that fits into a register, we would pick it. The problem here
6733/// is that if we have something that could either be in a register or in
6734/// memory that use of the register could cause selection of *other*
6735/// operands to fail: they might only succeed if we pick memory. Because of
6736/// this the heuristic we use is:
6737///
6738/// 1) If there is an 'other' constraint, and if the operand is valid for
6739/// that constraint, use it. This makes us take advantage of 'i'
6740/// constraints when available.
6741/// 2) Otherwise, pick the most general constraint present. This prefers
6742/// 'm' over 'r', for example.
6743///
6745 TargetLowering::AsmOperandInfo &OpInfo) const {
6746 ConstraintGroup Ret;
6747
6748 Ret.reserve(OpInfo.Codes.size());
6749 for (StringRef Code : OpInfo.Codes) {
6751
6752 // Indirect 'other' or 'immediate' constraints are not allowed.
6753 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6754 CType == TargetLowering::C_Register ||
6756 continue;
6757
6758 // Things with matching constraints can only be registers, per gcc
6759 // documentation. This mainly affects "g" constraints.
6760 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6761 continue;
6762
6763 Ret.emplace_back(Code, CType);
6764 }
6765
6767 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6768 });
6769
6770 return Ret;
6771}
6772
6773/// If we have an immediate, see if we can lower it. Return true if we can,
6774/// false otherwise.
6776 SDValue Op, SelectionDAG *DAG,
6777 const TargetLowering &TLI) {
6778
6779 assert((P.second == TargetLowering::C_Other ||
6780 P.second == TargetLowering::C_Immediate) &&
6781 "need immediate or other");
6782
6783 if (!Op.getNode())
6784 return false;
6785
6786 std::vector<SDValue> ResultOps;
6787 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6788 return !ResultOps.empty();
6789}
6790
6791/// Determines the constraint code and constraint type to use for the specific
6792/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6794 SDValue Op,
6795 SelectionDAG *DAG) const {
6796 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6797
6798 // Single-letter constraints ('r') are very common.
6799 if (OpInfo.Codes.size() == 1) {
6800 OpInfo.ConstraintCode = OpInfo.Codes[0];
6801 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6802 } else {
6804 if (G.empty())
6805 return;
6806
6807 unsigned BestIdx = 0;
6808 for (const unsigned E = G.size();
6809 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6810 G[BestIdx].second == TargetLowering::C_Immediate);
6811 ++BestIdx) {
6812 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6813 break;
6814 // If we're out of constraints, just pick the first one.
6815 if (BestIdx + 1 == E) {
6816 BestIdx = 0;
6817 break;
6818 }
6819 }
6820
6821 OpInfo.ConstraintCode = G[BestIdx].first;
6822 OpInfo.ConstraintType = G[BestIdx].second;
6823 }
6824
6825 // 'X' matches anything.
6826 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6827 // Constants are handled elsewhere. For Functions, the type here is the
6828 // type of the result, which is not what we want to look at; leave them
6829 // alone.
6830 Value *v = OpInfo.CallOperandVal;
6831 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6832 return;
6833 }
6834
6835 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6836 OpInfo.ConstraintCode = "i";
6837 return;
6838 }
6839
6840 // Otherwise, try to resolve it to something we know about by looking at
6841 // the actual operand type.
6842 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6843 OpInfo.ConstraintCode = Repl;
6844 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6845 }
6846 }
6847}
6848
6849/// Given an exact SDIV by a constant, create a multiplication
6850/// with the multiplicative inverse of the constant.
6851/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6853 const SDLoc &dl, SelectionDAG &DAG,
6854 SmallVectorImpl<SDNode *> &Created) {
6855 SDValue Op0 = N->getOperand(0);
6856 SDValue Op1 = N->getOperand(1);
6857 EVT VT = N->getValueType(0);
6858 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6859 EVT ShSVT = ShVT.getScalarType();
6860
6861 bool UseSRA = false;
6862 SmallVector<SDValue, 16> Shifts, Factors;
6863
6864 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6865 if (C->isZero())
6866 return false;
6867
6868 EVT CT = C->getValueType(0);
6869 APInt Divisor = C->getAPIntValue();
6870 unsigned Shift = Divisor.countr_zero();
6871 if (Shift) {
6872 Divisor.ashrInPlace(Shift);
6873 UseSRA = true;
6874 }
6875 APInt Factor = Divisor.multiplicativeInverse();
6876 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6877 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6878 return true;
6879 };
6880
6881 // Collect all magic values from the build vector.
6882 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6883 return SDValue();
6884
6885 SDValue Shift, Factor;
6886 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6887 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6888 Factor = DAG.getBuildVector(VT, dl, Factors);
6889 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6890 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6891 "Expected matchUnaryPredicate to return one element for scalable "
6892 "vectors");
6893 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6894 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6895 } else {
6896 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6897 Shift = Shifts[0];
6898 Factor = Factors[0];
6899 }
6900
6901 SDValue Res = Op0;
6902 if (UseSRA) {
6903 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6904 Created.push_back(Res.getNode());
6905 }
6906
6907 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6908}
6909
6910/// Given an exact UDIV by a constant, create a multiplication
6911/// with the multiplicative inverse of the constant.
6912/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6914 const SDLoc &dl, SelectionDAG &DAG,
6915 SmallVectorImpl<SDNode *> &Created) {
6916 EVT VT = N->getValueType(0);
6917 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6918 EVT ShSVT = ShVT.getScalarType();
6919
6920 bool UseSRL = false;
6921 SmallVector<SDValue, 16> Shifts, Factors;
6922
6923 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6924 if (C->isZero())
6925 return false;
6926
6927 EVT CT = C->getValueType(0);
6928 APInt Divisor = C->getAPIntValue();
6929 unsigned Shift = Divisor.countr_zero();
6930 if (Shift) {
6931 Divisor.lshrInPlace(Shift);
6932 UseSRL = true;
6933 }
6934 // Calculate the multiplicative inverse modulo BW.
6935 APInt Factor = Divisor.multiplicativeInverse();
6936 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6937 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6938 return true;
6939 };
6940
6941 SDValue Op1 = N->getOperand(1);
6942
6943 // Collect all magic values from the build vector.
6944 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6945 return SDValue();
6946
6947 SDValue Shift, Factor;
6948 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6949 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6950 Factor = DAG.getBuildVector(VT, dl, Factors);
6951 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6952 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6953 "Expected matchUnaryPredicate to return one element for scalable "
6954 "vectors");
6955 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6956 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6957 } else {
6958 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6959 Shift = Shifts[0];
6960 Factor = Factors[0];
6961 }
6962
6963 SDValue Res = N->getOperand(0);
6964 if (UseSRL) {
6965 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
6966 Created.push_back(Res.getNode());
6967 }
6968
6969 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6970}
6971
6973 SelectionDAG &DAG,
6974 SmallVectorImpl<SDNode *> &Created) const {
6976 if (isIntDivCheap(N->getValueType(0), Attr))
6977 return SDValue(N, 0); // Lower SDIV as SDIV
6978 return SDValue();
6979}
6980
6981SDValue
6983 SelectionDAG &DAG,
6984 SmallVectorImpl<SDNode *> &Created) const {
6986 if (isIntDivCheap(N->getValueType(0), Attr))
6987 return SDValue(N, 0); // Lower SREM as SREM
6988 return SDValue();
6989}
6990
6991/// Build sdiv by power-of-2 with conditional move instructions
6992/// Ref: "Hacker's Delight" by Henry Warren 10-1
6993/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6994/// bgez x, label
6995/// add x, x, 2**k-1
6996/// label:
6997/// sra res, x, k
6998/// neg res, res (when the divisor is negative)
7000 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
7001 SmallVectorImpl<SDNode *> &Created) const {
7002 unsigned Lg2 = Divisor.countr_zero();
7003 EVT VT = N->getValueType(0);
7004
7005 SDLoc DL(N);
7006 SDValue N0 = N->getOperand(0);
7007 SDValue Zero = DAG.getConstant(0, DL, VT);
7008 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
7009 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
7010
7011 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
7012 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7013 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
7014 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7015 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
7016
7017 Created.push_back(Cmp.getNode());
7018 Created.push_back(Add.getNode());
7019 Created.push_back(CMov.getNode());
7020
7021 // Divide by pow2.
7022 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
7023 DAG.getShiftAmountConstant(Lg2, VT, DL));
7024
7025 // If we're dividing by a positive value, we're done. Otherwise, we must
7026 // negate the result.
7027 if (Divisor.isNonNegative())
7028 return SRA;
7029
7030 Created.push_back(SRA.getNode());
7031 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
7032}
7033
7034/// Given an ISD::SDIV node expressing a divide by constant,
7035/// return a DAG expression to select that will generate the same value by
7036/// multiplying by a magic number.
7037/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7039 bool IsAfterLegalization,
7040 bool IsAfterLegalTypes,
7041 SmallVectorImpl<SDNode *> &Created) const {
7042 SDLoc dl(N);
7043
7044 // If the sdiv has an 'exact' bit we can use a simpler lowering.
7045 if (N->getFlags().hasExact())
7046 return BuildExactSDIV(*this, N, dl, DAG, Created);
7047
7048 EVT VT = N->getValueType(0);
7049 EVT SVT = VT.getScalarType();
7050 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7051 EVT ShSVT = ShVT.getScalarType();
7052 unsigned EltBits = VT.getScalarSizeInBits();
7053 EVT MulVT;
7054
7055 // Check to see if we can do this.
7056 // FIXME: We should be more aggressive here.
7057 EVT QueryVT = VT;
7058 if (VT.isVector()) {
7059 // If the vector type will be legalized to a vector type with the same
7060 // element type, allow the transform before type legalization if MULHS or
7061 // SMUL_LOHI are supported.
7062 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7063 if (!QueryVT.isVector() ||
7065 return SDValue();
7066 } else if (!isTypeLegal(VT)) {
7067 // Limit this to simple scalars for now.
7068 if (!VT.isSimple())
7069 return SDValue();
7070
7071 // If this type will be promoted to a large enough type with a legal
7072 // multiply operation, we can go ahead and do this transform.
7074 return SDValue();
7075
7076 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7077 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7078 !isOperationLegal(ISD::MUL, MulVT))
7079 return SDValue();
7080 }
7081
7082 bool HasMULHS =
7083 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
7084 bool HasSMUL_LOHI =
7085 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
7086
7087 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
7088 // If type twice as wide legal, widen and use a mul plus a shift.
7089 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7090 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
7091 // custom lowered. This is very expensive so avoid it at all costs for
7092 // constant divisors.
7093 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
7096 MulVT = WideVT;
7097 }
7098
7099 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
7100 return SDValue();
7101
7102 // If we're after type legalization and SVT is not legal, use the
7103 // promoted type for creating constants to avoid creating nodes with
7104 // illegal types.
7105 if (IsAfterLegalTypes && VT.isVector()) {
7106 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7107 if (SVT.bitsLT(VT.getScalarType()))
7108 return SDValue();
7109 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7110 if (ShSVT.bitsLT(ShVT.getScalarType()))
7111 return SDValue();
7112 }
7113 const unsigned SVTBits = SVT.getSizeInBits();
7114
7115 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
7116
7117 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
7118 if (C->isZero())
7119 return false;
7120 // Truncate the divisor to the target scalar type in case it was promoted
7121 // during type legalization.
7122 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7124 int NumeratorFactor = 0;
7125 int ShiftMask = -1;
7126
7127 if (Divisor.isOne() || Divisor.isAllOnes()) {
7128 // If d is +1/-1, we just multiply the numerator by +1/-1.
7129 NumeratorFactor = Divisor.getSExtValue();
7130 magics.Magic = 0;
7131 magics.ShiftAmount = 0;
7132 ShiftMask = 0;
7133 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
7134 // If d > 0 and m < 0, add the numerator.
7135 NumeratorFactor = 1;
7136 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
7137 // If d < 0 and m > 0, subtract the numerator.
7138 NumeratorFactor = -1;
7139 }
7140
7141 MagicFactors.push_back(
7142 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
7143 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
7144 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
7145 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
7146 return true;
7147 };
7148
7149 SDValue N0 = N->getOperand(0);
7150 SDValue N1 = N->getOperand(1);
7151
7152 // Collect the shifts / magic values from each element.
7153 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
7154 /*AllowTruncation=*/true))
7155 return SDValue();
7156
7157 SDValue MagicFactor, Factor, Shift, ShiftMask;
7158 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7159 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7160 Factor = DAG.getBuildVector(VT, dl, Factors);
7161 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
7162 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
7163 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7164 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
7165 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
7166 "Expected matchUnaryPredicate to return one element for scalable "
7167 "vectors");
7168 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7169 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
7170 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
7171 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
7172 } else {
7173 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7174 MagicFactor = MagicFactors[0];
7175 Factor = Factors[0];
7176 Shift = Shifts[0];
7177 ShiftMask = ShiftMasks[0];
7178 }
7179
7180 // Multiply the numerator (operand 0) by the magic value.
7181 auto GetMULHS = [&](SDValue X, SDValue Y) {
7182 if (HasMULHS)
7183 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
7184 if (HasSMUL_LOHI) {
7185 SDValue LoHi =
7186 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7187 return LoHi.getValue(1);
7188 }
7189
7190 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
7191 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
7192 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7193 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7194 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7195 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7196 };
7197
7198 SDValue Q = GetMULHS(N0, MagicFactor);
7199 if (!Q)
7200 return SDValue();
7201
7202 Created.push_back(Q.getNode());
7203
7204 // (Optionally) Add/subtract the numerator using Factor.
7205 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
7206 Created.push_back(Factor.getNode());
7207 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
7208 Created.push_back(Q.getNode());
7209
7210 // Shift right algebraic by shift value.
7211 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
7212 Created.push_back(Q.getNode());
7213
7214 // Extract the sign bit, mask it and add it to the quotient.
7215 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
7216 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
7217 Created.push_back(T.getNode());
7218 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
7219 Created.push_back(T.getNode());
7220 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
7221}
7222
7223/// Given an ISD::UDIV node expressing a divide by constant,
7224/// return a DAG expression to select that will generate the same value by
7225/// multiplying by a magic number.
7226/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7228 bool IsAfterLegalization,
7229 bool IsAfterLegalTypes,
7230 SmallVectorImpl<SDNode *> &Created) const {
7231 SDLoc dl(N);
7232
7233 // If the udiv has an 'exact' bit we can use a simpler lowering.
7234 if (N->getFlags().hasExact())
7235 return BuildExactUDIV(*this, N, dl, DAG, Created);
7236
7237 EVT VT = N->getValueType(0);
7238 EVT SVT = VT.getScalarType();
7239 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7240 EVT ShSVT = ShVT.getScalarType();
7241 unsigned EltBits = VT.getScalarSizeInBits();
7242 EVT MulVT;
7243
7244 // Check to see if we can do this.
7245 // FIXME: We should be more aggressive here.
7246 EVT QueryVT = VT;
7247 if (VT.isVector()) {
7248 // If the vector type will be legalized to a vector type with the same
7249 // element type, allow the transform before type legalization if MULHU or
7250 // UMUL_LOHI are supported.
7251 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7252 if (!QueryVT.isVector() ||
7254 return SDValue();
7255 } else if (!isTypeLegal(VT)) {
7256 // Limit this to simple scalars for now.
7257 if (!VT.isSimple())
7258 return SDValue();
7259
7260 // If this type will be promoted to a large enough type with a legal
7261 // multiply operation, we can go ahead and do this transform.
7263 return SDValue();
7264
7265 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7266 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7267 !isOperationLegal(ISD::MUL, MulVT))
7268 return SDValue();
7269 }
7270
7271 bool HasMULHU =
7272 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
7273 bool HasUMUL_LOHI =
7274 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
7275
7276 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
7277 // If type twice as wide legal, widen and use a mul plus a shift.
7278 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7279 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
7280 // custom lowered. This is very expensive so avoid it at all costs for
7281 // constant divisors.
7282 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
7285 MulVT = WideVT;
7286 }
7287
7288 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
7289 return SDValue();
7290
7291 SDValue N0 = N->getOperand(0);
7292 SDValue N1 = N->getOperand(1);
7293
7294 // Try to use leading zeros of the dividend to reduce the multiplier and
7295 // avoid expensive fixups.
7296 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
7297
7298 // If we're after type legalization and SVT is not legal, use the
7299 // promoted type for creating constants to avoid creating nodes with
7300 // illegal types.
7301 if (IsAfterLegalTypes && VT.isVector()) {
7302 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7303 if (SVT.bitsLT(VT.getScalarType()))
7304 return SDValue();
7305 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7306 if (ShSVT.bitsLT(ShVT.getScalarType()))
7307 return SDValue();
7308 }
7309 const unsigned SVTBits = SVT.getSizeInBits();
7310
7311 // Allow i32 to be widened to i64 for uncooperative divisors if i64 MULHU or
7312 // UMUL_LOHI is supported.
7313 const EVT WideSVT = MVT::i64;
7314 const bool HasWideMULHU =
7315 VT == MVT::i32 &&
7316 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
7317 const bool HasWideUMUL_LOHI =
7318 VT == MVT::i32 &&
7319 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
7320 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
7321
7322 // For even divisors with a 33-bit magic number, the widened high-multiply
7323 // path is only worthwhile over the even-divisor rewrite on targets that
7324 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
7325 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
7326 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
7327
7328 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
7329 bool UseWiden = false;
7330 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
7331
7332 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
7333 if (C->isZero())
7334 return false;
7335 // Truncate the divisor to the target scalar type in case it was promoted
7336 // during type legalization.
7337 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7338
7339 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
7340
7341 // Magic algorithm doesn't work for division by 1. We need to emit a select
7342 // at the end.
7343 if (Divisor.isOne()) {
7344 PreShift = PostShift = DAG.getUNDEF(ShSVT);
7345 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
7346 } else {
7349 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7350 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7351 /*AllowWidenOptimization=*/AllowWiden);
7352
7353 if (magics.Widen) {
7354 UseWiden = true;
7355 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7356 } else {
7357 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7358 }
7359
7360 assert(magics.PreShift < Divisor.getBitWidth() &&
7361 "We shouldn't generate an undefined shift!");
7362 assert(magics.PostShift < Divisor.getBitWidth() &&
7363 "We shouldn't generate an undefined shift!");
7364 assert((!magics.IsAdd || magics.PreShift == 0) &&
7365 "Unexpected pre-shift");
7366 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7367 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7368 NPQFactor = DAG.getConstant(
7369 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7370 : APInt::getZero(SVTBits),
7371 dl, SVT);
7372 UseNPQ |= magics.IsAdd;
7373 UsePreShift |= magics.PreShift != 0;
7374 UsePostShift |= magics.PostShift != 0;
7375 }
7376
7377 PreShifts.push_back(PreShift);
7378 MagicFactors.push_back(MagicFactor);
7379 NPQFactors.push_back(NPQFactor);
7380 PostShifts.push_back(PostShift);
7381 return true;
7382 };
7383
7384 // Collect the shifts/magic values from each element.
7385 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7386 /*AllowTruncation=*/true))
7387 return SDValue();
7388
7389 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7390 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7391 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7392 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7393 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7394 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7395 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7396 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7397 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7398 "Expected matchUnaryPredicate to return one for scalable vectors");
7399 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7400 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7401 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7402 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7403 } else {
7404 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7405 PreShift = PreShifts[0];
7406 MagicFactor = MagicFactors[0];
7407 PostShift = PostShifts[0];
7408 }
7409
7410 if (UseWiden) {
7411 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7412 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7413
7414 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7415 // WideSVT bits
7416 SDValue High;
7417 if (HasWideMULHU) {
7418 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7419 } else {
7420 assert(HasWideUMUL_LOHI);
7421 SDValue LoHi =
7422 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7423 WideN0, MagicFactor);
7424 High = LoHi.getValue(1);
7425 }
7426
7427 Created.push_back(High.getNode());
7428 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7429 }
7430
7431 SDValue Q = N0;
7432 if (UsePreShift) {
7433 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7434 Created.push_back(Q.getNode());
7435 }
7436
7437 auto GetMULHU = [&](SDValue X, SDValue Y) {
7438 if (HasMULHU)
7439 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7440 if (HasUMUL_LOHI) {
7441 SDValue LoHi =
7442 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7443 return LoHi.getValue(1);
7444 }
7445
7446 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7447 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7448 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7449 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7450 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7451 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7452 };
7453
7454 // Multiply the numerator (operand 0) by the magic value.
7455 Q = GetMULHU(Q, MagicFactor);
7456 if (!Q)
7457 return SDValue();
7458
7459 Created.push_back(Q.getNode());
7460
7461 if (UseNPQ) {
7462 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7463 Created.push_back(NPQ.getNode());
7464
7465 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7466 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7467 if (VT.isVector())
7468 NPQ = GetMULHU(NPQ, NPQFactor);
7469 else
7470 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7471
7472 Created.push_back(NPQ.getNode());
7473
7474 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7475 Created.push_back(Q.getNode());
7476 }
7477
7478 if (UsePostShift) {
7479 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7480 Created.push_back(Q.getNode());
7481 }
7482
7483 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7484
7485 SDValue One = DAG.getConstant(1, dl, VT);
7486 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7487 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7488}
7489
7490/// If all values in Values that *don't* match the predicate are same 'splat'
7491/// value, then replace all values with that splat value.
7492/// Else, if AlternativeReplacement was provided, then replace all values that
7493/// do match predicate with AlternativeReplacement value.
7494static void
7496 std::function<bool(SDValue)> Predicate,
7497 SDValue AlternativeReplacement = SDValue()) {
7498 SDValue Replacement;
7499 // Is there a value for which the Predicate does *NOT* match? What is it?
7500 auto SplatValue = llvm::find_if_not(Values, Predicate);
7501 if (SplatValue != Values.end()) {
7502 // Does Values consist only of SplatValue's and values matching Predicate?
7503 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7504 return Value == *SplatValue || Predicate(Value);
7505 })) // Then we shall replace values matching predicate with SplatValue.
7506 Replacement = *SplatValue;
7507 }
7508 if (!Replacement) {
7509 // Oops, we did not find the "baseline" splat value.
7510 if (!AlternativeReplacement)
7511 return; // Nothing to do.
7512 // Let's replace with provided value then.
7513 Replacement = AlternativeReplacement;
7514 }
7515 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7516}
7517
7518/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7519/// where the divisor and comparison target are constants,
7520/// return a DAG expression that will generate the same comparison result
7521/// using only multiplications, additions and shifts/rotations.
7522/// Ref: "Hacker's Delight" 10-17.
7523SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7524 SDValue CompTargetNode,
7526 DAGCombinerInfo &DCI,
7527 const SDLoc &DL) const {
7529 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7530 DCI, DL, Built)) {
7531 for (SDNode *N : Built)
7532 DCI.AddToWorklist(N);
7533 return Folded;
7534 }
7535
7536 return SDValue();
7537}
7538
7539SDValue
7540TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7541 SDValue CompTargetNode, ISD::CondCode Cond,
7542 DAGCombinerInfo &DCI, const SDLoc &DL,
7543 SmallVectorImpl<SDNode *> &Created) const {
7544 // fold (seteq/ne (urem N, D), C) ->
7545 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7546 // - D must be constant, with D = D0 * 2^K where D0 is odd
7547 // - P is the multiplicative inverse of D0 modulo 2^W
7548 // - Q = floor(((2^W) - 1) / D)
7549 // where W is the width of the common type of N and D.
7550 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7551 "Only applicable for (in)equality comparisons.");
7552
7553 SelectionDAG &DAG = DCI.DAG;
7554
7555 EVT VT = REMNode.getValueType();
7556 EVT SVT = VT.getScalarType();
7557 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7558 EVT ShSVT = ShVT.getScalarType();
7559
7560 // If MUL is unavailable, we cannot proceed in any case.
7561 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7562 return SDValue();
7563
7564 bool ComparingWithAllZeros = true;
7565 bool AllComparisonsWithNonZerosAreTautological = true;
7566 bool HadTautologicalLanes = false;
7567 bool AllLanesAreTautological = true;
7568 bool HadEvenDivisor = false;
7569 bool AllDivisorsArePowerOfTwo = true;
7570 bool HadTautologicalInvertedLanes = false;
7571 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7572
7573 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7574 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7575 if (CDiv->isZero())
7576 return false;
7577
7578 const APInt &D = CDiv->getAPIntValue();
7579 const APInt &Cmp = CCmp->getAPIntValue();
7580
7581 ComparingWithAllZeros &= Cmp.isZero();
7582
7583 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7584 // if C2 is not less than C1, the comparison is always false.
7585 // But we will only be able to produce the comparison that will give the
7586 // opposive tautological answer. So this lane would need to be fixed up.
7587 bool TautologicalInvertedLane = D.ule(Cmp);
7588 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7589
7590 // If all lanes are tautological (either all divisors are ones, or divisor
7591 // is not greater than the constant we are comparing with),
7592 // we will prefer to avoid the fold.
7593 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7594 HadTautologicalLanes |= TautologicalLane;
7595 AllLanesAreTautological &= TautologicalLane;
7596
7597 // If we are comparing with non-zero, we need'll need to subtract said
7598 // comparison value from the LHS. But there is no point in doing that if
7599 // every lane where we are comparing with non-zero is tautological..
7600 if (!Cmp.isZero())
7601 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7602
7603 // Decompose D into D0 * 2^K
7604 unsigned K = D.countr_zero();
7605 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7606 APInt D0 = D.lshr(K);
7607
7608 // D is even if it has trailing zeros.
7609 HadEvenDivisor |= (K != 0);
7610 // D is a power-of-two if D0 is one.
7611 // If all divisors are power-of-two, we will prefer to avoid the fold.
7612 AllDivisorsArePowerOfTwo &= D0.isOne();
7613
7614 // P = inv(D0, 2^W)
7615 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7616 unsigned W = D.getBitWidth();
7617 APInt P = D0.multiplicativeInverse();
7618 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7619
7620 // Q = floor((2^W - 1) u/ D)
7621 // R = ((2^W - 1) u% D)
7622 APInt Q, R;
7624
7625 // If we are comparing with zero, then that comparison constant is okay,
7626 // else it may need to be one less than that.
7627 if (Cmp.ugt(R))
7628 Q -= 1;
7629
7631 "We are expecting that K is always less than all-ones for ShSVT");
7632
7633 // If the lane is tautological the result can be constant-folded.
7634 if (TautologicalLane) {
7635 // Set P and K amount to a bogus values so we can try to splat them.
7636 P = 0;
7637 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7638 // And ensure that comparison constant is tautological,
7639 // it will always compare true/false.
7640 Q.setAllBits();
7641 } else {
7642 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7643 }
7644
7645 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7646 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7647 return true;
7648 };
7649
7650 SDValue N = REMNode.getOperand(0);
7651 SDValue D = REMNode.getOperand(1);
7652
7653 // Collect the values from each element.
7654 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7655 return SDValue();
7656
7657 // If all lanes are tautological, the result can be constant-folded.
7658 if (AllLanesAreTautological)
7659 return SDValue();
7660
7661 // If this is a urem by a powers-of-two, avoid the fold since it can be
7662 // best implemented as a bit test.
7663 if (AllDivisorsArePowerOfTwo)
7664 return SDValue();
7665
7666 SDValue PVal, KVal, QVal;
7667 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7668 if (HadTautologicalLanes) {
7669 // Try to turn PAmts into a splat, since we don't care about the values
7670 // that are currently '0'. If we can't, just keep '0'`s.
7672 // Try to turn KAmts into a splat, since we don't care about the values
7673 // that are currently '-1'. If we can't, change them to '0'`s.
7675 DAG.getConstant(0, DL, ShSVT));
7676 }
7677
7678 PVal = DAG.getBuildVector(VT, DL, PAmts);
7679 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7680 QVal = DAG.getBuildVector(VT, DL, QAmts);
7681 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7682 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7683 "Expected matchBinaryPredicate to return one element for "
7684 "SPLAT_VECTORs");
7685 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7686 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7687 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7688 } else {
7689 PVal = PAmts[0];
7690 KVal = KAmts[0];
7691 QVal = QAmts[0];
7692 }
7693
7694 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7695 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7696 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7697 assert(CompTargetNode.getValueType() == N.getValueType() &&
7698 "Expecting that the types on LHS and RHS of comparisons match.");
7699 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7700 }
7701
7702 // (mul N, P)
7703 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7704 Created.push_back(Op0.getNode());
7705
7706 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7707 // divisors as a performance improvement, since rotating by 0 is a no-op.
7708 if (HadEvenDivisor) {
7709 // We need ROTR to do this.
7710 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7711 return SDValue();
7712 // UREM: (rotr (mul N, P), K)
7713 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7714 Created.push_back(Op0.getNode());
7715 }
7716
7717 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7718 SDValue NewCC =
7719 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7721 if (!HadTautologicalInvertedLanes)
7722 return NewCC;
7723
7724 // If any lanes previously compared always-false, the NewCC will give
7725 // always-true result for them, so we need to fixup those lanes.
7726 // Or the other way around for inequality predicate.
7727 assert(VT.isVector() && "Can/should only get here for vectors.");
7728 Created.push_back(NewCC.getNode());
7729
7730 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7731 // if C2 is not less than C1, the comparison is always false.
7732 // But we have produced the comparison that will give the
7733 // opposive tautological answer. So these lanes would need to be fixed up.
7734 SDValue TautologicalInvertedChannels =
7735 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7736 Created.push_back(TautologicalInvertedChannels.getNode());
7737
7738 // NOTE: we avoid letting illegal types through even if we're before legalize
7739 // ops – legalization has a hard time producing good code for this.
7740 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7741 // If we have a vector select, let's replace the comparison results in the
7742 // affected lanes with the correct tautological result.
7743 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7744 DL, SETCCVT, SETCCVT);
7745 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7746 Replacement, NewCC);
7747 }
7748
7749 // Else, we can just invert the comparison result in the appropriate lanes.
7750 //
7751 // NOTE: see the note above VSELECT above.
7752 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7753 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7754 TautologicalInvertedChannels);
7755
7756 return SDValue(); // Don't know how to lower.
7757}
7758
7759/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7760/// where the divisor is constant and the comparison target is zero,
7761/// return a DAG expression that will generate the same comparison result
7762/// using only multiplications, additions and shifts/rotations.
7763/// Ref: "Hacker's Delight" 10-17.
7764SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7765 SDValue CompTargetNode,
7767 DAGCombinerInfo &DCI,
7768 const SDLoc &DL) const {
7770 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7771 DCI, DL, Built)) {
7772 assert(Built.size() <= 7 && "Max size prediction failed.");
7773 for (SDNode *N : Built)
7774 DCI.AddToWorklist(N);
7775 return Folded;
7776 }
7777
7778 return SDValue();
7779}
7780
7781SDValue
7782TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7783 SDValue CompTargetNode, ISD::CondCode Cond,
7784 DAGCombinerInfo &DCI, const SDLoc &DL,
7785 SmallVectorImpl<SDNode *> &Created) const {
7786 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7787 // Fold:
7788 // (seteq/ne (srem N, D), 0)
7789 // To:
7790 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7791 //
7792 // - D must be constant, with D = D0 * 2^K where D0 is odd
7793 // - P is the multiplicative inverse of D0 modulo 2^W
7794 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7795 // - Q = floor((2 * A) / (2^K))
7796 // where W is the width of the common type of N and D.
7797 //
7798 // When D is a power of two (and thus D0 is 1), the normal
7799 // formula for A and Q don't apply, because the derivation
7800 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7801 // does not apply. This specifically fails when N = INT_MIN.
7802 //
7803 // Instead, for power-of-two D, we use:
7804 // - A = 0
7805 // | -> No offset needed. We're effectively treating it the same as urem.
7806 // - Q = 2^(W-K) - 1
7807 // |-> Test that the top K bits are zero after rotation
7808 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7809 "Only applicable for (in)equality comparisons.");
7810
7811 SelectionDAG &DAG = DCI.DAG;
7812
7813 EVT VT = REMNode.getValueType();
7814 EVT SVT = VT.getScalarType();
7815 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7816 EVT ShSVT = ShVT.getScalarType();
7817
7818 // If we are after ops legalization, and MUL is unavailable, we can not
7819 // proceed.
7820 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7821 return SDValue();
7822
7823 // TODO: Could support comparing with non-zero too.
7824 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7825 if (!CompTarget || !CompTarget->isZero())
7826 return SDValue();
7827
7828 bool HadOneDivisor = false;
7829 bool AllDivisorsAreOnes = true;
7830 bool HadEvenDivisor = false;
7831 bool AllDivisorsArePowerOfTwo = true;
7832 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7833
7834 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7835 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7836 if (C->isZero())
7837 return false;
7838
7839 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7840
7841 // WARNING: this fold is only valid for positive divisors!
7842 // `rem %X, -C` is equivalent to `rem %X, C`
7843 APInt D = C->getAPIntValue().abs();
7844
7845 // If all divisors are ones, we will prefer to avoid the fold.
7846 HadOneDivisor |= D.isOne();
7847 AllDivisorsAreOnes &= D.isOne();
7848
7849 // Decompose D into D0 * 2^K
7850 unsigned K = D.countr_zero();
7851 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7852 APInt D0 = D.lshr(K);
7853
7854 // D is even if it has trailing zeros.
7855 HadEvenDivisor |= (K != 0);
7856
7857 // D is a power-of-two if D0 is one. This includes INT_MIN.
7858 // If all divisors are power-of-two, we will prefer to avoid the fold.
7859 AllDivisorsArePowerOfTwo &= D0.isOne();
7860
7861 // P = inv(D0, 2^W)
7862 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7863 unsigned W = D.getBitWidth();
7864 APInt P = D0.multiplicativeInverse();
7865 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7866
7867 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7868 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7869 A.clearLowBits(K);
7870
7871 // Q = floor((2 * A) / (2^K))
7872 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7873
7875 "We are expecting that A is always less than all-ones for SVT");
7877 "We are expecting that K is always less than all-ones for ShSVT");
7878
7879 // If D was a power of two, apply the alternate constant derivation.
7880 if (D0.isOne()) {
7881 // A = 0
7882 A = APInt(W, 0);
7883 // - Q = 2^(W-K) - 1
7884 Q = APInt::getLowBitsSet(W, W - K);
7885 }
7886
7887 // If the divisor is 1 the result can be constant-folded.
7888 if (D.isOne()) {
7889 // Set P, A and K to a bogus values so we can try to splat them.
7890 P = 0;
7891 A.setAllBits();
7892 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7893
7894 // x ?% 1 == 0 <--> true <--> x u<= -1
7895 Q.setAllBits();
7896 } else {
7897 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7898 }
7899
7900 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7901 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7902 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7903 return true;
7904 };
7905
7906 SDValue N = REMNode.getOperand(0);
7907 SDValue D = REMNode.getOperand(1);
7908
7909 // Collect the values from each element.
7910 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7911 return SDValue();
7912
7913 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7914 if (AllDivisorsAreOnes)
7915 return SDValue();
7916
7917 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7918 // since it can be best implemented as a bit test.
7919 if (AllDivisorsArePowerOfTwo)
7920 return SDValue();
7921
7922 SDValue PVal, AVal, KVal, QVal;
7923 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7924 if (HadOneDivisor) {
7925 // Try to turn PAmts into a splat, since we don't care about the values
7926 // that are currently '0'. If we can't, just keep '0'`s.
7928 // Try to turn AAmts into a splat, since we don't care about the
7929 // values that are currently '-1'. If we can't, change them to '0'`s.
7931 DAG.getConstant(0, DL, SVT));
7932 // Try to turn KAmts into a splat, since we don't care about the values
7933 // that are currently '-1'. If we can't, change them to '0'`s.
7935 DAG.getConstant(0, DL, ShSVT));
7936 }
7937
7938 PVal = DAG.getBuildVector(VT, DL, PAmts);
7939 AVal = DAG.getBuildVector(VT, DL, AAmts);
7940 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7941 QVal = DAG.getBuildVector(VT, DL, QAmts);
7942 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7943 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7944 QAmts.size() == 1 &&
7945 "Expected matchUnaryPredicate to return one element for scalable "
7946 "vectors");
7947 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7948 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7949 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7950 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7951 } else {
7952 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7953 PVal = PAmts[0];
7954 AVal = AAmts[0];
7955 KVal = KAmts[0];
7956 QVal = QAmts[0];
7957 }
7958
7959 // (mul N, P)
7960 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7961 Created.push_back(Op0.getNode());
7962
7963 // We need ADD to do this.
7964 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
7965 return SDValue();
7966
7967 // (add (mul N, P), A)
7968 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
7969 Created.push_back(Op0.getNode());
7970
7971 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7972 // divisors as a performance improvement, since rotating by 0 is a no-op.
7973 if (HadEvenDivisor) {
7974 // We need ROTR to do this.
7975 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7976 return SDValue();
7977 // SREM: (rotr (add (mul N, P), A), K)
7978 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7979 Created.push_back(Op0.getNode());
7980 }
7981
7982 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
7983 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7985}
7986
7988 const DenormalMode &Mode,
7989 SDNodeFlags Flags) const {
7990 SDLoc DL(Op);
7991 EVT VT = Op.getValueType();
7992 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7993 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7994
7995 // This is specifically a check for the handling of denormal inputs, not the
7996 // result.
7997 if (Mode.Input == DenormalMode::PreserveSign ||
7998 Mode.Input == DenormalMode::PositiveZero) {
7999 // Test = X == 0.0
8000 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
8001 /*Signaling=*/false, Flags);
8002 }
8003
8004 // Testing it with denormal inputs to avoid wrong estimate.
8005 //
8006 // Test = fabs(X) < SmallestNormal
8007 const fltSemantics &FltSem = VT.getFltSemantics();
8008 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
8009 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
8010 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
8011 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
8012 /*Signaling=*/false, Flags);
8013}
8014
8016 bool LegalOps, bool OptForSize,
8018 unsigned Depth) const {
8019 // fneg is removable even if it has multiple uses.
8020 if (Op.getOpcode() == ISD::FNEG) {
8022 return Op.getOperand(0);
8023 }
8024
8025 // Don't recurse exponentially.
8027 return SDValue();
8028
8029 // Pre-increment recursion depth for use in recursive calls.
8030 ++Depth;
8031 const SDNodeFlags Flags = Op->getFlags();
8032 EVT VT = Op.getValueType();
8033 unsigned Opcode = Op.getOpcode();
8034
8035 // Don't allow anything with multiple uses unless we know it is free.
8036 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
8037 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
8038 isFPExtFree(VT, Op.getOperand(0).getValueType());
8039 if (!IsFreeExtend)
8040 return SDValue();
8041 }
8042
8043 auto RemoveDeadNode = [&](SDValue N) {
8044 if (N && N.getNode()->use_empty())
8045 DAG.RemoveDeadNode(N.getNode());
8046 };
8047
8048 SDLoc DL(Op);
8049
8050 // Because getNegatedExpression can delete nodes we need a handle to keep
8051 // temporary nodes alive in case the recursion manages to create an identical
8052 // node.
8053 std::list<HandleSDNode> Handles;
8054
8055 switch (Opcode) {
8056 case ISD::ConstantFP: {
8057 // Don't invert constant FP values after legalization unless the target says
8058 // the negated constant is legal.
8059 bool IsOpLegal =
8061 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
8062 OptForSize);
8063
8064 if (LegalOps && !IsOpLegal)
8065 break;
8066
8067 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
8068 V.changeSign();
8069 SDValue CFP = DAG.getConstantFP(V, DL, VT);
8070
8071 // If we already have the use of the negated floating constant, it is free
8072 // to negate it even it has multiple uses.
8073 if (!Op.hasOneUse() && CFP.use_empty())
8074 break;
8076 return CFP;
8077 }
8078 case ISD::SPLAT_VECTOR: {
8079 // fold splat_vector(fneg(X)) -> splat_vector(-X)
8080 SDValue X = Op.getOperand(0);
8082 break;
8083
8084 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
8085 if (!NegX)
8086 break;
8088 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
8089 }
8090 case ISD::BUILD_VECTOR: {
8091 // Only permit BUILD_VECTOR of constants.
8092 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
8093 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
8094 }))
8095 break;
8096
8097 bool IsOpLegal =
8100 llvm::all_of(Op->op_values(), [&](SDValue N) {
8101 return N.isUndef() ||
8102 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
8103 OptForSize);
8104 });
8105
8106 if (LegalOps && !IsOpLegal)
8107 break;
8108
8110 for (SDValue C : Op->op_values()) {
8111 if (C.isUndef()) {
8112 Ops.push_back(C);
8113 continue;
8114 }
8115 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
8116 V.changeSign();
8117 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
8118 }
8120 return DAG.getBuildVector(VT, DL, Ops);
8121 }
8122 case ISD::FADD: {
8123 if (!Flags.hasNoSignedZeros())
8124 break;
8125
8126 // After operation legalization, it might not be legal to create new FSUBs.
8127 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
8128 break;
8129 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8130
8131 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
8133 SDValue NegX =
8134 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8135 // Prevent this node from being deleted by the next call.
8136 if (NegX)
8137 Handles.emplace_back(NegX);
8138
8139 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
8141 SDValue NegY =
8142 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8143
8144 // We're done with the handles.
8145 Handles.clear();
8146
8147 // Negate the X if its cost is less or equal than Y.
8148 if (NegX && (CostX <= CostY)) {
8149 Cost = CostX;
8150 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
8151 if (NegY != N)
8152 RemoveDeadNode(NegY);
8153 return N;
8154 }
8155
8156 // Negate the Y if it is not expensive.
8157 if (NegY) {
8158 Cost = CostY;
8159 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
8160 if (NegX != N)
8161 RemoveDeadNode(NegX);
8162 return N;
8163 }
8164 break;
8165 }
8166 case ISD::FSUB: {
8167 // We can't turn -(A-B) into B-A when we honor signed zeros.
8168 if (!Flags.hasNoSignedZeros())
8169 break;
8170
8171 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8172 // fold (fneg (fsub 0, Y)) -> Y
8173 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
8174 if (C->isZero()) {
8176 return Y;
8177 }
8178
8179 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
8181 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
8182 }
8183 case ISD::FMUL:
8184 case ISD::FDIV: {
8185 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8186
8187 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
8189 SDValue NegX =
8190 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8191 // Prevent this node from being deleted by the next call.
8192 if (NegX)
8193 Handles.emplace_back(NegX);
8194
8195 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
8197 SDValue NegY =
8198 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8199
8200 // We're done with the handles.
8201 Handles.clear();
8202
8203 // Negate the X if its cost is less or equal than Y.
8204 if (NegX && (CostX <= CostY)) {
8205 Cost = CostX;
8206 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
8207 if (NegY != N)
8208 RemoveDeadNode(NegY);
8209 return N;
8210 }
8211
8212 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
8213 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
8214 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
8215 break;
8216
8217 // Negate the Y if it is not expensive.
8218 if (NegY) {
8219 Cost = CostY;
8220 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
8221 if (NegX != N)
8222 RemoveDeadNode(NegX);
8223 return N;
8224 }
8225 break;
8226 }
8227 case ISD::FMA:
8228 case ISD::FMULADD:
8229 case ISD::FMAD: {
8230 if (!Flags.hasNoSignedZeros())
8231 break;
8232
8233 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
8235 SDValue NegZ =
8236 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
8237 // Give up if fail to negate the Z.
8238 if (!NegZ)
8239 break;
8240
8241 // Prevent this node from being deleted by the next two calls.
8242 Handles.emplace_back(NegZ);
8243
8244 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
8246 SDValue NegX =
8247 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8248 // Prevent this node from being deleted by the next call.
8249 if (NegX)
8250 Handles.emplace_back(NegX);
8251
8252 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
8254 SDValue NegY =
8255 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8256
8257 // We're done with the handles.
8258 Handles.clear();
8259
8260 // Negate the X if its cost is less or equal than Y.
8261 if (NegX && (CostX <= CostY)) {
8262 Cost = std::min(CostX, CostZ);
8263 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
8264 if (NegY != N)
8265 RemoveDeadNode(NegY);
8266 return N;
8267 }
8268
8269 // Negate the Y if it is not expensive.
8270 if (NegY) {
8271 Cost = std::min(CostY, CostZ);
8272 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
8273 if (NegX != N)
8274 RemoveDeadNode(NegX);
8275 return N;
8276 }
8277 break;
8278 }
8279
8280 case ISD::FP_EXTEND:
8281 case ISD::FSIN:
8282 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8283 OptForSize, Cost, Depth))
8284 return DAG.getNode(Opcode, DL, VT, NegV);
8285 break;
8286 case ISD::FP_ROUND:
8287 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8288 OptForSize, Cost, Depth))
8289 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
8290 break;
8291 case ISD::SELECT:
8292 case ISD::VSELECT: {
8293 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
8294 // iff at least one cost is cheaper and the other is neutral/cheaper
8295 SDValue LHS = Op.getOperand(1);
8297 SDValue NegLHS =
8298 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
8299 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
8300 RemoveDeadNode(NegLHS);
8301 break;
8302 }
8303
8304 // Prevent this node from being deleted by the next call.
8305 Handles.emplace_back(NegLHS);
8306
8307 SDValue RHS = Op.getOperand(2);
8309 SDValue NegRHS =
8310 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
8311
8312 // We're done with the handles.
8313 Handles.clear();
8314
8315 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
8316 (CostLHS != NegatibleCost::Cheaper &&
8317 CostRHS != NegatibleCost::Cheaper)) {
8318 RemoveDeadNode(NegLHS);
8319 RemoveDeadNode(NegRHS);
8320 break;
8321 }
8322
8323 Cost = std::min(CostLHS, CostRHS);
8324 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
8325 }
8326 }
8327
8328 return SDValue();
8329}
8330
8331//===----------------------------------------------------------------------===//
8332// Legalization Utilities
8333//===----------------------------------------------------------------------===//
8334
8335bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
8336 SDValue LHS, SDValue RHS,
8338 EVT HiLoVT, SelectionDAG &DAG,
8339 MulExpansionKind Kind, SDValue LL,
8340 SDValue LH, SDValue RL, SDValue RH) const {
8341 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
8342 Opcode == ISD::SMUL_LOHI);
8343
8344 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
8346 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8348 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8350 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8352
8353 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8354 return false;
8355
8356 unsigned OuterBitSize = VT.getScalarSizeInBits();
8357 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8358
8359 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8360 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8361 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8362
8363 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8364 bool Signed) -> bool {
8365 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8366 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8367 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8368 Hi = Lo.getValue(1);
8369 return true;
8370 }
8371 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8372 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8373 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8374 return true;
8375 }
8376 return false;
8377 };
8378
8379 SDValue Lo, Hi;
8380
8381 if (!LL.getNode() && !RL.getNode() &&
8383 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8384 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8385 }
8386
8387 if (!LL.getNode())
8388 return false;
8389
8390 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8391 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8392 DAG.MaskedValueIsZero(RHS, HighMask)) {
8393 // The inputs are both zero-extended.
8394 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8395 Result.push_back(Lo);
8396 Result.push_back(Hi);
8397 if (Opcode != ISD::MUL) {
8398 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8399 Result.push_back(Zero);
8400 Result.push_back(Zero);
8401 }
8402 return true;
8403 }
8404 }
8405
8406 if (!VT.isVector() && Opcode == ISD::MUL &&
8407 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8408 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8409 // The input values are both sign-extended.
8410 // TODO non-MUL case?
8411 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8412 Result.push_back(Lo);
8413 Result.push_back(Hi);
8414 return true;
8415 }
8416 }
8417
8418 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8419 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8420
8421 if (!LH.getNode() && !RH.getNode() &&
8424 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8425 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8426 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8427 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8428 }
8429
8430 if (!LH.getNode())
8431 return false;
8432
8433 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8434 return false;
8435
8436 Result.push_back(Lo);
8437
8438 if (Opcode == ISD::MUL) {
8439 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8440 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8441 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8442 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8443 Result.push_back(Hi);
8444 return true;
8445 }
8446
8447 // Compute the full width result.
8448 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8449 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8450 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8451 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8452 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8453 };
8454
8455 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8456 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8457 return false;
8458
8459 // This is effectively the add part of a multiply-add of half-sized operands,
8460 // so it cannot overflow.
8461 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8462
8463 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8464 return false;
8465
8466 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8467 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8468
8469 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8471 if (UseGlue)
8472 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8473 Merge(Lo, Hi));
8474 else
8475 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8476 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8477
8478 SDValue Carry = Next.getValue(1);
8479 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8480 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8481
8482 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8483 return false;
8484
8485 if (UseGlue)
8486 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8487 Carry);
8488 else
8489 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8490 Zero, Carry);
8491
8492 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8493
8494 if (Opcode == ISD::SMUL_LOHI) {
8495 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8496 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8497 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8498
8499 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8500 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8501 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8502 }
8503
8504 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8505 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8506 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8507 return true;
8508}
8509
8511 SelectionDAG &DAG, MulExpansionKind Kind,
8512 SDValue LL, SDValue LH, SDValue RL,
8513 SDValue RH) const {
8515 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8516 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8517 DAG, Kind, LL, LH, RL, RH);
8518 if (Ok) {
8519 assert(Result.size() == 2);
8520 Lo = Result[0];
8521 Hi = Result[1];
8522 }
8523 return Ok;
8524}
8525
8526// Optimize unsigned division or remainder by constants for types twice as large
8527// as a legal VT.
8528//
8529// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8530// can be computed
8531// as:
8532// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8533// Remainder = Sum % Constant;
8534//
8535// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8536// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8537// High:Low into 3 chunks of W bits and compute remainder as
8538// Sum = Chunk0 + Chunk1 + Chunk2;
8539// Remainder = Sum % Constant;
8540//
8541// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8542//
8543// For division, we can compute the remainder using the algorithm described
8544// above, subtract it from the dividend to get an exact multiple of Constant.
8545// Then multiply that exact multiply by the multiplicative inverse modulo
8546// (1 << (BitWidth / 2)) to get the quotient.
8547
8548// If Constant is even, we can shift right the dividend and the divisor by the
8549// number of trailing zeros in Constant before applying the remainder algorithm.
8550// If we're after the quotient, we can subtract this value from the shifted
8551// dividend and multiply by the multiplicative inverse of the shifted divisor.
8552// If we want the remainder, we shift the value left by the number of trailing
8553// zeros and add the bits that were shifted out of the dividend.
8554bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8555 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8556 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8557 unsigned Opcode = N->getOpcode();
8558 EVT VT = N->getValueType(0);
8559
8560 unsigned BitWidth = Divisor.getBitWidth();
8561 unsigned HBitWidth = BitWidth / 2;
8563 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8564
8565 // If the divisor is even, shift it until it becomes odd.
8566 unsigned TrailingZeros = 0;
8567 if (!Divisor[0]) {
8568 TrailingZeros = Divisor.countr_zero();
8569 Divisor.lshrInPlace(TrailingZeros);
8570 }
8571
8572 // After removing trailing zeros, the divisor needs to be less than
8573 // (1 << HBitWidth).
8574 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8575 if (Divisor.uge(HalfMaxPlus1))
8576 return false;
8577
8578 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8579 // (1 << W) % Divisor == -1.
8580 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8581 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8582 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8583 if (I == HBitWidth - 1)
8584 continue;
8585
8586 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8587
8588 if (Mod.isOne()) {
8589 BestChunkWidth = I;
8590 break;
8591 }
8592
8593 // We have an alternate strategy for Remainder == Divisor - 1.
8594 // FIXME: Support HBitWidth.
8595 if (I != HBitWidth && Mod == Divisor - 1)
8596 AltChunkWidth = I;
8597 }
8598
8599 bool Alternate = false;
8600 if (!BestChunkWidth) {
8601 if (!AltChunkWidth)
8602 return false;
8603 Alternate = true;
8604 BestChunkWidth = AltChunkWidth;
8605 }
8606
8607 SDLoc dl(N);
8608
8609 assert(!LL == !LH && "Expected both input halves or no input halves!");
8610 if (!LL)
8611 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8612
8613 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8614
8615 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8616 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8617 if (HasFSHR)
8618 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8619 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8620 return DAG.getNode(
8621 ISD::OR, dl, HiLoVT,
8622 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8623 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8624 DAG.getNode(
8625 ISD::SHL, dl, HiLoVT, Hi,
8626 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8627 };
8628
8629 // Helper to perform a right shift on a 128-bit value split into two halves.
8630 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8631 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8632 if (ShiftAmt == 0)
8633 return;
8634 if (ShiftAmt < HBitWidth) {
8635 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8636 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8637 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8638 } else if (ShiftAmt == HBitWidth) {
8639 Lo = Hi;
8640 Hi = DAG.getConstant(0, dl, HiLoVT);
8641 } else {
8642 Lo = DAG.getNode(
8643 ISD::SRL, dl, HiLoVT, Hi,
8644 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8645 Hi = DAG.getConstant(0, dl, HiLoVT);
8646 }
8647 };
8648
8649 // Shift the input by the number of TrailingZeros in the divisor. The
8650 // shifted out bits will be added to the remainder later.
8651 SDValue PartialRemL, PartialRemH;
8652 if (TrailingZeros && Opcode != ISD::UDIV) {
8653 // Save the shifted off bits if we need the remainder.
8654 if (TrailingZeros < HBitWidth) {
8655 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8656 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8657 DAG.getConstant(Mask, dl, HiLoVT));
8658 } else if (TrailingZeros == HBitWidth) {
8659 // All of LL is part of the remainder.
8660 PartialRemL = LL;
8661 } else {
8662 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8663 PartialRemL = LL;
8664 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8665 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8666 DAG.getConstant(Mask, dl, HiLoVT));
8667 }
8668 }
8669
8670 SDValue Sum;
8671 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8672 // out, add that to the final sum.
8673 if (BestChunkWidth == HBitWidth) {
8674 assert(!Alternate);
8675 // Shift LH:LL right if there were trailing zeros in the divisor.
8676 ShiftRight(LL, LH, TrailingZeros);
8677
8678 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8679 EVT SetCCType =
8680 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8682 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8683 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8684 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8685 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8686 } else {
8687 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8688 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8689 // If the boolean for the target is 0 or 1, we can add the setcc result
8690 // directly.
8691 if (getBooleanContents(HiLoVT) ==
8693 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8694 else
8695 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8696 DAG.getConstant(0, dl, HiLoVT));
8697 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8698 }
8699 } else {
8700 // Otherwise split into multple chunks and add them together. We chose
8701 // BestChunkWidth so that the sum will not overflow.
8702 SDValue Mask = DAG.getConstant(
8703 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8704
8705 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8706 // If there were trailing zeros in the divisor, increase the shift amount.
8707 unsigned Shift = I + TrailingZeros;
8708 SDValue Chunk;
8709 if (Shift == 0)
8710 Chunk = LL;
8711 else if (Shift >= HBitWidth)
8712 Chunk = DAG.getNode(
8713 ISD::SRL, dl, HiLoVT, LH,
8714 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8715 else
8716 Chunk = GetFSHR(LL, LH, Shift);
8717 // If we're on the last chunk, we don't need an AND.
8718 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8719 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8720 if (!Sum) {
8721 Sum = Chunk;
8722 } else {
8723 // For Alternate, we need to subtract odd chunks.
8724 unsigned ChunkNum = I / BestChunkWidth;
8725 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8726 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8727 }
8728 }
8729
8730 // For Alternate, the sum may be negative, but we need a positive sum. We
8731 // can increase it by a multiple of the divisor to make it positive. For 3
8732 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8733 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8734 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8735 // positive.
8736 if (Alternate) {
8737 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8738 assert(NumChunks <= 4);
8739
8740 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8741 Adjust.setBit(0);
8742 // If there are 4 chunks, we need to adjust twice.
8743 if (NumChunks == 4)
8744 Adjust <<= 1;
8745 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8746 DAG.getConstant(Adjust, dl, HiLoVT));
8747 }
8748 }
8749
8750 // Perform a HiLoVT urem on the Sum using truncated divisor.
8751 SDValue RemL =
8752 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8753 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8754 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8755
8756 if (Opcode != ISD::UREM) {
8757 // If we didn't shift LH/LR earlier, do it now.
8758 if (BestChunkWidth != HBitWidth)
8759 ShiftRight(LL, LH, TrailingZeros);
8760
8761 // Subtract the remainder from the shifted dividend.
8762 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8763 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8764
8765 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8766
8767 // Multiply by the multiplicative inverse of the divisor modulo
8768 // (1 << BitWidth).
8769 APInt MulFactor = Divisor.multiplicativeInverse();
8770
8771 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8772 DAG.getConstant(MulFactor, dl, VT));
8773
8774 // Split the quotient into low and high parts.
8775 SDValue QuotL, QuotH;
8776 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8777 Result.push_back(QuotL);
8778 Result.push_back(QuotH);
8779 }
8780
8781 if (Opcode != ISD::UDIV) {
8782 // If we shifted the input, shift the remainder left and add the bits we
8783 // shifted off the input.
8784 if (TrailingZeros) {
8785 if (TrailingZeros < HBitWidth) {
8786 // Shift RemH:RemL left by TrailingZeros.
8787 // RemH gets the high bits shifted out of RemL.
8788 RemH = DAG.getNode(
8789 ISD::SRL, dl, HiLoVT, RemL,
8790 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8791 RemL =
8792 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8793 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8794 // OR in the partial remainder.
8795 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8797 } else if (TrailingZeros == HBitWidth) {
8798 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8799 // PartialRemL.
8800 RemH = RemL;
8801 RemL = PartialRemL;
8802 } else {
8803 // Shift left by more than HBitWidth.
8804 RemH = DAG.getNode(
8805 ISD::SHL, dl, HiLoVT, RemL,
8806 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8807 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8809 RemL = PartialRemL;
8810 }
8811 }
8812 Result.push_back(RemL);
8813 Result.push_back(RemH);
8814 }
8815
8816 return true;
8817}
8818
8819bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8820 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8821 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8822
8823 SDValue N0 = N->getOperand(0);
8824 EVT VT = N0->getValueType(0);
8825 SDLoc DL{N};
8826
8827 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8828
8829 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8830 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8831 const APInt &Const,
8832 SmallVectorImpl<SDValue> &Result) {
8833 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8834 SDValue RHS = DAG.getConstant(Const, DL, VT);
8835 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8836 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8838 LL, LH, RL, RH);
8839 };
8840
8841 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8842 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8843 SDValue RH) {
8844 SDValue AddSubNode =
8846 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8847 SDValue OutL = AddSubNode.getValue(0);
8848 SDValue Overflow = AddSubNode.getValue(1);
8849 SDValue AddSubWithOverflow =
8851 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8852 SDValue OutH = AddSubWithOverflow.getValue(0);
8853 return std::make_pair(OutL, OutH);
8854 };
8855
8856 // This helper creates a SRL of the pair (LL, LH) by Shift.
8857 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8858 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8859 if (Shift < HBitWidth) {
8860 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8861 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8862 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8863 return std::make_pair(ResL, ResH);
8864 }
8865 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8866 if (Shift == HBitWidth)
8867 return std::make_pair(LH, Zero);
8868 assert(Shift - HBitWidth < HBitWidth &&
8869 "We shouldn't generate an undefined shift");
8870 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8871 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8872 };
8873
8874 // Knowledge of leading zeros may help to reduce the multiplier.
8875 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8876
8877 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8878 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8879
8880 assert(!LL == !LH && "Expected both input halves or no input halves!");
8881 if (!LL)
8882 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8883 SDValue QL = LL;
8884 SDValue QH = LH;
8885 if (Magics.PreShift != 0)
8886 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8887
8888 SmallVector<SDValue, 4> UMulResult;
8889 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8890 return false;
8891
8892 QL = UMulResult[2];
8893 QH = UMulResult[3];
8894
8895 if (Magics.IsAdd) {
8896 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8897 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8898 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8899 }
8900
8901 if (Magics.PostShift != 0)
8902 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8903
8904 unsigned Opcode = N->getOpcode();
8905 if (Opcode != ISD::UREM) {
8906 Result.push_back(QL);
8907 Result.push_back(QH);
8908 }
8909
8910 if (Opcode != ISD::UDIV) {
8911 SmallVector<SDValue, 2> MulResult;
8912 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8913 return false;
8914
8915 assert(MulResult.size() == 2);
8916
8917 auto [RemL, RemH] =
8918 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8919
8920 Result.push_back(RemL);
8921 Result.push_back(RemH);
8922 }
8923
8924 return true;
8925}
8926
8929 EVT HiLoVT, SelectionDAG &DAG,
8930 SDValue LL, SDValue LH) const {
8931 unsigned Opcode = N->getOpcode();
8932
8933 // TODO: Support signed division/remainder.
8934 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8935 return false;
8936 assert(
8937 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8938 "Unexpected opcode");
8939
8940 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8941 if (!CN)
8942 return false;
8943
8944 APInt Divisor = CN->getAPIntValue();
8945
8946 // The generated half-width UREM is normally optimized using high multiply.
8947 // If the wide UREM libcall is unavailable, a legal or custom half-width
8948 // UDIVREM can lower it instead.
8949 bool CanDecomposeUREMWithoutMulHi =
8950 Opcode == ISD::UREM &&
8951 DAG.getLibcalls().getLibcallImpl(RTLIB::getUREM(N->getValueType(0))) ==
8952 RTLIB::Unsupported &&
8954 if (!CanDecomposeUREMWithoutMulHi &&
8957 return false;
8958
8959 // Prefer the smaller libcall when one is available.
8960 if (DAG.shouldOptForSize() && !CanDecomposeUREMWithoutMulHi)
8961 return false;
8962
8963 // Early out for 0 or 1 divisors.
8964 if (Divisor.ule(1))
8965 return false;
8966
8967 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
8968 DAG, LL, LH))
8969 return true;
8970
8971 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
8972 LH))
8973 return true;
8974
8975 return false;
8976}
8977
8978// Check that (every element of) Z is undef or not an exact multiple of BW.
8979static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
8981 Z,
8982 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
8983 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
8984}
8985
8987 SelectionDAG &DAG) const {
8988 EVT VT = Node->getValueType(0);
8989
8990 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
8994 return SDValue();
8995
8996 SDValue X = Node->getOperand(0);
8997 SDValue Y = Node->getOperand(1);
8998 SDValue Z = Node->getOperand(2);
8999
9000 unsigned BW = VT.getScalarSizeInBits();
9001 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
9002 SDLoc DL(SDValue(Node, 0));
9003
9004 EVT ShVT = Z.getValueType();
9005
9006 // If a funnel shift in the other direction is more supported, use it.
9007 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
9008 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
9009 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
9010 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
9011 // fshl X, Y, Z -> fshr X, Y, -Z
9012 // fshr X, Y, Z -> fshl X, Y, -Z
9013 Z = DAG.getNegative(Z, DL, ShVT);
9014 } else {
9015 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
9016 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
9017 SDValue One = DAG.getConstant(1, DL, ShVT);
9018 if (IsFSHL) {
9019 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
9020 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
9021 } else {
9022 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
9023 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
9024 }
9025 Z = DAG.getNOT(DL, Z, ShVT);
9026 }
9027 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
9028 }
9029
9030 SDValue ShX, ShY;
9031 SDValue ShAmt, InvShAmt;
9032 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
9033 // fshl: X << C | Y >> (BW - C)
9034 // fshr: X << (BW - C) | Y >> C
9035 // where C = Z % BW is not zero
9036 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
9037 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
9038 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
9039 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
9040 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
9041 } else {
9042 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
9043 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
9044 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
9045 if (isPowerOf2_32(BW)) {
9046 // Z % BW -> Z & (BW - 1)
9047 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
9048 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
9049 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
9050 } else {
9051 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
9052 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
9053 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
9054 }
9055
9056 SDValue One = DAG.getConstant(1, DL, ShVT);
9057 if (IsFSHL) {
9058 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
9059 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
9060 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
9061 } else {
9062 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
9063 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
9064 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
9065 }
9066 }
9067 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
9068}
9069
9070// TODO: Merge with expandFunnelShift.
9072 SelectionDAG &DAG) const {
9073 EVT VT = Node->getValueType(0);
9074 unsigned EltSizeInBits = VT.getScalarSizeInBits();
9075 bool IsLeft = Node->getOpcode() == ISD::ROTL;
9076 SDValue Op0 = Node->getOperand(0);
9077 SDValue Op1 = Node->getOperand(1);
9078 SDLoc DL(SDValue(Node, 0));
9079
9080 EVT ShVT = Op1.getValueType();
9081 SDValue Zero = DAG.getConstant(0, DL, ShVT);
9082
9083 // If a rotate in the other direction is more supported, use it.
9084 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
9085 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
9086 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
9087 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
9088 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
9089 }
9090
9091 if (!AllowVectorOps && VT.isVector() &&
9097 return SDValue();
9098
9099 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
9100 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
9101 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
9102 SDValue ShVal;
9103 SDValue HsVal;
9104 if (isPowerOf2_32(EltSizeInBits)) {
9105 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
9106 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
9107 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
9108 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
9109 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
9110 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
9111 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
9112 } else {
9113 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
9114 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
9115 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
9116 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
9117 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
9118 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
9119 SDValue One = DAG.getConstant(1, DL, ShVT);
9120 HsVal =
9121 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
9122 }
9123 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
9124}
9125
9126/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
9127/// a chain of halving decompositions (halving element width) and/or vector
9128/// widening (doubling element count). This guides expansion strategy selection:
9129/// if true, the halving/widening path produces better code than bit-by-bit.
9130///
9131/// HalveDepth tracks halving steps only (each creates ~4x more operations).
9132/// Widening steps are cheap (O(1) pad/extract) and don't count.
9133/// Limiting halvings to 2 prevents exponential blowup:
9134/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
9135/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
9136/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
9138 EVT VT, unsigned HalveDepth = 0,
9139 unsigned TotalDepth = 0) {
9140 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
9141 return false;
9142 if (TLI.isOperationLegalOrCustom(ISD::CLMUL, VT))
9143 return true;
9144 if (!TLI.isTypeLegal(VT))
9145 return false;
9146
9147 unsigned BW = VT.getScalarSizeInBits();
9148
9149 // Halve: halve element width, same element count.
9150 // This is the expensive step -- each halving creates ~4x more operations.
9151 if (BW % 2 == 0) {
9152 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
9153 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
9154 if (TLI.isTypeLegal(HalfVT) &&
9155 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
9156 return true;
9157 }
9158
9159 // Widen: double element count (fixed-width vectors only).
9160 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
9161 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
9162 if (TLI.isTypeLegal(WideVT) &&
9163 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
9164 return true;
9165
9166 return false;
9167}
9168
9170 SDLoc DL(Node);
9171 EVT VT = Node->getValueType(0);
9172 SDValue X = Node->getOperand(0);
9173 SDValue Y = Node->getOperand(1);
9174 unsigned BW = VT.getScalarSizeInBits();
9175 unsigned Opcode = Node->getOpcode();
9176 LLVMContext &Ctx = *DAG.getContext();
9177
9178 switch (Opcode) {
9179 case ISD::CLMUL: {
9180 // For vector types, try decomposition strategies that leverage legal
9181 // CLMUL on narrower or wider element types, avoiding the expensive
9182 // bit-by-bit expansion.
9183 if (VT.isVector()) {
9184 // Strategy 1: Halving decomposition to half-element-width CLMUL.
9185 // Applies ExpandIntRes_CLMUL's identity element-wise:
9186 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
9187 // where:
9188 // Lo = CLMUL(XLo, YLo)
9189 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9190 unsigned HalfBW = BW / 2;
9191 if (BW % 2 == 0) {
9192 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
9193 EVT HalfVT =
9194 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
9195 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
9196 /*HalveDepth=*/1)) {
9197 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
9198
9199 // Extract low and high halves of each element.
9200 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
9201 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9202 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
9203 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
9204 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9205 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
9206
9207 // Lo = CLMUL(XLo, YLo)
9208 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
9209
9210 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9211 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
9212 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
9213 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
9214 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
9215 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
9216
9217 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
9218 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
9219 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
9220 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
9221 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
9222 }
9223 }
9224
9225 // Strategy 2: Promote to double-element-width CLMUL.
9226 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
9227 {
9228 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9229 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
9230 // If CLMUL on ExtVT is Custom (not Legal), the target may
9231 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
9232 // fallback costs O(BW) vectorized iterations. Only widen when
9233 // element count is small enough that scalarization is cheaper.
9234 unsigned NumElts = VT.getVectorMinNumElements();
9235 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
9236 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
9237 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
9238 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9239 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
9240 }
9241 }
9242 }
9243
9244 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
9245 // vector, extract lower result). CLMUL is element-wise, so upper
9246 // (undef) lanes don't affect the lower results.
9247 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
9248 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
9249 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
9250 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
9251 SDValue Undef = DAG.getUNDEF(WideVT);
9252 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9253 X, DAG.getVectorIdxConstant(0, DL));
9254 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9255 Y, DAG.getVectorIdxConstant(0, DL));
9256 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
9257 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
9258 DAG.getVectorIdxConstant(0, DL));
9259 }
9260 }
9261 }
9262
9263 // Special case: clmul(X, Y) where Y is a known constant (splat) that forms
9264 // a contiguous block of trailing ones whose length N is a power of two
9265 // (e.g. i8 0xFF, i8 0x0F, ...) or equal to the operand width. In this
9266 // special case, clmul(X, Y) is equivalent to a "parallel prefix XOR" or
9267 // "bitwise parity" operation on X.
9268 //
9269 // Note: This special currently dose NOT apply when the mask is neither a
9270 // power of two nor equal to the operand width because the loop inside
9271 // behaves as if the mask was bit-ceiled, and "undoing" the XOR with parts
9272 // of that CLMUL is a recursive problem (e.g. CLMUL with a 20-bit mask
9273 // requires correction XOR with CLMUL with 12-bit mask).
9274 if (auto *C = isConstOrConstSplat(Y, /*AllowUndefs=*/true)) {
9275 const APInt &YVal = C->getAPIntValue();
9276 unsigned N = YVal.countr_one();
9277 if (YVal.isAllOnes() || (YVal.isMask() && isPowerOf2_32(N))) {
9278 SDValue R = X;
9279 for (unsigned I = 1; I < N; I <<= 1) {
9280 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
9281 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
9282 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
9283 }
9284 return R;
9285 }
9286 }
9287
9288 // NOTE: If you change this expansion, please update the cost model
9289 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
9290 // Intrinsic::clmul.
9291
9292 // Strategy 4: multiplication with holes.
9293 //
9294 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
9295 // do occur, they wind up in a "hole" and are subsequently masked out of the
9296 // result.
9297 //
9298 // https://www.bearssl.org/constanttime.html#ghash-for-gcm describes this
9299 // approach.
9300
9301 // Stride S handles operands up to S·2^S bits using S² multiplies.
9302 //
9303 // * BW <= 8 uses S = 2 (holes of 1 bit)
9304 // * BW <= 24 uses S = 3 (holes of 2 bits)
9305 // * BW <= 64 uses S = 4 (holes of 3 bits)
9306 // * BW <= 160 uses S = 5 (holes of 4 bits)
9307 // * BW <= 384 uses S = 6 (holes of 5 bits)
9308 //
9309 // We distribute the BW bits over S phases:
9310 //
9311 // phase 0 keeps bits: 0, S, 2S, ...
9312 // phase 1 keeps bits: 1, S + 1, 2S + 1, ...
9313 // ...
9314 //
9315 // Each phase has up to n = ceil(BW / S) bits set, and the holes are S-1
9316 // bits wide.
9317 //
9318 // Take BW = 4, S = 2, n = 2. The worst case is a fully populated phase (all
9319 // non-hole bits are set to 1) multiplied by itself, 0b0101 * 0b0101. Each
9320 // set bit of one operand shifts a copy of the other, and we add the copies:
9321 //
9322 // col: 4 3 2 1 0
9323 // 0b0101 << 0: 0 0 1 0 1
9324 // 0b0101 << 2: 1 0 1 0 0
9325 // ----------------- +
9326 // count: 1 0 2 0 1
9327 //
9328 // Counting the number of one-bits in each column gives a triangle: the
9329 // counts climb 1, 2, ..., n and back down (here 1, 2, 1 across the data
9330 // columns). So a column holds at most n one-bits, and that maximum n is
9331 // reached in only one column: the peak. Every other column holds at most n
9332 // - 1 one-bits.
9333 //
9334 // A stack of one-bits in a column turns into carries: column 2 above really
9335 // stores the value 1 + 1 = 2 = n. A column spans S bits, its kept bit
9336 // plus S-1 hole bits, and the count is written from the kept bit upward,
9337 // so any count <= 2^S - 1 stays within the column and never interferes with
9338 // the next data bit S positions up. Every non-peak column holds at most n -
9339 // 1, so they all fit as soon as n - 1 <= 2^S - 1.
9340 //
9341 // That leaves only the peak column. Because both operands set all data
9342 // bits, the triangle peaks at the top of the word at the highest data bit
9343 // still inside BW. Here the count reaches exactly n = 2^S and overflows.
9344 // But its carry lands at bit n*S >= BW, off the top, where it (and the
9345 // whole descending half of the triangle) is truncated.
9346 //
9347 // Hence the holes suffice exactly when n = ceil(BW / S) <= 2^S, i.e. BW <=
9348 // S*2^S.
9349 //
9350 // Here we find the smallest S that satisfies this inequality.
9351 unsigned S = 1;
9352 while (S < 32 && divideCeil(BW, S) > (1u << S))
9353 ++S;
9354
9355 // The "multiplication with holes" expansion emits S*S MULs, 3*S ANDs,
9356 // S*(S-1) XORs and S-1 ORs.
9357 unsigned HolesCost = S * S + 3 * S + S * (S - 1) + (S - 1);
9358
9359 // Estimate the cost of the naive algorithm.
9360 KnownBits KnownY = DAG.computeKnownBits(Y);
9361 unsigned NaiveCost = 0;
9362 for (unsigned I = 0; I < BW; ++I) {
9363 // The iteration folds away entirely and is free.
9364 if (KnownY.Zero[I])
9365 continue;
9366
9367 // On targets with a fast bit test instruction more instructions are used
9368 // to not need a (potentially expensive) multiplication. See also below.
9369 if (hasBitTest(Y, DAG.getShiftAmountConstant(I, VT, DL))) {
9370 // AND + SETCC + SHL + SELECT + XOR.
9371 NaiveCost += 5;
9372 } else {
9373 // AND + MUL + XOR.
9374 NaiveCost += 3;
9375 }
9376 }
9377
9378 // Only use multiplication with holes when it is cheaper, else use the naive
9379 // fallback below.
9380 if (HolesCost < NaiveCost &&
9382
9383 // Set a bit every S positions, e.g. for S = 4 this is equivalent to
9384 // 0b...00010001...0001.
9385 APInt MaskVal = APInt::getSplat(BW, APInt(S, 1));
9386
9387 // Create versions of X and Y that keep only the I-th bit of each S-bit
9388 // slice.
9389 SmallVector<SDValue, 4> M(S), Xp(S), Yp(S);
9390 for (unsigned I = 0; I < S; ++I) {
9391 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9392 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9393 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9394 }
9395
9396 // Codegens these expressions (S*S multiplications), e.g. for S=4:
9397 //
9398 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9399 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9400 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9401 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9402 SDValue Res = DAG.getConstant(0, DL, VT);
9403 for (unsigned I = 0; I < S; ++I) {
9404 SDValue Zi = DAG.getConstant(0, DL, VT);
9405 for (unsigned J = 0; J < S; ++J) {
9406 unsigned K = (I + S - J) % S;
9407 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9408 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9409 }
9410
9411 // Keep only the bits belonging to this iteration, and bitwise or it all
9412 // together.
9413 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9414 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9415 }
9416 return Res;
9417 }
9418
9419 // Strategy 5: the naive fallback.
9420 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9421
9422 SDValue Res = DAG.getConstant(0, DL, VT);
9423 for (unsigned I = 0; I < BW; ++I) {
9424 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9425 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9426 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9427
9428 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9429 // multiply, use a shift-based expansion to avoid expensive MUL
9430 // instructions.
9431 SDValue Part;
9432 if (!hasBitTest(Y, ShiftAmt) &&
9435 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9436 } else {
9437 // Canonical bit test: (Y & (1 << I)) != 0
9438 SDValue Zero = DAG.getConstant(0, DL, VT);
9439 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9440 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9441 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9442 }
9443 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9444 }
9445 return Res;
9446 }
9447 case ISD::CLMULR:
9448 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9451 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9452 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9453 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9454 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9455 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9456 DAG.getShiftAmountConstant(1, VT, DL));
9457 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9458 }
9459 [[fallthrough]];
9460 case ISD::CLMULH: {
9461 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9462 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9463 // when any of these hold:
9464 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9465 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9466 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9467 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9468 // path creates CLMUL(VT) which will be expanded efficiently. The
9469 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9470 // causing a cycle.
9471 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9472 // => trunc path is preferred over the bitreverse path, as it avoids the
9473 // cost of 3 bitreverse operations.
9478 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9479 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9480 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9481 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9482 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9483 if (Opcode == ISD::CLMULH)
9484 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9485 DAG.getShiftAmountConstant(1, VT, DL));
9486 return Res;
9487 }
9488 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9489 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9490 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9491 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9492 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9493 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9494 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9495 }
9496 }
9497 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9498}
9499
9502 SDLoc dl(Node);
9503 SDValue Val = Node->getOperand(0);
9504 EVT VT = Val.getValueType();
9505 SDNodeFlags Flags = Node->getFlags();
9506
9507 SDValue IntPart = DAG.getNode(ISD::FTRUNC, dl, VT, Val, Flags);
9508 SDValue FracPart = DAG.getNode(ISD::FSUB, dl, VT, Val, IntPart, Flags);
9509
9510 SDValue FracToUse = FracPart;
9511 if (!Flags.hasNoInfs()) {
9512 SDValue Abs = DAG.getNode(ISD::FABS, dl, VT, Val, Flags);
9513 SDValue Inf =
9515 EVT SetCCVT =
9516 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9517 SDValue IsInf = DAG.getSetCC(dl, SetCCVT, Abs, Inf, ISD::SETOEQ);
9518 SDValue Zero = DAG.getConstantFP(0.0, dl, VT);
9519 FracToUse = DAG.getSelect(dl, VT, IsInf, Zero, FracPart);
9520 }
9521
9522 SDValue ResultFrac =
9523 DAG.getNode(ISD::FCOPYSIGN, dl, VT, FracToUse, Val, Flags);
9524 Results.push_back(ResultFrac);
9525 Results.push_back(IntPart);
9526 return true;
9527}
9528
9530 SDLoc DL(Node);
9531 EVT VT = Node->getValueType(0);
9532 SDValue Val = Node->getOperand(0);
9533 SDValue Msk = Node->getOperand(1);
9534 unsigned BW = VT.getScalarSizeInBits();
9535
9536 // Just scalarize if scalar PEXT is legal
9538 return DAG.UnrollVectorOp(Node);
9539
9540 // Hacker's Delight §7-4: Compress, or Generalized Extract
9541 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9542 SDValue M = Msk;
9543 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9544 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9545
9546 // Repeatedly compute which bits would shift to the right by an odd amount,
9547 // shift all such bits in parallel using a mask, and double the shift amount.
9548 for (unsigned I = 1; I < BW; I *= 2) {
9549 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9550 SDValue Mp =
9551 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9552 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9553 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9554 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9555 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9557 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9558 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9559 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9561 if (I * 2 < BW)
9562 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9563 }
9564
9565 return X;
9566}
9567
9569 SDLoc DL(Node);
9570 EVT VT = Node->getValueType(0);
9571 SDValue Val = Node->getOperand(0);
9572 SDValue Msk = Node->getOperand(1);
9573 unsigned BW = VT.getScalarSizeInBits();
9574
9575 // Just scalarize if scalar PDEP is legal
9577 return DAG.UnrollVectorOp(Node);
9578
9579 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9580 unsigned LogBW = Log2_32_Ceil(BW);
9581 SmallVector<SDValue, 8> MvArray(LogBW);
9582 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9583 SDValue Mc = Msk;
9584 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9585
9586 // First pass: compute move masks for each power of two that a bit moves by.
9587 for (unsigned S = 0; S < LogBW; ++S) {
9588 unsigned ShiftS = 1u << S;
9589 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9590 SDValue Mp =
9591 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9592 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9593 MvArray[S] = Mv;
9594 if (S + 1 < LogBW) {
9595 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9596 SDValue MvShifted = DAG.getNode(
9597 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9598 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9600 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9601 }
9602 }
9603
9604 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9605 // Each pass handles half the shift amount of the previous pass.
9606 SDValue X = Val;
9607 for (int S = (int)LogBW - 1; S >= 0; --S) {
9608 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9609 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9610 SDValue UnshiftedBits =
9611 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9612 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9613 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9615 }
9616
9617 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9618}
9619
9621 SelectionDAG &DAG) const {
9622 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9623 EVT VT = Node->getValueType(0);
9624 unsigned VTBits = VT.getScalarSizeInBits();
9625 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9626
9627 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9628 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9629 SDValue ShOpLo = Node->getOperand(0);
9630 SDValue ShOpHi = Node->getOperand(1);
9631 SDValue ShAmt = Node->getOperand(2);
9632 EVT ShAmtVT = ShAmt.getValueType();
9633 EVT ShAmtCCVT =
9634 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9635 SDLoc dl(Node);
9636
9637 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9638 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9639 // away during isel.
9640 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9641 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9642 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9643 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9644 : DAG.getConstant(0, dl, VT);
9645
9646 SDValue Tmp2, Tmp3;
9647 if (IsSHL) {
9648 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9649 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9650 } else {
9651 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9652 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9653 }
9654
9655 // If the shift amount is larger or equal than the width of a part we don't
9656 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9657 // values for large shift amounts.
9658 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9659 DAG.getConstant(VTBits, dl, ShAmtVT));
9660 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9661 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9662
9663 if (IsSHL) {
9664 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9665 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9666 } else {
9667 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9668 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9669 }
9670}
9671
9673 SelectionDAG &DAG) const {
9674 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9675 // suggested in
9676 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9677 // It uses strict_fp operations even outside a strict_fp context in order
9678 // to guarantee that the canonicalization is not optimized away by later
9679 // passes. The result chain introduced by that is intentionally ignored
9680 // since no ordering requirement is intended here.
9681 EVT VT = Node->getValueType(0);
9682 SDLoc DL(Node);
9683 SDNodeFlags Flags = Node->getFlags();
9684 Flags.setNoFPExcept(true);
9685 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9686 SDValue Mul =
9687 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9688 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9689 return Mul;
9690}
9691
9693 SelectionDAG &DAG) const {
9694 // Expand conversion from a native IEEE float type to an arbitrary FP format
9695 // returning the result as an integer using bit manipulation.
9696 EVT ResVT = Node->getValueType(0);
9697 SDLoc dl(Node);
9698
9699 SDValue FloatVal = Node->getOperand(0);
9700 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9701 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9702 const auto RoundMode =
9703 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9704 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9705
9706 // Supported destination formats.
9707 switch (Sem) {
9714 break;
9715 default:
9716 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9717 "destination format (semantics enum " +
9718 Twine(SemEnum) + ")");
9719 return SDValue();
9720 }
9721
9722 // Supported rounding modes.
9723 switch (RoundMode) {
9729 break;
9730 default:
9731 DAG.getContext()->emitError(
9732 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9733 Twine(static_cast<int>(RoundMode)) + ")");
9734 return SDValue();
9735 }
9736
9737 // Destination format parameters.
9738 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9739 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9740 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9741 const unsigned DstMant = DstPrecision - 1;
9742 // Unsigned formats spend no bit on the sign.
9743 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9744 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9745 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9746 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9747 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9748 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9749 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9750
9751 // Compute the maximum normal exponent for the destination format.
9752 const unsigned DstExpMaxNormal =
9753 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9754 : DstExpMax;
9755
9756 // For NanOnly formats the max exponent field for finite values
9757 // is DstExpMax, but the encoding with exp = DstExpMax and
9758 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9759 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9760 // avoid the NaN encoding.
9761 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9762 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9763 DstNanEnc == fltNanEncoding::AllOnes)
9764 DstMaxMantAtMaxExp = DstMantMask - 1;
9765
9766 // Source format parameters.
9767 EVT SrcVT = FloatVal.getValueType();
9768 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9769 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9770 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9771 const unsigned SrcMant = SrcPrecision - 1;
9772 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9773
9774 // Work in the source integer type. Match the destination shape so the
9775 // expansion stays vector when ResVT is a vector.
9776 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9777 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9778 EVT SetCCVT =
9779 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9780 EVT FPSetCCVT =
9781 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9782
9783 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9784 SDValue One = DAG.getConstant(1, dl, IntVT);
9785
9786 // Bitcast source float to integer to extract the sign bit.
9787 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9788 SDValue SignBit =
9789 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9790 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9791
9792 // Classify the input.
9793 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9794 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9795 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9796 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9797 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9798 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9799
9800 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9801 // source denormals automatically. The result is unspecified for Inf/NaN, but
9802 // those inputs are detected above and override the final result.
9803 EVT FrexpExpScalarVT =
9805 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9806 SDValue Frexp =
9807 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9808 SDValue FrexpFrac = Frexp.getValue(0);
9809 SDValue FrexpExp = Frexp.getValue(1);
9810
9811 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9812 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9813 DAG.getConstant(SrcMantMask, dl, IntVT));
9814
9815 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9816 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9817 DAG.getConstant(DstBias - 1, dl, IntVT));
9818
9819 // Compute rounding increment given the round bit, sticky bits, and LSB
9820 // of the truncated mantissa.
9821 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9822 SDValue LSB) -> SDValue {
9823 switch (RoundMode) {
9825 // Round up if round_bit && (sticky || lsb)
9826 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9827 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9828 }
9830 return Zero;
9832 // Round up if positive and any truncated bits are set.
9833 SDValue AnyTruncBits =
9834 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9835 SDValue HasTruncBits =
9836 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9837 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9838 SDValue DoRound =
9839 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9840 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9841 }
9843 // Round up if negative and any truncated bits are set (to -Inf).
9844 SDValue AnyTruncBits =
9845 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9846 SDValue HasTruncBits =
9847 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9848 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9849 SDValue DoRound =
9850 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9851 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9852 }
9854 return RoundBit;
9855 default:
9856 llvm_unreachable("unsupported rounding mode");
9857 }
9858 };
9859
9860 // Round mantissa from SrcMant bits to DstMant bits.
9861 SDValue TruncMant;
9862 SDValue RoundUp;
9863 if (SrcMant > DstMant) {
9864 const unsigned Shift = SrcMant - DstMant;
9865 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9866 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9867
9868 // Check bit at position Shift - 1 aka the round bit.
9869 SDValue RoundBit;
9870 if (Shift >= 1) {
9871 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9872 SDValue ShiftedMant =
9873 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9874 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9875 } else {
9876 RoundBit = Zero;
9877 }
9878
9879 // OR of all bits below the round bit to get sticky bits.
9880 SDValue StickyBits;
9881 if (Shift >= 2) {
9882 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9883 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9884 DAG.getConstant(StickyMask, dl, IntVT));
9885 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9886 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9887 } else {
9888 StickyBits = Zero;
9889 }
9890
9891 // LSB of truncated mantissa.
9892 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9893
9894 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9895 } else {
9896 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9897 SDValue MantShift =
9898 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9899 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9900 RoundUp = Zero;
9901 }
9902
9903 // Apply rounding.
9904 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9905
9906 // Handle mantissa overflow from rounding.
9907 // If rounded_mant > DstMantMask, carry into exponent.
9908 SDValue MantOverflow =
9909 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9910 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9911 // On overflow: mant = 0, exp += 1.
9912 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9913 SDValue AdjExp =
9914 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9915 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9916
9917 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9918 // sign bit to merge in.
9919 SDValue SignShifted =
9920 DstHasSign
9921 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9922 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9923 : Zero;
9924
9925 // Destination denormal conversion (when new_exp <= 0).
9926 // Shift the mantissa right by 1 - new_exp additional bits and set the
9927 // exponent field to 0.
9928 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9929 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9930
9931 SDValue DenormResult;
9932 {
9933 // denorm_shift = 1 - NewExp.
9934 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9935
9936 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9937 SDValue ImplicitOne =
9938 DAG.getNode(ISD::SHL, dl, IntVT, One,
9939 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9940 SDValue FullSrcMant =
9941 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9942
9943 // Total right shift = DenormShift + (SrcMant - DstMant).
9944 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9945 SDValue TotalShift =
9946 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9947 DAG.getSignedConstant(MantDelta, dl, IntVT));
9948
9949 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9950 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9951 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9952 SDValue ClampedShift =
9953 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9954 SDValue DenormTruncMant =
9955 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9956 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9957
9958 // Rounding for denorm path.
9959 SDValue DenormRoundUp;
9960 {
9961 // Round bit is at position TotalShift - 1 of FullSrcMant.
9962 // Clamp to at least 1 so the subtraction doesn't underflow and create
9963 // shift nodes with invalid shift amounts.
9964 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
9965 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
9966 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
9967 SDValue DenormRoundBit = DAG.getNode(
9968 ISD::AND, dl, IntVT,
9969 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
9970
9971 // Sticky: all bits below round bit.
9972 // sticky_mask = (1 << RoundBitPos) - 1
9973 SDValue StickyMask = DAG.getNode(
9974 ISD::SUB, dl, IntVT,
9975 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
9976 SDValue DenormStickyBits =
9977 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
9978 SDValue HasSticky = DAG.getNode(
9979 ISD::ZERO_EXTEND, dl, IntVT,
9980 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
9981
9982 SDValue DenormLSB =
9983 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
9984
9985 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
9986
9987 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
9988 SDValue ShiftGEOne =
9989 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
9990 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
9991 }
9992
9993 SDValue DenormRoundedMant =
9994 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
9995
9996 // If rounding caused overflow into the normal range, then we get the
9997 // smallest normal number.
9998 SDValue DenormMantOF =
9999 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
10000 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
10001 SDValue DenormFinalMant =
10002 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
10003 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
10004
10005 // Assemble: sign | (exp << DstMant) | mant
10006 SDValue DenormExpShifted =
10007 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
10008 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
10009 DenormResult = DAG.getNode(
10010 ISD::OR, dl, IntVT,
10011 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10012 DenormFinalMant);
10013 }
10014
10015 // Exponent overflow detection.
10016 SDValue ExpOF =
10017 DAG.getSetCC(dl, SetCCVT, AdjExp,
10018 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
10019
10020 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
10021 // a value that exceeds the max allowed mantissa at that exponent.
10022 SDValue ExpAtMax =
10023 DAG.getSetCC(dl, SetCCVT, AdjExp,
10024 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
10025 SDValue MantExceedsMax =
10026 DAG.getSetCC(dl, SetCCVT, AdjMant,
10027 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
10028 SDValue ExpMantOF =
10029 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
10030 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
10031
10032 // Build overflow result.
10034
10035 if (Saturate) {
10036 // Clamp to max finite value:
10037 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
10038 uint64_t MaxFinite =
10039 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
10040 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10041 DAG.getConstant(MaxFinite, dl, IntVT));
10042 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10043 // Produce infinity.
10044 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
10045 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10046 DAG.getConstant(InfBits, dl, IntVT));
10047 } else {
10048 // Emit poison if no Inf in format and not saturating.
10049 OverflowResult = DAG.getPOISON(IntVT);
10050 }
10051
10052 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
10053 SDValue NormExpShifted =
10054 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
10055 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
10056 SDValue NormResult = DAG.getNode(
10057 ISD::OR, dl, IntVT,
10058 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
10059
10060 // Build special-value results.
10061 SDValue NaNResult;
10062 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10063 // Produce canonical NaN.
10064 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10065 NaNResult =
10066 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
10067 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
10068 DstNanEnc == fltNanEncoding::AllOnes) {
10069 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
10070 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
10071 dl, IntVT);
10072 } else {
10073 // NaN -> poison for finite only values.
10074 NaNResult = DAG.getPOISON(IntVT);
10075 }
10076
10077 // Inf handling.
10078 SDValue InfResult;
10079 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10080 // Produce signed infinity.
10081 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
10082 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10083 DAG.getConstant(InfBits, dl, IntVT));
10084 } else if (Saturate) {
10085 // Inf saturates to max finite.
10086 uint64_t MaxFinite =
10087 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
10088 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10089 DAG.getConstant(MaxFinite, dl, IntVT));
10090 } else {
10091 // No Inf and not saturating -> poison.
10092 InfResult = DAG.getPOISON(IntVT);
10093 }
10094
10095 SDValue ZeroResult = SignShifted;
10096
10097 // Final selection in an order: NaN takes priority, then Inf, then Zero.
10098 SDValue FiniteResult =
10099 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
10100 FiniteResult =
10101 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
10102
10103 SDValue Result = FiniteResult;
10104 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10105 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10106
10107 // Negative values are unrepresentable in an unsigned format: clamp to zero
10108 // when saturating, poison otherwise so no select is needed. -0.0 is handled
10109 // by IsZero above. Run before the NaN case so a negative NaN still yields
10110 // NaN.
10111 if (!DstHasSign && Saturate) {
10112 SDValue IsNegative =
10113 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
10114 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
10115 }
10116
10117 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10118
10119 // Truncate to destination integer type.
10120 return DAG.getZExtOrTrunc(Result, dl, ResVT);
10121}
10122
10123SDValue
10125 SelectionDAG &DAG) const {
10126 SDLoc dl(Node);
10127 EVT DstVT = Node->getValueType(0);
10128 EVT DstScalarVT = DstVT.getScalarType();
10129
10130 SDValue IntVal = Node->getOperand(0);
10131 const uint64_t SemEnum = Node->getConstantOperandVal(1);
10132 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
10133
10134 // Supported source formats.
10135 switch (Sem) {
10142 break;
10143 default:
10144 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
10145 "source format (semantics enum " +
10146 Twine(SemEnum) + ")");
10147 return SDValue();
10148 }
10149
10150 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
10151 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
10152 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
10153 const unsigned SrcMant = SrcPrecision - 1;
10154 // Unsigned formats spend no bit on the sign.
10155 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
10156 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
10157 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
10158 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
10159
10160 // Destination format parameters.
10161 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
10162 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
10163 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
10164 const unsigned DstExpBits = DstBits - DstMant - 1;
10165 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
10166 const int DstBias = 1 - DstMinExp;
10167 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
10168
10169 // Work in an integer type matching the destination float width.
10170 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
10171 EVT IntVT = IntScalarVT;
10172 if (DstVT.isVector()) {
10173 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
10174 DstVT.getVectorElementCount());
10175 } else if (!isTypeLegal(IntScalarVT)) {
10176 // Avoid generating illegal type as there is no other places that'll
10177 // legalize it. Vector types don't have this problem because they
10178 // are subject to LegalizeVectorOps and another type legalization phase
10179 // will follow.
10180 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
10181 // We only know how to handle situations where the legal type is wider.
10182 DAG.getContext()->emitError(
10183 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
10184 "legalization is not supported");
10185 return SDValue();
10186 }
10187 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
10188 }
10189
10190 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
10191
10192 EVT SetCCVT =
10193 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
10194
10195 SDValue Zero = DAG.getConstant(0, dl, IntVT);
10196 SDValue One = DAG.getConstant(1, dl, IntVT);
10197
10198 // Extract bit fields.
10199 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
10200 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
10201
10202 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
10203 DAG.getConstant(MantMask, dl, IntVT));
10204
10205 SDValue ExpField =
10206 DAG.getNode(ISD::AND, dl, IntVT,
10207 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10208 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
10209 DAG.getConstant(ExpMask, dl, IntVT));
10210
10211 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
10212 // exponent.
10213 SDValue SignShifted =
10214 SrcHasSign
10215 ? DAG.getNode(
10216 ISD::SHL, dl, IntVT,
10217 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10218 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
10219 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
10220 : Zero;
10221
10222 // Classify the input.
10223 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
10224 SDValue IsExpAllOnes =
10225 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
10226 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
10227 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
10228 SDValue IsMantNonZero =
10229 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
10230
10231 SDValue IsNaN;
10232 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
10233 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10234 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
10235 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
10236 } else {
10238 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
10239 SDValue IsMantAllOnes =
10240 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
10241 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
10242 }
10243
10244 SDValue IsInf;
10245 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
10246 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
10247 else
10248 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10249
10250 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
10251 SDValue IsDenorm =
10252 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
10253
10254 // Normal value conversion.
10255 const int BiasAdjust = DstBias - SrcBias;
10256 SDValue NormDstExp = DAG.getNode(
10257 ISD::ADD, dl, IntVT, ExpField,
10258 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
10259 IntVT));
10260
10261 SDValue NormDstMant;
10262 if (DstMant > SrcMant) {
10263 SDValue NormDstMantShift =
10264 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
10265 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
10266 } else {
10267 NormDstMant = MantField;
10268 }
10269
10270 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
10271 SDValue NormExpShifted =
10272 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
10273 SDValue NormResult =
10274 DAG.getNode(ISD::OR, dl, IntVT,
10275 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
10276 NormDstMant);
10277
10278 // With identical exponent biases, denormal values remain denormal and the
10279 // normal conversion's mantissa shift is sufficient.
10280 SDValue DenormResult = NormResult;
10281 if (BiasAdjust != 0) {
10282 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
10283 SDValue LeadingZeros =
10284 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
10285
10286 const int DenormExpConst =
10287 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
10288 SDValue DenormDstExp = DAG.getNode(
10289 ISD::SUB, dl, IntVT,
10290 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
10291 LeadingZeros);
10292
10293 SDValue MantMSB =
10294 DAG.getNode(ISD::SUB, dl, IntVT,
10295 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
10296
10297 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
10298 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
10299
10300 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
10301 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
10302 DAG.getConstant(ShiftSub, dl, IntVT));
10303
10304 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
10305
10306 SDValue DenormExpShifted =
10307 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
10308 DenormResult = DAG.getNode(
10309 ISD::OR, dl, IntVT,
10310 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10311 DenormDstMant);
10312 }
10313
10314 SDValue FiniteResult =
10315 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
10316
10317 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10318 SDValue NaNResult =
10319 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
10320
10321 SDValue InfResult =
10322 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10323 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
10324
10325 // A source format may have a larger finite exponent range despite having
10326 // fewer bits, as with Float8E5M3FNU converted to half. Its overflowing finite
10327 // values become infinity. The NaN selection below still takes precedence.
10328 if (APFloat::semanticsMaxExponent(SrcSem) >
10330 SDValue IsOverflow =
10331 DAG.getSetCC(dl, SetCCVT, NormDstExp,
10332 DAG.getConstant(DstExpAllOnes, dl, IntVT), ISD::SETUGE);
10333 FiniteResult =
10334 DAG.getSelect(dl, IntVT, IsOverflow, InfResult, FiniteResult);
10335 }
10336
10337 SDValue ZeroResult = SignShifted;
10338
10339 SDValue Result = FiniteResult;
10340 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10341 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10342 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10343
10344 if (!DstVT.bitsEq(IntVT)) {
10345 // Store to stack before loading it back.
10346 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
10347 // IntScalarVT is the original type that has the same width as DstVT.
10348 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
10349 SDValue StackPtr =
10350 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
10351 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10353 MachinePointerInfo PtrInfo =
10354 MachinePointerInfo::getFixedStack(MF, FrameIndex);
10355 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
10356 PtrInfo, IntScalarVT, Alignment);
10357
10358 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
10359 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
10360 }
10361
10362 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
10363}
10364
10366 SelectionDAG &DAG) const {
10367 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10368 SDValue Src = Node->getOperand(OpNo);
10369 EVT SrcVT = Src.getValueType();
10370 EVT DstVT = Node->getValueType(0);
10371 SDLoc dl(SDValue(Node, 0));
10372
10373 // FIXME: Only f32 to i64 conversions are supported.
10374 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
10375 return false;
10376
10377 if (Node->isStrictFPOpcode())
10378 // When a NaN is converted to an integer a trap is allowed. We can't
10379 // use this expansion here because it would eliminate that trap. Other
10380 // traps are also allowed and cannot be eliminated. See
10381 // IEEE 754-2008 sec 5.8.
10382 return false;
10383
10384 // Expand f32 -> i64 conversion
10385 // This algorithm comes from compiler-rt's implementation of fixsfdi:
10386 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
10387 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
10388 EVT IntVT = SrcVT.changeTypeToInteger();
10389 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
10390
10391 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
10392 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
10393 SDValue Bias = DAG.getConstant(127, dl, IntVT);
10394 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
10395 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
10396 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
10397
10398 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
10399
10400 SDValue ExponentBits = DAG.getNode(
10401 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
10402 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
10403 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
10404
10405 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
10406 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
10407 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
10408 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10409
10410 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10411 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10412 DAG.getConstant(0x00800000, dl, IntVT));
10413
10414 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10415
10416 R = DAG.getSelectCC(
10417 dl, Exponent, ExponentLoBit,
10418 DAG.getNode(ISD::SHL, dl, DstVT, R,
10419 DAG.getZExtOrTrunc(
10420 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10421 dl, IntShVT)),
10422 DAG.getNode(ISD::SRL, dl, DstVT, R,
10423 DAG.getZExtOrTrunc(
10424 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10425 dl, IntShVT)),
10426 ISD::SETGT);
10427
10428 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10429 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10430
10431 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10432 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10433 return true;
10434}
10435
10437 SDValue &Chain,
10438 SelectionDAG &DAG) const {
10439 SDLoc dl(SDValue(Node, 0));
10440 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10441 SDValue Src = Node->getOperand(OpNo);
10442
10443 EVT SrcVT = Src.getValueType();
10444 EVT DstVT = Node->getValueType(0);
10445 EVT SetCCVT =
10446 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10447 EVT DstSetCCVT =
10448 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10449
10450 // Only expand vector types if we have the appropriate vector bit operations.
10451 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10453 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10455 return false;
10456
10457 // If the maximum float value is smaller then the signed integer range,
10458 // the destination signmask can't be represented by the float, so we can
10459 // just use FP_TO_SINT directly.
10460 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10461 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10462 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10464 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10465 if (Node->isStrictFPOpcode()) {
10466 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10467 { Node->getOperand(0), Src });
10468 Chain = Result.getValue(1);
10469 } else
10470 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10471 return true;
10472 }
10473
10474 // Don't expand it if there isn't cheap fsub instruction.
10476 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10477 return false;
10478
10479 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10480 SDValue Sel;
10481
10482 if (Node->isStrictFPOpcode()) {
10483 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10484 Node->getOperand(0), /*IsSignaling*/ true);
10485 Chain = Sel.getValue(1);
10486 } else {
10487 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10488 }
10489
10490 bool Strict = Node->isStrictFPOpcode() ||
10491 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10492
10493 if (Strict) {
10494 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10495 // signmask then offset (the result of which should be fully representable).
10496 // Sel = Src < 0x8000000000000000
10497 // FltOfs = select Sel, 0, 0x8000000000000000
10498 // IntOfs = select Sel, 0, 0x8000000000000000
10499 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10500
10501 // TODO: Should any fast-math-flags be set for the FSUB?
10502 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10503 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10504 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10505 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10506 DAG.getConstant(0, dl, DstVT),
10507 DAG.getConstant(SignMask, dl, DstVT));
10508 SDValue SInt;
10509 if (Node->isStrictFPOpcode()) {
10510 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10511 { Chain, Src, FltOfs });
10512 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10513 { Val.getValue(1), Val });
10514 Chain = SInt.getValue(1);
10515 } else {
10516 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10517 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10518 }
10519 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10520 } else {
10521 // Expand based on maximum range of FP_TO_SINT:
10522 // True = fp_to_sint(Src)
10523 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10524 // Result = select (Src < 0x8000000000000000), True, False
10525
10526 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10527 // TODO: Should any fast-math-flags be set for the FSUB?
10528 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10529 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10530 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10531 DAG.getConstant(SignMask, dl, DstVT));
10532 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10533 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10534 }
10535 return true;
10536}
10537
10539 SDValue &Chain, SelectionDAG &DAG) const {
10540 // This transform is not correct for converting 0 when rounding mode is set
10541 // to round toward negative infinity which will produce -0.0. So disable
10542 // under strictfp.
10543 if (Node->isStrictFPOpcode())
10544 return false;
10545
10546 SDValue Src = Node->getOperand(0);
10547 EVT SrcVT = Src.getValueType();
10548 EVT DstVT = Node->getValueType(0);
10549
10550 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10551 // it.
10552 if (Node->getFlags().hasNonNeg() &&
10554 Result =
10555 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10556 return true;
10557 }
10558
10559 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10560 return false;
10561
10562 // Only expand vector types if we have the appropriate vector bit
10563 // operations.
10564 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10569 return false;
10570
10571 SDLoc dl(SDValue(Node, 0));
10572
10573 // Implementation of unsigned i64 to f64 following the algorithm in
10574 // __floatundidf in compiler_rt. This implementation performs rounding
10575 // correctly in all rounding modes with the exception of converting 0
10576 // when rounding toward negative infinity. In that case the fsub will
10577 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10578 // incorrect.
10579 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10580 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10581 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10582 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10583 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10584 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10585
10586 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10587 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10588 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10589 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10590 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10591 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10592 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10593 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10594 return true;
10595}
10596
10597SDValue
10599 SelectionDAG &DAG) const {
10600 unsigned Opcode = Node->getOpcode();
10601 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10602 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10603 "Wrong opcode");
10604
10605 if (Node->getFlags().hasNoNaNs()) {
10606 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10607 EVT VT = Node->getValueType(0);
10608 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10610 VT.isVector())
10611 return SDValue();
10612 SDValue Op1 = Node->getOperand(0);
10613 SDValue Op2 = Node->getOperand(1);
10614 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10615 Node->getFlags());
10616 }
10617
10618 return SDValue();
10619}
10620
10622 SelectionDAG &DAG) const {
10623 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10624 return Expanded;
10625
10626 EVT VT = Node->getValueType(0);
10627 if (VT.isScalableVector())
10629 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10630
10631 SDLoc dl(Node);
10632 unsigned NewOp =
10634
10635 if (isOperationLegalOrCustom(NewOp, VT)) {
10636 SDValue Quiet0 = Node->getOperand(0);
10637 SDValue Quiet1 = Node->getOperand(1);
10638
10639 if (!Node->getFlags().hasNoNaNs()) {
10640 // Insert canonicalizes if it's possible we need to quiet to get correct
10641 // sNaN behavior.
10642 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10643 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10644 Node->getFlags());
10645 }
10646 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10647 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10648 Node->getFlags());
10649 }
10650 }
10651
10652 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10653 }
10654
10655 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10656 // instead if there are no NaNs.
10657 if (Node->getFlags().hasNoNaNs() ||
10658 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10659 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10660 unsigned IEEE2018Op =
10661 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10662 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10663 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10664 Node->getOperand(1), Node->getFlags());
10665 }
10666
10668 return SelCC;
10669
10670 return SDValue();
10671}
10672
10674 const TargetLowering &TLI,
10675 const SDLoc &DL, SDValue Val,
10676 FPClassTest FPClass) {
10677 EVT VT = Val.getValueType();
10678 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10679 EVT IntVT = VT.changeTypeToInteger();
10680 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10681 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10682 if (!TLI.isTypeLegal(IntVT) &&
10683 !TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, VT))
10684 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10685 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10686 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10687}
10688
10690 SelectionDAG &DAG) const {
10691 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10692 return Expanded;
10693
10694 SDLoc DL(N);
10695 SDValue LHS = N->getOperand(0);
10696 SDValue RHS = N->getOperand(1);
10697 unsigned Opc = N->getOpcode();
10698 EVT VT = N->getValueType(0);
10699 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10700 bool IsMax = Opc == ISD::FMAXIMUM;
10701 SDNodeFlags Flags = N->getFlags();
10702
10703 // First, implement comparison not propagating NaN. If no native fmin or fmax
10704 // available, use plain select with setcc instead.
10706 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10707 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10708
10709 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10710 // signed zero behavior.
10711 bool MinMaxMustRespectOrderedZero = false;
10712
10713 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10714 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10715 MinMaxMustRespectOrderedZero = true;
10716 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10717 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10718 } else {
10720 return DAG.UnrollVectorOp(N);
10721
10722 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10723 SDValue Compare =
10724 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10725 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10726 }
10727
10728 // Propagate any NaN of both operands
10729 if (!N->getFlags().hasNoNaNs() &&
10730 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10731 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10733 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10734 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10735 }
10736
10737 // fminimum/fmaximum requires -0.0 less than +0.0
10738 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10739 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10740 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10742 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10743 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10744 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10745 }
10746
10747 return MinMax;
10748}
10749
10751 SelectionDAG &DAG) const {
10752 SDLoc DL(Node);
10753 SDValue LHS = Node->getOperand(0);
10754 SDValue RHS = Node->getOperand(1);
10755 unsigned Opc = Node->getOpcode();
10756 EVT VT = Node->getValueType(0);
10757 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10758 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10759 SDNodeFlags Flags = Node->getFlags();
10760
10761 unsigned NewOp =
10763
10764 if (isOperationLegalOrCustom(NewOp, VT)) {
10765 if (!Flags.hasNoNaNs()) {
10766 // Insert canonicalizes if it's possible we need to quiet to get correct
10767 // sNaN behavior.
10768 if (!DAG.isKnownNeverSNaN(LHS)) {
10769 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10770 }
10771 if (!DAG.isKnownNeverSNaN(RHS)) {
10772 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10773 }
10774 }
10775
10776 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10777 }
10778
10779 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10780 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10781 if (Flags.hasNoNaNs() ||
10782 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10783 unsigned IEEE2019Op =
10785 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10786 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10787 }
10788
10789 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10790 // either one for +0.0 vs -0.0.
10791 if ((Flags.hasNoNaNs() ||
10792 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10793 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10794 DAG.isKnownNeverLogicalZero(RHS))) {
10795 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10796 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10797 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10798 }
10799
10800 if (VT.isVector() &&
10803 return DAG.UnrollVectorOp(Node);
10804
10805 // If only one operand is NaN, override it with another operand.
10806 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10807 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10808 }
10809 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10810 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10811 }
10812
10813 // Always prefer RHS if equal.
10814 SDValue MinMax =
10815 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10816
10817 // TODO: We need quiet sNaN if strictfp.
10818
10819 // Fixup signed zero behavior.
10820 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10821 DAG.isKnownNeverLogicalZero(RHS)) {
10822 return MinMax;
10823 }
10824 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10825 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10827 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10828 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10829 // we preferred RHS when generate MinMax, if the operands are equal.
10830 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10831 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10832}
10833
10834/// Returns a true value if if this FPClassTest can be performed with an ordered
10835/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10836/// std::nullopt if it cannot be performed as a compare with 0.
10837static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10838 const fltSemantics &Semantics,
10839 const MachineFunction &MF) {
10840 FPClassTest OrderedMask = Test & ~fcNan;
10841 FPClassTest NanTest = Test & fcNan;
10842 bool IsOrdered = NanTest == fcNone;
10843 bool IsUnordered = NanTest == fcNan;
10844
10845 // Skip cases that are testing for only a qnan or snan.
10846 if (!IsOrdered && !IsUnordered)
10847 return std::nullopt;
10848
10849 if (OrderedMask == fcZero &&
10850 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10851 return IsOrdered;
10852 if (OrderedMask == (fcZero | fcSubnormal) &&
10853 MF.getDenormalMode(Semantics).inputsAreZero())
10854 return IsOrdered;
10855 return std::nullopt;
10856}
10857
10859 const FPClassTest OrigTestMask,
10860 SDNodeFlags Flags, const SDLoc &DL,
10861 SelectionDAG &DAG) const {
10862 EVT OperandVT = Op.getValueType();
10863 assert(OperandVT.isFloatingPoint());
10864 FPClassTest Test = OrigTestMask;
10865
10866 // Degenerated cases.
10867 if (Test == fcNone)
10868 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10869 if (Test == fcAllFlags)
10870 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10871
10872 // PPC double double is a pair of doubles, of which the higher part determines
10873 // the value class.
10874 if (OperandVT == MVT::ppcf128) {
10875 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10876 DAG.getConstant(1, DL, MVT::i32));
10877 OperandVT = MVT::f64;
10878 }
10879
10880 // Floating-point type properties.
10881 EVT ScalarFloatVT = OperandVT.getScalarType();
10882 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10883 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10884 bool IsF80 = (ScalarFloatVT == MVT::f80);
10885
10886 // Some checks can be implemented using float comparisons, if floating point
10887 // exceptions are ignored.
10888 if (Flags.hasNoFPExcept() &&
10890 FPClassTest FPTestMask = Test;
10891 bool IsInvertedFP = false;
10892
10893 if (FPClassTest InvertedFPCheck =
10894 invertFPClassTestIfSimpler(FPTestMask, true)) {
10895 FPTestMask = InvertedFPCheck;
10896 IsInvertedFP = true;
10897 }
10898
10899 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10900 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10901
10902 // See if we can fold an | fcNan into an unordered compare.
10903 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10904
10905 // Can't fold the ordered check if we're only testing for snan or qnan
10906 // individually.
10907 if ((FPTestMask & fcNan) != fcNan)
10908 OrderedFPTestMask = FPTestMask;
10909
10910 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10911
10912 if (std::optional<bool> IsCmp0 =
10913 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10914 IsCmp0 && (isCondCodeLegalOrCustom(
10915 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10916 OperandVT.getScalarType().getSimpleVT()))) {
10917
10918 // If denormals could be implicitly treated as 0, this is not equivalent
10919 // to a compare with 0 since it will also be true for denormals.
10920 return DAG.getSetCC(DL, ResultVT, Op,
10921 DAG.getConstantFP(0.0, DL, OperandVT),
10922 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10923 }
10924
10925 if (FPTestMask == fcNan &&
10927 OperandVT.getScalarType().getSimpleVT()))
10928 return DAG.getSetCC(DL, ResultVT, Op, Op,
10929 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10930
10931 bool IsOrderedInf = FPTestMask == fcInf;
10932 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10933 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10934 : UnorderedCmpOpcode,
10935 OperandVT.getScalarType().getSimpleVT()) &&
10938 (OperandVT.isVector() &&
10940 // isinf(x) --> fabs(x) == inf
10941 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10942 SDValue Inf =
10943 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10944 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10945 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10946 }
10947
10948 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10949 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10950 : UnorderedCmpOpcode,
10951 OperandVT.getSimpleVT())) {
10952 // isposinf(x) --> x == inf
10953 // isneginf(x) --> x == -inf
10954 // isposinf(x) || nan --> x u== inf
10955 // isneginf(x) || nan --> x u== -inf
10956
10957 SDValue Inf = DAG.getConstantFP(
10958 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
10959 OperandVT);
10960 return DAG.getSetCC(DL, ResultVT, Op, Inf,
10961 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
10962 }
10963
10964 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
10965 // TODO: Could handle ordered case, but it produces worse code for
10966 // x86. Maybe handle ordered if fabs is free?
10967
10968 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10969 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
10970
10971 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
10972 OperandVT.getScalarType().getSimpleVT())) {
10973 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
10974
10975 // TODO: Maybe only makes sense if fabs is free. Integer test of
10976 // exponent bits seems better for x86.
10977 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10978 SDValue SmallestNormal = DAG.getConstantFP(
10979 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10980 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
10981 IsOrdered ? OrderedOp : UnorderedOp);
10982 }
10983 }
10984
10985 if (FPTestMask == fcNormal) {
10986 // TODO: Handle unordered
10987 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10988 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
10989
10990 if (isCondCodeLegalOrCustom(IsFiniteOp,
10991 OperandVT.getScalarType().getSimpleVT()) &&
10992 isCondCodeLegalOrCustom(IsNormalOp,
10993 OperandVT.getScalarType().getSimpleVT()) &&
10994 isFAbsFree(OperandVT)) {
10995 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
10996 SDValue Inf =
10997 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10998 SDValue SmallestNormal = DAG.getConstantFP(
10999 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
11000
11001 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
11002 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
11003 SDValue IsNormal =
11004 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
11005 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
11006 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
11007 }
11008 }
11009 }
11010
11011 // Some checks may be represented as inversion of simpler check, for example
11012 // "inf|normal|subnormal|zero" => !"nan".
11013 bool IsInverted = false;
11014
11015 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
11016 Test = InvertedCheck;
11017 IsInverted = true;
11018 }
11019
11020 // In the general case use integer operations.
11021 unsigned BitSize = OperandVT.getScalarSizeInBits();
11022 EVT IntVT = OperandVT.changeElementType(
11023 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
11024 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
11025
11026 // Various masks.
11027 APInt SignBit = APInt::getSignMask(BitSize);
11028 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
11029 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
11030 const unsigned ExplicitIntBitInF80 = 63;
11031 APInt ExpMask = Inf;
11032 if (IsF80)
11033 ExpMask.clearBit(ExplicitIntBitInF80);
11034 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
11035 APInt QNaNBitMask =
11036 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
11037 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
11038
11039 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
11040 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
11041 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
11042 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
11043 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
11044 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
11045
11046 SDValue Res;
11047 const auto appendResult = [&](SDValue PartialRes) {
11048 if (PartialRes) {
11049 if (Res)
11050 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
11051 else
11052 Res = PartialRes;
11053 }
11054 };
11055
11056 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
11057 const auto getIntBitIsSet = [&]() -> SDValue {
11058 if (!IntBitIsSetV) {
11059 APInt IntBitMask(BitSize, 0);
11060 IntBitMask.setBit(ExplicitIntBitInF80);
11061 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
11062 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
11063 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
11064 }
11065 return IntBitIsSetV;
11066 };
11067
11068 // Split the value into sign bit and absolute value.
11069 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
11070 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
11071 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
11072
11073 // Tests that involve more than one class should be processed first.
11074 SDValue PartialRes;
11075
11076 if (IsF80)
11077 ; // Detect finite numbers of f80 by checking individual classes because
11078 // they have different settings of the explicit integer bit.
11079 else if ((Test & fcFinite) == fcFinite) {
11080 // finite(V) ==> (a << 1) < (inf << 1)
11081 //
11082 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
11083 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
11084
11086 "finite check requires IEEE-like FP");
11087
11088 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
11089 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
11090 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
11091
11092 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
11093 Test &= ~fcFinite;
11094 } else if ((Test & fcFinite) == fcPosFinite) {
11095 // finite(V) && V > 0 ==> V < exp_mask
11096 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
11097 Test &= ~fcPosFinite;
11098 } else if ((Test & fcFinite) == fcNegFinite) {
11099 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
11100 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
11101 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11102 Test &= ~fcNegFinite;
11103 }
11104 appendResult(PartialRes);
11105
11106 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
11107 // fcZero | fcSubnormal => test all exponent bits are 0
11108 // TODO: Handle sign bit specific cases
11109 if (PartialCheck == (fcZero | fcSubnormal)) {
11110 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
11111 SDValue ExpIsZero =
11112 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11113 appendResult(ExpIsZero);
11114 Test &= ~PartialCheck & fcAllFlags;
11115 }
11116 }
11117
11118 // Check for individual classes.
11119
11120 if (unsigned PartialCheck = Test & fcZero) {
11121 if (PartialCheck == fcPosZero)
11122 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
11123 else if (PartialCheck == fcZero)
11124 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
11125 else // ISD::fcNegZero
11126 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
11127 appendResult(PartialRes);
11128 }
11129
11130 if (unsigned PartialCheck = Test & fcSubnormal) {
11131 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
11132 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
11133 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
11134 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
11135 SDValue VMinusOneV =
11136 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
11137 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
11138 if (PartialCheck == fcNegSubnormal)
11139 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11140 appendResult(PartialRes);
11141 }
11142
11143 if (unsigned PartialCheck = Test & fcInf) {
11144 if (PartialCheck == fcPosInf)
11145 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
11146 else if (PartialCheck == fcInf)
11147 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
11148 else { // ISD::fcNegInf
11149 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
11150 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
11151 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
11152 }
11153 appendResult(PartialRes);
11154 }
11155
11156 if (unsigned PartialCheck = Test & fcNan) {
11157 APInt InfWithQnanBit = Inf | QNaNBitMask;
11158 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
11159 if (PartialCheck == fcNan) {
11160 // isnan(V) ==> abs(V) > int(inf)
11161 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11162 if (IsF80) {
11163 // Recognize unsupported values as NaNs for compatibility with glibc.
11164 // In them (exp(V)==0) == int_bit.
11165 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
11166 SDValue ExpIsZero =
11167 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11168 SDValue IsPseudo =
11169 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
11170 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
11171 }
11172 } else if (PartialCheck == fcQNan) {
11173 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
11174 PartialRes =
11175 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
11176 } else { // ISD::fcSNan
11177 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
11178 // abs(V) < (unsigned(Inf) | quiet_bit)
11179 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11180 SDValue IsNotQnan =
11181 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
11182 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
11183 }
11184 appendResult(PartialRes);
11185 }
11186
11187 if (unsigned PartialCheck = Test & fcNormal) {
11188 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
11189 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
11190 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
11191 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
11192 APInt ExpLimit = ExpMask - ExpLSB;
11193 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
11194 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
11195 if (PartialCheck == fcNegNormal)
11196 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11197 else if (PartialCheck == fcPosNormal) {
11198 SDValue PosSignV =
11199 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
11200 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
11201 }
11202 if (IsF80)
11203 PartialRes =
11204 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
11205 appendResult(PartialRes);
11206 }
11207
11208 if (!Res)
11209 return DAG.getConstant(IsInverted, DL, ResultVT);
11210 if (IsInverted)
11211 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
11212 return Res;
11213}
11214
11215// Only expand vector types if we have the appropriate vector bit operations.
11217 assert(VT.isVector() && "Expected vector type");
11218 unsigned Len = VT.getScalarSizeInBits();
11219 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
11220 TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
11221 TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
11222 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
11223 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
11224}
11225
11227 SDLoc dl(Node);
11228 EVT VT = Node->getValueType(0);
11229 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11230 SDValue Op = Node->getOperand(0);
11231 unsigned Len = VT.getScalarSizeInBits();
11232
11233 // Compute effective bit width from known bits, allowing us to shift the
11234 // active bits down if necessary to fit into smaller specialized expansions.
11236 unsigned LZ = Known.countMinLeadingZeros();
11237 unsigned TZ = Known.countMinTrailingZeros();
11238 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
11239
11240 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
11241 unsigned EffectiveLen = Len;
11242 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
11243 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
11244
11245 assert(VT.isInteger() && "CTPOP not implemented for this type.");
11246
11247 // TODO: Add support for irregular type lengths.
11248 if (!(Len <= 128 && Len % 8 == 0))
11249 return SDValue();
11250
11251 // Only expand vector types if we have the appropriate vector bit operations.
11252 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
11253 return SDValue();
11254
11255 // If the active bits are not at the low end, shift them down
11256 if (EffectiveLen < Len && TZ > 0) {
11257 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
11258 DAG.getShiftAmountConstant(TZ, VT, dl));
11259 }
11260
11261 // This is the "best" algorithm from
11262 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
11263 SDValue Mask55 =
11264 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
11265 SDValue Mask33 =
11266 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
11267 SDValue Mask0F =
11268 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
11269
11270 // v = v - ((v >> 1) & 0x55555555...)
11271 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
11272 DAG.getNode(ISD::AND, dl, VT,
11273 DAG.getNode(ISD::SRL, dl, VT, Op,
11274 DAG.getConstant(1, dl, ShVT)),
11275 Mask55));
11276 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
11277 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
11278 DAG.getNode(ISD::AND, dl, VT,
11279 DAG.getNode(ISD::SRL, dl, VT, Op,
11280 DAG.getConstant(2, dl, ShVT)),
11281 Mask33));
11282 // v = (v + (v >> 4)) & 0x0F0F0F0F...
11283 Op = DAG.getNode(ISD::AND, dl, VT,
11284 DAG.getNode(ISD::ADD, dl, VT, Op,
11285 DAG.getNode(ISD::SRL, dl, VT, Op,
11286 DAG.getConstant(4, dl, ShVT))),
11287 Mask0F);
11288
11289 if (EffectiveLen <= 8)
11290 return Op;
11291
11292 // Avoid the multiply if we only have 2 bytes to add.
11293 // TODO: Only doing this for scalars because vectors weren't as obviously
11294 // improved.
11295 if (EffectiveLen == 16 && !VT.isVector()) {
11296 // v = (v + (v >> 8)) & 0x00FF;
11297 return DAG.getNode(ISD::AND, dl, VT,
11298 DAG.getNode(ISD::ADD, dl, VT, Op,
11299 DAG.getNode(ISD::SRL, dl, VT, Op,
11300 DAG.getConstant(8, dl, ShVT))),
11301 DAG.getConstant(0xFF, dl, VT));
11302 }
11303
11304 // v = (v * 0x01010101...) >> (Len - 8)
11305 SDValue V;
11308 SDValue Mask01 =
11309 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
11310 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
11311 } else {
11312 V = Op;
11313 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
11314 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
11315 V = DAG.getNode(ISD::ADD, dl, VT, V,
11316 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
11317 }
11318 }
11319 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
11320}
11321
11323 SDLoc dl(Node);
11324 EVT VT = Node->getValueType(0);
11325 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11326 SDValue Op = Node->getOperand(0);
11327 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11328
11329 // If the non-ZERO_POISON version is supported we can use that instead.
11330 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
11332 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
11333
11334 // If the ZERO_POISON version is supported use that and handle the zero case.
11336 EVT SetCCVT =
11337 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11338 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
11339 SDValue Zero = DAG.getConstant(0, dl, VT);
11340 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11341 return DAG.getSelect(dl, VT, SrcIsZero,
11342 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
11343 }
11344
11345 // Only expand vector types if we have the appropriate vector bit operations.
11346 // This includes the operations needed to expand CTPOP if it isn't supported.
11347 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11349 !canExpandVectorCTPOP(*this, VT)) ||
11352 return SDValue();
11353
11354 // for now, we do this:
11355 // x = x | (x >> 1);
11356 // x = x | (x >> 2);
11357 // ...
11358 // x = x | (x >>16);
11359 // x = x | (x >>32); // for 64-bit input
11360 // return popcount(~x);
11361 //
11362 // Ref: "Hacker's Delight" by Henry Warren
11363 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
11364 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
11365 Op = DAG.getNode(ISD::OR, dl, VT, Op,
11366 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
11367 }
11368 Op = DAG.getNOT(dl, Op, VT);
11369 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
11370}
11371
11373 SDLoc dl(Node);
11374 EVT VT = Node->getValueType(0);
11375 SDValue Op = DAG.getFreeze(Node->getOperand(0));
11376 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11377
11378 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
11379 // This transforms the sign bits into leading zeros that can be counted.
11380 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
11381 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
11382 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
11383 SDValue Shl =
11384 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11385 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
11386 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
11387}
11388
11390 const SDLoc &DL, EVT VT, SDValue Op,
11391 unsigned BitWidth) const {
11392 if (BitWidth != 32 && BitWidth != 64)
11393 return SDValue();
11394
11395 const DataLayout &TD = DAG.getDataLayout();
11397 return SDValue();
11398
11399 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
11400 : APInt(64, 0x0218A392CD3D5DBFULL);
11401 MachinePointerInfo PtrInfo =
11403 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
11404 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11405 SDValue Lookup = DAG.getNode(
11406 ISD::SRL, DL, VT,
11407 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
11408 DAG.getConstant(DeBruijn, DL, VT)),
11409 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11411
11413 for (unsigned i = 0; i < BitWidth; i++) {
11414 APInt Shl = DeBruijn.shl(i);
11415 APInt Lshr = Shl.lshr(ShiftAmt);
11416 Table[Lshr.getZExtValue()] = i;
11417 }
11418
11419 // Create a ConstantArray in Constant Pool
11420 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11421 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11422 TD.getPrefTypeAlign(CA->getType()));
11423 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11424 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11425 PtrInfo, MVT::i8);
11426 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11427 return ExtLoad;
11428
11429 EVT SetCCVT =
11430 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11431 SDValue Zero = DAG.getConstant(0, DL, VT);
11432 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11433 return DAG.getSelect(DL, VT, SrcIsZero,
11434 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11435}
11436
11438 SDLoc dl(Node);
11439 EVT VT = Node->getValueType(0);
11440 SDValue Op = Node->getOperand(0);
11441 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11442
11443 // If the non-ZERO_POISON version is supported we can use that instead.
11444 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11446 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11447
11448 // If the ZERO_POISON version is supported use that and handle the zero case.
11450 EVT SetCCVT =
11451 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11452 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11453 SDValue Zero = DAG.getConstant(0, dl, VT);
11454 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11455 return DAG.getSelect(dl, VT, SrcIsZero,
11456 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11457 }
11458
11459 // Only expand vector types if we have the appropriate vector bit operations.
11460 // This includes the operations needed to expand CTPOP if it isn't supported.
11461 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11464 !canExpandVectorCTPOP(*this, VT)) ||
11468 return SDValue();
11469
11470 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11471 // to be expanded or converted to a libcall.
11474 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11475 return V;
11476
11477 bool UseCTLZ =
11479
11480 // When only ctlz is available and the operand is nonzero we can use:
11481 // { return nlz(x & -x) ^ 31; }
11482 // which is more efficient than:
11483 // { return 32 - nlz(~x & (x - 1)); }.
11484 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11485 SDValue LowestBit =
11486 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11487 return DAG.getNode(ISD::XOR, dl, VT,
11488 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11489 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11490 }
11491
11492 // If ctpop is available, we use:
11493 // { return popcount(~x & (x-1)); }
11494 // If the target has ctlz but not ctpop, we use:
11495 // { return 32 - nlz(~x & (x-1)); }
11496 // Ref: "Hacker's Delight" by Henry Warren
11497 SDValue Tmp = DAG.getNode(
11498 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11499 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11500
11501 if (UseCTLZ)
11502 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11503 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11504
11505 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11506}
11507
11509 SelectionDAG &DAG) const {
11510 // %cond = to_bool_vec %source
11511 // %splat = splat /*val=*/VL
11512 // %tz = step_vector
11513 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11514 // %r = vp.reduce.umin %v
11515 SDLoc DL(N);
11516 SDValue Source = N->getOperand(0);
11517 SDValue Mask = N->getOperand(1);
11518 SDValue EVL = N->getOperand(2);
11519 EVT SrcVT = Source.getValueType();
11520 EVT ResVT = N->getValueType(0);
11521 EVT ResVecVT =
11522 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11523
11524 // Convert to boolean vector.
11525 if (SrcVT.getScalarType() != MVT::i1) {
11526 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11527 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11528 SrcVT.getVectorElementCount());
11529 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11530 }
11531
11532 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11533 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11534 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11535 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11536 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11537}
11538
11539/// Returns a type-legalized version of \p Mask as the first item in the
11540/// pair. The second item contains a type-legalized step vector that's
11541/// guaranteed to fit the number of elements in \p Mask.
11542/// If the stepvector would require splitting, returns an empty SDValue
11543/// as the second item to signal that the operation should be split instead.
11544static std::pair<SDValue, SDValue>
11546 SelectionDAG &DAG) {
11547 EVT MaskVT = Mask.getValueType();
11548 EVT BoolVT = MaskVT.getScalarType();
11549
11550 // Find a suitable type for a stepvector.
11551 // If zero is poison, we can assume the upper limit of the result is VF-1.
11552 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11553 if (MaskVT.isScalableVector())
11554 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11556 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11557 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11558 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11559 // If the step vector element type is smaller than the mask element type,
11560 // use the mask type directly to avoid widening issues.
11561 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11562 EVT StepVT = MVT::getIntegerVT(EltWidth);
11563 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11564
11565 // If promotion or widening is required to make the type legal, do it here.
11566 // Promotion of integers within LegalizeVectorOps is looking for types of
11567 // the same size but with a smaller number of larger elements, not the usual
11568 // larger size with the same number of larger elements.
11570 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11571 SDValue StepVec;
11572 if (TypeAction == TargetLowering::TypePromoteInteger) {
11573 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11574 StepVec = DAG.getStepVector(DL, StepVecVT);
11575 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11576 // For widening, the element count changes. Create a step vector with only
11577 // the original elements valid and zeros for padding. Also widen the mask.
11578 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11579 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11580
11581 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11582 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11583 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11584 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11585
11586 // Widen mask: pad with zeros.
11587 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11588 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11589 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11590 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11591 // The stepvector type would require splitting. Signal to the caller
11592 // that the operation should be split instead of expanded.
11593 return {Mask, SDValue()};
11594 } else {
11595 StepVec = DAG.getStepVector(DL, StepVecVT);
11596 }
11597
11598 return {Mask, StepVec};
11599}
11600
11602 SelectionDAG &DAG) const {
11603 SDLoc DL(N);
11604 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11605 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11606
11607 // If StepVec is empty, the stepvector would require splitting.
11608 // Split the operation instead and let it be recursively legalized.
11609 if (!StepVec) {
11610 EVT MaskVT = N->getOperand(0).getValueType();
11611 EVT ResVT = N->getValueType(0);
11612
11613 // Split the mask
11614 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11615 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11616
11617 // Create split VECTOR_FIND_LAST_ACTIVE operations
11618 SDValue LoResult =
11619 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11620 SDValue HiResult =
11621 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11622
11623 // Check if any lane is active in the high mask.
11624 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11626 AnyHiActive, DL,
11627 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11628 MVT::i1);
11629
11630 // Adjust HiResult by adding the number of elements in Lo
11631 SDValue LoNumElts =
11632 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11633 SDValue AdjustedHiResult =
11634 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11635
11636 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11637 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11638 LoResult);
11639 }
11640
11641 EVT StepVecVT = StepVec.getValueType();
11642 EVT StepVT = StepVec.getValueType().getVectorElementType();
11643
11644 // Zero out lanes with inactive elements, then find the highest remaining
11645 // value from the stepvector.
11646 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11647 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11648 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11649 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11650}
11651
11653 SelectionDAG &DAG) const {
11654 SDLoc DL(N);
11655
11656 SDValue Start = N->getOperand(0);
11657 SDValue End = N->getOperand(1);
11658 EVT VT = N->getValueType(0);
11659 EVT OpVT = Start.getValueType();
11660
11661 auto [Mask, StepVector] = getLegalMaskAndStepVector(
11662 DAG.getPOISON(VT), /*ZeroIsPoison=*/false, DL, DAG);
11663
11664 // No legal step vector: split the mask in half and recombine the results.
11665 // Lo = get_active_lane_mask Start, End
11666 // Hi = get_active_lane_mask (uaddsat Start, LoNumElts), End
11667 if (!StepVector) {
11668 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
11669 SDValue Lo = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, LoVT, Start, End);
11670 SDValue LoNumElts =
11671 DAG.getElementCount(DL, OpVT, LoVT.getVectorElementCount());
11672 SDValue HiStart = DAG.getNode(ISD::UADDSAT, DL, OpVT, Start, LoNumElts);
11673 SDValue Hi = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, HiVT, HiStart, End);
11674 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
11675 }
11676
11677 // Rebase and saturate the termination value.
11678 SDValue Max =
11679 DAG.getConstant(maxUIntN(std::min(StepVector.getScalarValueSizeInBits(),
11680 OpVT.getScalarSizeInBits())),
11681 DL, OpVT);
11682 End = DAG.getNode(ISD::USUBSAT, DL, OpVT, End, Start);
11683 End = DAG.getNode(ISD::UMIN, DL, OpVT, End, Max);
11684 End = DAG.getZExtOrTrunc(End, DL, StepVector.getValueType().getScalarType());
11685
11686 // cmp <0, 1, 2, 3...>, End
11687 SDValue EndV = DAG.getSplat(StepVector.getValueType(), DL, End);
11688 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11689 StepVector.getValueType());
11690 SDValue Cmp = DAG.getSetCC(DL, CCVT, StepVector, EndV, ISD::SETULT);
11691 SDValue Res = DAG.getBoolExtOrTrunc(Cmp, DL, Mask.getValueType(),
11692 StepVector.getValueType());
11693 if (Mask.getValueType() != VT)
11694 Res = DAG.getExtractSubvector(DL, VT, Res, 0);
11695 return Res;
11696}
11697
11699 SelectionDAG &DAG) const {
11700 SDLoc DL(N);
11701 EVT VT = N->getValueType(0);
11702 SDValue SourceValue = N->getOperand(0);
11703 SDValue SinkValue = N->getOperand(1);
11704 SDValue EltSizeInBytes = N->getOperand(2);
11705
11706 // Note: The lane offset is scalable if the mask is scalable.
11707 ElementCount LaneOffsetEC =
11708 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11709
11710 EVT AddrVT = SourceValue->getValueType(0);
11711 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11712
11713 EVT CmpVT =
11714 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11715
11716 // Unsigned compare: Source >= Sink.
11717 SDValue SourceAheadOfOrEqualToSink =
11718 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11719
11720 // Take the difference between the pointers and divided by the element size,
11721 // to see how many lanes separate them.
11722 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11723
11724 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11725 if (IsReadAfterWrite)
11726 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11727 DAG.getNegative(Diff, DL, AddrVT), Diff);
11728
11729 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11730
11731 // The pointers do not alias if:
11732 // - Source >= Sink (WAR_MASK)
11733 // - Source == Sink (RAW_MASK)
11734 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11735 if (IsReadAfterWrite)
11736 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11737
11738 // The pointers do not alias if:
11739 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11740 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11741 SDValue MaskN = DAG.getSelect(
11742 DL, AddrVT, NoAlias,
11744 AddrVT),
11745 Diff);
11746
11747 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11748}
11749
11751 bool IsNegative) const {
11752 SDLoc dl(N);
11753 EVT VT = N->getValueType(0);
11754 SDValue Op = N->getOperand(0);
11755
11756 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11757 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11759 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11760 if (IsNegative)
11761 return DAG.getNegative(AbsVal, dl, VT);
11762 return AbsVal;
11763 }
11764
11765 // abs(x) -> smax(x,sub(0,x))
11766 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11768 SDValue Zero = DAG.getConstant(0, dl, VT);
11769 Op = DAG.getFreeze(Op);
11770 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11771 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11772 }
11773
11774 // abs(x) -> umin(x,sub(0,x))
11775 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11777 SDValue Zero = DAG.getConstant(0, dl, VT);
11778 Op = DAG.getFreeze(Op);
11779 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11780 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11781 }
11782
11783 // 0 - abs(x) -> smin(x, sub(0,x))
11784 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11786 SDValue Zero = DAG.getConstant(0, dl, VT);
11787 Op = DAG.getFreeze(Op);
11788 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11789 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11790 }
11791
11792 // Only expand vector types if we have the appropriate vector operations.
11793 if (VT.isVector() &&
11795 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11796 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11798 return SDValue();
11799
11800 Op = DAG.getFreeze(Op);
11801 SDValue Shift = DAG.getNode(
11802 ISD::SRA, dl, VT, Op,
11803 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11804 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11805
11806 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11807 if (!IsNegative)
11808 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11809
11810 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11811 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11812}
11813
11815 SDLoc dl(N);
11816 EVT VT = N->getValueType(0);
11817 SDValue LHS = N->getOperand(0);
11818 SDValue RHS = N->getOperand(1);
11819 bool IsSigned = N->getOpcode() == ISD::ABDS;
11820
11821 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11822 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11823 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11824 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11825 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11826 LHS = DAG.getFreeze(LHS);
11827 RHS = DAG.getFreeze(RHS);
11828 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11829 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11830 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11831 }
11832
11833 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11834 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11835 LHS = DAG.getFreeze(LHS);
11836 RHS = DAG.getFreeze(RHS);
11837 return DAG.getNode(ISD::OR, dl, VT,
11838 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11839 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11840 }
11841
11842 // abds: if the sub is nsw -> abs(sub)
11843 // abdu with non-negative operands -> abs(sub)
11844 // The abdu case where the sub is nuw is handled in DAGCombine.
11845 if (IsSigned) {
11846 if (DAG.willNotOverflowSub(/*IsSigned=*/true, LHS, RHS))
11847 return DAG.getNode(ISD::ABS, dl, VT,
11848 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11849
11850 if (DAG.willNotOverflowSub(/*IsSigned=*/true, RHS, LHS))
11851 return DAG.getNode(ISD::ABS, dl, VT,
11852 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11853 } else if (DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS)) {
11854 return DAG.getNode(ISD::ABS, dl, VT,
11855 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11856 }
11857
11858 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11860 LHS = DAG.getFreeze(LHS);
11861 RHS = DAG.getFreeze(RHS);
11862 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11863
11864 // Branchless expansion iff cmp result is allbits:
11865 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11866 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11867 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11868 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11869 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11870 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11871 }
11872
11873 // Similar to the branchless expansion, if we don't prefer selects, use the
11874 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11875 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11876 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11877 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11879 SDValue USubO =
11880 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11881 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11882 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11883 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11884 }
11885
11886 // FIXME: Should really try to split the vector in case it's legal on a
11887 // subvector.
11889 return DAG.UnrollVectorOp(N);
11890
11891 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11892 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11893 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11894 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11895}
11896
11898 SDLoc dl(N);
11899 EVT VT = N->getValueType(0);
11900 SDValue LHS = N->getOperand(0);
11901 SDValue RHS = N->getOperand(1);
11902
11903 unsigned Opc = N->getOpcode();
11904 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11905 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11906 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11907 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11908 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11909 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11911 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11912 "Unknown AVG node");
11913
11914 // If the operands are already extended, we can add+shift.
11915 bool IsExt =
11916 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11917 DAG.ComputeNumSignBits(RHS) >= 2) ||
11918 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11919 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11920 if (IsExt) {
11921 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11922 if (!IsFloor)
11923 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11924 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11925 DAG.getShiftAmountConstant(1, VT, dl));
11926 }
11927
11928 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11929 if (VT.isScalarInteger()) {
11930 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11931 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11932 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11933 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11934 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11935 if (!IsFloor)
11936 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11937 DAG.getConstant(1, dl, ExtVT));
11938 // Just use SRL as we will be truncating away the extended sign bits.
11939 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11940 DAG.getShiftAmountConstant(1, ExtVT, dl));
11941 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11942 }
11943 }
11944
11945 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11946 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11949 SDValue UAddWithOverflow =
11950 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11951
11952 SDValue Sum = UAddWithOverflow.getValue(0);
11953 SDValue Overflow = UAddWithOverflow.getValue(1);
11954
11955 // Right shift the sum by 1
11956 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
11957 DAG.getShiftAmountConstant(1, VT, dl));
11958
11959 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
11960 SDValue OverflowShl = DAG.getNode(
11961 ISD::SHL, dl, VT, ZeroExtOverflow,
11962 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11963
11964 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
11965 }
11966
11967 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
11968 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
11969 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
11970 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
11971 LHS = DAG.getFreeze(LHS);
11972 RHS = DAG.getFreeze(RHS);
11973 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
11974 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
11975 SDValue Shift =
11976 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11977 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
11978}
11979
11981 SDLoc dl(N);
11982 EVT VT = N->getValueType(0);
11983 SDValue Op = N->getOperand(0);
11984
11985 if (!VT.isSimple())
11986 return SDValue();
11987
11988 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11989 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11990 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11991 default:
11992 return SDValue();
11993 case MVT::i16:
11994 // Use a rotate by 8. This can be further expanded if necessary.
11995 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11996 case MVT::i32:
11997 // This is meant for ARM specifically, which has ROTR but no ROTL.
11998 // t = x ^ rotr(x, 16)
11999 // t = bic(t, 0x00ff0000)
12000 // t = lshr(t, 8)
12001 // x = t ^ rotr(x, 8)
12003 SDValue Rotr16 =
12004 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
12005 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
12006 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
12007 DAG.getConstant(0xFF00FFFF, dl, VT));
12008 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
12009 SDValue Rotr8 =
12010 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12011 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
12012 }
12013 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12014 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
12015 DAG.getConstant(0xFF00, dl, VT));
12016 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
12017 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12018 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
12019 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12020 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
12021 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
12022 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
12023 case MVT::i64:
12024 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
12025 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
12026 DAG.getConstant(255ULL<<8, dl, VT));
12027 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
12028 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
12029 DAG.getConstant(255ULL<<16, dl, VT));
12030 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
12031 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
12032 DAG.getConstant(255ULL<<24, dl, VT));
12033 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
12034 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12035 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
12036 DAG.getConstant(255ULL<<24, dl, VT));
12037 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12038 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
12039 DAG.getConstant(255ULL<<16, dl, VT));
12040 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
12041 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
12042 DAG.getConstant(255ULL<<8, dl, VT));
12043 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
12044 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
12045 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
12046 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
12047 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
12048 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
12049 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
12050 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
12051 }
12052}
12053
12055 SDLoc dl(N);
12056 EVT VT = N->getValueType(0);
12057 SDValue Op = N->getOperand(0);
12058 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
12059 unsigned Sz = VT.getScalarSizeInBits();
12060
12061 SDValue Tmp, Tmp2, Tmp3;
12062
12063 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
12064 // and finally the i1 pairs.
12065 // TODO: We can easily support i4/i2 legal types if any target ever does.
12066 if (Sz >= 8 && isPowerOf2_32(Sz)) {
12067 // Create the masks - repeating the pattern every byte.
12068 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
12069 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
12070 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
12071
12072 // BSWAP if the type is wider than a single byte.
12073 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
12074
12075 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
12076 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
12077 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
12078 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
12079 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
12080 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12081
12082 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
12083 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
12084 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
12085 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
12086 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
12087 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12088
12089 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
12090 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
12091 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
12092 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
12093 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
12094 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12095 return Tmp;
12096 }
12097
12098 Tmp = DAG.getConstant(0, dl, VT);
12099 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
12100 if (I < J)
12101 Tmp2 =
12102 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
12103 else
12104 Tmp2 =
12105 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
12106
12107 APInt Shift = APInt::getOneBitSet(Sz, J);
12108 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
12109 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
12110 }
12111
12112 return Tmp;
12113}
12114
12115std::pair<SDValue, SDValue>
12117 SelectionDAG &DAG) const {
12118 SDLoc SL(LD);
12119 SDValue Chain = LD->getChain();
12120 SDValue BasePTR = LD->getBasePtr();
12121 EVT SrcVT = LD->getMemoryVT();
12122 EVT DstVT = LD->getValueType(0);
12123 ISD::LoadExtType ExtType = LD->getExtensionType();
12124
12125 if (SrcVT.isScalableVector())
12126 report_fatal_error("Cannot scalarize scalable vector loads");
12127
12128 unsigned NumElem = SrcVT.getVectorNumElements();
12129
12130 EVT SrcEltVT = SrcVT.getScalarType();
12131 EVT DstEltVT = DstVT.getScalarType();
12132
12133 // A vector must always be stored in memory as-is, i.e. without any padding
12134 // between the elements, since various code depend on it, e.g. in the
12135 // handling of a bitcast of a vector type to int, which may be done with a
12136 // vector store followed by an integer load. A vector that does not have
12137 // elements that are byte-sized must therefore be stored as an integer
12138 // built out of the extracted vector elements.
12139 if (!SrcEltVT.isByteSized()) {
12140 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
12141 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
12142
12143 unsigned NumSrcBits = SrcVT.getSizeInBits();
12144 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
12145
12146 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
12147 SDValue SrcEltBitMask = DAG.getConstant(
12148 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
12149
12150 // Load the whole vector and avoid masking off the top bits as it makes
12151 // the codegen worse.
12152 SDValue Load = DAG.getExtLoad(
12153 ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, LD->getPointerInfo(),
12154 SrcIntVT, LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12155 LD->getMMOMetadataForSubAccess());
12156
12158 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12159 unsigned ShiftIntoIdx =
12160 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12161 SDValue ShiftAmount = DAG.getShiftAmountConstant(
12162 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
12163 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
12164 SDValue Elt =
12165 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
12166 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
12167
12168 if (ExtType != ISD::NON_EXTLOAD) {
12169 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
12170 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
12171 }
12172
12173 Vals.push_back(Scalar);
12174 }
12175
12176 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12177 return std::make_pair(Value, Load.getValue(1));
12178 }
12179
12180 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
12181 assert(SrcEltVT.isByteSized());
12182
12184 SmallVector<SDValue, 8> LoadChains;
12185
12186 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12187 SDValue ScalarLoad = DAG.getExtLoad(
12188 ExtType, SL, DstEltVT, Chain, BasePTR,
12189 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
12190 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12191 LD->getMMOMetadataForSubAccess());
12192
12193 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
12194
12195 Vals.push_back(ScalarLoad.getValue(0));
12196 LoadChains.push_back(ScalarLoad.getValue(1));
12197 }
12198
12199 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
12200 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12201
12202 return std::make_pair(Value, NewChain);
12203}
12204
12206 SelectionDAG &DAG) const {
12207 SDLoc SL(ST);
12208
12209 SDValue Chain = ST->getChain();
12210 SDValue BasePtr = ST->getBasePtr();
12211 SDValue Value = ST->getValue();
12212 EVT StVT = ST->getMemoryVT();
12213
12214 if (StVT.isScalableVector())
12215 report_fatal_error("Cannot scalarize scalable vector stores");
12216
12217 // The type of the data we want to save
12218 EVT RegVT = Value.getValueType();
12219 EVT RegSclVT = RegVT.getScalarType();
12220
12221 // The type of data as saved in memory.
12222 EVT MemSclVT = StVT.getScalarType();
12223
12224 unsigned NumElem = StVT.getVectorNumElements();
12225
12226 // A vector must always be stored in memory as-is, i.e. without any padding
12227 // between the elements, since various code depend on it, e.g. in the
12228 // handling of a bitcast of a vector type to int, which may be done with a
12229 // vector store followed by an integer load. A vector that does not have
12230 // elements that are byte-sized must therefore be stored as an integer
12231 // built out of the extracted vector elements.
12232 if (!MemSclVT.isByteSized()) {
12233 unsigned NumBits = StVT.getSizeInBits();
12234 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
12235
12236 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
12237
12238 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12239 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12240 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
12241 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
12242 unsigned ShiftIntoIdx =
12243 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12244 SDValue ShiftAmount =
12245 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
12246 SDValue ShiftedElt =
12247 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
12248 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
12249 }
12250
12251 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
12252 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12253 ST->getMMOMetadataForSubAccess());
12254 }
12255
12256 // Store Stride in bytes
12257 unsigned Stride = MemSclVT.getSizeInBits() / 8;
12258 assert(Stride && "Zero stride!");
12259 // Extract each of the elements from the original vector and save them into
12260 // memory individually.
12262 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12263 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12264
12265 SDValue Ptr =
12266 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
12267
12268 // This scalar TruncStore may be illegal, but we legalize it later.
12270 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
12271 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12272 ST->getMMOMetadataForSubAccess());
12273
12274 Stores.push_back(Store);
12275 }
12276
12277 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
12278}
12279
12280std::pair<SDValue, SDValue>
12282 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
12283 "unaligned indexed loads not implemented!");
12284 SDValue Chain = LD->getChain();
12285 SDValue Ptr = LD->getBasePtr();
12286 EVT VT = LD->getValueType(0);
12287 EVT LoadedVT = LD->getMemoryVT();
12288 SDLoc dl(LD);
12289 auto &MF = DAG.getMachineFunction();
12290
12291 if (VT.isFloatingPoint() || VT.isVector()) {
12292 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
12293 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
12294 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
12295 LoadedVT.isVector()) {
12296 // Scalarize the load and let the individual components be handled.
12297 return scalarizeVectorLoad(LD, DAG);
12298 }
12299
12300 // Expand to a (misaligned) integer load of the same size,
12301 // then bitconvert to floating point or vector.
12302 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
12303 LD->getMemOperand());
12304 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
12305 if (LoadedVT != VT)
12306 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
12307 ISD::ANY_EXTEND, dl, VT, Result);
12308
12309 return std::make_pair(Result, newLoad.getValue(1));
12310 }
12311
12312 // Copy the value to a (aligned) stack slot using (unaligned) integer
12313 // loads and stores, then do a (aligned) load from the stack slot.
12314 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
12315 unsigned LoadedBytes = LoadedVT.getStoreSize();
12316 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12317 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
12318
12319 // Make sure the stack slot is also aligned for the register type.
12320 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
12321 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
12323 SDValue StackPtr = StackBase;
12324 unsigned Offset = 0;
12325
12326 EVT PtrVT = Ptr.getValueType();
12327 EVT StackPtrVT = StackPtr.getValueType();
12328
12329 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12330 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12331
12332 // Do all but one copies using the full register width.
12333 for (unsigned i = 1; i < NumRegs; i++) {
12334 // Load one integer register's worth from the original location.
12335 SDValue Load = DAG.getLoad(
12336 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12337 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12338 LD->getMMOMetadataForSubAccess());
12339 // Follow the load with a store to the stack slot. Remember the store.
12340 Stores.push_back(DAG.getStore(
12341 Load.getValue(1), dl, Load, StackPtr,
12342 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12343 // Increment the pointers.
12344 Offset += RegBytes;
12345
12346 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12347 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12348 }
12349
12350 // The last copy may be partial. Do an extending load.
12351 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12352 8 * (LoadedBytes - Offset));
12353 SDValue Load = DAG.getExtLoad(
12354 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12355 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12356 LD->getMemOperand()->getFlags(), LD->getMMOMetadataForSubAccess());
12357 // Follow the load with a store to the stack slot. Remember the store.
12358 // On big-endian machines this requires a truncating store to ensure
12359 // that the bits end up in the right place.
12360 Stores.push_back(DAG.getTruncStore(
12361 Load.getValue(1), dl, Load, StackPtr,
12362 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12363
12364 // The order of the stores doesn't matter - say it with a TokenFactor.
12365 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12366
12367 // Finally, perform the original load only redirected to the stack slot.
12368 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12369 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12370 LoadedVT);
12371
12372 // Callers expect a MERGE_VALUES node.
12373 return std::make_pair(Load, TF);
12374 }
12375
12376 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12377 "Unaligned load of unsupported type.");
12378
12379 // Compute the new VT that is half the size of the old one. This is an
12380 // integer MVT.
12381 unsigned NumBits = LoadedVT.getSizeInBits();
12382 EVT NewLoadedVT;
12383 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12384 NumBits >>= 1;
12385
12386 Align Alignment = LD->getBaseAlign();
12387 unsigned IncrementSize = NumBits / 8;
12388 ISD::LoadExtType HiExtType = LD->getExtensionType();
12389
12390 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12391 if (HiExtType == ISD::NON_EXTLOAD)
12392 HiExtType = ISD::ZEXTLOAD;
12393
12394 // Load the value in two parts
12395 SDValue Lo, Hi;
12396 if (DAG.getDataLayout().isLittleEndian()) {
12397 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12398 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12399 LD->getMMOMetadataForSubAccess());
12400
12401 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12402 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12403 LD->getPointerInfo().getWithOffset(IncrementSize),
12404 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12405 LD->getMMOMetadataForSubAccess());
12406 } else {
12407 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12408 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12409 LD->getMMOMetadataForSubAccess());
12410
12411 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12412 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12413 LD->getPointerInfo().getWithOffset(IncrementSize),
12414 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12415 LD->getMMOMetadataForSubAccess());
12416 }
12417
12418 // aggregate the two parts
12419 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12420 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12421 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12422
12423 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12424 Hi.getValue(1));
12425
12426 return std::make_pair(Result, TF);
12427}
12428
12430 SelectionDAG &DAG) const {
12431 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12432 "unaligned indexed stores not implemented!");
12433 SDValue Chain = ST->getChain();
12434 SDValue Ptr = ST->getBasePtr();
12435 SDValue Val = ST->getValue();
12436 EVT VT = Val.getValueType();
12437 Align Alignment = ST->getBaseAlign();
12438 auto &MF = DAG.getMachineFunction();
12439 EVT StoreMemVT = ST->getMemoryVT();
12440
12441 SDLoc dl(ST);
12442 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12443 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12444 if (isTypeLegal(intVT)) {
12445 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12446 StoreMemVT.isVector()) {
12447 // Scalarize the store and let the individual components be handled.
12448 SDValue Result = scalarizeVectorStore(ST, DAG);
12449 return Result;
12450 }
12451 // Expand to a bitconvert of the value to the integer type of the
12452 // same size, then a (misaligned) int store.
12453 // FIXME: Does not handle truncating floating point stores!
12454 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12455 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12456 Alignment, ST->getMemOperand()->getFlags(),
12457 ST->getMMOMetadataForSubAccess());
12458 return Result;
12459 }
12460 // Do a (aligned) store to a stack slot, then copy from the stack slot
12461 // to the final destination using (unaligned) integer loads and stores.
12462 MVT RegVT = getRegisterType(
12463 *DAG.getContext(),
12464 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12465 EVT PtrVT = Ptr.getValueType();
12466 unsigned StoredBytes = StoreMemVT.getStoreSize();
12467 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12468 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12469
12470 // Make sure the stack slot is also aligned for the register type.
12471 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12472 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12473
12474 // Perform the original store, only redirected to the stack slot.
12476 Chain, dl, Val, StackPtr,
12477 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12478
12479 EVT StackPtrVT = StackPtr.getValueType();
12480
12481 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12482 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12484 unsigned Offset = 0;
12485
12486 // Do all but one copies using the full register width.
12487 for (unsigned i = 1; i < NumRegs; i++) {
12488 // Load one integer register's worth from the stack slot.
12489 SDValue Load = DAG.getLoad(
12490 RegVT, dl, Store, StackPtr,
12491 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12492 // Store it to the final location. Remember the store.
12493 Stores.push_back(DAG.getStore(
12494 Load.getValue(1), dl, Load, Ptr,
12495 ST->getPointerInfo().getWithOffset(Offset), ST->getBaseAlign(),
12496 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess()));
12497 // Increment the pointers.
12498 Offset += RegBytes;
12499 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12500 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12501 }
12502
12503 // The last store may be partial. Do a truncating store. On big-endian
12504 // machines this requires an extending load from the stack slot to ensure
12505 // that the bits are in the right place.
12506 EVT LoadMemVT =
12507 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12508
12509 // Load from the stack slot.
12510 SDValue Load = DAG.getExtLoad(
12511 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12512 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12513
12514 Stores.push_back(
12515 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
12516 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12517 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12518 ST->getMMOMetadataForSubAccess()));
12519 // The order of the stores doesn't matter - say it with a TokenFactor.
12520 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12521 return Result;
12522 }
12523
12524 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12525 "Unaligned store of unknown type.");
12526 // Get the half-size VT
12527 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12528 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12529 unsigned IncrementSize = NumBits / 8;
12530
12531 // Divide the stored value in two parts.
12532 SDValue ShiftAmount =
12533 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12534 SDValue Lo = Val;
12535 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12536 // fold and not use the upper bits. A smaller constant may be easier to
12537 // materialize.
12538 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12539 Lo = DAG.getNode(
12540 ISD::AND, dl, VT, Lo,
12541 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12542 VT));
12543 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12544
12545 // Store the two parts
12546 SDValue Store1, Store2;
12547 Store1 = DAG.getTruncStore(
12548 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Lo : Hi, Ptr,
12549 ST->getPointerInfo(), NewStoredVT, Alignment,
12550 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12551
12552 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12553 Store2 = DAG.getTruncStore(
12554 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12555 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12556 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12557
12558 SDValue Result =
12559 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12560 return Result;
12561}
12562
12563SDValue
12565 const SDLoc &DL, EVT DataVT,
12566 SelectionDAG &DAG,
12567 bool IsCompressedMemory) const {
12569 EVT AddrVT = Addr.getValueType();
12570 EVT MaskVT = Mask.getValueType();
12571 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12572 "Incompatible types of Data and Mask");
12573 if (IsCompressedMemory) {
12574 // Incrementing the pointer according to number of '1's in the mask.
12575 if (DataVT.isScalableVector()) {
12576 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12577 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12578 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12579 } else {
12580 EVT MaskIntVT =
12581 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12582 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12583 if (MaskIntVT.getSizeInBits() < 32) {
12584 MaskInIntReg =
12585 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12586 MaskIntVT = MVT::i32;
12587 }
12588 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12589 }
12590 // Scale is an element size in bytes.
12591 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12592 AddrVT);
12593 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12594 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12595 } else
12596 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12597
12598 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12599}
12600
12602 EVT VecVT, const SDLoc &DL,
12603 ElementCount SubEC) {
12604 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12605 "Cannot index a scalable vector within a fixed-width vector");
12606 ElementCount NElts = VecVT.getVectorElementCount();
12607 EVT IdxVT = Idx.getValueType();
12608
12609 // Attempt to prove all accessed lanes sit within VecVT.
12610 ElementCount IdxAsEC;
12611 if (sd_match(Idx, m_ElementCount(IdxAsEC))) {
12612 if (SubEC.isScalar() && ElementCount::isKnownLT(IdxAsEC, NElts))
12613 return Idx;
12614 // Calculate end index as TypeSize to remove possibility of overflow.
12615 if (IdxAsEC.isScalable() == SubEC.isScalable() &&
12616 TypeSize::isKnownLE(TypeSize(IdxAsEC) + TypeSize(SubEC),
12617 TypeSize(NElts)))
12618 return Idx;
12619 }
12620
12621 // Can we mask Idx rather than clamp it.
12622 if (SubEC.isScalar() && NElts.isPowerOf2()) {
12623 SDValue EC = DAG.getElementCount(DL, IdxVT, NElts);
12624 SDValue Mask =
12625 DAG.getNode(ISD::SUB, DL, IdxVT, EC, DAG.getConstant(1, DL, IdxVT));
12626 return DAG.getNode(ISD::AND, DL, IdxVT, Idx, Mask);
12627 }
12628
12629 unsigned SubOpcode =
12631 SDValue MaxSafeIndex =
12632 DAG.getNode(SubOpcode, DL, IdxVT, DAG.getElementCount(DL, IdxVT, NElts),
12633 DAG.getElementCount(DL, IdxVT, SubEC));
12634 return DAG.getNode(ISD::UMIN, DL, IdxVT, Idx, MaxSafeIndex);
12635}
12636
12637SDValue
12639 EVT VecVT, SDValue Index,
12640 const SDNodeFlags PtrArithFlags) const {
12642 DAG, VecPtr, VecVT,
12644 Index, PtrArithFlags);
12645}
12646
12647SDValue
12649 EVT VecVT, EVT SubVecVT, SDValue Index,
12650 const SDNodeFlags PtrArithFlags) const {
12651 SDLoc dl(Index);
12652 // Make sure the index type is big enough to compute in.
12653 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12654
12655 EVT EltVT = VecVT.getVectorElementType();
12656
12657 // Calculate the element offset and add it to the pointer.
12658 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12659 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12660 "Converting bits to bytes lost precision");
12661 assert(SubVecVT.getVectorElementType() == EltVT &&
12662 "Sub-vector must be a vector with matching element type");
12663 assert((SubVecVT.getVectorElementCount().isScalar() ||
12664 isa<ConstantSDNode>(Index)) &&
12665 "Subvector Index must be constant!");
12666
12667 // An out-of-range index only makes the vector operation return poison, but
12668 // a load/store through the pointer computed below would be immediate UB, so
12669 // freeze the index before clamping it into range.
12670 if (!DAG.isGuaranteedNotToBePoison(Index))
12671 Index = DAG.getFreeze(Index);
12672
12673 EVT IdxVT = Index.getValueType();
12674 if (SubVecVT.isScalableVector())
12675 Index =
12676 DAG.getVScale(dl, IdxVT, cast<ConstantSDNode>(Index)->getAPIntValue());
12677
12678 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12679 SubVecVT.getVectorElementCount());
12680 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12681 DAG.getConstant(EltSize, dl, IdxVT));
12682 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12683}
12684
12685//===----------------------------------------------------------------------===//
12686// Implementation of Emulated TLS Model
12687//===----------------------------------------------------------------------===//
12688
12690 SelectionDAG &DAG) const {
12691 // Access to address of TLS varialbe xyz is lowered to a function call:
12692 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12693 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12694 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12695 SDLoc dl(GA);
12696
12697 ArgListTy Args;
12698 const GlobalValue *GV =
12700 SmallString<32> NameString("__emutls_v.");
12701 NameString += GV->getName();
12702 StringRef EmuTlsVarName(NameString);
12703 const GlobalVariable *EmuTlsVar =
12704 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12705 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12706 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12707
12708 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12709
12711 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12712 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12713 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12714
12715 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12716 // At last for X86 targets, maybe good for other targets too?
12718 MFI.setAdjustsStack(true); // Is this only for X86 target?
12719 MFI.setHasCalls(true);
12720
12721 assert((GA->getOffset() == 0) &&
12722 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12723 return CallResult.first;
12724}
12725
12727 SelectionDAG &DAG) const {
12728 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12729 if (!isCtlzFast())
12730 return SDValue();
12731 ISD::CondCode CC = Op.getOperandCondCode(2);
12732 SDLoc dl(Op);
12733 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12734 EVT VT = Op.getOperand(0).getValueType();
12735 SDValue Zext = Op.getOperand(0);
12736 if (VT.bitsLT(MVT::i32)) {
12737 VT = MVT::i32;
12738 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12739 }
12740 unsigned Log2b = Log2_32(VT.getSizeInBits());
12741 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12742 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12743 DAG.getConstant(Log2b, dl, MVT::i32));
12744 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12745 }
12746 return SDValue();
12747}
12748
12750 SDValue Op0 = Node->getOperand(0);
12751 SDValue Op1 = Node->getOperand(1);
12752 EVT VT = Op0.getValueType();
12753 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12754 unsigned Opcode = Node->getOpcode();
12755 SDLoc DL(Node);
12756
12757 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12758 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12759 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12760 DAG.SignBitIsZero(Op1))
12761 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12762
12763 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12764 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12766 Op0 = DAG.getFreeze(Op0);
12767 SDValue Zero = DAG.getConstant(0, DL, VT);
12768 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12769 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12770 }
12771
12772 // umin(x,y) -> sub(x,usubsat(x,y))
12773 // TODO: Missing freeze(Op0)?
12774 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12776 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12777 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12778 }
12779
12780 // umax(x,y) -> add(x,usubsat(y,x))
12781 // TODO: Missing freeze(Op0)?
12782 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12784 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12785 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12786 }
12787
12788 // FIXME: Should really try to split the vector in case it's legal on a
12789 // subvector.
12791 return DAG.UnrollVectorOp(Node);
12792
12793 // Attempt to find an existing SETCC node that we can reuse.
12794 // TODO: Do we need a generic doesSETCCNodeExist?
12795 // TODO: Missing freeze(Op0)/freeze(Op1)?
12796 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12797 ISD::CondCode PrefCommuteCC,
12798 ISD::CondCode AltCommuteCC) {
12799 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12800 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12801 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12802 {Op0, Op1, DAG.getCondCode(CC)})) {
12803 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12804 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12805 }
12806 }
12807 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12808 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12809 {Op0, Op1, DAG.getCondCode(CC)})) {
12810 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12811 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12812 }
12813 }
12814 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12815 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12816 };
12817
12818 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12819 // -> Y = (A < B) ? B : A
12820 // -> Y = (A >= B) ? A : B
12821 // -> Y = (A <= B) ? B : A
12822 switch (Opcode) {
12823 case ISD::SMAX:
12824 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12825 case ISD::SMIN:
12826 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12827 case ISD::UMAX:
12828 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12829 case ISD::UMIN:
12830 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12831 }
12832
12833 llvm_unreachable("How did we get here?");
12834}
12835
12837 unsigned Opcode = Node->getOpcode();
12838 SDValue LHS = Node->getOperand(0);
12839 SDValue RHS = Node->getOperand(1);
12840 EVT VT = LHS.getValueType();
12841 SDLoc dl(Node);
12842
12843 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12844 assert(VT.isInteger() && "Expected operands to be integers");
12845
12846 // usub.sat(a, b) -> umax(a, b) - b
12847 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12848 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12849 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12850 }
12851
12852 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12853 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12854 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12856 LHS = DAG.getFreeze(LHS);
12857 SDValue Zero = DAG.getConstant(0, dl, VT);
12858 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12859 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12860 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12861 Subtrahend =
12862 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12863 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12864 }
12865
12866 // uadd.sat(a, b) -> umin(a, ~b) + b
12867 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12868 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12869 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12870 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12871 }
12872
12873 unsigned OverflowOp;
12874 switch (Opcode) {
12875 case ISD::SADDSAT:
12876 OverflowOp = ISD::SADDO;
12877 break;
12878 case ISD::UADDSAT:
12879 OverflowOp = ISD::UADDO;
12880 break;
12881 case ISD::SSUBSAT:
12882 OverflowOp = ISD::SSUBO;
12883 break;
12884 case ISD::USUBSAT:
12885 OverflowOp = ISD::USUBO;
12886 break;
12887 default:
12888 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12889 "addition or subtraction node.");
12890 }
12891
12892 // FIXME: Should really try to split the vector in case it's legal on a
12893 // subvector.
12895 return DAG.UnrollVectorOp(Node);
12896
12897 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12898 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12899 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12900 SDValue SumDiff = Result.getValue(0);
12901 SDValue Overflow = Result.getValue(1);
12902 SDValue Zero = DAG.getConstant(0, dl, VT);
12903 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12904
12905 if (Opcode == ISD::UADDSAT) {
12907 // (LHS + RHS) | OverflowMask
12908 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12909 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12910 }
12911 // Overflow ? 0xffff.... : (LHS + RHS)
12912 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12913 }
12914
12915 if (Opcode == ISD::USUBSAT) {
12917 // (LHS - RHS) & ~OverflowMask
12918 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12919 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12920 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12921 }
12922 // Overflow ? 0 : (LHS - RHS)
12923 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12924 }
12925
12926 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12927 "Expected signed saturating add/sub opcode");
12928
12929 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12930 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12931
12932 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12933 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12934
12935 // If either of the operand signs are known, then they are guaranteed to
12936 // only saturate in one direction. If non-negative they will saturate
12937 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12938 //
12939 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12940 // sign of 'y' has to be flipped.
12941
12942 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12943 bool RHSIsNonNegative =
12944 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12945 if (LHSIsNonNegative || RHSIsNonNegative) {
12946 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12947 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12948 }
12949
12950 bool LHSIsNegative = KnownLHS.isNegative();
12951 bool RHSIsNegative =
12952 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12953 if (LHSIsNegative || RHSIsNegative) {
12954 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12955 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
12956 }
12957
12958 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
12959 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12960 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
12961 DAG.getConstant(BitWidth - 1, dl, VT));
12962 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
12963 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
12964}
12965
12967 unsigned Opcode = Node->getOpcode();
12968 SDValue LHS = Node->getOperand(0);
12969 SDValue RHS = Node->getOperand(1);
12970 EVT VT = LHS.getValueType();
12971 EVT ResVT = Node->getValueType(0);
12972 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12973 SDLoc dl(Node);
12974
12975 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
12976 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
12977 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
12978 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
12979
12980 // We can't perform arithmetic on i1 values. Extending them would
12981 // probably result in worse codegen, so let's just use two selects instead.
12982 // Some targets are also just better off using selects rather than subtraction
12983 // because one of the conditions can be merged with one of the selects.
12984 // And finally, if we don't know the contents of high bits of a boolean value
12985 // we can't perform any arithmetic either.
12987 BoolVT.getScalarSizeInBits() == 1 ||
12989 SDValue SelectZeroOrOne =
12990 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
12991 DAG.getConstant(0, dl, ResVT));
12992 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
12993 SelectZeroOrOne);
12994 }
12995
12997 std::swap(IsGT, IsLT);
12998 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
12999 ResVT);
13000}
13001
13003 unsigned Opcode = Node->getOpcode();
13004 bool IsSigned = Opcode == ISD::SSHLSAT;
13005 SDValue LHS = Node->getOperand(0);
13006 SDValue RHS = Node->getOperand(1);
13007 EVT VT = LHS.getValueType();
13008 SDLoc dl(Node);
13009
13010 assert((Node->getOpcode() == ISD::SSHLSAT ||
13011 Node->getOpcode() == ISD::USHLSAT) &&
13012 "Expected a SHLSAT opcode");
13013 assert(VT.isInteger() && "Expected operands to be integers");
13014
13016 return DAG.UnrollVectorOp(Node);
13017
13018 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
13019
13020 unsigned BW = VT.getScalarSizeInBits();
13021 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13022 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
13023 SDValue Orig =
13024 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
13025
13026 SDValue SatVal;
13027 if (IsSigned) {
13028 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
13029 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
13030 SDValue Cond =
13031 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
13032 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
13033 } else {
13034 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
13035 }
13036 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
13037 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
13038}
13039
13041 bool Signed, SDValue &Lo, SDValue &Hi,
13042 SDValue LHS, SDValue RHS,
13043 SDValue HiLHS, SDValue HiRHS) const {
13044 EVT VT = LHS.getValueType();
13045 assert(RHS.getValueType() == VT && "Mismatching operand types");
13046
13047 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
13048 assert((!Signed || !HiLHS) &&
13049 "Signed flag should only be set when HiLHS and RiRHS are null");
13050
13051 // We'll expand the multiplication by brute force because we have no other
13052 // options. This is a trivially-generalized version of the code from
13053 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
13054 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
13055 // sign bits while calculating the Hi half.
13056 unsigned Bits = VT.getScalarSizeInBits();
13057 unsigned HalfBits = Bits / 2;
13058 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
13059 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
13060 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
13061
13062 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
13063 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
13064
13065 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
13066 // This is always an unsigned shift.
13067 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
13068
13069 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
13070 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
13071 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
13072
13073 SDValue U =
13074 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
13075 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
13076 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
13077
13078 SDValue V =
13079 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
13080 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
13081
13082 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
13083 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
13084
13085 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
13086 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
13087
13088 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
13089 // the products to Hi.
13090 if (HiLHS) {
13091 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
13092 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
13093 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
13094 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
13095 }
13096}
13097
13099 bool Signed, const SDValue LHS,
13100 const SDValue RHS, SDValue &Lo,
13101 SDValue &Hi) const {
13102 EVT VT = LHS.getValueType();
13103 assert(RHS.getValueType() == VT && "Mismatching operand types");
13104 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13105 // We can fall back to a libcall with an illegal type for the MUL if we
13106 // have a libcall big enough.
13107 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
13108 if (WideVT == MVT::i16)
13109 LC = RTLIB::MUL_I16;
13110 else if (WideVT == MVT::i32)
13111 LC = RTLIB::MUL_I32;
13112 else if (WideVT == MVT::i64)
13113 LC = RTLIB::MUL_I64;
13114 else if (WideVT == MVT::i128)
13115 LC = RTLIB::MUL_I128;
13116
13117 RTLIB::LibcallImpl LibcallImpl = DAG.getLibcalls().getLibcallImpl(LC);
13118 if (LibcallImpl == RTLIB::Unsupported) {
13119 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
13120 return;
13121 }
13122
13123 // The libcall takes and returns WideVT values as packed VT halves. This only
13124 // works if VT is legal and WideVT isn't. Otherwise, emit a wide multiply and
13125 // let it legalise normally, possibly into a wider libcall.
13126 if (isTypeLegal(WideVT) || !isTypeLegal(VT)) {
13127 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT,
13128 DAG.getExtOrTrunc(Signed, LHS, dl, WideVT),
13129 DAG.getExtOrTrunc(Signed, RHS, dl, WideVT));
13130 SDValue Shift =
13131 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13132 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13133 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT,
13134 DAG.getNode(ISD::SRL, dl, WideVT, Mul, Shift));
13135 return;
13136 }
13137
13138 SDValue HiLHS, HiRHS;
13139 if (Signed) {
13140 // The high part is obtained by SRA'ing all but one of the bits of low
13141 // part.
13142 unsigned LoSize = VT.getFixedSizeInBits();
13143 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
13144 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
13145 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
13146 } else {
13147 HiLHS = DAG.getConstant(0, dl, VT);
13148 HiRHS = DAG.getConstant(0, dl, VT);
13149 }
13150
13151 // Attempt a libcall.
13152 SDValue Ret;
13154 CallOptions.setIsSigned(Signed);
13155 CallOptions.setIsPostTypeLegalization(true);
13157 // Halves of WideVT are packed into registers in different order
13158 // depending on platform endianness. This is usually handled by
13159 // the C calling convention, but we can't defer to it in
13160 // the legalizer.
13161 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
13162 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13163 } else {
13164 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
13165 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13166 }
13168 "Ret value is a collection of constituent nodes holding result.");
13169 if (DAG.getDataLayout().isLittleEndian()) {
13170 // Same as above.
13171 Lo = Ret.getOperand(0);
13172 Hi = Ret.getOperand(1);
13173 } else {
13174 Lo = Ret.getOperand(1);
13175 Hi = Ret.getOperand(0);
13176 }
13177}
13178
13179SDValue
13181 assert((Node->getOpcode() == ISD::SMULFIX ||
13182 Node->getOpcode() == ISD::UMULFIX ||
13183 Node->getOpcode() == ISD::SMULFIXSAT ||
13184 Node->getOpcode() == ISD::UMULFIXSAT) &&
13185 "Expected a fixed point multiplication opcode");
13186
13187 SDLoc dl(Node);
13188 SDValue LHS = Node->getOperand(0);
13189 SDValue RHS = Node->getOperand(1);
13190 EVT VT = LHS.getValueType();
13191 unsigned Scale = Node->getConstantOperandVal(2);
13192 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
13193 Node->getOpcode() == ISD::UMULFIXSAT);
13194 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
13195 Node->getOpcode() == ISD::SMULFIXSAT);
13196 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13197 unsigned VTSize = VT.getScalarSizeInBits();
13198
13199 if (!Scale) {
13200 // [us]mul.fix(a, b, 0) -> mul(a, b)
13201 if (!Saturating) {
13203 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13204 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
13205 SDValue Result =
13206 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13207 SDValue Product = Result.getValue(0);
13208 SDValue Overflow = Result.getValue(1);
13209 SDValue Zero = DAG.getConstant(0, dl, VT);
13210
13211 APInt MinVal = APInt::getSignedMinValue(VTSize);
13212 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
13213 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13214 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13215 // Xor the inputs, if resulting sign bit is 0 the product will be
13216 // positive, else negative.
13217 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
13218 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
13219 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
13220 return DAG.getSelect(dl, VT, Overflow, Result, Product);
13221 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
13222 SDValue Result =
13223 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13224 SDValue Product = Result.getValue(0);
13225 SDValue Overflow = Result.getValue(1);
13226
13227 APInt MaxVal = APInt::getMaxValue(VTSize);
13228 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13229 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
13230 }
13231 }
13232
13233 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
13234 "Expected scale to be less than the number of bits if signed or at "
13235 "most the number of bits if unsigned.");
13236 assert(LHS.getValueType() == RHS.getValueType() &&
13237 "Expected both operands to be the same type");
13238
13239 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
13240 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
13241 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
13242 SDValue Val, ISD::CondCode CC) {
13243 if (VT.isVector())
13244 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
13245 Sat, Val);
13246 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
13247 };
13248
13249 // Get the upper and lower bits of the result.
13250 SDValue Lo, Hi;
13251 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13252 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
13253 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13254 if (isOperationLegalOrCustom(LoHiOp, VT)) {
13255 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
13256 Lo = Result.getValue(0);
13257 Hi = Result.getValue(1);
13258 } else if (isOperationLegalOrCustom(HiOp, VT)) {
13259 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13260 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
13261 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13262 // Try for a multiplication using a wider type.
13263 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13264 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
13265 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
13266 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
13267 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
13268 SDValue Shifted =
13269 DAG.getNode(ISD::SRA, dl, WideVT, Res,
13270 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
13271 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
13272 } else if (VT.isVector()) {
13273 return SDValue();
13274 } else {
13275 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
13276 }
13277
13278 if (Scale == VTSize)
13279 // Result is just the top half since we'd be shifting by the width of the
13280 // operand. Overflow impossible so this works for both UMULFIX and
13281 // UMULFIXSAT.
13282 return Hi;
13283
13284 // The result will need to be shifted right by the scale since both operands
13285 // are scaled. The result is given to us in 2 halves, so we only want part of
13286 // both in the result.
13287 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
13288 DAG.getShiftAmountConstant(Scale, VT, dl));
13289 if (!Saturating)
13290 return Result;
13291
13292 if (!Signed) {
13293 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
13294 // widened multiplication) aren't all zeroes.
13295
13296 // Saturate to max if ((Hi >> Scale) != 0),
13297 // which is the same as if (Hi > ((1 << Scale) - 1))
13298 APInt MaxVal = APInt::getMaxValue(VTSize);
13299 SDValue LowMask =
13300 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
13301 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
13302 Result, ISD::SETUGT);
13303 }
13304
13305 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
13306 // widened multiplication) aren't all ones or all zeroes.
13307
13308 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
13309 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
13310
13311 if (Scale == 0) {
13312 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
13313 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
13314 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
13315 // Saturated to SatMin if wide product is negative, and SatMax if wide
13316 // product is positive ...
13317 SDValue Zero = DAG.getConstant(0, dl, VT);
13318 SDValue ResultIfOverflow =
13319 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
13320 // ... but only if we overflowed.
13321 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
13322 }
13323
13324 // We handled Scale==0 above so all the bits to examine is in Hi.
13325
13326 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
13327 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
13328 SDValue LowMask =
13329 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
13330 // Saturate to min if (Hi >> (Scale - 1)) < -1),
13331 // which is the same as if (HI < (-1 << (Scale - 1))
13332 SDValue HighMask = DAG.getConstant(
13333 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
13334 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
13335 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
13336 return Result;
13337}
13338
13339SDValue
13341 SDValue LHS, SDValue RHS,
13342 unsigned Scale, SelectionDAG &DAG) const {
13343 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
13344 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
13345 "Expected a fixed point division opcode");
13346
13347 EVT VT = LHS.getValueType();
13348 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
13349 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
13350 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13351
13352 // If there is enough room in the type to upscale the LHS or downscale the
13353 // RHS before the division, we can perform it in this type without having to
13354 // resize. For signed operations, the LHS headroom is the number of
13355 // redundant sign bits, and for unsigned ones it is the number of zeroes.
13356 // The headroom for the RHS is the number of trailing zeroes.
13357 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
13359 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
13360
13361 // For signed saturating operations, we need to be able to detect true integer
13362 // division overflow; that is, when you have MIN / -EPS. However, this
13363 // is undefined behavior and if we emit divisions that could take such
13364 // values it may cause undesired behavior (arithmetic exceptions on x86, for
13365 // example).
13366 // Avoid this by requiring an extra bit so that we never get this case.
13367 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13368 // signed saturating division, we need to emit a whopping 32-bit division.
13369 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13370 return SDValue();
13371
13372 unsigned LHSShift = std::min(LHSLead, Scale);
13373 unsigned RHSShift = Scale - LHSShift;
13374
13375 // At this point, we know that if we shift the LHS up by LHSShift and the
13376 // RHS down by RHSShift, we can emit a regular division with a final scaling
13377 // factor of Scale.
13378
13379 if (LHSShift)
13380 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13381 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13382 if (RHSShift)
13383 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13384 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13385
13386 SDValue Quot;
13387 if (Signed) {
13388 // For signed operations, if the resulting quotient is negative and the
13389 // remainder is nonzero, subtract 1 from the quotient to round towards
13390 // negative infinity.
13391 SDValue Rem;
13392 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13393 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13394 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13395 if (isTypeLegal(VT) &&
13397 Quot = DAG.getNode(ISD::SDIVREM, dl,
13398 DAG.getVTList(VT, VT),
13399 LHS, RHS);
13400 Rem = Quot.getValue(1);
13401 Quot = Quot.getValue(0);
13402 } else {
13403 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13404 LHS, RHS);
13405 Rem = DAG.getNode(ISD::SREM, dl, VT,
13406 LHS, RHS);
13407 }
13408 SDValue Zero = DAG.getConstant(0, dl, VT);
13409 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13410 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13411 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13412 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13413 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13414 DAG.getConstant(1, dl, VT));
13415 Quot = DAG.getSelect(dl, VT,
13416 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13417 Sub1, Quot);
13418 } else
13419 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13420 LHS, RHS);
13421
13422 return Quot;
13423}
13424
13426 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13427 SDLoc dl(Node);
13428 SDValue LHS = Node->getOperand(0);
13429 SDValue RHS = Node->getOperand(1);
13430 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13431
13432 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13433 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13434 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13435 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13436 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13437 { LHS, RHS, CarryIn });
13438 Result = SDValue(NodeCarry.getNode(), 0);
13439 Overflow = SDValue(NodeCarry.getNode(), 1);
13440 return;
13441 }
13442
13443 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13444 LHS.getValueType(), LHS, RHS);
13445
13446 EVT ResultType = Node->getValueType(1);
13447 EVT SetCCType = getSetCCResultType(
13448 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13449 SDValue SetCC;
13450 if (IsAdd && isOneConstant(RHS)) {
13451 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13452 // the live range of X. We assume comparing with 0 is cheap.
13453 // The general case (X + C) < C is not necessarily beneficial. Although we
13454 // reduce the live range of X, we may introduce the materialization of
13455 // constant C.
13456 SetCC =
13457 DAG.getSetCC(dl, SetCCType, Result,
13458 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13459 } else if (IsAdd && isAllOnesConstant(RHS)) {
13460 // Special case: uaddo X, -1 overflows if X != 0.
13461 SetCC =
13462 DAG.getSetCC(dl, SetCCType, LHS,
13463 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13464 } else {
13466 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13467 }
13468 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13469}
13470
13472 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13473 SDLoc dl(Node);
13474 SDValue LHS = Node->getOperand(0);
13475 SDValue RHS = Node->getOperand(1);
13476 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13477
13478 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13479 LHS.getValueType(), LHS, RHS);
13480
13481 EVT ResultType = Node->getValueType(1);
13482 EVT OType = getSetCCResultType(
13483 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13484
13485 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13486 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13487 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13488 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13489 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13490 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13491 return;
13492 }
13493
13494 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13495
13496 if (IsAdd) {
13497 // For an addition, the result should be less than one of the operands (LHS)
13498 // if and only if the other operand (RHS) is negative, otherwise there will
13499 // be overflow.
13500 SDValue ResultLowerThanLHS =
13501 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13502 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13503 Overflow = DAG.getBoolExtOrTrunc(
13504 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13505 ResultType, ResultType);
13506 } else {
13507 // For subtraction, overflow occurs when the signed comparison of operands
13508 // doesn't match the sign of the result.
13509 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13510 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13511 Overflow = DAG.getBoolExtOrTrunc(
13512 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13513 ResultType, ResultType);
13514 }
13515}
13516
13518 SDValue &Overflow, SelectionDAG &DAG) const {
13519 SDLoc dl(Node);
13520 EVT VT = Node->getValueType(0);
13521 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13522 SDValue LHS = Node->getOperand(0);
13523 SDValue RHS = Node->getOperand(1);
13524 bool isSigned = Node->getOpcode() == ISD::SMULO;
13525
13526 // For power-of-two multiplications we can use a simpler shift expansion.
13527 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13528 const APInt &C = RHSC->getAPIntValue();
13529 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13530 if (C.isPowerOf2()) {
13531 // smulo(x, signed_min) is same as umulo(x, signed_min).
13532 bool UseArithShift = isSigned && !C.isMinSignedValue();
13533 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13534 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13535 Overflow = DAG.getSetCC(dl, SetCCVT,
13536 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13537 dl, VT, Result, ShiftAmt),
13538 LHS, ISD::SETNE);
13539 return true;
13540 }
13541 }
13542
13543 SDValue BottomHalf;
13544 SDValue TopHalf;
13545 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13546
13547 static const unsigned Ops[2][3] =
13550 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13551 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13552 RHS);
13553 TopHalf = BottomHalf.getValue(1);
13554 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13555 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13556 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13557 } else if (isTypeLegal(WideVT)) {
13558 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13559 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13560 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13561 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13562 SDValue ShiftAmt =
13563 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13564 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13565 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13566 } else {
13567 if (VT.isVector())
13568 return false;
13569
13570 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13571 }
13572
13573 Result = BottomHalf;
13574 if (isSigned) {
13575 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13576 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13577 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13578 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13579 } else {
13580 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13581 DAG.getConstant(0, dl, VT), ISD::SETNE);
13582 }
13583
13584 // Truncate the result if SetCC returns a larger type than needed.
13585 EVT RType = Node->getValueType(1);
13586 if (RType.bitsLT(Overflow.getValueType()))
13587 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13588
13589 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13590 "Unexpected result type for S/UMULO legalization");
13591 return true;
13592}
13593
13595 SDLoc dl(Node);
13596 EVT VT = Node->getValueType(0);
13597 SDValue LHS = Node->getOperand(0);
13598 SDValue RHS = Node->getOperand(1);
13599 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13600
13601 // Use MUL_LOHI if legal/custom for the original type.
13602 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13603 if (isOperationLegalOrCustom(LoHiOp, VT))
13604 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13605
13606 // Use a wide multiply if available.
13607 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13608 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13609 unsigned BW = VT.getScalarSizeInBits();
13610 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13611 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13612 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13613 DAG.getNode(ISD::SRL, dl, WideVT,
13614 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13615 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13616 }
13617
13618 // Let fixed-length vectors be scalarised by the caller.
13619 // Expand everything else with a wide multiply.
13620 if (!VT.isFixedLengthVector()) {
13621 SDValue Lo, Hi;
13622 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13623 return Hi;
13624 }
13625
13626 return SDValue();
13627}
13628
13630 SDLoc dl(Node);
13631 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13632 SDValue Op = Node->getOperand(0);
13633 SDNodeFlags Flags = Node->getFlags();
13634 EVT VT = Op.getValueType();
13635
13636 // Try to use a shuffle reduction for power of two vectors.
13637 if (VT.isPow2VectorType()) {
13638 // See if the reduction opcode is safe to use with widened types.
13639 bool WidenSrc = false;
13640 switch (Node->getOpcode()) {
13643 case ISD::VECREDUCE_ADD:
13644 case ISD::VECREDUCE_MUL:
13645 case ISD::VECREDUCE_AND:
13646 case ISD::VECREDUCE_OR:
13647 case ISD::VECREDUCE_XOR:
13652 WidenSrc = VT.isFixedLengthVector();
13653 break;
13654 }
13655
13657 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13658 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13659 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13660 // Attempt to widen the source vectors to a legal op.
13661 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13662 if (WideVT.isVector() &&
13663 WideVT.getScalarType() == HalfVT.getScalarType() &&
13664 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13665 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13666 SDValue Lo, Hi;
13667 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13668 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13669 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13670 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13671 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13672 VT = HalfVT;
13673 continue;
13674 }
13675 }
13676 break;
13677 }
13678
13679 SDValue Lo, Hi;
13680 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13681 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13682 VT = HalfVT;
13683
13684 // Stop if splitting is enough to make the reduction legal.
13685 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13686 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13687 Flags);
13688 }
13689 }
13690
13691 if (VT.isScalableVector())
13693 "Expanding reductions for scalable vectors is undefined.");
13694
13695 EVT EltVT = VT.getVectorElementType();
13696 unsigned NumElts = VT.getVectorNumElements();
13697
13699 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13700
13701 SDValue Res = Ops[0];
13702 for (unsigned i = 1; i < NumElts; i++)
13703 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13704
13705 // Result type may be wider than element type.
13706 if (EltVT != Node->getValueType(0))
13707 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13708 return Res;
13709}
13710
13712 SDLoc dl(Node);
13713 SDValue AccOp = Node->getOperand(0);
13714 SDValue VecOp = Node->getOperand(1);
13715 SDNodeFlags Flags = Node->getFlags();
13716
13717 EVT VT = VecOp.getValueType();
13718 EVT EltVT = VT.getVectorElementType();
13719
13720 if (VT.isScalableVector())
13722 "Expanding reductions for scalable vectors is undefined.");
13723
13724 unsigned NumElts = VT.getVectorNumElements();
13725
13727 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13728
13729 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13730
13731 SDValue Res = AccOp;
13732 for (unsigned i = 0; i < NumElts; i++)
13733 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13734
13735 return Res;
13736}
13737
13739 SelectionDAG &DAG) const {
13740 EVT VT = Node->getValueType(0);
13741 SDLoc dl(Node);
13742 bool isSigned = Node->getOpcode() == ISD::SREM;
13743 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13744 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13745 SDValue Dividend = Node->getOperand(0);
13746 SDValue Divisor = Node->getOperand(1);
13747 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13748 SDVTList VTs = DAG.getVTList(VT, VT);
13749 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13750 return true;
13751 }
13752 if (isOperationLegalOrCustom(DivOpc, VT)) {
13753 // X % Y -> X-X/Y*Y
13754 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13755 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13756 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13757 return true;
13758 }
13759 return false;
13760}
13761
13763 SelectionDAG &DAG) const {
13764 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13765 SDLoc dl(SDValue(Node, 0));
13766 SDValue Src = Node->getOperand(0);
13767
13768 // DstVT is the result type, while SatVT is the size to which we saturate
13769 EVT SrcVT = Src.getValueType();
13770 EVT DstVT = Node->getValueType(0);
13771
13772 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13773 unsigned SatWidth = SatVT.getScalarSizeInBits();
13774 unsigned DstWidth = DstVT.getScalarSizeInBits();
13775 assert(SatWidth <= DstWidth &&
13776 "Expected saturation width smaller than result width");
13777
13778 // Determine minimum and maximum integer values and their corresponding
13779 // floating-point values.
13780 APInt MinInt, MaxInt;
13781 if (IsSigned) {
13782 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13783 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13784 } else {
13785 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13786 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13787 }
13788
13789 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13790 // libcall emission cannot handle this. Large result types will fail.
13791 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13792 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13793 SrcVT = Src.getValueType();
13794 }
13795
13796 const fltSemantics &Sem = SrcVT.getFltSemantics();
13797 APFloat MinFloat(Sem);
13798 APFloat MaxFloat(Sem);
13799
13800 APFloat::opStatus MinStatus =
13801 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13802 APFloat::opStatus MaxStatus =
13803 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13804 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13805 !(MaxStatus & APFloat::opStatus::opInexact);
13806
13807 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13808 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13809
13810 // If the integer bounds are exactly representable as floats and min/max are
13811 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13812 // of comparisons and selects.
13813 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13814 bool MayPropagateNaN) {
13815 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13816 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13817 if (!MinMaxLegal)
13818 return SDValue();
13819
13820 SDValue Clamped = Src;
13821
13822 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13823 // then the result is MinFloat.
13824 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13825 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13826 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13827 // Convert clamped value to integer.
13828 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13829 dl, DstVT, Clamped);
13830
13831 // If !MayPropagateNan and the conversion is unsigned case we're done,
13832 // because we mapped NaN to MinFloat, which will cast to zero.
13833 if (!MayPropagateNaN && !IsSigned)
13834 return FpToInt;
13835
13836 // Otherwise, select 0 if Src is NaN.
13837 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13838 EVT SetCCVT =
13839 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13840 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13841 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13842 };
13843 if (AreExactFloatBounds) {
13844 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13845 /*MayPropagateNaN=*/false))
13846 return Res;
13847 // These may propagate NaN for sNaN operands.
13848 if (SDValue Res =
13849 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13850 return Res;
13851 // These always propagate NaN.
13852 if (SDValue Res =
13853 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13854 return Res;
13855 }
13856
13857 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13858 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13859
13860 // Result of direct conversion. The assumption here is that the operation is
13861 // non-trapping and it's fine to apply it to an out-of-range value if we
13862 // select it away later.
13863 SDValue FpToInt =
13864 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13865
13866 SDValue Select = FpToInt;
13867
13868 EVT SetCCVT =
13869 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13870
13871 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13872 // MinInt if Src is NaN.
13873 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13874 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13875 // If Src OGT MaxFloat, select MaxInt.
13876 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13877 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13878
13879 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13880 // is already zero.
13881 if (!IsSigned)
13882 return Select;
13883
13884 // Otherwise, select 0 if Src is NaN.
13885 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13886 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13887 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13888}
13889
13891 const SDLoc &dl,
13892 SelectionDAG &DAG) const {
13893 EVT OperandVT = Op.getValueType();
13894 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13895 return Op;
13896 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13897 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13898 // can induce double-rounding which may alter the results. We can
13899 // correct for this using a trick explained in: Boldo, Sylvie, and
13900 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13901 // World Congress. 2005.
13902 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13903 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13904
13905 // We can keep the narrow value as-is if narrowing was exact (no
13906 // rounding error), the wide value was NaN (the narrow value is also
13907 // NaN and should be preserved) or if we rounded to the odd value.
13908 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13909 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13910 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13911 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13912 EVT ResultIntVTCCVT = getSetCCResultType(
13913 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13914 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13915 // The result is already odd so we don't need to do anything.
13916 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13917
13918 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13919 Op.getValueType());
13920 // We keep results which are exact, odd or NaN.
13921 SDValue KeepNarrow =
13922 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13923 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13924 // We morally performed a round-down if AbsNarrow is smaller than
13925 // AbsWide.
13926 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13927 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13928 SDValue NarrowIsRd =
13929 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13930 // If the narrow value is odd or exact, pick it.
13931 // Otherwise, narrow is even and corresponds to either the rounded-up
13932 // or rounded-down value. If narrow is the rounded-down value, we want
13933 // the rounded-up value as it will be odd.
13934 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13935 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13936 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13937 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13938}
13939
13941 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13942 SDValue Op = Node->getOperand(0);
13943 EVT VT = Node->getValueType(0);
13944 SDLoc dl(Node);
13945 if (VT.getScalarType() == MVT::bf16) {
13946 if (Node->getConstantOperandVal(1) == 1) {
13947 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13948 }
13949 EVT OperandVT = Op.getValueType();
13950
13951 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13952 // can induce double-rounding which may alter the results. We can
13953 // correct for this using a trick explained in: Boldo, Sylvie, and
13954 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13955 // World Congress. 2005.
13956 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
13957 EVT I32 = F32.changeTypeToInteger();
13958 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
13959 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
13960
13961 // Factor in the contribution of the low 16 bits.
13962 SDValue One = DAG.getConstant(1, dl, I32);
13963 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
13964 DAG.getShiftAmountConstant(16, I32, dl));
13965 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
13966 SDValue RoundingBias =
13967 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
13968 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
13969
13970 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
13971 // 0x80000000.
13972 if (!Node->getFlags().hasNoNaNs() &&
13973 !DAG.isKnownNeverNaN(Node->getOperand(0))) {
13974 // Conversions should set NaN's quiet bit. This also prevents NaNs from
13975 // turning into infinities.
13976 SDValue NaN =
13977 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
13978
13979 SDValue IsNaN = DAG.getSetCC(
13980 dl,
13981 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
13982 Node->getOperand(0), Node->getOperand(0), ISD::SETUO);
13983 Add = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
13984 }
13985
13986 // Now that we have rounded, shift the bits into position.
13987 Op = DAG.getNode(ISD::SRL, dl, I32, Add,
13988 DAG.getShiftAmountConstant(16, I32, dl));
13989 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
13990 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
13991 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13992 }
13993 return SDValue();
13994}
13995
13998 SelectionDAG &DAG) const {
13999 assert(Node->getOpcode() == ISD::VECTOR_INTERLEAVE && "Unexpected opcode");
14000 EVT VT = Node->getValueType(0);
14001 unsigned Factor = Node->getNumOperands();
14002 SDLoc DL(Node);
14003
14004 if (Factor > 2 && Factor % 2 == 0) {
14005 SmallVector<EVT> HalfVTs(Factor / 2, VT);
14006 SmallVector<SDValue, 8> LOps, ROps;
14007 // Interleave so we have 2 factors per result:
14008 // a0a1 b0b1 c0c1 d0d1 -> [a0c0 b0d0] [a1c1 b1d1]
14009 for (unsigned I = 0; I < Factor / 2; I++) {
14010 SDValue Interleave =
14011 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, {VT, VT},
14012 {Node->getOperand(I), Node->getOperand(I + Factor / 2)});
14013 LOps.push_back(Interleave.getValue(0));
14014 ROps.push_back(Interleave.getValue(1));
14015 }
14016 // Interleave at Factor/2:
14017 // [a0c0 b0d0] [a1c1 b1d1] -> a0b0 c0d0 a1b1 c1d1
14018 SDValue L = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, LOps);
14019 SDValue R = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, ROps);
14020 for (unsigned I = 0; I < Factor / 2; I++)
14021 Results.push_back(L.getValue(I));
14022 for (unsigned I = 0; I < Factor / 2; I++)
14023 Results.push_back(R.getValue(I));
14024 return;
14025 }
14026
14027 if (!VT.isFixedLengthVector())
14028 return;
14029
14030 unsigned NumElts = VT.getVectorNumElements();
14031 EVT EltVT = VT.getVectorElementType();
14032
14033 // A factor of two needs only same-width, two-input shuffles.
14034 if (Factor == 2) {
14035 SmallVector<int, 8> Mask = createInterleaveMask(NumElts, Factor);
14036 for (unsigned I = 0; I != Factor; ++I)
14037 Results.push_back(DAG.getVectorShuffle(
14038 VT, DL, Node->getOperand(0), Node->getOperand(1),
14039 ArrayRef<int>(Mask).slice(I * NumElts, NumElts)));
14040 return;
14041 }
14042
14043 SmallVector<SDValue> InterleavedElts;
14044 InterleavedElts.reserve(Factor * NumElts);
14045 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14046 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
14047 InterleavedElts.push_back(DAG.getExtractVectorElt(
14048 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
14049
14050 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx)
14051 Results.push_back(DAG.getBuildVector(
14052 VT, DL, ArrayRef(InterleavedElts).slice(ResultIdx * NumElts, NumElts)));
14053}
14054
14057 SelectionDAG &DAG) const {
14058 assert(Node->getOpcode() == ISD::VECTOR_DEINTERLEAVE && "Unexpected opcode");
14059 EVT VT = Node->getValueType(0);
14060 unsigned Factor = Node->getNumOperands();
14061 SDLoc DL(Node);
14062
14063 if (Factor > 2 && Factor % 2 == 0) {
14065 SmallVector<EVT> HalfVTs(Factor / 2, VT);
14066 // Deinterleave at Factor/2 so each result contains two factors interleaved:
14067 // a0b0 c0d0 a1b1 c1d1 -> [a0c0 b0d0] [a1c1 b1d1]
14068 SDValue L = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
14069 ArrayRef(Ops).take_front(Factor / 2));
14070 SDValue R = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
14071 ArrayRef(Ops).take_back(Factor / 2));
14072 Results.resize(Factor);
14073 // Deinterleave the 2 factors out:
14074 // [a0c0 a1c1] [b0d0 b1d1] -> a0a1 b0b1 c0c1 d0d1
14075 for (unsigned I = 0; I < Factor / 2; ++I) {
14077 {L.getValue(I), R.getValue(I)});
14078 Results[I] = Deinterleave.getValue(0);
14079 Results[I + Factor / 2] = Deinterleave.getValue(1);
14080 }
14081 return;
14082 }
14083
14084 if (!VT.isFixedLengthVector())
14085 return;
14086
14087 unsigned NumElts = VT.getVectorNumElements();
14088 EVT EltVT = VT.getVectorElementType();
14089
14090 // A factor of two needs only same-width, two-input shuffles.
14091 if (Factor == 2) {
14092 for (unsigned I = 0; I != Factor; ++I)
14093 Results.push_back(
14094 DAG.getVectorShuffle(VT, DL, Node->getOperand(0), Node->getOperand(1),
14095 createStrideMask(I, Factor, NumElts)));
14096 return;
14097 }
14098
14099 SmallVector<SDValue> ConcatElts;
14100 ConcatElts.reserve(Factor * NumElts);
14101 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
14102 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14103 ConcatElts.push_back(DAG.getExtractVectorElt(
14104 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
14105
14106 SmallVector<SDValue> DeinterleavedElts;
14107 DeinterleavedElts.reserve(Factor * NumElts);
14108 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx) {
14109 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14110 DeinterleavedElts.push_back(ConcatElts[ResultIdx + EltIdx * Factor]);
14111 Results.push_back(DAG.getBuildVector(
14112 VT, DL,
14113 ArrayRef(DeinterleavedElts).slice(ResultIdx * NumElts, NumElts)));
14114 }
14115}
14116
14118 SelectionDAG &DAG) const {
14119 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
14120 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
14121 "Unexpected opcode!");
14122 assert((Node->getValueType(0).isScalableVector() ||
14123 !isa<ConstantSDNode>(Node->getOperand(2))) &&
14124 "Fixed length vector types with constant offsets expected to use "
14125 "SHUFFLE_VECTOR!");
14126
14127 EVT VT = Node->getValueType(0);
14128 SDValue V1 = Node->getOperand(0);
14129 SDValue V2 = Node->getOperand(1);
14130 SDValue Offset = Node->getOperand(2);
14131 SDLoc DL(Node);
14132
14133 // Expand through memory thusly:
14134 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
14135 // Store V1, Ptr
14136 // Store V2, Ptr + sizeof(V1)
14137 // if (VECTOR_SPLICE_LEFT)
14138 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
14139 // else
14140 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
14141 // Res = Load Ptr
14142
14143 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
14144
14146 VT.getVectorElementCount() * 2);
14147 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
14148 EVT PtrVT = StackPtr.getValueType();
14149 auto &MF = DAG.getMachineFunction();
14150 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14151 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
14152
14153 // Store the lo part of CONCAT_VECTORS(V1, V2)
14154 SDValue StoreV1 =
14155 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
14156 // Store the hi part of CONCAT_VECTORS(V1, V2)
14157 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
14158 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
14159 SDValue StoreV2 =
14160 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
14161
14162 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
14163 SDValue EltByteSize =
14164 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
14165 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
14166 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
14167
14168 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
14169
14170 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
14171 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
14172 else
14173 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
14174
14175 // Load the spliced result
14176 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
14178}
14179
14181 SelectionDAG &DAG) const {
14182 SDLoc DL(Node);
14183 SDValue Vec = Node->getOperand(0);
14184 SDValue Mask = Node->getOperand(1);
14185 SDValue Passthru = Node->getOperand(2);
14186
14187 EVT VecVT = Vec.getValueType();
14188 EVT ScalarVT = VecVT.getScalarType();
14189 EVT MaskVT = Mask.getValueType();
14190 EVT MaskScalarVT = MaskVT.getScalarType();
14191
14192 // Needs to be handled by targets that have scalable vector types.
14193 if (VecVT.isScalableVector())
14194 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
14195
14196 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
14197 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
14198 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14199 MachinePointerInfo PtrInfo =
14201
14202 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
14203 SDValue Chain = DAG.getEntryNode();
14204 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
14205
14206 bool HasPassthru = !Passthru.isUndef();
14207
14208 // If we have a passthru vector, store it on the stack, overwrite the matching
14209 // positions and then re-write the last element that was potentially
14210 // overwritten even though mask[i] = false.
14211 if (HasPassthru)
14212 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
14213
14214 SDValue LastWriteVal;
14215 APInt PassthruSplatVal;
14216 bool IsSplatPassthru =
14217 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal);
14218
14219 if (IsSplatPassthru) {
14220 // As we do not know which position we wrote to last, we cannot simply
14221 // access that index from the passthru vector. So we first check if passthru
14222 // is a splat vector, to use any element ...
14223 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
14224 } else if (HasPassthru) {
14225 // ... if it is not a splat vector, we need to get the passthru value at
14226 // position = popcount(mask) and re-load it from the stack before it is
14227 // overwritten in the loop below.
14228 EVT PopcountVT = ScalarVT.changeTypeToInteger();
14229 SDValue Popcount = DAG.getNode(
14231 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
14232 Popcount = DAG.getNode(
14234 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
14235 Popcount);
14236 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
14237 SDValue LastElmtPtr =
14238 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
14239 LastWriteVal = DAG.getLoad(
14240 ScalarVT, DL, Chain, LastElmtPtr,
14242 Chain = LastWriteVal.getValue(1);
14243 }
14244
14245 unsigned NumElms = VecVT.getVectorNumElements();
14246 for (unsigned I = 0; I < NumElms; I++) {
14247 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
14248 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14249 Chain = DAG.getStore(
14250 Chain, DL, ValI, OutPtr,
14252
14253 // Get the mask value and add it to the current output position. This
14254 // either increments by 1 if MaskI is true or adds 0 otherwise.
14255 // Freeze in case we have poison/undef mask entries.
14256 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
14257 MaskI = DAG.getFreeze(MaskI);
14258 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
14259 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
14260 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
14261
14262 if (HasPassthru && I == NumElms - 1) {
14263 SDValue EndOfVector =
14264 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
14265 SDValue AllLanesSelected =
14266 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
14267 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
14268 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14269
14270 // Re-write the last ValI if all lanes were selected. Otherwise,
14271 // overwrite the last write it with the passthru value.
14272 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
14273 LastWriteVal, SDNodeFlags::Unpredictable);
14274 Chain = DAG.getStore(
14275 Chain, DL, LastWriteVal, OutPtr,
14277 }
14278 }
14279
14280 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
14281}
14282
14284 SDLoc DL(Node);
14285 EVT VT = Node->getValueType(0);
14286 SDValue Op = Node->getOperand(0);
14287 ElementCount EC = Op.getValueType().getVectorElementCount();
14288
14289 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
14290 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
14291
14292 // No legal step vector: split mask in half and recombine results.
14293 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
14294 // (== LoNumElts when no active lane), allowing the SETNE comparison.
14295 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
14296 if (!StepVec) {
14297 EVT ResVT = Node->getValueType(0);
14298 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
14299 SDValue LoNumElts = DAG.getElementCount(
14300 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
14301 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
14302 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
14303 SDValue ResLoNotNumElts = DAG.getSetCC(
14304 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
14305 ResLo, LoNumElts, ISD::SETNE);
14306 // Per LangRef, ResVT must be wide enough to hold the total element count,
14307 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
14308 // the count is only required to fit unsigned.
14309 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
14311 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
14312 }
14313
14314 EVT StepVecVT = StepVec.getValueType();
14315 EVT StepVT = StepVecVT.getVectorElementType();
14316
14317 // Promote the scalar result type early to avoid redundant zexts.
14319 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
14320
14321 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
14322 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
14323 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
14324 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
14325 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
14327 StepVecVT.getVectorElementType(), Select);
14328 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
14329 DAG.getZExtOrTrunc(Max, DL, StepVT));
14330
14331 return DAG.getZExtOrTrunc(Sub, DL, VT);
14332}
14333
14335 SDLoc DL(N);
14336 SDValue Source = N->getOperand(0);
14337 SDValue Needle = N->getOperand(1);
14338 SDValue Mask = N->getOperand(2);
14339 EVT SourceVT = Source.getValueType();
14340 EVT NeedleVT = Needle.getValueType();
14341 EVT ResVT = N->getValueType(0);
14342 EVT CmpVT =
14343 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
14344
14345 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
14346
14347 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
14348 EVT NeedleEltVT = NeedleVT.getVectorElementType();
14349 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
14350 SDValue Splat;
14351 if (NeedleVT == SourceVT) {
14352 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
14353 Splat = DAG.getVectorShuffle(
14354 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
14356 } else {
14357 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
14358 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
14359 }
14360 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
14361 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
14362 }
14363
14364 EVT UseVT = ResVT;
14365 // If the result is immediately truncated, only extend to that type (to avoid
14366 // unnecessary sign/zero extends).
14367 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
14368 UseVT = N->user_begin()->getValueType(0);
14369
14370 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
14371 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
14372
14373 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
14374 if (UseVT != ResVT)
14375 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
14376 return Ret;
14377}
14378
14380 SelectionDAG &DAG) const {
14381 SDLoc DL(N);
14382 SDValue Acc = N->getOperand(0);
14383 SDValue MulLHS = N->getOperand(1);
14384 SDValue MulRHS = N->getOperand(2);
14385 EVT AccVT = Acc.getValueType();
14386 EVT MulOpVT = MulLHS.getValueType();
14387
14388 EVT ExtMulOpVT =
14390 MulOpVT.getVectorElementCount());
14391
14392 unsigned ExtOpcLHS, ExtOpcRHS;
14393 switch (N->getOpcode()) {
14394 default:
14395 llvm_unreachable("Unexpected opcode");
14397 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
14398 break;
14400 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
14401 break;
14403 ExtOpcLHS = ISD::SIGN_EXTEND;
14404 ExtOpcRHS = ISD::ZERO_EXTEND;
14405 break;
14407 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
14408 break;
14409 }
14410
14411 // A wide partial reduction is built from a ladder of narrower ones, a rung
14412 // at a time, each halving the element count and doubling the width.
14413 unsigned Opc = N->getOpcode();
14414 ElementCount MulEC = MulOpVT.getVectorElementCount();
14415 ElementCount AccEC = AccVT.getVectorElementCount();
14416 unsigned CountRatio =
14417 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
14418 unsigned WidthRatio =
14419 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
14420 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
14421 LLVMContext &Ctx = *DAG.getContext();
14422 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
14423
14424 // A pure reduction peels one rung and re-enters.
14425 if (llvm::isOneOrOneSplat(MulRHS)) {
14426 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
14427 return DAG.getNode(Opc, DL, AccVT, Acc,
14428 DAG.getNode(Opc, DL, RungVT,
14429 DAG.getConstant(0, DL, RungVT), MulLHS,
14430 MulRHS),
14431 DAG.getConstant(1, DL, RungVT));
14432 }
14433
14434 // A multiply widens the products by one rung, which legalizes back into a
14435 // widening multiply per half, and the ladder re-enters as a plain sum.
14436 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
14437 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
14438 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
14439 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
14440 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
14441
14442 // The halves meet at the narrowest rung, so the accumulator is added once.
14443 EVT MidVT = Lo.getValueType()
14444 .widenIntegerVectorElementType(Ctx)
14445 .getHalfNumVectorElementsVT(Ctx);
14447 return DAG.getNode(Opc, DL, AccVT,
14448 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
14449 SDValue Mid =
14450 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
14451 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
14452 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
14453 }
14454
14455 if (ExtMulOpVT != MulOpVT) {
14456 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
14457 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
14458 }
14459 SDValue Input = MulLHS;
14460 // Maintain the FP flags (if any).
14461 SDNodeFlags Flags = N->getFlags();
14462 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
14463 if (!llvm::isOneOrOneSplatFP(MulRHS))
14464 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS, Flags);
14465 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
14466 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14467 }
14468
14469 unsigned Stride = AccVT.getVectorMinNumElements();
14470 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
14471
14472 // Collect all of the subvectors
14473 std::deque<SDValue> Subvectors = {Acc};
14474 for (unsigned I = 0; I < ScaleFactor; I++)
14475 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
14476
14477 unsigned FlatNode =
14478 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
14479
14480 // Flatten the subvector tree
14481 while (Subvectors.size() > 1) {
14482 Subvectors.push_back(DAG.getNode(FlatNode, DL, AccVT,
14483 {Subvectors[0], Subvectors[1]}, Flags));
14484 Subvectors.pop_front();
14485 Subvectors.pop_front();
14486 }
14487
14488 assert(Subvectors.size() == 1 &&
14489 "There should only be one subvector after tree flattening");
14490
14491 return Subvectors[0];
14492}
14493
14494/// Given a store node \p StoreNode, return true if it is safe to fold that node
14495/// into \p FPNode, which expands to a library call with output pointers.
14497 SDNode *FPNode) {
14499 SmallVector<const SDNode *, 8> DeferredNodes;
14501
14502 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
14503 for (SDValue Op : StoreNode->ops())
14504 if (Op.getNode() != FPNode)
14505 Worklist.push_back(Op.getNode());
14506
14508 while (!Worklist.empty()) {
14509 const SDNode *Node = Worklist.pop_back_val();
14510 auto [_, Inserted] = Visited.insert(Node);
14511 if (!Inserted)
14512 continue;
14513
14514 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
14515 return false;
14516
14517 // Reached the FPNode (would result in a cycle).
14518 // OR Reached CALLSEQ_START (would result in nested call sequences).
14519 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
14520 return false;
14521
14522 if (Node->getOpcode() == ISD::CALLSEQ_END) {
14523 // Defer looking into call sequences (so we can check we're outside one).
14524 // We still need to look through these for the predecessor check.
14525 DeferredNodes.push_back(Node);
14526 continue;
14527 }
14528
14529 for (SDValue Op : Node->ops())
14530 Worklist.push_back(Op.getNode());
14531 }
14532
14533 // True if we're outside a call sequence and don't have the FPNode as a
14534 // predecessor. No cycles or nested call sequences possible.
14535 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
14536 MaxSteps);
14537}
14538
14540 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
14542 std::optional<unsigned> CallRetResNo) const {
14543 if (LC == RTLIB::UNKNOWN_LIBCALL)
14544 return false;
14545
14546 RTLIB::LibcallImpl LibcallImpl =
14548 if (LibcallImpl == RTLIB::Unsupported)
14549 return false;
14550
14551 LLVMContext &Ctx = *DAG.getContext();
14552 EVT VT = Node->getValueType(0);
14553 unsigned NumResults = Node->getNumValues();
14554
14555 // Find users of the node that store the results (and share input chains). The
14556 // destination pointers can be used instead of creating stack allocations.
14557 SDValue StoresInChain;
14558 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
14559 for (SDNode *User : Node->users()) {
14561 continue;
14562 auto *ST = cast<StoreSDNode>(User);
14563 SDValue StoreValue = ST->getValue();
14564 unsigned ResNo = StoreValue.getResNo();
14565 // Ensure the store corresponds to an output pointer.
14566 if (CallRetResNo == ResNo)
14567 continue;
14568 // Ensure the store to the default address space and not atomic or volatile.
14569 if (!ST->isSimple() || ST->getAddressSpace() != 0)
14570 continue;
14571 // Ensure all store chains are the same (so they don't alias).
14572 if (StoresInChain && ST->getChain() != StoresInChain)
14573 continue;
14574 // Ensure the store is properly aligned.
14575 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
14576 if (ST->getAlign() <
14577 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
14578 continue;
14579 // Avoid:
14580 // 1. Creating cyclic dependencies.
14581 // 2. Expanding the node to a call within a call sequence.
14583 continue;
14584 ResultStores[ResNo] = ST;
14585 StoresInChain = ST->getChain();
14586 }
14587
14588 ArgListTy Args;
14589
14590 // Pass the arguments.
14591 for (const SDValue &Op : Node->op_values()) {
14592 EVT ArgVT = Op.getValueType();
14593 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
14594 Args.emplace_back(Op, ArgTy);
14595 }
14596
14597 // Pass the output pointers.
14598 SmallVector<SDValue, 2> ResultPtrs(NumResults);
14600 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
14601 if (ResNo == CallRetResNo)
14602 continue;
14603 EVT ResVT = Node->getValueType(ResNo);
14604 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
14605 ResultPtrs[ResNo] = ResultPtr;
14606 Args.emplace_back(ResultPtr, PointerTy);
14607 }
14608
14609 SDLoc DL(Node);
14610
14612 // Pass the vector mask (if required).
14613 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
14614 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
14615 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14616 }
14617
14618 Type *RetType = CallRetResNo.has_value()
14619 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14620 : Type::getVoidTy(Ctx);
14621 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14622 SDValue Callee =
14623 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14625 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14626 DAG.getLibcalls().getLibcallImplCallingConv(LibcallImpl), RetType, Callee,
14627 std::move(Args));
14628
14629 auto [Call, CallChain] = LowerCallTo(CLI);
14630
14631 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14632 if (ResNo == CallRetResNo) {
14633 Results.push_back(Call);
14634 continue;
14635 }
14636 MachinePointerInfo PtrInfo;
14637 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14638 ResultPtr, PtrInfo);
14639 SDValue OutChain = LoadResult.getValue(1);
14640
14641 if (StoreSDNode *ST = ResultStores[ResNo]) {
14642 // Replace store with the library call.
14643 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14644 PtrInfo = ST->getPointerInfo();
14645 } else {
14647 DAG.getMachineFunction(),
14648 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14649 }
14650
14651 Results.push_back(LoadResult);
14652 }
14653
14654 return true;
14655}
14656
14658 SDValue &LHS, SDValue &RHS,
14659 SDValue &CC, bool &NeedInvert,
14660 const SDLoc &dl, SDValue &Chain,
14661 bool IsSignaling) const {
14662 MVT OpVT = LHS.getSimpleValueType();
14663 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14664 NeedInvert = false;
14665 switch (getCondCodeAction(CCCode, OpVT)) {
14666 default:
14667 llvm_unreachable("Unknown condition code action!");
14669 // Nothing to do.
14670 break;
14673 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14674 std::swap(LHS, RHS);
14675 CC = DAG.getCondCode(InvCC);
14676 return true;
14677 }
14678 // Swapping operands didn't work. Try inverting the condition.
14679 bool NeedSwap = false;
14680 InvCC = getSetCCInverse(CCCode, OpVT);
14681 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14682 // If inverting the condition is not enough, try swapping operands
14683 // on top of it.
14684 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14685 NeedSwap = true;
14686 }
14687 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14688 CC = DAG.getCondCode(InvCC);
14689 NeedInvert = true;
14690 if (NeedSwap)
14691 std::swap(LHS, RHS);
14692 return true;
14693 }
14694
14695 // Special case: expand i1 comparisons using logical operations.
14696 if (OpVT == MVT::i1) {
14697 SDValue Ret;
14698 switch (CCCode) {
14699 default:
14700 llvm_unreachable("Unknown integer setcc!");
14701 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14702 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14703 MVT::i1);
14704 break;
14705 case ISD::SETNE: // X != Y --> (X ^ Y)
14706 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14707 break;
14708 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14709 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14710 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14711 DAG.getNOT(dl, LHS, MVT::i1));
14712 break;
14713 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14714 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14715 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14716 DAG.getNOT(dl, RHS, MVT::i1));
14717 break;
14718 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14719 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14720 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14721 DAG.getNOT(dl, LHS, MVT::i1));
14722 break;
14723 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14724 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14725 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14726 DAG.getNOT(dl, RHS, MVT::i1));
14727 break;
14728 }
14729
14730 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14731 RHS = SDValue();
14732 CC = SDValue();
14733 return true;
14734 }
14735
14737 unsigned Opc = 0;
14738 switch (CCCode) {
14739 default:
14740 llvm_unreachable("Don't know how to expand this condition!");
14741 case ISD::SETUO:
14742 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14743 CC1 = ISD::SETUNE;
14744 CC2 = ISD::SETUNE;
14745 Opc = ISD::OR;
14746 break;
14747 }
14749 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14750 NeedInvert = true;
14751 [[fallthrough]];
14752 case ISD::SETO:
14754 "If SETO is expanded, SETOEQ must be legal!");
14755 CC1 = ISD::SETOEQ;
14756 CC2 = ISD::SETOEQ;
14757 Opc = ISD::AND;
14758 break;
14759 case ISD::SETONE:
14760 case ISD::SETUEQ:
14761 // If the SETUO or SETO CC isn't legal, we might be able to use
14762 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14763 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14764 // the operands.
14765 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14766 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14767 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14768 CC1 = ISD::SETOGT;
14769 CC2 = ISD::SETOLT;
14770 Opc = ISD::OR;
14771 NeedInvert = ((unsigned)CCCode & 0x8U);
14772 break;
14773 }
14774 [[fallthrough]];
14775 case ISD::SETOEQ:
14776 case ISD::SETOGT:
14777 case ISD::SETOGE:
14778 case ISD::SETOLT:
14779 case ISD::SETOLE:
14780 case ISD::SETUNE:
14781 case ISD::SETUGT:
14782 case ISD::SETUGE:
14783 case ISD::SETULT:
14784 case ISD::SETULE:
14785 // If we are floating point, assign and break, otherwise fall through.
14786 if (!OpVT.isInteger()) {
14787 // We can use the 4th bit to tell if we are the unordered
14788 // or ordered version of the opcode.
14789 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14790 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14791 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14792 break;
14793 }
14794 // Fallthrough if we are unsigned integer.
14795 [[fallthrough]];
14796 case ISD::SETLE:
14797 case ISD::SETGT:
14798 case ISD::SETGE:
14799 case ISD::SETLT:
14800 case ISD::SETNE:
14801 case ISD::SETEQ:
14802 // If all combinations of inverting the condition and swapping operands
14803 // didn't work then we have no means to expand the condition.
14804 llvm_unreachable("Don't know how to expand this condition!");
14805 }
14806
14807 SDValue SetCC1, SetCC2;
14808 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14809 // If we aren't the ordered or unorder operation,
14810 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14811 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14812 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14813 } else {
14814 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14815 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14816 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14817 }
14818 if (Chain)
14819 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14820 SetCC2.getValue(1));
14821 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14822 RHS = SDValue();
14823 CC = SDValue();
14824 return true;
14825 }
14826 }
14827 return false;
14828}
14829
14831 SelectionDAG &DAG) const {
14832 EVT VT = Node->getValueType(0);
14833 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14834 // split into two equal parts.
14835 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14836 return SDValue();
14837
14838 // Restrict expansion to cases where both parts can be concatenated.
14839 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14840 if (LoVT != HiVT || !isTypeLegal(LoVT))
14841 return SDValue();
14842
14843 SDLoc DL(Node);
14844 unsigned Opcode = Node->getOpcode();
14845
14846 // Don't expand if the result is likely to be unrolled anyway.
14847 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14848 return SDValue();
14849
14850 SmallVector<SDValue, 4> LoOps, HiOps;
14851 for (const SDValue &V : Node->op_values()) {
14852 if (!V.getValueType().isVector()) {
14853 // Scalar operands pass through to both halves unchanged.
14854 LoOps.push_back(V);
14855 HiOps.push_back(V);
14856 continue;
14857 }
14858 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14859 LoOps.push_back(Lo);
14860 HiOps.push_back(Hi);
14861 }
14862
14863 bool IsStrict = Node->isStrictFPOpcode();
14864 SDVTList LoVTs =
14865 IsStrict ? DAG.getVTList(LoVT, MVT::Other) : DAG.getVTList(LoVT);
14866 SDVTList HiVTs =
14867 IsStrict ? DAG.getVTList(HiVT, MVT::Other) : DAG.getVTList(HiVT);
14868 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVTs, LoOps, Node->getFlags());
14869 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVTs, HiOps, Node->getFlags());
14870 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14871
14872 if (!IsStrict)
14873 return Res;
14874
14875 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14876 SplitOpLo.getValue(1), SplitOpHi.getValue(1));
14877 return DAG.getMergeValues({Res, Chain}, DL);
14878}
14879
14881 const SDLoc &DL,
14882 EVT InVecVT, SDValue EltNo,
14883 LoadSDNode *OriginalLoad,
14884 SelectionDAG &DAG) const {
14885 assert(OriginalLoad->isSimple());
14886
14887 EVT VecEltVT = InVecVT.getVectorElementType();
14888
14889 // If the vector element type is not a multiple of a byte then we are unable
14890 // to correctly compute an address to load only the extracted element as a
14891 // scalar.
14892 if (!VecEltVT.isByteSized())
14893 return SDValue();
14894
14895 ISD::LoadExtType ExtTy =
14896 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14897 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14898 return SDValue();
14899
14900 std::optional<unsigned> ByteOffset;
14901 Align Alignment = OriginalLoad->getAlign();
14903 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14904 int Elt = ConstEltNo->getZExtValue();
14905 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14906 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14907 Alignment = commonAlignment(Alignment, *ByteOffset);
14908 } else {
14909 // Discard the pointer info except the address space because the memory
14910 // operand can't represent this new access since the offset is variable.
14911 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14912 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14913 }
14914
14915 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14916 return SDValue();
14917
14918 unsigned IsFast = 0;
14919 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14920 OriginalLoad->getAddressSpace(), Alignment,
14921 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14922 !IsFast)
14923 return SDValue();
14924
14925 // The original DAG loaded the entire vector from memory, so arithmetic
14926 // within it must be inbounds.
14928 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
14929
14930 // We are replacing a vector load with a scalar load. The new load must have
14931 // identical memory op ordering to the original.
14932 SDValue Load;
14933 if (ResultVT.bitsGT(VecEltVT)) {
14934 // If the result type of vextract is wider than the load, then issue an
14935 // extending load instead.
14936 ISD::LoadExtType ExtType =
14937 isLoadLegal(ResultVT, VecEltVT, Alignment,
14938 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
14940 : ISD::EXTLOAD;
14941 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
14942 NewPtr, MPI, VecEltVT, Alignment,
14943 OriginalLoad->getMemOperand()->getFlags(),
14944 OriginalLoad->getMMOMetadataForSubAccess());
14945 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14946 } else {
14947 // The result type is narrower or the same width as the vector element
14948 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
14949 Alignment, OriginalLoad->getMemOperand()->getFlags(),
14950 OriginalLoad->getMMOMetadataForSubAccess());
14951 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14952 if (ResultVT.bitsLT(VecEltVT))
14953 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
14954 else
14955 Load = DAG.getBitcast(ResultVT, Load);
14956 }
14957
14958 return Load;
14959}
14960
14961// Set type id for call site info and metadata 'call_target'.
14962// We are filtering for:
14963// a) The call-graph-section use case that wants to know about indirect
14964// calls, or
14965// b) We want to annotate indirect calls.
14967 const CallBase *CB, MachineFunction &MF,
14968 MachineFunction::CallSiteInfo &CSInfo) const {
14969 if (CB && CB->isIndirectCall() &&
14972 CSInfo = MachineFunction::CallSiteInfo(*CB);
14973}
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 _
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:540
#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 cl::opt< unsigned > MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192), cl::desc("DAG combiner limit number of steps when searching DAG " "for predecessor nodes"))
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 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 bool canFoldStoreIntoLibCallOutputPointers(StoreSDNode *StoreNode, SDNode *FPNode)
Given a store node StoreNode, return true if it is safe to fold that node into FPNode,...
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:136
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:343
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:364
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:399
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:339
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:335
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:376
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1451
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1262
APInt bitcastToAPInt() const
Definition APFloat.h:1475
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
void changeSign()
Definition APFloat.h:1401
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1213
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1360
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1416
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:836
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
void negate()
Negate this APInt in place.
Definition APInt.h:1488
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
unsigned countLeadingZeros() const
Definition APInt.h:1626
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1472
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1455
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
void setAllBits()
Set every bit to 1.
Definition APInt.h:1339
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool isMask(unsigned numBits) const
Definition APInt.h:484
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1387
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1437
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1408
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
void clearHighBits(unsigned hiBits)
Set top hiBits bits to 0.
Definition APInt.h:1462
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1676
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
void setBitVal(unsigned BitPosition, bool BitValue)
Set a given bit to a given value.
Definition APInt.h:1363
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
@ None
No attributes have been set.
Definition Attributes.h:127
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI ConstantSDNode * getConstantSplatNode(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted constant or null if this is not a constant splat.
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This class represents a range of values.
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:217
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:104
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
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:83
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:526
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:887
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 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 getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
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.
static LLVM_ABI unsigned getHasPredecessorMaxSteps()
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
bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth=0) const
Return true if this function can prove that Op is never poison.
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 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
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:26
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:597
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.
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
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.
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 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:870
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:299
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
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:3043
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:845
@ 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:733
@ 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:805
@ 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:879
@ 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:906
@ 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
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:765
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:936
@ 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:796
@ 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:814
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:725
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:675
@ 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:822
@ 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:682
@ 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:714
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ 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:876
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:837
@ 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:663
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:925
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:914
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:745
@ 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:831
@ 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:801
@ 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:952
@ 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:757
@ 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:720
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:667
@ 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:813
@ 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:985
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:947
@ 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:971
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:882
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:859
@ 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:740
@ 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:769
@ 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 bool isBuildVectorOfConstantSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantSDNode or undef.
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 bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
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 isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
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:2570
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:977
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:1742
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:1001
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
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#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
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:559
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:563
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:61
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:1039
fltNanEncoding nanEncoding
Definition APFloat.h:1041