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
225/// Generate a libcall taking the given operands as arguments and returning a
226/// result of type RetVT.
227std::pair<SDValue, SDValue>
228TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl,
230 MakeLibCallOptions CallOptions, const SDLoc &dl,
231 SDValue InChain) const {
232 if (LibcallImpl == RTLIB::Unsupported)
233 reportFatalInternalError("unsupported library call operation");
234
235 if (!InChain)
236 InChain = DAG.getEntryNode();
237
239 Args.reserve(Ops.size());
240
241 ArrayRef<Type *> OpsTypeOverrides = CallOptions.OpsTypeOverrides;
242 for (unsigned i = 0; i < Ops.size(); ++i) {
243 SDValue NewOp = Ops[i];
244 Type *Ty = i < OpsTypeOverrides.size() && OpsTypeOverrides[i]
245 ? OpsTypeOverrides[i]
246 : NewOp.getValueType().getTypeForEVT(*DAG.getContext());
247 TargetLowering::ArgListEntry Entry(NewOp, Ty);
248 if (CallOptions.IsSoften)
249 Entry.OrigTy =
250 CallOptions.OpsVTBeforeSoften[i].getTypeForEVT(*DAG.getContext());
251
252 Entry.IsSExt =
253 shouldSignExtendTypeInLibCall(Entry.Ty, CallOptions.IsSigned);
254 Entry.IsZExt = !Entry.IsSExt;
255
256 if (CallOptions.IsSoften &&
258 Entry.IsSExt = Entry.IsZExt = false;
259 }
260 Args.push_back(Entry);
261 }
262
263 SDValue Callee =
264 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
265
266 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
267 Type *OrigRetTy = RetTy;
269 bool signExtend = shouldSignExtendTypeInLibCall(RetTy, CallOptions.IsSigned);
270 bool zeroExtend = !signExtend;
271
272 if (CallOptions.IsSoften) {
273 OrigRetTy = CallOptions.RetVTBeforeSoften.getTypeForEVT(*DAG.getContext());
275 signExtend = zeroExtend = false;
276 }
277
278 CLI.setDebugLoc(dl)
279 .setChain(InChain)
280 .setLibCallee(getLibcallImplCallingConv(LibcallImpl), RetTy, OrigRetTy,
281 Callee, std::move(Args))
282 .setNoReturn(CallOptions.DoesNotReturn)
285 .setSExtResult(signExtend)
286 .setZExtResult(zeroExtend);
287 return LowerCallTo(CLI);
288}
289
291 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
292 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
293 const AttributeList &FuncAttributes, EVT *LargestVT) const {
294 EVT VT = getOptimalMemOpType(Context, Op, FuncAttributes);
295
296 if (VT == MVT::Other) {
297 // Use the largest integer type whose alignment constraints are satisfied.
298 VT = MVT::LAST_INTEGER_VALUETYPE;
299 if (Op.isFixedDstAlign()) {
300 bool LoadsFromSrc = Op.isMemcpyOrMemmove() && !Op.isMemcpyStrSrc();
301 while (VT != MVT::i8) {
302 unsigned VTSize = VT.getSizeInBits() / 8;
303 bool DstOk =
304 Op.getDstAlign() >= VTSize ||
305 allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign());
306 bool SrcOk =
307 !LoadsFromSrc || Op.getSrcAlign() >= VTSize ||
308 allowsMisalignedMemoryAccesses(VT, SrcAS, Op.getSrcAlign());
309 if (DstOk && SrcOk)
310 break;
312 }
313 }
314 assert(VT.isInteger());
315
316 // Find the largest legal integer type.
317 MVT LVT = MVT::LAST_INTEGER_VALUETYPE;
318 while (!isTypeLegal(LVT))
319 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
320 assert(LVT.isInteger());
321
322 // If the type we've chosen is larger than the largest legal integer type
323 // then use the largest legal type.
324 if (VT.bitsGT(LVT))
325 VT = LVT;
326 }
327
328 unsigned NumMemOps = 0;
329 uint64_t Size = Op.size();
330 while (Size) {
331 unsigned VTSize = VT.getSizeInBits() / 8;
332 while (VTSize > Size) {
333 // For now, only use non-vector load / store's for the left-over pieces.
334 EVT NewVT = VT;
335 unsigned NewVTSize;
336
337 bool Found = false;
338 if (VT.isVector() || VT.isFloatingPoint()) {
339 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
342 Found = true;
343 else if (NewVT == MVT::i64 &&
345 isSafeMemOpType(MVT::f64)) {
346 // i64 is usually not legal on 32-bit targets, but f64 may be.
347 NewVT = MVT::f64;
348 Found = true;
349 }
350 }
351
352 if (!Found) {
353 do {
354 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
355 if (NewVT == MVT::i8)
356 break;
357 } while (!isSafeMemOpType(NewVT.getSimpleVT()));
358 }
359 NewVTSize = NewVT.getSizeInBits() / 8;
360
361 // If the new VT cannot cover all of the remaining bits, then consider
362 // issuing a (or a pair of) unaligned and overlapping load / store.
363 unsigned Fast;
364 if (NumMemOps && !Op.isVolatile() && NewVTSize < Size &&
366 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
368 Fast)
369 VTSize = Size;
370 else {
371 VT = NewVT;
372 VTSize = NewVTSize;
373 }
374 }
375
376 if (++NumMemOps > Limit)
377 return false;
378
379 MemOps.push_back(VT);
380 Size -= VTSize;
381 }
382
383 return true;
384}
385
386/// Soften the operands of a comparison. This code is shared among BR_CC,
387/// SELECT_CC, and SETCC handlers.
389 SDValue &NewLHS, SDValue &NewRHS,
390 ISD::CondCode &CCCode,
391 const SDLoc &dl, const SDValue OldLHS,
392 const SDValue OldRHS) const {
393 SDValue Chain;
394 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
395 OldRHS, Chain);
396}
397
398/// Select the libcall and the condition code to test its result against 0 for
399/// an ordered floating-point compare. \p BoolLC is the boolean helper (result
400/// is 0/1). \p TriStateLC is the per-predicate three-way helper and \p
401/// GenericLC the generic single-symbol three-way helper (both return -1/0/1,
402/// tested against 0 with \p TriStateCC). The boolean form is preferred, then
403/// the per-predicate three-way, then the generic three-way.
404static std::pair<RTLIB::Libcall, ISD::CondCode>
405selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC,
406 RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC,
407 ISD::CondCode TriStateCC) {
408 if (Libcalls.getLibcallImpl(BoolLC) != RTLIB::Unsupported)
409 return {BoolLC, ISD::SETNE};
410 if (Libcalls.getLibcallImpl(TriStateLC) != RTLIB::Unsupported)
411 return {TriStateLC, TriStateCC};
412 return {GenericLC, TriStateCC};
413}
414
416 SDValue &NewLHS, SDValue &NewRHS,
417 ISD::CondCode &CCCode,
418 const SDLoc &dl, const SDValue OldLHS,
419 const SDValue OldRHS,
420 SDValue &Chain,
421 bool IsSignaling) const {
422 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
423 // not supporting it. We can update this code when libgcc provides such
424 // functions.
425
426 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
427 && "Unsupported setcc type!");
428
429 // Expand into one or more soft-fp libcall(s).
430 ISD::CondCode OrigCCCode = CCCode;
431 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
433 bool ShouldInvertCC = false;
434
435 // Expand a compare libcall family name (e.g. OEQ, FCMP3_PRED_OEQ) to the
436 // RTLIB::Libcall for VT.
437#define FP_CMP_LIBCALL(BASE) \
438 RTLIB::getFPLibCall(VT, RTLIB::BASE##_F32, RTLIB::BASE##_F64, \
439 RTLIB::UNKNOWN_LIBCALL, RTLIB::BASE##_F128, \
440 RTLIB::BASE##_PPCF128)
441
442 switch (CCCode) {
443 case ISD::SETEQ:
444 case ISD::SETOEQ:
445 std::tie(LC1, CC1) = selectFPCmpLibcall(
446 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
447 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
448 break;
449 case ISD::SETNE:
450 case ISD::SETUNE:
451 std::tie(LC1, CC1) = selectFPCmpLibcall(
452 DAG.getLibcalls(), FP_CMP_LIBCALL(UNE), FP_CMP_LIBCALL(FCMP3_PRED_UNE),
453 FP_CMP_LIBCALL(FCMP3), ISD::SETNE);
454 // Some ABIs (e.g. AEABI) provide neither a not-equal nor a three-way
455 // compare; obtain not-equal (UNE = !OEQ) by inverting ordered-equal.
456 if (DAG.getLibcalls().getLibcallImpl(LC1) == RTLIB::Unsupported) {
457 std::tie(LC1, CC1) = selectFPCmpLibcall(
458 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ),
459 FP_CMP_LIBCALL(FCMP3_PRED_OEQ), FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
460 ShouldInvertCC = true;
461 }
462 break;
463 case ISD::SETGE:
464 case ISD::SETOGE:
465 std::tie(LC1, CC1) = selectFPCmpLibcall(
466 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE), FP_CMP_LIBCALL(FCMP3_PRED_OGE),
467 FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
468 break;
469 case ISD::SETLT:
470 case ISD::SETOLT:
471 std::tie(LC1, CC1) = selectFPCmpLibcall(
472 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT), FP_CMP_LIBCALL(FCMP3_PRED_OLT),
473 FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
474 break;
475 case ISD::SETLE:
476 case ISD::SETOLE:
477 std::tie(LC1, CC1) = selectFPCmpLibcall(
478 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE), FP_CMP_LIBCALL(FCMP3_PRED_OLE),
479 FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
480 break;
481 case ISD::SETGT:
482 case ISD::SETOGT:
483 std::tie(LC1, CC1) = selectFPCmpLibcall(
484 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT), FP_CMP_LIBCALL(FCMP3_PRED_OGT),
485 FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
486 break;
487 case ISD::SETO:
488 ShouldInvertCC = true;
489 [[fallthrough]];
490 case ISD::SETUO:
491 // Unordered is a boolean everywhere (__unordXf2 returns 0/1).
492 LC1 = FP_CMP_LIBCALL(UO);
493 CC1 = ISD::SETNE;
494 break;
495 case ISD::SETONE:
496 // SETONE = O && UNE
497 ShouldInvertCC = true;
498 [[fallthrough]];
499 case ISD::SETUEQ:
500 LC1 = FP_CMP_LIBCALL(UO);
501 CC1 = ISD::SETNE;
502 std::tie(LC2, CC2) = selectFPCmpLibcall(
503 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
504 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
505 break;
506 default:
507 // Invert CC for unordered comparisons, handled by the ordered inverse.
508 ShouldInvertCC = true;
509 switch (CCCode) {
510 case ISD::SETULT:
511 std::tie(LC1, CC1) = selectFPCmpLibcall(
512 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE),
513 FP_CMP_LIBCALL(FCMP3_PRED_OGE), FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
514 break;
515 case ISD::SETULE:
516 std::tie(LC1, CC1) = selectFPCmpLibcall(
517 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT),
518 FP_CMP_LIBCALL(FCMP3_PRED_OGT), FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
519 break;
520 case ISD::SETUGT:
521 std::tie(LC1, CC1) = selectFPCmpLibcall(
522 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE),
523 FP_CMP_LIBCALL(FCMP3_PRED_OLE), FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
524 break;
525 case ISD::SETUGE:
526 std::tie(LC1, CC1) = selectFPCmpLibcall(
527 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT),
528 FP_CMP_LIBCALL(FCMP3_PRED_OLT), FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
529 break;
530 default:
531 llvm_unreachable("Do not know how to soften this setcc!");
532 }
533 }
534
535#undef FP_CMP_LIBCALL
536
537 // Use the target specific return value for comparison lib calls.
539 SDValue Ops[2] = {NewLHS, NewRHS};
541 EVT OpsVT[2] = { OldLHS.getValueType(),
542 OldRHS.getValueType() };
543 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT);
544
545 auto ReportNoLibcall = [&]() {
546 DAG.getContext()->emitError(
547 Twine("no libcall available to soften floating-point ") +
548 ISD::getCondCodeName(OrigCCCode) + " compare with type " +
549 VT.getEVTString());
550 NewLHS = DAG.getPOISON(RetVT);
551 NewRHS = DAG.getConstant(0, dl, RetVT);
552 CCCode = ISD::SETNE;
553 };
554
555 // Check availability before makeLibCall, which fatally errors otherwise.
556 RTLIB::LibcallImpl LC1Impl = DAG.getLibcalls().getLibcallImpl(LC1);
557 if (LC1Impl == RTLIB::Unsupported) {
558 ReportNoLibcall();
559 return;
560 }
561
562 auto Call = makeLibCall(DAG, LC1Impl, RetVT, Ops, CallOptions, dl, Chain);
563 NewLHS = Call.first;
564 NewRHS = DAG.getConstant(0, dl, RetVT);
565
566 CCCode = CC1;
567 if (ShouldInvertCC) {
568 assert(RetVT.isInteger());
569 CCCode = getSetCCInverse(CCCode, RetVT);
570 }
571
572 if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
573 // Update Chain.
574 Chain = Call.second;
575 } else {
576 RTLIB::LibcallImpl LC2Impl = DAG.getLibcalls().getLibcallImpl(LC2);
577 if (LC2Impl == RTLIB::Unsupported) {
578 ReportNoLibcall();
579 return;
580 }
581
582 assert(CCCode == (ShouldInvertCC ? ISD::SETEQ : ISD::SETNE) &&
583 "unordered call should be simple boolean");
584
585 EVT SetCCVT =
586 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
588 NewLHS = DAG.getNode(ISD::AssertZext, dl, RetVT, Call.first,
589 DAG.getValueType(MVT::i1));
590 }
591
592 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
593 auto Call2 = makeLibCall(DAG, LC2Impl, RetVT, Ops, CallOptions, dl, Chain);
594 CCCode = CC2;
595 if (ShouldInvertCC)
596 CCCode = getSetCCInverse(CCCode, RetVT);
597 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
598 if (Chain)
599 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
600 Call2.second);
601 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
602 Tmp.getValueType(), Tmp, NewLHS);
603 NewRHS = SDValue();
604 }
605}
606
607/// Return the entry encoding for a jump table in the current function. The
608/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
610 // In non-pic modes, just use the address of a block.
613
614 // Otherwise, use a label difference.
616}
617
622
623/// This returns the relocation base for the given PIC jumptable, the same as
624/// getPICJumpTableRelocBase, but as an MCExpr.
625const MCExpr *
627 unsigned JTI,MCContext &Ctx) const{
628 // The normal PIC reloc base is the label at the start of the jump table.
629 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
630}
631
633 SDValue Addr, int JTI,
634 SelectionDAG &DAG) const {
635 SDValue Chain = Value;
636 // Jump table debug info is only needed if CodeView is enabled.
638 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl);
639 }
640 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr);
641}
642
643bool
645 const TargetMachine &TM = getTargetMachine();
646 const GlobalValue *GV = GA->getGlobal();
647
648 // If the address is not even local to this DSO we will have to load it from
649 // a got and then add the offset.
650 if (!TM.shouldAssumeDSOLocal(GV))
651 return false;
652
653 // If the code is position independent we will have to add a base register.
655 return false;
656
657 // Otherwise we can do it.
658 return true;
659}
660
661//===----------------------------------------------------------------------===//
662// Optimization Methods
663//===----------------------------------------------------------------------===//
664
665/// If the specified instruction has a constant integer operand and there are
666/// bits set in that constant that are not demanded, then clear those bits and
667/// return true.
669 const APInt &DemandedBits,
670 const APInt &DemandedElts,
671 TargetLoweringOpt &TLO) const {
672 SDLoc DL(Op);
673 unsigned Opcode = Op.getOpcode();
674
675 // Early-out if we've ended up calling an undemanded node, leave this to
676 // constant folding.
677 if (DemandedBits.isZero() || DemandedElts.isZero())
678 return false;
679
680 // Do target-specific constant optimization.
681 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
682 return TLO.New.getNode();
683
684 // FIXME: ISD::SELECT, ISD::SELECT_CC
685 switch (Opcode) {
686 default:
687 break;
688 case ISD::XOR:
689 case ISD::AND:
690 case ISD::OR: {
691 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
692 if (!Op1C || Op1C->isOpaque())
693 return false;
694
695 // If this is a 'not' op, don't touch it because that's a canonical form.
696 const APInt &C = Op1C->getAPIntValue();
697 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
698 return false;
699
700 if (!C.isSubsetOf(DemandedBits)) {
701 EVT VT = Op.getValueType();
702 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
703 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC,
704 Op->getFlags());
705 return TLO.CombineTo(Op, NewOp);
706 }
707
708 break;
709 }
710 }
711
712 return false;
713}
714
716 const APInt &DemandedBits,
717 TargetLoweringOpt &TLO) const {
718 EVT VT = Op.getValueType();
719 APInt DemandedElts = VT.isVector()
721 : APInt(1, 1);
722 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
723}
724
725/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
726/// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
727/// but it could be generalized for targets with other types of implicit
728/// widening casts.
730 const APInt &DemandedBits,
731 TargetLoweringOpt &TLO) const {
732 assert(Op.getNumOperands() == 2 &&
733 "ShrinkDemandedOp only supports binary operators!");
734 assert(Op.getNode()->getNumValues() == 1 &&
735 "ShrinkDemandedOp only supports nodes with one result!");
736
737 EVT VT = Op.getValueType();
738 SelectionDAG &DAG = TLO.DAG;
739 SDLoc dl(Op);
740
741 // Early return, as this function cannot handle vector types.
742 if (VT.isVector())
743 return false;
744
745 assert(Op.getOperand(0).getValueType().getScalarSizeInBits() == BitWidth &&
746 Op.getOperand(1).getValueType().getScalarSizeInBits() == BitWidth &&
747 "ShrinkDemandedOp only supports operands that have the same size!");
748
749 // Don't do this if the node has another user, which may require the
750 // full value.
751 if (!Op.getNode()->hasOneUse())
752 return false;
753
754 // Search for the smallest integer type with free casts to and from
755 // Op's type. For expedience, just check power-of-2 integer types.
756 unsigned DemandedSize = DemandedBits.getActiveBits();
757 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
758 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
759 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
760 if (isTruncateFree(Op, SmallVT) && isZExtFree(SmallVT, VT)) {
761 // We found a type with free casts.
762
763 // If the operation has the 'disjoint' flag, then the
764 // operands on the new node are also disjoint.
765 SDNodeFlags Flags(Op->getFlags().hasDisjoint() ? SDNodeFlags::Disjoint
767 unsigned Opcode = Op.getOpcode();
768 if (Opcode == ISD::PTRADD) {
769 // It isn't a ptradd anymore if it doesn't operate on the entire
770 // pointer.
771 Opcode = ISD::ADD;
772 }
773 SDValue X = DAG.getNode(
774 Opcode, dl, SmallVT,
775 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
776 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)), Flags);
777 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
778 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X);
779 return TLO.CombineTo(Op, Z);
780 }
781 }
782 return false;
783}
784
786 DAGCombinerInfo &DCI) const {
787 SelectionDAG &DAG = DCI.DAG;
788 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
789 !DCI.isBeforeLegalizeOps());
791
792 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
793 if (Simplified) {
794 DCI.AddToWorklist(Op.getNode());
796 }
797 return Simplified;
798}
799
801 const APInt &DemandedElts,
802 DAGCombinerInfo &DCI) const {
803 SelectionDAG &DAG = DCI.DAG;
804 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
805 !DCI.isBeforeLegalizeOps());
807
808 bool Simplified =
809 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
810 if (Simplified) {
811 DCI.AddToWorklist(Op.getNode());
813 }
814 return Simplified;
815}
816
820 unsigned Depth,
821 bool AssumeSingleUse) const {
822 EVT VT = Op.getValueType();
823
824 // Since the number of lanes in a scalable vector is unknown at compile time,
825 // we track one bit which is implicitly broadcast to all lanes. This means
826 // that all lanes in a scalable vector are considered demanded.
827 APInt DemandedElts = VT.isFixedLengthVector()
829 : APInt(1, 1);
830 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
831 AssumeSingleUse);
832}
833
834// TODO: Under what circumstances can we create nodes? Constant folding?
836 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
837 SelectionDAG &DAG, unsigned Depth) const {
838 EVT VT = Op.getValueType();
839
840 // Limit search depth.
842 return SDValue();
843
844 // Ignore UNDEFs.
845 if (Op.isUndef())
846 return SDValue();
847
848 // Not demanding any bits/elts from Op.
849 if (DemandedBits == 0 || DemandedElts == 0)
850 return DAG.getUNDEF(VT);
851
852 bool IsLE = DAG.getDataLayout().isLittleEndian();
853 unsigned NumElts = DemandedElts.getBitWidth();
854 unsigned BitWidth = DemandedBits.getBitWidth();
855 KnownBits LHSKnown, RHSKnown;
856 switch (Op.getOpcode()) {
857 case ISD::Constant: {
858 const APInt &Value = Op->getAsAPIntVal();
859 if (!Value.isZero() && (Value & DemandedBits).isZero())
860 return DAG.getConstant(0, SDLoc(Op), VT);
861 break;
862 }
863 case ISD::BITCAST: {
864 if (VT.isScalableVector())
865 return SDValue();
866
867 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
868 EVT SrcVT = Src.getValueType();
869 EVT DstVT = Op.getValueType();
870 if (SrcVT == DstVT)
871 return Src;
872
873 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
874 unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
875 if (NumSrcEltBits == NumDstEltBits)
877 Src, DemandedBits, DemandedElts, DAG, Depth + 1))
878 return DAG.getBitcast(DstVT, V);
879
880 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
881 unsigned Scale = NumDstEltBits / NumSrcEltBits;
882 unsigned NumSrcElts = SrcVT.getVectorNumElements();
883 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
884 for (unsigned i = 0; i != Scale; ++i) {
885 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
886 unsigned BitOffset = EltOffset * NumSrcEltBits;
887 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
888 }
889 // Recursive calls below may turn not demanded elements into poison, so we
890 // need to demand all smaller source elements that maps to a demanded
891 // destination element.
892 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
893
895 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
896 return DAG.getBitcast(DstVT, V);
897 }
898
899 // TODO - bigendian once we have test coverage.
900 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
901 unsigned Scale = NumSrcEltBits / NumDstEltBits;
902 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
903 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
904 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
905 for (unsigned i = 0; i != NumElts; ++i)
906 if (DemandedElts[i]) {
907 unsigned Offset = (i % Scale) * NumDstEltBits;
908 DemandedSrcBits.insertBits(DemandedBits, Offset);
909 DemandedSrcElts.setBit(i / Scale);
910 }
911
913 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
914 return DAG.getBitcast(DstVT, V);
915 }
916
917 break;
918 }
920 if (!VT.isScalableVector() && !DemandedElts[0])
921 return DAG.getPOISON(VT);
922 break;
923 }
924 case ISD::AND: {
925 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
926 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
927
928 // If all of the demanded bits are known 1 on one side, return the other.
929 // These bits cannot contribute to the result of the 'and' in this
930 // context.
931 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
932 return Op.getOperand(0);
933 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
934 return Op.getOperand(1);
935 break;
936 }
937 case ISD::OR: {
938 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
939 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
940
941 // If all of the demanded bits are known zero on one side, return the
942 // other. These bits cannot contribute to the result of the 'or' in this
943 // context.
944 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
945 return Op.getOperand(0);
946 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
947 return Op.getOperand(1);
948 break;
949 }
950 case ISD::XOR: {
951 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
952 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
953
954 // If all of the demanded bits are known zero on one side, return the
955 // other.
956 if (DemandedBits.isSubsetOf(RHSKnown.Zero))
957 return Op.getOperand(0);
958 if (DemandedBits.isSubsetOf(LHSKnown.Zero))
959 return Op.getOperand(1);
960 break;
961 }
962 case ISD::ADD:
963 case ISD::MUL:
964 case ISD::SMIN:
965 case ISD::SMAX:
966 case ISD::UMIN:
967 case ISD::UMAX: {
968 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(1),
969 DemandedElts, 1, Depth + 1))
970 return Op.getOperand(0);
971
972 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(0),
973 DemandedElts, 0, Depth + 1))
974 return Op.getOperand(1);
975 break;
976 }
977 case ISD::SHL: {
978 // If we are only demanding sign bits then we can use the shift source
979 // directly.
980 if (std::optional<unsigned> MaxSA =
981 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
982 SDValue Op0 = Op.getOperand(0);
983 unsigned ShAmt = *MaxSA;
984 unsigned NumSignBits =
985 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
986 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
987 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
988 return Op0;
989 }
990 break;
991 }
992 case ISD::SRL: {
993 // If we are only demanding sign bits then we can use the shift source
994 // directly.
995 if (std::optional<unsigned> MaxSA =
996 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
997 SDValue Op0 = Op.getOperand(0);
998 unsigned ShAmt = *MaxSA;
999 // Must already be signbits in DemandedBits bounds, and can't demand any
1000 // shifted in zeroes.
1001 if (DemandedBits.countl_zero() >= ShAmt) {
1002 unsigned NumSignBits =
1003 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1004 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
1005 return Op0;
1006 }
1007 }
1008 break;
1009 }
1010 case ISD::SETCC: {
1011 SDValue Op0 = Op.getOperand(0);
1012 SDValue Op1 = Op.getOperand(1);
1013 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1014 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1015 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1016 // -1, we may be able to bypass the setcc.
1017 if (DemandedBits.isSignMask() &&
1021 // If we're testing X < 0, then this compare isn't needed - just use X!
1022 // FIXME: We're limiting to integer types here, but this should also work
1023 // if we don't care about FP signed-zero. The use of SETLT with FP means
1024 // that we don't care about NaNs.
1025 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1027 return Op0;
1028 }
1029 break;
1030 }
1032 // If none of the extended bits are demanded, eliminate the sextinreg.
1033 SDValue Op0 = Op.getOperand(0);
1034 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1035 unsigned ExBits = ExVT.getScalarSizeInBits();
1036 if (DemandedBits.getActiveBits() <= ExBits &&
1038 return Op0;
1039 // If the input is already sign extended, just drop the extension.
1040 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1041 if (NumSignBits >= (BitWidth - ExBits + 1))
1042 return Op0;
1043 break;
1044 }
1048 if (VT.isScalableVector())
1049 return SDValue();
1050
1051 // If we only want the lowest element and none of extended bits, then we can
1052 // return the bitcasted source vector.
1053 SDValue Src = Op.getOperand(0);
1054 EVT SrcVT = Src.getValueType();
1055 EVT DstVT = Op.getValueType();
1056 if (IsLE && DemandedElts == 1 &&
1057 DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
1058 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
1059 return DAG.getBitcast(DstVT, Src);
1060 }
1061 break;
1062 }
1064 if (VT.isScalableVector())
1065 return SDValue();
1066
1067 // If we don't demand the inserted element, return the base vector.
1068 SDValue Vec = Op.getOperand(0);
1069 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1070 EVT VecVT = Vec.getValueType();
1071 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
1072 !DemandedElts[CIdx->getZExtValue()])
1073 return Vec;
1074 break;
1075 }
1076 case ISD::INSERT_SUBVECTOR: {
1077 if (VT.isScalableVector())
1078 return SDValue();
1079
1080 SDValue Vec = Op.getOperand(0);
1081 SDValue Sub = Op.getOperand(1);
1082 uint64_t Idx = Op.getConstantOperandVal(2);
1083 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1084 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1085 // If we don't demand the inserted subvector, return the base vector.
1086 if (DemandedSubElts == 0)
1087 return Vec;
1088 break;
1089 }
1090 case ISD::VECTOR_SHUFFLE: {
1091 assert(!VT.isScalableVector());
1092 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1093
1094 // If all the demanded elts are from one operand and are inline,
1095 // then we can use the operand directly.
1096 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
1097 for (unsigned i = 0; i != NumElts; ++i) {
1098 int M = ShuffleMask[i];
1099 if (M < 0 || !DemandedElts[i])
1100 continue;
1101 AllUndef = false;
1102 IdentityLHS &= (M == (int)i);
1103 IdentityRHS &= ((M - NumElts) == i);
1104 }
1105
1106 if (AllUndef)
1107 return DAG.getUNDEF(Op.getValueType());
1108 if (IdentityLHS)
1109 return Op.getOperand(0);
1110 if (IdentityRHS)
1111 return Op.getOperand(1);
1112 break;
1113 }
1114 default:
1115 // TODO: Probably okay to remove after audit; here to reduce change size
1116 // in initial enablement patch for scalable vectors
1117 if (VT.isScalableVector())
1118 return SDValue();
1119
1120 if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
1122 Op, DemandedBits, DemandedElts, DAG, Depth))
1123 return V;
1124 break;
1125 }
1126 return SDValue();
1127}
1128
1131 unsigned Depth) const {
1132 EVT VT = Op.getValueType();
1133 // Since the number of lanes in a scalable vector is unknown at compile time,
1134 // we track one bit which is implicitly broadcast to all lanes. This means
1135 // that all lanes in a scalable vector are considered demanded.
1136 APInt DemandedElts = VT.isFixedLengthVector()
1138 : APInt(1, 1);
1139 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1140 Depth);
1141}
1142
1144 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
1145 unsigned Depth) const {
1146 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
1147 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1148 Depth);
1149}
1150
1151// Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
1152// or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
1155 const TargetLowering &TLI,
1156 const APInt &DemandedBits,
1157 const APInt &DemandedElts, unsigned Depth) {
1158 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1159 "SRL or SRA node is required here!");
1160 // Is the right shift using an immediate value of 1?
1161 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1162 if (!N1C || !N1C->isOne())
1163 return SDValue();
1164
1165 // We are looking for an avgfloor
1166 // add(ext, ext)
1167 // or one of these as a avgceil
1168 // add(add(ext, ext), 1)
1169 // add(add(ext, 1), ext)
1170 // add(ext, add(ext, 1))
1171 SDValue Add = Op.getOperand(0);
1172 if (Add.getOpcode() != ISD::ADD)
1173 return SDValue();
1174
1175 SDValue ExtOpA = Add.getOperand(0);
1176 SDValue ExtOpB = Add.getOperand(1);
1177 SDValue Add2;
1178 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) {
1179 ConstantSDNode *ConstOp;
1180 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
1181 ConstOp->isOne()) {
1182 ExtOpA = Op1;
1183 ExtOpB = Op3;
1184 Add2 = A;
1185 return true;
1186 }
1187 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
1188 ConstOp->isOne()) {
1189 ExtOpA = Op1;
1190 ExtOpB = Op2;
1191 Add2 = A;
1192 return true;
1193 }
1194 return false;
1195 };
1196 bool IsCeil =
1197 (ExtOpA.getOpcode() == ISD::ADD &&
1198 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) ||
1199 (ExtOpB.getOpcode() == ISD::ADD &&
1200 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB));
1201
1202 // If the shift is signed (sra):
1203 // - Needs >= 2 sign bit for both operands.
1204 // - Needs >= 2 zero bits.
1205 // If the shift is unsigned (srl):
1206 // - Needs >= 1 zero bit for both operands.
1207 // - Needs 1 demanded bit zero and >= 2 sign bits.
1208 SelectionDAG &DAG = TLO.DAG;
1209 unsigned ShiftOpc = Op.getOpcode();
1210 bool IsSigned = false;
1211 unsigned KnownBits;
1212 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
1213 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
1214 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
1215 unsigned NumZeroA =
1216 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
1217 unsigned NumZeroB =
1218 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
1219 unsigned NumZero = std::min(NumZeroA, NumZeroB);
1220
1221 switch (ShiftOpc) {
1222 default:
1223 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
1224 case ISD::SRA: {
1225 if (NumZero >= 2 && NumSigned < NumZero) {
1226 IsSigned = false;
1227 KnownBits = NumZero;
1228 break;
1229 }
1230 if (NumSigned >= 1) {
1231 IsSigned = true;
1232 KnownBits = NumSigned;
1233 break;
1234 }
1235 return SDValue();
1236 }
1237 case ISD::SRL: {
1238 if (NumZero >= 1 && NumSigned < NumZero) {
1239 IsSigned = false;
1240 KnownBits = NumZero;
1241 break;
1242 }
1243 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1244 IsSigned = true;
1245 KnownBits = NumSigned;
1246 break;
1247 }
1248 return SDValue();
1249 }
1250 }
1251
1252 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1253 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1254
1255 // Find the smallest power-2 type that is legal for this vector size and
1256 // operation, given the original type size and the number of known sign/zero
1257 // bits.
1258 EVT VT = Op.getValueType();
1259 unsigned MinWidth =
1260 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1261 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth));
1263 return SDValue();
1264 if (VT.isVector())
1265 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1266 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) {
1267 // If we could not transform, and (both) adds are nuw/nsw, we can use the
1268 // larger type size to do the transform.
1269 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT))
1270 return SDValue();
1271 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0),
1272 Add.getOperand(1)) &&
1273 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0),
1274 Add2.getOperand(1))))
1275 NVT = VT;
1276 else
1277 return SDValue();
1278 }
1279
1280 // Don't create a AVGFLOOR node with a scalar constant unless its legal as
1281 // this is likely to stop other folds (reassociation, value tracking etc.)
1282 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) &&
1283 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB)))
1284 return SDValue();
1285
1286 SDLoc DL(Op);
1287 SDValue ResultAVG =
1288 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT),
1289 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT));
1290 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT);
1291}
1292
1293/// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1294/// result of Op are ever used downstream. If we can use this information to
1295/// simplify Op, create a new simplified DAG node and return true, returning the
1296/// original and new nodes in Old and New. Otherwise, analyze the expression and
1297/// return a mask of Known bits for the expression (used to simplify the
1298/// caller). The Known bits may only be accurate for those bits in the
1299/// OriginalDemandedBits and OriginalDemandedElts.
1301 SDValue Op, const APInt &OriginalDemandedBits,
1302 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1303 unsigned Depth, bool AssumeSingleUse) const {
1304 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1305 assert(Op.getScalarValueSizeInBits() == BitWidth &&
1306 "Mask size mismatches value type size!");
1307
1308 // Don't know anything.
1310
1311 EVT VT = Op.getValueType();
1312 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1313 unsigned NumElts = OriginalDemandedElts.getBitWidth();
1314 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1315 "Unexpected vector size");
1316
1317 APInt DemandedBits = OriginalDemandedBits;
1318 APInt DemandedElts = OriginalDemandedElts;
1319 SDLoc dl(Op);
1320
1321 // Undef operand.
1322 if (Op.isUndef())
1323 return false;
1324
1325 // We can't simplify target constants.
1326 if (Op.getOpcode() == ISD::TargetConstant)
1327 return false;
1328
1329 if (Op.getOpcode() == ISD::Constant) {
1330 // We know all of the bits for a constant!
1331 Known = KnownBits::makeConstant(Op->getAsAPIntVal());
1332 return false;
1333 }
1334
1335 if (Op.getOpcode() == ISD::ConstantFP) {
1336 // We know all of the bits for a floating point constant!
1338 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1339 return false;
1340 }
1341
1342 // Other users may use these bits.
1343 bool HasMultiUse = false;
1344 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1346 // Limit search depth.
1347 return false;
1348 }
1349 // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1351 DemandedElts = APInt::getAllOnes(NumElts);
1352 HasMultiUse = true;
1353 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1354 // Not demanding any bits/elts from Op.
1355 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1356 } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1357 // Limit search depth.
1358 return false;
1359 }
1360
1361 // Before folding to the LHS, recheck bits excluded from its earlier demand
1362 // using the full result demand. Mask identifies these excluded bits.
1363 // KnownMask selects the Zero/One member of the recomputed LHS known bits
1364 // that must cover Mask & DemandedBits.
1365 auto TryFoldToLHS = [&](const APInt &Mask,
1366 const APInt KnownBits::*KnownMask) {
1367 SDValue LHS = Op.getOperand(0);
1368 APInt MaskedBits = Mask & DemandedBits;
1369 if (MaskedBits.isZero())
1370 return TLO.CombineTo(Op, LHS);
1371
1372 KnownBits LHSKnown;
1373 if (SimplifyDemandedBits(LHS, DemandedBits, DemandedElts, LHSKnown, TLO,
1374 Depth + 1))
1375 return true;
1376
1377 return MaskedBits.isSubsetOf(LHSKnown.*KnownMask) && TLO.CombineTo(Op, LHS);
1378 };
1379
1380 // Try reducing the RHS demand using LHS known bits.
1381 // KnownMask selects the LHS Zero/One bits that make RHS bits irrelevant.
1382 auto TryReduceRHSDemand = [&](const KnownBits &LHSKnown,
1383 const APInt KnownBits::*KnownMask) {
1384 SDValue RHS = Op.getOperand(1);
1385 if (!RHS.hasOneUse() || isConstOrConstSplat(RHS, DemandedElts))
1386 return false;
1387
1388 // Reuse LHS facts if the RHS did not reduce its earlier demand. Otherwise,
1389 // query independent facts to avoid using bits outside that demand.
1390 SDValue LHS = Op.getOperand(0);
1391 // Keep only the selected mask, then compute DemandedBits & ~Mask in place.
1392 // This avoids copying the unused KnownBits mask and extra APInt
1393 // temporaries, which can allocate memory for masks wider than one word.
1394 APInt RHSDemandedBits =
1395 DemandedBits.intersects(Known.*KnownMask)
1396 ? TLO.DAG.computeKnownBits(LHS, DemandedElts, Depth + 1).*KnownMask
1397 : LHSKnown.*KnownMask;
1398 RHSDemandedBits.flipAllBits();
1399 RHSDemandedBits &= DemandedBits;
1400 if (RHSDemandedBits == DemandedBits)
1401 return false;
1402
1403 // A failed retry must not replace Known with reduced-demand facts.
1404 KnownBits RetryKnown;
1405 return SimplifyDemandedBits(RHS, RHSDemandedBits, DemandedElts, RetryKnown,
1406 TLO, Depth + 1);
1407 };
1408
1409 KnownBits Known2;
1410 switch (Op.getOpcode()) {
1411 case ISD::SCALAR_TO_VECTOR: {
1412 if (VT.isScalableVector())
1413 return false;
1414 if (!DemandedElts[0])
1415 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
1416
1417 KnownBits SrcKnown;
1418 SDValue Src = Op.getOperand(0);
1419 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1420 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1421 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1422 return true;
1423
1424 // Upper elements are poison, so only get the knownbits if we just demand
1425 // the bottom element.
1426 if (DemandedElts == 1)
1427 Known = SrcKnown.anyextOrTrunc(BitWidth);
1428 break;
1429 }
1430 case ISD::BUILD_VECTOR:
1431 // Collect the known bits that are shared by every demanded element.
1432 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1433 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1434 return false; // Don't fall through, will infinitely loop.
1435 case ISD::SPLAT_VECTOR: {
1436 SDValue Scl = Op.getOperand(0);
1437 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1438 KnownBits KnownScl;
1439 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1440 return true;
1441
1442 // Implicitly truncate the bits to match the official semantics of
1443 // SPLAT_VECTOR.
1444 Known = KnownScl.trunc(BitWidth);
1445 break;
1446 }
1447 case ISD::FREEZE: {
1448 SDValue N0 = Op.getOperand(0);
1450 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
1451 return TLO.CombineTo(Op, N0);
1452 break;
1453 }
1454 case ISD::LOAD: {
1455 auto *LD = cast<LoadSDNode>(Op);
1456 if (getTargetConstantFromLoad(LD)) {
1457 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1458 return false; // Don't fall through, will infinitely loop.
1459 }
1460 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1461 // If this is a ZEXTLoad and we are looking at the loaded value.
1462 EVT MemVT = LD->getMemoryVT();
1463 unsigned MemBits = MemVT.getScalarSizeInBits();
1464 Known.Zero.setBitsFrom(MemBits);
1465 return false; // Don't fall through, will infinitely loop.
1466 }
1467 break;
1468 }
1470 if (VT.isScalableVector())
1471 return false;
1472 SDValue Vec = Op.getOperand(0);
1473 SDValue Scl = Op.getOperand(1);
1474 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1475 EVT VecVT = Vec.getValueType();
1476
1477 // If index isn't constant, assume we need all vector elements AND the
1478 // inserted element.
1479 APInt DemandedVecElts(DemandedElts);
1480 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1481 unsigned Idx = CIdx->getZExtValue();
1482 DemandedVecElts.clearBit(Idx);
1483
1484 // Inserted element is not required.
1485 if (!DemandedElts[Idx])
1486 return TLO.CombineTo(Op, Vec);
1487 }
1488
1489 KnownBits KnownScl;
1490 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1491 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1492 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1493 return true;
1494
1495 Known = KnownScl.anyextOrTrunc(BitWidth);
1496
1497 KnownBits KnownVec;
1498 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1499 Depth + 1))
1500 return true;
1501
1502 if (!!DemandedVecElts)
1503 Known = Known.intersectWith(KnownVec);
1504
1505 return false;
1506 }
1507 case ISD::INSERT_SUBVECTOR: {
1508 if (VT.isScalableVector())
1509 return false;
1510 // Demand any elements from the subvector and the remainder from the src its
1511 // inserted into.
1512 SDValue Src = Op.getOperand(0);
1513 SDValue Sub = Op.getOperand(1);
1514 uint64_t Idx = Op.getConstantOperandVal(2);
1515 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1516 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1517 APInt DemandedSrcElts = DemandedElts;
1518 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
1519
1520 KnownBits KnownSub, KnownSrc;
1521 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1522 Depth + 1))
1523 return true;
1524 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1525 Depth + 1))
1526 return true;
1527
1528 Known.setAllConflict();
1529 if (!!DemandedSubElts)
1530 Known = Known.intersectWith(KnownSub);
1531 if (!!DemandedSrcElts)
1532 Known = Known.intersectWith(KnownSrc);
1533
1534 // Attempt to avoid multi-use src if we don't need anything from it.
1535 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1536 !DemandedSrcElts.isAllOnes()) {
1538 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1540 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1541 if (NewSub || NewSrc) {
1542 NewSub = NewSub ? NewSub : Sub;
1543 NewSrc = NewSrc ? NewSrc : Src;
1544 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1545 Op.getOperand(2));
1546 return TLO.CombineTo(Op, NewOp);
1547 }
1548 }
1549 break;
1550 }
1552 if (VT.isScalableVector())
1553 return false;
1554 // Offset the demanded elts by the subvector index.
1555 SDValue Src = Op.getOperand(0);
1556 if (Src.getValueType().isScalableVector())
1557 break;
1558 uint64_t Idx = Op.getConstantOperandVal(1);
1559 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1560 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1561
1562 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1563 Depth + 1))
1564 return true;
1565
1566 // Attempt to avoid multi-use src if we don't need anything from it.
1567 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1569 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1570 if (DemandedSrc) {
1571 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1572 Op.getOperand(1));
1573 return TLO.CombineTo(Op, NewOp);
1574 }
1575 }
1576 break;
1577 }
1578 case ISD::CONCAT_VECTORS: {
1579 if (VT.isScalableVector())
1580 return false;
1581 Known.setAllConflict();
1582 EVT SubVT = Op.getOperand(0).getValueType();
1583 unsigned NumSubVecs = Op.getNumOperands();
1584 unsigned NumSubElts = SubVT.getVectorNumElements();
1585 for (unsigned i = 0; i != NumSubVecs; ++i) {
1586 APInt DemandedSubElts =
1587 DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1588 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1589 Known2, TLO, Depth + 1))
1590 return true;
1591 // Known bits are shared by every demanded subvector element.
1592 if (!!DemandedSubElts)
1593 Known = Known.intersectWith(Known2);
1594 }
1595 break;
1596 }
1597 case ISD::VECTOR_SHUFFLE: {
1598 assert(!VT.isScalableVector());
1599 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1600
1601 // Collect demanded elements from shuffle operands..
1602 APInt DemandedLHS, DemandedRHS;
1603 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1604 DemandedRHS))
1605 break;
1606
1607 if (!!DemandedLHS || !!DemandedRHS) {
1608 SDValue Op0 = Op.getOperand(0);
1609 SDValue Op1 = Op.getOperand(1);
1610
1611 Known.setAllConflict();
1612 if (!!DemandedLHS) {
1613 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1614 Depth + 1))
1615 return true;
1616 Known = Known.intersectWith(Known2);
1617 }
1618 if (!!DemandedRHS) {
1619 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1620 Depth + 1))
1621 return true;
1622 Known = Known.intersectWith(Known2);
1623 }
1624
1625 // Attempt to avoid multi-use ops if we don't need anything from them.
1627 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1629 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1630 if (DemandedOp0 || DemandedOp1) {
1631 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1632 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1633 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1634 return TLO.CombineTo(Op, NewOp);
1635 }
1636 }
1637 break;
1638 }
1639 case ISD::AND: {
1640 SDValue Op0 = Op.getOperand(0);
1641 SDValue Op1 = Op.getOperand(1);
1642
1643 // If the RHS is a constant, check to see if the LHS would be zero without
1644 // using the bits from the RHS. Below, we use knowledge about the RHS to
1645 // simplify the LHS, here we're using information from the LHS to simplify
1646 // the RHS.
1647 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) {
1648 // Do not increment Depth here; that can cause an infinite loop.
1649 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1650 // If the LHS already has zeros where RHSC does, this 'and' is dead.
1651 if ((LHSKnown.Zero & DemandedBits) ==
1652 (~RHSC->getAPIntValue() & DemandedBits))
1653 return TLO.CombineTo(Op, Op0);
1654
1655 // If any of the set bits in the RHS are known zero on the LHS, shrink
1656 // the constant.
1657 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1658 DemandedElts, TLO))
1659 return true;
1660
1661 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1662 // constant, but if this 'and' is only clearing bits that were just set by
1663 // the xor, then this 'and' can be eliminated by shrinking the mask of
1664 // the xor. For example, for a 32-bit X:
1665 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1666 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1667 LHSKnown.One == ~RHSC->getAPIntValue()) {
1668 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1669 return TLO.CombineTo(Op, Xor);
1670 }
1671 }
1672
1673 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2 (or zero).
1674 SDValue X, Y;
1675 if (sd_match(Op,
1676 m_And(m_Value(Y),
1678 m_Sub(m_Value(X), m_Deferred(Y)))))) &&
1679 TLO.DAG.isKnownToBeAPowerOfTwo(Y, DemandedElts, /*OrZero=*/true)) {
1680 return TLO.CombineTo(
1681 Op, TLO.DAG.getNode(ISD::AND, dl, VT, TLO.DAG.getNOT(dl, X, VT), Y));
1682 }
1683
1684 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1685 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1686 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1687 (Op0.getOperand(0).isUndef() ||
1689 Op0->hasOneUse()) {
1690 unsigned NumSubElts =
1692 unsigned SubIdx = Op0.getConstantOperandVal(2);
1693 APInt DemandedSub =
1694 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1695 KnownBits KnownSubMask =
1696 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1697 if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1698 SDValue NewAnd =
1699 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1700 SDValue NewInsert =
1701 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1702 Op0.getOperand(1), Op0.getOperand(2));
1703 return TLO.CombineTo(Op, NewInsert);
1704 }
1705 }
1706
1707 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1708 Depth + 1))
1709 return true;
1710 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1711 Known2, TLO, Depth + 1))
1712 return true;
1713
1714 // If all of the demanded bits are known one on one side, return the other.
1715 // These bits cannot contribute to the result of the 'and'.
1716 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) {
1717 if (TryFoldToLHS(Known.Zero, &KnownBits::Zero))
1718 return true;
1719 }
1720 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1721 return TLO.CombineTo(Op, Op1);
1722 // If all of the demanded bits in the inputs are known zeros, return zero.
1723 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1724 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1725 // If the RHS is a constant, see if we can simplify it.
1726 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1727 TLO))
1728 return true;
1729 // If the operation can be done in a smaller type, do so.
1731 return true;
1732
1733 // Attempt to avoid multi-use ops if we don't need anything from them.
1734 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1736 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1738 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1739 if (DemandedOp0 || DemandedOp1) {
1740 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1741 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1742 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1743 return TLO.CombineTo(Op, NewOp);
1744 }
1745 }
1746
1747 if (TryReduceRHSDemand(Known2, &KnownBits::Zero))
1748 return true;
1749
1750 Known &= Known2;
1751 break;
1752 }
1753 case ISD::OR: {
1754 SDValue Op0 = Op.getOperand(0);
1755 SDValue Op1 = Op.getOperand(1);
1756 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1757 Depth + 1)) {
1758 Op->dropFlags(SDNodeFlags::Disjoint);
1759 return true;
1760 }
1761
1762 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1763 Known2, TLO, Depth + 1)) {
1764 Op->dropFlags(SDNodeFlags::Disjoint);
1765 return true;
1766 }
1767
1768 // If all of the demanded bits are known zero on one side, return the other.
1769 // These bits cannot contribute to the result of the 'or'.
1770 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) {
1771 if (TryFoldToLHS(Known.One, &KnownBits::One)) {
1772 Op->dropFlags(SDNodeFlags::Disjoint);
1773 return true;
1774 }
1775 }
1776 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1777 return TLO.CombineTo(Op, Op1);
1778 // If the RHS is a constant, see if we can simplify it.
1779 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1780 return true;
1781 // If the operation can be done in a smaller type, do so.
1783 return true;
1784
1785 // Attempt to avoid multi-use ops if we don't need anything from them.
1786 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1788 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1790 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1791 if (DemandedOp0 || DemandedOp1) {
1792 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1793 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1794 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1795 return TLO.CombineTo(Op, NewOp);
1796 }
1797 }
1798
1799 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1800 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1801 SDValue X, Y, C1, C2;
1804 m_Value(C2)))))) {
1805 if (SDValue C12 =
1806 TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, {C1, C2})) {
1807 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1808 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1809 return TLO.CombineTo(Op,
1810 TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1811 }
1812 }
1813
1814 if (TryReduceRHSDemand(Known2, &KnownBits::One)) {
1815 Op->dropFlags(SDNodeFlags::Disjoint);
1816 return true;
1817 }
1818
1819 Known |= Known2;
1820 break;
1821 }
1822 case ISD::XOR: {
1823 SDValue Op0 = Op.getOperand(0);
1824 SDValue Op1 = Op.getOperand(1);
1825
1826 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1827 Depth + 1))
1828 return true;
1829 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1830 Depth + 1))
1831 return true;
1832
1833 // If all of the demanded bits are known zero on one side, return the other.
1834 // These bits cannot contribute to the result of the 'xor'.
1835 if (DemandedBits.isSubsetOf(Known.Zero))
1836 return TLO.CombineTo(Op, Op0);
1837 if (DemandedBits.isSubsetOf(Known2.Zero))
1838 return TLO.CombineTo(Op, Op1);
1839 // If the operation can be done in a smaller type, do so.
1841 return true;
1842
1843 // If all of the unknown bits are known to be zero on one side or the other
1844 // turn this into an *inclusive* or.
1845 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1846 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1847 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1848
1849 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1850 if (C) {
1851 // If one side is a constant, and all of the set bits in the constant are
1852 // also known set on the other side, turn this into an AND, as we know
1853 // the bits will be cleared.
1854 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1855 // NB: it is okay if more bits are known than are requested
1856 if (C->getAPIntValue() == Known2.One) {
1857 SDValue ANDC =
1858 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1859 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1860 }
1861
1862 // If the RHS is a constant, see if we can change it. Don't alter a -1
1863 // constant because that's a 'not' op, and that is better for combining
1864 // and codegen.
1865 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1866 // We're flipping all demanded bits. Flip the undemanded bits too.
1867 SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1868 return TLO.CombineTo(Op, New);
1869 }
1870
1871 unsigned Op0Opcode = Op0.getOpcode();
1872 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1873 if (ConstantSDNode *ShiftC =
1874 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1875 // Don't crash on an oversized shift. We can not guarantee that a
1876 // bogus shift has been simplified to undef.
1877 if (ShiftC->getAPIntValue().ult(BitWidth)) {
1878 uint64_t ShiftAmt = ShiftC->getZExtValue();
1880 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1881 : Ones.lshr(ShiftAmt);
1882 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1884 // If the xor constant is a demanded mask, do a 'not' before the
1885 // shift:
1886 // xor (X << ShiftC), XorC --> (not X) << ShiftC
1887 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1888 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1889 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1890 Op0.getOperand(1)));
1891 }
1892 }
1893 }
1894 }
1895 }
1896
1897 // If we can't turn this into a 'not', try to shrink the constant.
1898 if (!C || !C->isAllOnes())
1899 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1900 return true;
1901
1902 // Attempt to avoid multi-use ops if we don't need anything from them.
1903 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1905 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1907 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1908 if (DemandedOp0 || DemandedOp1) {
1909 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1910 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1911 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1912 return TLO.CombineTo(Op, NewOp);
1913 }
1914 }
1915
1916 Known ^= Known2;
1917 break;
1918 }
1919 case ISD::SELECT:
1920 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1921 Known, TLO, Depth + 1))
1922 return true;
1923 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1924 Known2, TLO, Depth + 1))
1925 return true;
1926
1927 // If the operands are constants, see if we can simplify them.
1928 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1929 return true;
1930
1931 // Only known if known in both the LHS and RHS.
1932 Known = Known.intersectWith(Known2);
1933 break;
1934 case ISD::VSELECT:
1935 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1936 Known, TLO, Depth + 1))
1937 return true;
1938 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1939 Known2, TLO, Depth + 1))
1940 return true;
1941
1942 // Only known if known in both the LHS and RHS.
1943 Known = Known.intersectWith(Known2);
1944 break;
1945 case ISD::SELECT_CC:
1946 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts,
1947 Known, TLO, Depth + 1))
1948 return true;
1949 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1950 Known2, TLO, Depth + 1))
1951 return true;
1952
1953 // If the operands are constants, see if we can simplify them.
1954 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1955 return true;
1956
1957 // Only known if known in both the LHS and RHS.
1958 Known = Known.intersectWith(Known2);
1959 break;
1960 case ISD::SETCC: {
1961 SDValue Op0 = Op.getOperand(0);
1962 SDValue Op1 = Op.getOperand(1);
1963 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1964 // If we're testing X < 0, X >= 0, X <= -1 or X > -1
1965 // (X is of integer type) then we only need the sign mask of the previous
1966 // result
1967 if (Op1.getValueType().isInteger() &&
1968 (((CC == ISD::SETLT || CC == ISD::SETGE) && isNullOrNullSplat(Op1)) ||
1969 ((CC == ISD::SETLE || CC == ISD::SETGT) &&
1970 isAllOnesOrAllOnesSplat(Op1)))) {
1971 KnownBits KnownOp0;
1974 DemandedElts, KnownOp0, TLO, Depth + 1))
1975 return true;
1976 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1977 // width as the setcc result, and (3) the result of a setcc conforms to 0
1978 // or -1, we may be able to bypass the setcc.
1979 if (DemandedBits.isSignMask() &&
1983 // If we remove a >= 0 or > -1 (for integers), we need to introduce a
1984 // NOT Operation
1985 if (CC == ISD::SETGE || CC == ISD::SETGT) {
1986 SDLoc DL(Op);
1987 EVT VT = Op0.getValueType();
1988 SDValue NotOp0 = TLO.DAG.getNOT(DL, Op0, VT);
1989 return TLO.CombineTo(Op, NotOp0);
1990 }
1991 return TLO.CombineTo(Op, Op0);
1992 }
1993 }
1994 if (getBooleanContents(Op0.getValueType()) ==
1996 BitWidth > 1)
1997 Known.Zero.setBitsFrom(1);
1998 break;
1999 }
2000 case ISD::SHL: {
2001 SDValue Op0 = Op.getOperand(0);
2002 SDValue Op1 = Op.getOperand(1);
2003 EVT ShiftVT = Op1.getValueType();
2004
2005 if (std::optional<unsigned> KnownSA =
2006 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2007 unsigned ShAmt = *KnownSA;
2008 if (ShAmt == 0)
2009 return TLO.CombineTo(Op, Op0);
2010
2011 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
2012 // single shift. We can do this if the bottom bits (which are shifted
2013 // out) are never demanded.
2014 // TODO - support non-uniform vector amounts.
2015 if (Op0.getOpcode() == ISD::SRL) {
2016 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
2017 if (std::optional<unsigned> InnerSA =
2018 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2019 unsigned C1 = *InnerSA;
2020 unsigned Opc = ISD::SHL;
2021 int Diff = ShAmt - C1;
2022 if (Diff < 0) {
2023 Diff = -Diff;
2024 Opc = ISD::SRL;
2025 }
2026 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2027 return TLO.CombineTo(
2028 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2029 }
2030 }
2031 }
2032
2033 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
2034 // are not demanded. This will likely allow the anyext to be folded away.
2035 // TODO - support non-uniform vector amounts.
2036 if (Op0.getOpcode() == ISD::ANY_EXTEND) {
2037 SDValue InnerOp = Op0.getOperand(0);
2038 EVT InnerVT = InnerOp.getValueType();
2039 unsigned InnerBits = InnerVT.getScalarSizeInBits();
2040 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
2041 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
2042 SDValue NarrowShl = TLO.DAG.getNode(
2043 ISD::SHL, dl, InnerVT, InnerOp,
2044 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
2045 return TLO.CombineTo(
2046 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2047 }
2048
2049 // Repeat the SHL optimization above in cases where an extension
2050 // intervenes: (shl (anyext (shr x, c1)), c2) to
2051 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
2052 // aren't demanded (as above) and that the shifted upper c1 bits of
2053 // x aren't demanded.
2054 // TODO - support non-uniform vector amounts.
2055 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
2056 InnerOp.hasOneUse()) {
2057 if (std::optional<unsigned> SA2 = TLO.DAG.getValidShiftAmount(
2058 InnerOp, DemandedElts, Depth + 2)) {
2059 unsigned InnerShAmt = *SA2;
2060 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
2061 DemandedBits.getActiveBits() <=
2062 (InnerBits - InnerShAmt + ShAmt) &&
2063 DemandedBits.countr_zero() >= ShAmt) {
2064 SDValue NewSA =
2065 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
2066 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
2067 InnerOp.getOperand(0));
2068 return TLO.CombineTo(
2069 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
2070 }
2071 }
2072 }
2073 }
2074
2075 APInt InDemandedMask = DemandedBits.lshr(ShAmt);
2076 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2077 Depth + 1)) {
2078 // Disable the nsw and nuw flags. We can no longer guarantee that we
2079 // won't wrap after simplification.
2080 Op->dropFlags(SDNodeFlags::NoWrap);
2081 return true;
2082 }
2083 Known <<= ShAmt;
2084 // low bits known zero.
2085 Known.Zero.setLowBits(ShAmt);
2086
2087 // Attempt to avoid multi-use ops if we don't need anything from them.
2088 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2090 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2091 if (DemandedOp0) {
2092 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
2093 return TLO.CombineTo(Op, NewOp);
2094 }
2095 }
2096
2097 // TODO: Can we merge this fold with the one below?
2098 // Try shrinking the operation as long as the shift amount will still be
2099 // in range.
2100 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() &&
2101 Op.getNode()->hasOneUse()) {
2102 // Search for the smallest integer type with free casts to and from
2103 // Op's type. For expedience, just check power-of-2 integer types.
2104 unsigned DemandedSize = DemandedBits.getActiveBits();
2105 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
2106 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
2107 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits);
2108 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) &&
2109 isTypeDesirableForOp(ISD::SHL, SmallVT) &&
2110 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) &&
2111 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) {
2112 assert(DemandedSize <= SmallVTBits &&
2113 "Narrowed below demanded bits?");
2114 // We found a type with free casts.
2115 SDValue NarrowShl = TLO.DAG.getNode(
2116 ISD::SHL, dl, SmallVT,
2117 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
2118 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl));
2119 return TLO.CombineTo(
2120 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2121 }
2122 }
2123 }
2124
2125 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2126 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
2127 // Only do this if we demand the upper half so the knownbits are correct.
2128 unsigned HalfWidth = BitWidth / 2;
2129 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
2130 DemandedBits.countLeadingOnes() >= HalfWidth) {
2131 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
2132 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2133 isTypeDesirableForOp(ISD::SHL, HalfVT) &&
2134 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2135 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
2136 // If we're demanding the upper bits at all, we must ensure
2137 // that the upper bits of the shift result are known to be zero,
2138 // which is equivalent to the narrow shift being NUW.
2139 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
2140 bool IsNSW = Known.countMinSignBits() > HalfWidth;
2141 SDNodeFlags Flags;
2142 Flags.setNoSignedWrap(IsNSW);
2143 Flags.setNoUnsignedWrap(IsNUW);
2144 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2145 SDValue NewShiftAmt =
2146 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2147 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
2148 NewShiftAmt, Flags);
2149 SDValue NewExt =
2150 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
2151 return TLO.CombineTo(Op, NewExt);
2152 }
2153 }
2154 }
2155 } else {
2156 // This is a variable shift, so we can't shift the demand mask by a known
2157 // amount. But if we are not demanding high bits, then we are not
2158 // demanding those bits from the pre-shifted operand either.
2159 if (unsigned CTLZ = DemandedBits.countl_zero()) {
2160 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
2161 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
2162 Depth + 1)) {
2163 // Disable the nsw and nuw flags. We can no longer guarantee that we
2164 // won't wrap after simplification.
2165 Op->dropFlags(SDNodeFlags::NoWrap);
2166 return true;
2167 }
2168 Known.resetAll();
2169 }
2170 }
2171
2172 // If we are only demanding sign bits then we can use the shift source
2173 // directly.
2174 if (std::optional<unsigned> MaxSA =
2175 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2176 unsigned ShAmt = *MaxSA;
2177 unsigned NumSignBits =
2178 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2179 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
2180 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
2181 return TLO.CombineTo(Op, Op0);
2182 }
2183 break;
2184 }
2185 case ISD::SRL: {
2186 SDValue Op0 = Op.getOperand(0);
2187 SDValue Op1 = Op.getOperand(1);
2188 EVT ShiftVT = Op1.getValueType();
2189
2190 if (std::optional<unsigned> KnownSA =
2191 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2192 unsigned ShAmt = *KnownSA;
2193 if (ShAmt == 0)
2194 return TLO.CombineTo(Op, Op0);
2195
2196 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
2197 // single shift. We can do this if the top bits (which are shifted out)
2198 // are never demanded.
2199 // TODO - support non-uniform vector amounts.
2200 if (Op0.getOpcode() == ISD::SHL) {
2201 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2202 if (std::optional<unsigned> InnerSA =
2203 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2204 unsigned C1 = *InnerSA;
2205 unsigned Opc = ISD::SRL;
2206 int Diff = ShAmt - C1;
2207 if (Diff < 0) {
2208 Diff = -Diff;
2209 Opc = ISD::SHL;
2210 }
2211 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2212 return TLO.CombineTo(
2213 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2214 }
2215 }
2216 }
2217
2218 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a
2219 // single sra. We can do this if the top bits are never demanded.
2220 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) {
2221 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2222 if (std::optional<unsigned> InnerSA =
2223 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2224 unsigned C1 = *InnerSA;
2225 // Clamp the combined shift amount if it exceeds the bit width.
2226 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1);
2227 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT);
2228 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT,
2229 Op0.getOperand(0), NewSA));
2230 }
2231 }
2232 }
2233
2234 APInt InDemandedMask = (DemandedBits << ShAmt);
2235
2236 // If the shift is exact, then it does demand the low bits (and knows that
2237 // they are zero).
2238 if (Op->getFlags().hasExact())
2239 InDemandedMask.setLowBits(ShAmt);
2240
2241 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2242 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
2243 if ((BitWidth % 2) == 0 && !VT.isVector()) {
2245 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
2246 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2247 isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2248 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2249 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
2250 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
2251 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
2252 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2253 SDValue NewShiftAmt =
2254 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2255 SDValue NewShift =
2256 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt);
2257 return TLO.CombineTo(
2258 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
2259 }
2260 }
2261
2262 // Compute the new bits that are at the top now.
2263 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2264 Depth + 1))
2265 return true;
2266 Known >>= ShAmt;
2267 // High bits known zero.
2268 Known.Zero.setHighBits(ShAmt);
2269
2270 // Attempt to avoid multi-use ops if we don't need anything from them.
2271 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2273 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2274 if (DemandedOp0) {
2275 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
2276 return TLO.CombineTo(Op, NewOp);
2277 }
2278 }
2279 } else {
2280 // Use generic knownbits computation as it has support for non-uniform
2281 // shift amounts.
2282 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2283 }
2284
2285 // If we are only demanding sign bits then we can use the shift source
2286 // directly.
2287 if (std::optional<unsigned> MaxSA =
2288 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2289 unsigned ShAmt = *MaxSA;
2290 // Must already be signbits in DemandedBits bounds, and can't demand any
2291 // shifted in zeroes.
2292 if (DemandedBits.countl_zero() >= ShAmt) {
2293 unsigned NumSignBits =
2294 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2295 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
2296 return TLO.CombineTo(Op, Op0);
2297 }
2298 }
2299
2300 // Try to match AVG patterns (after shift simplification).
2301 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2302 DemandedElts, Depth + 1))
2303 return TLO.CombineTo(Op, AVG);
2304
2305 break;
2306 }
2307 case ISD::SRA: {
2308 SDValue Op0 = Op.getOperand(0);
2309 SDValue Op1 = Op.getOperand(1);
2310 EVT ShiftVT = Op1.getValueType();
2311
2312 // If we only want bits that already match the signbit then we don't need
2313 // to shift.
2314 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
2315 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
2316 NumHiDemandedBits)
2317 return TLO.CombineTo(Op, Op0);
2318
2319 // If this is an arithmetic shift right and only the low-bit is set, we can
2320 // always convert this into a logical shr, even if the shift amount is
2321 // variable. The low bit of the shift cannot be an input sign bit unless
2322 // the shift amount is >= the size of the datatype, which is undefined.
2323 if (DemandedBits.isOne())
2324 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2325
2326 if (std::optional<unsigned> KnownSA =
2327 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2328 unsigned ShAmt = *KnownSA;
2329 if (ShAmt == 0)
2330 return TLO.CombineTo(Op, Op0);
2331
2332 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2333 // supports sext_inreg.
2334 if (Op0.getOpcode() == ISD::SHL) {
2335 if (std::optional<unsigned> InnerSA =
2336 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2337 unsigned LowBits = BitWidth - ShAmt;
2338 EVT ExtVT = VT.changeElementType(
2339 *TLO.DAG.getContext(),
2340 EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits));
2341
2342 if (*InnerSA == ShAmt) {
2343 if (!TLO.LegalOperations() ||
2345 return TLO.CombineTo(
2346 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2347 Op0.getOperand(0),
2348 TLO.DAG.getValueType(ExtVT)));
2349
2350 // Even if we can't convert to sext_inreg, we might be able to
2351 // remove this shift pair if the input is already sign extended.
2352 unsigned NumSignBits =
2353 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2354 if (NumSignBits > ShAmt)
2355 return TLO.CombineTo(Op, Op0.getOperand(0));
2356 }
2357 }
2358 }
2359
2360 APInt InDemandedMask = (DemandedBits << ShAmt);
2361
2362 // If the shift is exact, then it does demand the low bits (and knows that
2363 // they are zero).
2364 if (Op->getFlags().hasExact())
2365 InDemandedMask.setLowBits(ShAmt);
2366
2367 // If any of the demanded bits are produced by the sign extension, we also
2368 // demand the input sign bit.
2369 if (DemandedBits.countl_zero() < ShAmt)
2370 InDemandedMask.setSignBit();
2371
2372 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2373 Depth + 1))
2374 return true;
2375 Known >>= ShAmt;
2376
2377 // If the input sign bit is known to be zero, or if none of the top bits
2378 // are demanded, turn this into an unsigned shift right.
2379 if (Known.Zero[BitWidth - ShAmt - 1] ||
2380 DemandedBits.countl_zero() >= ShAmt) {
2381 SDNodeFlags Flags;
2382 Flags.setExact(Op->getFlags().hasExact());
2383 return TLO.CombineTo(
2384 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2385 }
2386
2387 int Log2 = DemandedBits.exactLogBase2();
2388 if (Log2 >= 0) {
2389 // The bit must come from the sign.
2390 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2391 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2392 }
2393
2394 if (Known.One[BitWidth - ShAmt - 1])
2395 // New bits are known one.
2396 Known.One.setHighBits(ShAmt);
2397
2398 // Attempt to avoid multi-use ops if we don't need anything from them.
2399 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2401 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2402 if (DemandedOp0) {
2403 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2404 return TLO.CombineTo(Op, NewOp);
2405 }
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
2414 break;
2415 }
2416 case ISD::FSHL:
2417 case ISD::FSHR: {
2418 SDValue Op0 = Op.getOperand(0);
2419 SDValue Op1 = Op.getOperand(1);
2420 SDValue Op2 = Op.getOperand(2);
2421 bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2422
2423 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2424 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2425
2426 // For fshl, 0-shift returns the 1st arg.
2427 // For fshr, 0-shift returns the 2nd arg.
2428 if (Amt == 0) {
2429 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2430 Known, TLO, Depth + 1))
2431 return true;
2432 break;
2433 }
2434
2435 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2436 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2437 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2438 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2439 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2440 Depth + 1))
2441 return true;
2442 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2443 Depth + 1))
2444 return true;
2445
2446 Known2 <<= (IsFSHL ? Amt : (BitWidth - Amt));
2447 Known >>= (IsFSHL ? (BitWidth - Amt) : Amt);
2448 Known = Known.unionWith(Known2);
2449
2450 // Attempt to avoid multi-use ops if we don't need anything from them.
2451 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2452 !DemandedElts.isAllOnes()) {
2454 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2456 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2457 if (DemandedOp0 || DemandedOp1) {
2458 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2459 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2460 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2461 DemandedOp1, Op2);
2462 return TLO.CombineTo(Op, NewOp);
2463 }
2464 }
2465 }
2466
2467 if (isPowerOf2_32(BitWidth)) {
2468 // Fold FSHR(Op0,Op1,Op2) -> SRL(Op1,Op2)
2469 // iff we're guaranteed not to use Op0.
2470 // TODO: Add FSHL equivalent?
2471 if (!IsFSHL && !DemandedBits.isAllOnes() &&
2472 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT))) {
2473 KnownBits KnownAmt =
2474 TLO.DAG.computeKnownBits(Op2, DemandedElts, Depth + 1);
2475 unsigned MaxShiftAmt =
2476 KnownAmt.getMaxValue().getLimitedValue(BitWidth - 1);
2477 // Check we don't demand any shifted bits outside Op1.
2478 if (DemandedBits.countl_zero() >= MaxShiftAmt) {
2479 EVT AmtVT = Op2.getValueType();
2480 SDValue NewAmt =
2481 TLO.DAG.getNode(ISD::AND, dl, AmtVT, Op2,
2482 TLO.DAG.getConstant(BitWidth - 1, dl, AmtVT));
2483 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, Op1, NewAmt);
2484 return TLO.CombineTo(Op, NewOp);
2485 }
2486 }
2487
2488 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2489 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2490 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, Known2, TLO,
2491 Depth + 1))
2492 return true;
2493 }
2494 break;
2495 }
2496 case ISD::ROTL:
2497 case ISD::ROTR: {
2498 SDValue Op0 = Op.getOperand(0);
2499 SDValue Op1 = Op.getOperand(1);
2500 bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2501
2502 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2503 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2504 return TLO.CombineTo(Op, Op0);
2505
2506 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2507 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2508 unsigned RevAmt = BitWidth - Amt;
2509
2510 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2511 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2512 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2513 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2514 Depth + 1))
2515 return true;
2516
2517 // rot*(x, 0) --> x
2518 if (Amt == 0)
2519 return TLO.CombineTo(Op, Op0);
2520
2521 // See if we don't demand either half of the rotated bits.
2522 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2523 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2524 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2525 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2526 }
2527 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2528 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2529 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2530 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2531 }
2532 }
2533
2534 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2535 if (isPowerOf2_32(BitWidth)) {
2536 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2537 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2538 Depth + 1))
2539 return true;
2540 }
2541 break;
2542 }
2543 case ISD::SMIN:
2544 case ISD::SMAX:
2545 case ISD::UMIN:
2546 case ISD::UMAX: {
2547 unsigned Opc = Op.getOpcode();
2548 SDValue Op0 = Op.getOperand(0);
2549 SDValue Op1 = Op.getOperand(1);
2550
2551 // If we're only demanding signbits, then we can simplify to OR/AND node.
2552 unsigned BitOp =
2553 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2554 unsigned NumSignBits =
2555 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2556 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2557 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2558 if (NumSignBits >= NumDemandedUpperBits)
2559 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2560
2561 // Check if one arg is always less/greater than (or equal) to the other arg.
2562 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2563 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2564 switch (Opc) {
2565 case ISD::SMIN:
2566 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2567 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2568 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2569 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2570 Known = KnownBits::smin(Known0, Known1);
2571 break;
2572 case ISD::SMAX:
2573 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2574 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2575 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2576 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2577 Known = KnownBits::smax(Known0, Known1);
2578 break;
2579 case ISD::UMIN:
2580 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2581 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2582 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2583 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2584 Known = KnownBits::umin(Known0, Known1);
2585 break;
2586 case ISD::UMAX:
2587 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2588 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2589 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2590 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2591 Known = KnownBits::umax(Known0, Known1);
2592 break;
2593 }
2594 break;
2595 }
2596 case ISD::BITREVERSE: {
2597 SDValue Src = Op.getOperand(0);
2598 APInt DemandedSrcBits = DemandedBits.reverseBits();
2599 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2600 Depth + 1))
2601 return true;
2602 Known = Known2.reverseBits();
2603 break;
2604 }
2605 case ISD::BSWAP: {
2606 SDValue Src = Op.getOperand(0);
2607
2608 // If the only bits demanded come from one byte of the bswap result,
2609 // just shift the input byte into position to eliminate the bswap.
2610 unsigned NLZ = DemandedBits.countl_zero();
2611 unsigned NTZ = DemandedBits.countr_zero();
2612
2613 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
2614 // we need all the bits down to bit 8. Likewise, round NLZ. If we
2615 // have 14 leading zeros, round to 8.
2616 NLZ = alignDown(NLZ, 8);
2617 NTZ = alignDown(NTZ, 8);
2618 // If we need exactly one byte, we can do this transformation.
2619 if (BitWidth - NLZ - NTZ == 8) {
2620 // Replace this with either a left or right shift to get the byte into
2621 // the right place.
2622 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2623 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2624 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2625 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
2626 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2627 return TLO.CombineTo(Op, NewOp);
2628 }
2629 }
2630
2631 APInt DemandedSrcBits = DemandedBits.byteSwap();
2632 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2633 Depth + 1))
2634 return true;
2635 Known = Known2.byteSwap();
2636 break;
2637 }
2638 case ISD::CTPOP: {
2639 // If only 1 bit is demanded, replace with PARITY as long as we're before
2640 // op legalization.
2641 // FIXME: Limit to scalars for now.
2642 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2643 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2644 Op.getOperand(0)));
2645
2646 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2647 break;
2648 }
2649 case ISD::PDEP: {
2650 SDValue Op0 = Op.getOperand(0);
2651 SDValue Op1 = Op.getOperand(1);
2652
2653 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2654 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2655
2656 // If the demanded bits has leading zeroes, we don't demand those from the
2657 // mask.
2658 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
2659 return true;
2660
2661 // The number of possible 1s in the mask determines the number of LSBs of
2662 // operand 0 used. Undemanded bits from the mask don't matter so filter
2663 // them before counting.
2664 KnownBits Known2;
2665 uint64_t Count = (~Known.Zero & LoMask).popcount();
2666 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
2667 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
2668 return true;
2669
2670 // Zeroes are retained from the mask, but not ones.
2671 Known.One.clearAllBits();
2672 // The result will have at least as many trailing zeros as the non-mask
2673 // operand since bits can only map to the same or higher bit position.
2674 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
2675 break;
2676 }
2678 SDValue Op0 = Op.getOperand(0);
2679 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2680 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2681
2682 // If we only care about the highest bit, don't bother shifting right.
2683 if (DemandedBits.isSignMask()) {
2684 unsigned MinSignedBits =
2685 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2686 bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2687 // However if the input is already sign extended we expect the sign
2688 // extension to be dropped altogether later and do not simplify.
2689 if (!AlreadySignExtended) {
2690 // Compute the correct shift amount type, which must be getShiftAmountTy
2691 // for scalar types after legalization.
2692 SDValue ShiftAmt =
2693 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl);
2694 return TLO.CombineTo(Op,
2695 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2696 }
2697 }
2698
2699 // If none of the extended bits are demanded, eliminate the sextinreg.
2700 if (DemandedBits.getActiveBits() <= ExVTBits)
2701 return TLO.CombineTo(Op, Op0);
2702
2703 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2704
2705 // Since the sign extended bits are demanded, we know that the sign
2706 // bit is demanded.
2707 InputDemandedBits.setBit(ExVTBits - 1);
2708
2709 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2710 Depth + 1))
2711 return true;
2712
2713 // If the sign bit of the input is known set or clear, then we know the
2714 // top bits of the result.
2715
2716 // If the input sign bit is known zero, convert this into a zero extension.
2717 if (Known.Zero[ExVTBits - 1])
2718 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2719
2720 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2721 if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2722 Known.One.setBitsFrom(ExVTBits);
2723 Known.Zero &= Mask;
2724 } else { // Input sign bit unknown
2725 Known.Zero &= Mask;
2726 Known.One &= Mask;
2727 }
2728 break;
2729 }
2730 case ISD::BUILD_PAIR: {
2731 EVT HalfVT = Op.getOperand(0).getValueType();
2732 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2733
2734 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2735 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2736
2737 KnownBits KnownLo, KnownHi;
2738
2739 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2740 return true;
2741
2742 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2743 return true;
2744
2745 Known = KnownHi.concat(KnownLo);
2746 break;
2747 }
2749 if (VT.isScalableVector())
2750 return false;
2751 [[fallthrough]];
2752 case ISD::ZERO_EXTEND: {
2753 SDValue Src = Op.getOperand(0);
2754 EVT SrcVT = Src.getValueType();
2755 unsigned InBits = SrcVT.getScalarSizeInBits();
2756 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2757 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2758
2759 // If none of the top bits are demanded, convert this into an any_extend.
2760 if (DemandedBits.getActiveBits() <= InBits) {
2761 // If we only need the non-extended bits of the bottom element
2762 // then we can just bitcast to the result.
2763 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2764 VT.getSizeInBits() == SrcVT.getSizeInBits())
2765 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2766
2767 unsigned Opc =
2769 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2770 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2771 }
2772
2773 APInt InDemandedBits = DemandedBits.trunc(InBits);
2774 APInt InDemandedElts = DemandedElts.zext(InElts);
2775 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2776 Depth + 1)) {
2777 Op->dropFlags(SDNodeFlags::NonNeg);
2778 return true;
2779 }
2780 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2781 Known = Known.zext(BitWidth);
2782
2783 // Attempt to avoid multi-use ops if we don't need anything from them.
2785 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2786 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2787 break;
2788 }
2790 if (VT.isScalableVector())
2791 return false;
2792 [[fallthrough]];
2793 case ISD::SIGN_EXTEND: {
2794 SDValue Src = Op.getOperand(0);
2795 EVT SrcVT = Src.getValueType();
2796 unsigned InBits = SrcVT.getScalarSizeInBits();
2797 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2798 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2799
2800 APInt InDemandedElts = DemandedElts.zext(InElts);
2801 APInt InDemandedBits = DemandedBits.trunc(InBits);
2802
2803 // Since some of the sign extended bits are demanded, we know that the sign
2804 // bit is demanded.
2805 InDemandedBits.setBit(InBits - 1);
2806
2807 // If none of the top bits are demanded, convert this into an any_extend.
2808 if (DemandedBits.getActiveBits() <= InBits) {
2809 // If we only need the non-extended bits of the bottom element
2810 // then we can just bitcast to the result.
2811 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2812 VT.getSizeInBits() == SrcVT.getSizeInBits())
2813 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2814
2815 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans.
2817 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) !=
2818 InBits) {
2819 unsigned Opc =
2821 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2822 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2823 }
2824 }
2825
2826 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2827 Depth + 1))
2828 return true;
2829 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2830
2831 // If the sign bit is known one, the top bits match.
2832 Known = Known.sext(BitWidth);
2833
2834 // If the sign bit is known zero, convert this to a zero extend.
2835 if (Known.isNonNegative()) {
2836 unsigned Opc =
2838 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) {
2839 SDNodeFlags Flags;
2840 if (!IsVecInReg)
2841 Flags |= SDNodeFlags::NonNeg;
2842 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags));
2843 }
2844 }
2845
2846 // Attempt to avoid multi-use ops if we don't need anything from them.
2848 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2849 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2850 break;
2851 }
2853 if (VT.isScalableVector())
2854 return false;
2855 [[fallthrough]];
2856 case ISD::ANY_EXTEND: {
2857 SDValue Src = Op.getOperand(0);
2858 EVT SrcVT = Src.getValueType();
2859 unsigned InBits = SrcVT.getScalarSizeInBits();
2860 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2861 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2862
2863 // If we only need the bottom element then we can just bitcast.
2864 // TODO: Handle ANY_EXTEND?
2865 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2866 VT.getSizeInBits() == SrcVT.getSizeInBits())
2867 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2868
2869 APInt InDemandedBits = DemandedBits.trunc(InBits);
2870 APInt InDemandedElts = DemandedElts.zext(InElts);
2871 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2872 Depth + 1))
2873 return true;
2874 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2875 Known = Known.anyext(BitWidth);
2876
2877 // Attempt to avoid multi-use ops if we don't need anything from them.
2879 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2880 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2881 break;
2882 }
2883 case ISD::TRUNCATE: {
2884 SDValue Src = Op.getOperand(0);
2885
2886 // Simplify the input, using demanded bit information, and compute the known
2887 // zero/one bits live out.
2888 unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2889 APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2890 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2891 Depth + 1)) {
2892 // Disable the nsw and nuw flags. We can no longer guarantee that we
2893 // won't wrap after simplification.
2894 Op->dropFlags(SDNodeFlags::NoWrap);
2895 return true;
2896 }
2897 Known = Known.trunc(BitWidth);
2898
2899 // Attempt to avoid multi-use ops if we don't need anything from them.
2901 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2902 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2903
2904 // If the input is only used by this truncate, see if we can shrink it based
2905 // on the known demanded bits.
2906 switch (Src.getOpcode()) {
2907 default:
2908 break;
2909 case ISD::SRL:
2910 // Shrink SRL by a constant if none of the high bits shifted in are
2911 // demanded.
2912 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2913 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2914 // undesirable.
2915 break;
2916
2917 if (Src.getNode()->hasOneUse()) {
2918 if (isTruncateFree(Src, VT) &&
2919 !isTruncateFree(Src.getValueType(), VT)) {
2920 // If truncate is only free at trunc(srl), do not turn it into
2921 // srl(trunc). The check is done by first check the truncate is free
2922 // at Src's opcode(srl), then check the truncate is not done by
2923 // referencing sub-register. In test, if both trunc(srl) and
2924 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only
2925 // trunc(srl)'s trunc is free, trunc(srl) is better.
2926 break;
2927 }
2928
2929 std::optional<unsigned> ShAmtC =
2930 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2);
2931 if (!ShAmtC || *ShAmtC >= BitWidth)
2932 break;
2933 unsigned ShVal = *ShAmtC;
2934
2935 APInt HighBits =
2936 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2937 HighBits.lshrInPlace(ShVal);
2938 HighBits = HighBits.trunc(BitWidth);
2939 if (!(HighBits & DemandedBits)) {
2940 // None of the shifted in bits are needed. Add a truncate of the
2941 // shift input, then shift it.
2942 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2943 SDValue NewTrunc =
2944 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2945 return TLO.CombineTo(
2946 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2947 }
2948 }
2949 break;
2950 }
2951
2952 break;
2953 }
2954 case ISD::AssertZext: {
2955 // AssertZext demands all of the high bits, plus any of the low bits
2956 // demanded by its users.
2957 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2959 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2960 TLO, Depth + 1))
2961 return true;
2962
2963 Known.Zero |= ~InMask;
2964 Known.One &= (~Known.Zero);
2965 break;
2966 }
2968 SDValue Src = Op.getOperand(0);
2969 SDValue Idx = Op.getOperand(1);
2970 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2971 unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2972
2973 if (SrcEltCnt.isScalable())
2974 return false;
2975
2976 // Demand the bits from every vector element without a constant index.
2977 unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2978 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2979 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2980 if (CIdx->getAPIntValue().ult(NumSrcElts))
2981 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2982
2983 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2984 // anything about the extended bits.
2985 APInt DemandedSrcBits = DemandedBits;
2986 if (BitWidth > EltBitWidth)
2987 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2988
2989 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2990 Depth + 1))
2991 return true;
2992
2993 // Attempt to avoid multi-use ops if we don't need anything from them.
2994 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2995 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2996 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2997 SDValue NewOp =
2998 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2999 return TLO.CombineTo(Op, NewOp);
3000 }
3001 }
3002
3003 Known = Known2;
3004 if (BitWidth > EltBitWidth)
3005 Known = Known.anyext(BitWidth);
3006 break;
3007 }
3008 case ISD::BITCAST: {
3009 if (VT.isScalableVector())
3010 return false;
3011 SDValue Src = Op.getOperand(0);
3012 EVT SrcVT = Src.getValueType();
3013 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
3014
3015 // If this is an FP->Int bitcast and if the sign bit is the only
3016 // thing demanded, turn this into a FGETSIGN.
3017 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
3018 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
3019 SrcVT.isFloatingPoint()) {
3021 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
3022 // place. We expect the SHL to be eliminated by other optimizations.
3023 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, VT, Src);
3024 unsigned ShVal = Op.getValueSizeInBits() - 1;
3025 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
3026 return TLO.CombineTo(Op,
3027 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
3028 }
3029 }
3030
3031 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
3032 // Demand the elt/bit if any of the original elts/bits are demanded.
3033 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
3034 unsigned Scale = BitWidth / NumSrcEltBits;
3035 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3036 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
3037 for (unsigned i = 0; i != Scale; ++i) {
3038 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
3039 unsigned BitOffset = EltOffset * NumSrcEltBits;
3040 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
3041 }
3042 // Recursive calls below may turn not demanded elements into poison, so we
3043 // need to demand all smaller source elements that maps to a demanded
3044 // destination element.
3045 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3046
3047 APInt KnownSrcUndef, KnownSrcZero;
3048 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
3049 KnownSrcZero, TLO, Depth + 1))
3050 return true;
3051
3052 KnownBits KnownSrcBits;
3053 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
3054 KnownSrcBits, TLO, Depth + 1))
3055 return true;
3056 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
3057 // TODO - bigendian once we have test coverage.
3058 unsigned Scale = NumSrcEltBits / BitWidth;
3059 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
3060 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
3061 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
3062 for (unsigned i = 0; i != NumElts; ++i)
3063 if (DemandedElts[i]) {
3064 unsigned Offset = (i % Scale) * BitWidth;
3065 DemandedSrcBits.insertBits(DemandedBits, Offset);
3066 DemandedSrcElts.setBit(i / Scale);
3067 }
3068
3069 if (SrcVT.isVector()) {
3070 APInt KnownSrcUndef, KnownSrcZero;
3071 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
3072 KnownSrcZero, TLO, Depth + 1))
3073 return true;
3074 }
3075
3076 KnownBits KnownSrcBits;
3077 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
3078 KnownSrcBits, TLO, Depth + 1))
3079 return true;
3080
3081 // Attempt to avoid multi-use ops if we don't need anything from them.
3082 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
3083 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
3084 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
3085 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
3086 return TLO.CombineTo(Op, NewOp);
3087 }
3088 }
3089 }
3090
3091 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
3092 // recursive call where Known may be useful to the caller.
3093 if (Depth > 0) {
3094 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3095 return false;
3096 }
3097 break;
3098 }
3099 case ISD::MUL:
3100 if (DemandedBits.isPowerOf2()) {
3101 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
3102 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
3103 // odd (has LSB set), then the left-shifted low bit of X is the answer.
3104 unsigned CTZ = DemandedBits.countr_zero();
3105 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
3106 if (C && C->getAPIntValue().countr_zero() == CTZ) {
3107 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl);
3108 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
3109 return TLO.CombineTo(Op, Shl);
3110 }
3111 }
3112 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
3113 // X * X is odd iff X is odd.
3114 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
3115 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
3116 SDValue One = TLO.DAG.getConstant(1, dl, VT);
3117 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
3118 return TLO.CombineTo(Op, And1);
3119 }
3120 [[fallthrough]];
3121 case ISD::PTRADD:
3122 if (Op.getOperand(0).getValueType() != Op.getOperand(1).getValueType())
3123 break;
3124 // PTRADD behaves like ADD if pointers are represented as integers.
3125 [[fallthrough]];
3126 case ISD::ADD:
3127 case ISD::SUB: {
3128 // Add, Sub, and Mul don't demand any bits in positions beyond that
3129 // of the highest bit demanded of them.
3130 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
3131 SDNodeFlags Flags = Op.getNode()->getFlags();
3132 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
3133 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
3134 KnownBits KnownOp0, KnownOp1;
3135 auto GetDemandedBitsLHSMask = [&](APInt Demanded,
3136 const KnownBits &KnownRHS) {
3137 if (Op.getOpcode() == ISD::MUL)
3138 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros());
3139 return Demanded;
3140 };
3141 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
3142 Depth + 1) ||
3143 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1),
3144 DemandedElts, KnownOp0, TLO, Depth + 1) ||
3145 // See if the operation should be performed at a smaller bit width.
3147 // Disable the nsw and nuw flags. We can no longer guarantee that we
3148 // won't wrap after simplification.
3149 Op->dropFlags(SDNodeFlags::NoWrap);
3150 return true;
3151 }
3152
3153 // neg x with only low bit demanded is simply x.
3154 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
3155 isNullConstant(Op0))
3156 return TLO.CombineTo(Op, Op1);
3157
3158 // Attempt to avoid multi-use ops if we don't need anything from them.
3159 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
3161 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3163 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3164 if (DemandedOp0 || DemandedOp1) {
3165 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
3166 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
3167 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
3168 Flags & ~SDNodeFlags::NoWrap);
3169 return TLO.CombineTo(Op, NewOp);
3170 }
3171 }
3172
3173 // If we have a constant operand, we may be able to turn it into -1 if we
3174 // do not demand the high bits. This can make the constant smaller to
3175 // encode, allow more general folding, or match specialized instruction
3176 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
3177 // is probably not useful (and could be detrimental).
3179 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
3180 if (C && !C->isAllOnes() && !C->isOne() &&
3181 (C->getAPIntValue() | HighMask).isAllOnes()) {
3182 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
3183 // Disable the nsw and nuw flags. We can no longer guarantee that we
3184 // won't wrap after simplification.
3185 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1,
3186 Flags & ~SDNodeFlags::NoWrap);
3187 return TLO.CombineTo(Op, NewOp);
3188 }
3189
3190 // Match a multiply with a disguised negated-power-of-2 and convert to a
3191 // an equivalent shift-left amount.
3192 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3193 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
3194 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
3195 return 0;
3196
3197 // Don't touch opaque constants. Also, ignore zero and power-of-2
3198 // multiplies. Those will get folded later.
3199 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
3200 if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
3201 !MulC->getAPIntValue().isPowerOf2()) {
3202 APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
3203 if (UnmaskedC.isNegatedPowerOf2())
3204 return (-UnmaskedC).logBase2();
3205 }
3206 return 0;
3207 };
3208
3209 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y,
3210 unsigned ShlAmt) {
3211 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl);
3212 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
3213 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
3214 return TLO.CombineTo(Op, Res);
3215 };
3216
3218 if (Op.getOpcode() == ISD::ADD) {
3219 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3220 if (unsigned ShAmt = getShiftLeftAmt(Op0))
3221 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
3222 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
3223 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3224 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
3225 }
3226 if (Op.getOpcode() == ISD::SUB) {
3227 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
3228 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3229 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
3230 }
3231 }
3232
3233 if (Op.getOpcode() == ISD::MUL) {
3234 Known = KnownBits::mul(KnownOp0, KnownOp1);
3235 } else { // Op.getOpcode() is either ISD::ADD, ISD::PTRADD, or ISD::SUB.
3237 Op.getOpcode() != ISD::SUB, Flags.hasNoSignedWrap(),
3238 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1);
3239 }
3240 break;
3241 }
3242 case ISD::FABS: {
3243 SDValue Op0 = Op.getOperand(0);
3244 APInt SignMask = APInt::getSignMask(BitWidth);
3245
3246 if (!DemandedBits.intersects(SignMask))
3247 return TLO.CombineTo(Op, Op0);
3248
3249 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3250 Depth + 1))
3251 return true;
3252
3253 if (Known.isNonNegative())
3254 return TLO.CombineTo(Op, Op0);
3255 if (Known.isNegative())
3256 return TLO.CombineTo(
3257 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT, Op0, Op->getFlags()));
3258
3259 Known.Zero |= SignMask;
3260 Known.One &= ~SignMask;
3261
3262 break;
3263 }
3264 case ISD::FCOPYSIGN: {
3265 SDValue Op0 = Op.getOperand(0);
3266 SDValue Op1 = Op.getOperand(1);
3267
3268 unsigned BitWidth0 = Op0.getScalarValueSizeInBits();
3269 unsigned BitWidth1 = Op1.getScalarValueSizeInBits();
3270 APInt SignMask0 = APInt::getSignMask(BitWidth0);
3271 APInt SignMask1 = APInt::getSignMask(BitWidth1);
3272
3273 if (!DemandedBits.intersects(SignMask0))
3274 return TLO.CombineTo(Op, Op0);
3275
3276 if (SimplifyDemandedBits(Op0, ~SignMask0 & DemandedBits, DemandedElts,
3277 Known, TLO, Depth + 1) ||
3278 SimplifyDemandedBits(Op1, SignMask1, DemandedElts, Known2, TLO,
3279 Depth + 1))
3280 return true;
3281
3282 if (Known2.isNonNegative())
3283 return TLO.CombineTo(
3284 Op, TLO.DAG.getNode(ISD::FABS, dl, VT, Op0, Op->getFlags()));
3285
3286 if (Known2.isNegative())
3287 return TLO.CombineTo(
3288 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT,
3289 TLO.DAG.getNode(ISD::FABS, SDLoc(Op0), VT, Op0)));
3290
3291 Known.Zero &= ~SignMask0;
3292 Known.One &= ~SignMask0;
3293 break;
3294 }
3295 case ISD::FNEG: {
3296 SDValue Op0 = Op.getOperand(0);
3297 APInt SignMask = APInt::getSignMask(BitWidth);
3298
3299 if (!DemandedBits.intersects(SignMask))
3300 return TLO.CombineTo(Op, Op0);
3301
3302 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3303 Depth + 1))
3304 return true;
3305
3306 if (!Known.isSignUnknown()) {
3307 Known.Zero ^= SignMask;
3308 Known.One ^= SignMask;
3309 }
3310
3311 break;
3312 }
3313 default:
3314 // We also ask the target about intrinsics (which could be specific to it).
3315 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3316 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
3317 // TODO: Probably okay to remove after audit; here to reduce change size
3318 // in initial enablement patch for scalable vectors
3319 if (Op.getValueType().isScalableVector())
3320 break;
3322 Known, TLO, Depth))
3323 return true;
3324 break;
3325 }
3326
3327 // Just use computeKnownBits to compute output bits.
3328 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3329 break;
3330 }
3331
3332 // If we know the value of all of the demanded bits, return this as a
3333 // constant.
3335 DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
3336 // Avoid folding to a constant if any OpaqueConstant is involved.
3337 if (llvm::any_of(Op->ops(), [](SDValue V) {
3338 auto *C = dyn_cast<ConstantSDNode>(V);
3339 return C && C->isOpaque();
3340 }))
3341 return false;
3342 if (VT.isInteger())
3343 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
3344 if (VT.isFloatingPoint())
3345 return TLO.CombineTo(
3347 dl, VT));
3348 }
3349
3350 // A multi use 'all demanded elts' simplify failed to find any knownbits.
3351 // Try again just for the original demanded elts.
3352 // Ensure we do this AFTER constant folding above.
3353 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
3354 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
3355
3356 return false;
3357}
3358
3360 const APInt &DemandedElts,
3361 DAGCombinerInfo &DCI) const {
3362 SelectionDAG &DAG = DCI.DAG;
3363 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3364 !DCI.isBeforeLegalizeOps());
3365
3366 APInt KnownUndef, KnownZero;
3367 bool Simplified =
3368 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
3369 if (Simplified) {
3370 DCI.AddToWorklist(Op.getNode());
3371 DCI.CommitTargetLoweringOpt(TLO);
3372 }
3373
3374 return Simplified;
3375}
3376
3377/// Given a vector binary operation and known undefined elements for each input
3378/// operand, compute whether each element of the output is undefined.
3380 const APInt &UndefOp0,
3381 const APInt &UndefOp1) {
3382 EVT VT = BO.getValueType();
3384 "Vector binop only");
3385
3386 EVT EltVT = VT.getVectorElementType();
3387 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
3388 assert(UndefOp0.getBitWidth() == NumElts &&
3389 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
3390
3391 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
3392 const APInt &UndefVals) {
3393 if (UndefVals[Index])
3394 return DAG.getUNDEF(EltVT);
3395
3396 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
3397 // Try hard to make sure that the getNode() call is not creating temporary
3398 // nodes. Ignore opaque integers because they do not constant fold.
3399 SDValue Elt = BV->getOperand(Index);
3400 auto *C = dyn_cast<ConstantSDNode>(Elt);
3401 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
3402 return Elt;
3403 }
3404
3405 return SDValue();
3406 };
3407
3408 APInt KnownUndef = APInt::getZero(NumElts);
3409 for (unsigned i = 0; i != NumElts; ++i) {
3410 // If both inputs for this element are either constant or undef and match
3411 // the element type, compute the constant/undef result for this element of
3412 // the vector.
3413 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
3414 // not handle FP constants. The code within getNode() should be refactored
3415 // to avoid the danger of creating a bogus temporary node here.
3416 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
3417 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
3418 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
3419 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
3420 KnownUndef.setBit(i);
3421 }
3422 return KnownUndef;
3423}
3424
3426 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3427 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3428 bool AssumeSingleUse) const {
3429 EVT VT = Op.getValueType();
3430 unsigned Opcode = Op.getOpcode();
3431 APInt DemandedElts = OriginalDemandedElts;
3432 unsigned NumElts = DemandedElts.getBitWidth();
3433 assert(VT.isVector() && "Expected vector op");
3434
3435 KnownUndef = KnownZero = APInt::getZero(NumElts);
3436
3438 return false;
3439
3440 // TODO: For now we assume we know nothing about scalable vectors.
3441 if (VT.isScalableVector())
3442 return false;
3443
3444 assert(VT.getVectorNumElements() == NumElts &&
3445 "Mask size mismatches value type element count!");
3446
3447 // Undef operand.
3448 if (Op.isUndef()) {
3449 KnownUndef.setAllBits();
3450 return false;
3451 }
3452
3453 // If Op has other users, assume that all elements are needed.
3454 if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3455 DemandedElts.setAllBits();
3456
3457 // Not demanding any elements from Op.
3458 if (DemandedElts == 0) {
3459 KnownUndef.setAllBits();
3460 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3461 }
3462
3463 // Limit search depth.
3465 return false;
3466
3467 SDLoc DL(Op);
3468 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3469 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3470
3471 auto TryShrinkBinOp = [&](SDValue Op0, SDValue Op1) {
3472 unsigned ShrunkSize = getPreferredShrunkVectorSizeInBits(Op, DemandedElts);
3473 if (!ShrunkSize)
3474 return false;
3475
3476 assert(ShrunkSize % EltSizeInBits == 0 &&
3477 "Shrunk size not a multiple of element size");
3478 assert(ShrunkSize < VT.getSizeInBits() &&
3479 "Shrunk size must be < original vector size");
3480 assert(ShrunkSize >= EltSizeInBits * DemandedElts.getActiveBits() &&
3481 "Shrunk size must be >= demanded size");
3482
3483 EVT ShrunkVT = VT.changeVectorElementCount(
3484 *TLO.DAG.getContext(),
3485 ElementCount::getFixed(ShrunkSize / EltSizeInBits));
3486 Op0 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op0, 0);
3487 Op1 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op1, 0);
3488 SDValue NewOp =
3489 TLO.DAG.getNode(Opcode, DL, ShrunkVT, Op0, Op1, Op->getFlags());
3490 return TLO.CombineTo(
3491 Op, TLO.DAG.getInsertSubvector(DL, TLO.DAG.getUNDEF(VT), NewOp, 0));
3492 };
3493
3494 // Helper for demanding the specified elements and all the bits of both binary
3495 // operands.
3496 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3497 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3498 TLO.DAG, Depth + 1);
3499 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3500 TLO.DAG, Depth + 1);
3501 if (NewOp0 || NewOp1) {
3502 SDValue NewOp =
3503 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3504 NewOp1 ? NewOp1 : Op1, Op->getFlags());
3505 return TLO.CombineTo(Op, NewOp);
3506 }
3507
3508 if (TryShrinkBinOp(Op0, Op1))
3509 return true;
3510
3511 return false;
3512 };
3513
3514 switch (Opcode) {
3515 case ISD::SCALAR_TO_VECTOR: {
3516 if (!DemandedElts[0])
3517 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
3518 // Upper elements are poison, not undef - don't mark them as KnownUndef.
3519 break;
3520 }
3521 case ISD::BITCAST: {
3522 SDValue Src = Op.getOperand(0);
3523 EVT SrcVT = Src.getValueType();
3524
3525 if (!SrcVT.isVector()) {
3526 // TODO - bigendian once we have test coverage.
3527 if (IsLE) {
3528 APInt DemandedSrcBits = APInt::getZero(SrcVT.getSizeInBits());
3529 unsigned EltSize = VT.getScalarSizeInBits();
3530 for (unsigned I = 0; I != NumElts; ++I) {
3531 if (DemandedElts[I]) {
3532 unsigned Offset = I * EltSize;
3533 DemandedSrcBits.setBits(Offset, Offset + EltSize);
3534 }
3535 }
3537 if (SimplifyDemandedBits(Src, DemandedSrcBits, Known, TLO, Depth + 1))
3538 return true;
3539 }
3540 break;
3541 }
3542
3543 // Fast handling of 'identity' bitcasts.
3544 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3545 if (NumSrcElts == NumElts)
3546 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3547 KnownZero, TLO, Depth + 1);
3548
3549 APInt SrcDemandedElts, SrcZero, SrcUndef;
3550
3551 // Bitcast from 'large element' src vector to 'small element' vector, we
3552 // must demand a source element if any DemandedElt maps to it.
3553 if ((NumElts % NumSrcElts) == 0) {
3554 unsigned Scale = NumElts / NumSrcElts;
3555 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3556 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3557 TLO, Depth + 1))
3558 return true;
3559
3560 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3561 // of the large element.
3562 // TODO - bigendian once we have test coverage.
3563 if (IsLE) {
3564 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3565 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3566 for (unsigned i = 0; i != NumElts; ++i)
3567 if (DemandedElts[i]) {
3568 unsigned Ofs = (i % Scale) * EltSizeInBits;
3569 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3570 }
3571
3573 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3574 TLO, Depth + 1))
3575 return true;
3576
3577 // The bitcast has split each wide element into a number of
3578 // narrow subelements. We have just computed the Known bits
3579 // for wide elements. See if element splitting results in
3580 // some subelements being zero. Only for demanded elements!
3581 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3582 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3583 .isAllOnes())
3584 continue;
3585 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3586 unsigned Elt = Scale * SrcElt + SubElt;
3587 // A wholly-undef source lane is reported as undef below; don't also
3588 // flag it as zero, keeping the undef and zero sets disjoint.
3589 if (DemandedElts[Elt] && !SrcUndef[SrcElt])
3590 KnownZero.setBit(Elt);
3591 }
3592 }
3593 }
3594
3595 // If the src element is zero/undef then all the output elements will be -
3596 // only demanded elements are guaranteed to be correct.
3597 for (unsigned i = 0; i != NumSrcElts; ++i) {
3598 if (SrcDemandedElts[i]) {
3599 if (SrcZero[i])
3600 KnownZero.setBits(i * Scale, (i + 1) * Scale);
3601 if (SrcUndef[i])
3602 KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3603 }
3604 }
3605 }
3606
3607 // Bitcast from 'small element' src vector to 'large element' vector, we
3608 // demand all smaller source elements covered by the larger demanded element
3609 // of this vector.
3610 if ((NumSrcElts % NumElts) == 0) {
3611 unsigned Scale = NumSrcElts / NumElts;
3612 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3613 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3614 TLO, Depth + 1))
3615 return true;
3616
3617 // If all the src elements covering an output element are zero/undef, then
3618 // the output element will be as well, assuming it was demanded.
3619 for (unsigned i = 0; i != NumElts; ++i) {
3620 if (DemandedElts[i]) {
3621 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3622 KnownZero.setBit(i);
3623 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3624 KnownUndef.setBit(i);
3625 }
3626 }
3627 }
3628 break;
3629 }
3630 case ISD::FREEZE: {
3631 SDValue N0 = Op.getOperand(0);
3633 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
3634 return TLO.CombineTo(Op, N0);
3635
3636 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE
3637 // freeze(op(x, ...)) -> op(freeze(x), ...).
3638 // Don't sink the freeze below SCALAR_TO_VECTOR when the scalar is a load
3639 // of a promoted (wider than the element) type: freeze(load) can never be
3640 // folded away (the loaded value may be poison in memory), and the extra
3641 // freeze node then blocks ISel patterns matching scalar_to_vector of a
3642 // load, e.g. the AArch64 scalar_to_vector(extload) -> ldr b/h forms.
3643 // freeze(scalar_to_vector(load)) is equivalent for the demanded element
3644 // zero, and ISel selects the freeze as a plain copy.
3645 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) {
3646 SDValue Scalar = N0.getOperand(0);
3647 bool IsPromotedLoad = Scalar.getOpcode() == ISD::LOAD &&
3648 Scalar.getValueType() != VT.getVectorElementType();
3649 if (!IsPromotedLoad)
3650 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
3651 TLO.DAG.getFreeze(Scalar)));
3652 }
3653 break;
3654 }
3655 case ISD::BUILD_VECTOR: {
3656 // Check all elements and simplify any unused elements with UNDEF.
3657 if (!DemandedElts.isAllOnes()) {
3658 // Don't simplify BROADCASTS.
3659 if (llvm::any_of(Op->op_values(),
3660 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3662 bool Updated = false;
3663 for (unsigned i = 0; i != NumElts; ++i) {
3664 if (!DemandedElts[i] && !Ops[i].isUndef()) {
3665 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3666 KnownUndef.setBit(i);
3667 Updated = true;
3668 }
3669 }
3670 if (Updated)
3671 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3672 }
3673 }
3674 for (unsigned i = 0; i != NumElts; ++i) {
3675 SDValue SrcOp = Op.getOperand(i);
3676 if (SrcOp.isUndef()) {
3677 KnownUndef.setBit(i);
3678 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3680 KnownZero.setBit(i);
3681 }
3682 }
3683 break;
3684 }
3685 case ISD::CONCAT_VECTORS: {
3686 EVT SubVT = Op.getOperand(0).getValueType();
3687 unsigned NumSubVecs = Op.getNumOperands();
3688 unsigned NumSubElts = SubVT.getVectorNumElements();
3689 for (unsigned i = 0; i != NumSubVecs; ++i) {
3690 SDValue SubOp = Op.getOperand(i);
3691 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3692 APInt SubUndef, SubZero;
3693 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3694 Depth + 1))
3695 return true;
3696 KnownUndef.insertBits(SubUndef, i * NumSubElts);
3697 KnownZero.insertBits(SubZero, i * NumSubElts);
3698 }
3699
3700 // Attempt to avoid multi-use ops if we don't need anything from them.
3701 if (!DemandedElts.isAllOnes()) {
3702 bool FoundNewSub = false;
3703 SmallVector<SDValue, 2> DemandedSubOps;
3704 for (unsigned i = 0; i != NumSubVecs; ++i) {
3705 SDValue SubOp = Op.getOperand(i);
3706 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3708 SubOp, SubElts, TLO.DAG, Depth + 1);
3709 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3710 FoundNewSub = NewSubOp ? true : FoundNewSub;
3711 }
3712 if (FoundNewSub) {
3713 SDValue NewOp =
3714 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3715 return TLO.CombineTo(Op, NewOp);
3716 }
3717 }
3718 break;
3719 }
3720 case ISD::INSERT_SUBVECTOR: {
3721 // Demand any elements from the subvector and the remainder from the src it
3722 // is inserted into.
3723 SDValue Src = Op.getOperand(0);
3724 SDValue Sub = Op.getOperand(1);
3725 uint64_t Idx = Op.getConstantOperandVal(2);
3726 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3727 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3728 APInt DemandedSrcElts = DemandedElts;
3729 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3730
3731 // If none of the sub operand elements are demanded, bypass the insert.
3732 if (!DemandedSubElts)
3733 return TLO.CombineTo(Op, Src);
3734
3735 APInt SubUndef, SubZero;
3736 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3737 Depth + 1))
3738 return true;
3739
3740 // If none of the src operand elements are demanded, replace it with undef.
3741 if (!DemandedSrcElts && !Src.isUndef())
3742 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3743 TLO.DAG.getUNDEF(VT), Sub,
3744 Op.getOperand(2)));
3745
3746 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3747 TLO, Depth + 1))
3748 return true;
3749 KnownUndef.insertBits(SubUndef, Idx);
3750 KnownZero.insertBits(SubZero, Idx);
3751
3752 // Attempt to avoid multi-use ops if we don't need anything from them.
3753 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3755 Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3757 Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3758 if (NewSrc || NewSub) {
3759 NewSrc = NewSrc ? NewSrc : Src;
3760 NewSub = NewSub ? NewSub : Sub;
3761 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3762 NewSub, Op.getOperand(2));
3763 return TLO.CombineTo(Op, NewOp);
3764 }
3765 }
3766 break;
3767 }
3769 // Offset the demanded elts by the subvector index.
3770 SDValue Src = Op.getOperand(0);
3771 if (Src.getValueType().isScalableVector())
3772 break;
3773 uint64_t Idx = Op.getConstantOperandVal(1);
3774 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3775 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3776
3777 APInt SrcUndef, SrcZero;
3778 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3779 Depth + 1))
3780 return true;
3781 KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3782 KnownZero = SrcZero.extractBits(NumElts, Idx);
3783
3784 // Attempt to avoid multi-use ops if we don't need anything from them.
3785 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(Src, DemandedSrcElts,
3786 TLO.DAG, Depth + 1);
3787 if (NewSrc) {
3788 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3789 Op.getOperand(1));
3790 return TLO.CombineTo(Op, NewOp);
3791 }
3792 break;
3793 }
3795 SDValue Vec = Op.getOperand(0);
3796 SDValue Scl = Op.getOperand(1);
3797 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3798
3799 // For a legal, constant insertion index, if we don't need this insertion
3800 // then strip it, else remove it from the demanded elts.
3801 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3802 unsigned Idx = CIdx->getZExtValue();
3803 if (!DemandedElts[Idx])
3804 return TLO.CombineTo(Op, Vec);
3805
3806 APInt DemandedVecElts(DemandedElts);
3807 DemandedVecElts.clearBit(Idx);
3808 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3809 KnownZero, TLO, Depth + 1))
3810 return true;
3811
3812 KnownUndef.setBitVal(Idx, Scl.isUndef());
3813
3814 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3815 break;
3816 }
3817
3818 APInt VecUndef, VecZero;
3819 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3820 Depth + 1))
3821 return true;
3822 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3823 break;
3824 }
3825 case ISD::VSELECT: {
3826 SDValue Sel = Op.getOperand(0);
3827 SDValue LHS = Op.getOperand(1);
3828 SDValue RHS = Op.getOperand(2);
3829
3830 // Try to transform the select condition based on the current demanded
3831 // elements.
3832 APInt UndefSel, ZeroSel;
3833 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3834 Depth + 1))
3835 return true;
3836
3837 // See if we can simplify either vselect operand.
3838 APInt DemandedLHS(DemandedElts);
3839 APInt DemandedRHS(DemandedElts);
3840 APInt UndefLHS, ZeroLHS;
3841 APInt UndefRHS, ZeroRHS;
3842 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3843 Depth + 1))
3844 return true;
3845 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3846 Depth + 1))
3847 return true;
3848
3849 KnownUndef = UndefLHS & UndefRHS;
3850 KnownZero = ZeroLHS & ZeroRHS;
3851
3852 // If we know that the selected element is always zero, we don't need the
3853 // select value element.
3854 APInt DemandedSel = DemandedElts & ~KnownZero;
3855 if (DemandedSel != DemandedElts)
3856 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3857 Depth + 1))
3858 return true;
3859
3860 break;
3861 }
3862 case ISD::VECTOR_SHUFFLE: {
3863 SDValue LHS = Op.getOperand(0);
3864 SDValue RHS = Op.getOperand(1);
3865 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3866
3867 // Collect demanded elements from shuffle operands..
3868 APInt DemandedLHS(NumElts, 0);
3869 APInt DemandedRHS(NumElts, 0);
3870 for (unsigned i = 0; i != NumElts; ++i) {
3871 int M = ShuffleMask[i];
3872 if (M < 0 || !DemandedElts[i])
3873 continue;
3874 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3875 if (M < (int)NumElts)
3876 DemandedLHS.setBit(M);
3877 else
3878 DemandedRHS.setBit(M - NumElts);
3879 }
3880
3881 // If either side isn't demanded, replace it by UNDEF. We handle this
3882 // explicitly here to also simplify in case of multiple uses (on the
3883 // contrary to the SimplifyDemandedVectorElts calls below).
3884 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
3885 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
3886 if (FoldLHS || FoldRHS) {
3887 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
3888 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
3889 SDValue NewOp =
3890 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
3891 return TLO.CombineTo(Op, NewOp);
3892 }
3893
3894 // See if we can simplify either shuffle operand.
3895 APInt UndefLHS, ZeroLHS;
3896 APInt UndefRHS, ZeroRHS;
3897 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3898 Depth + 1))
3899 return true;
3900 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3901 Depth + 1))
3902 return true;
3903
3904 // Simplify mask using undef elements from LHS/RHS.
3905 bool Updated = false;
3906 bool IdentityLHS = true, IdentityRHS = true;
3907 SmallVector<int, 32> NewMask(ShuffleMask);
3908 for (unsigned i = 0; i != NumElts; ++i) {
3909 int &M = NewMask[i];
3910 if (M < 0)
3911 continue;
3912 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3913 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3914 Updated = true;
3915 M = -1;
3916 }
3917 IdentityLHS &= (M < 0) || (M == (int)i);
3918 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3919 }
3920
3921 // Update legal shuffle masks based on demanded elements if it won't reduce
3922 // to Identity which can cause premature removal of the shuffle mask.
3923 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3924 SDValue LegalShuffle =
3925 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
3926 if (LegalShuffle)
3927 return TLO.CombineTo(Op, LegalShuffle);
3928 }
3929
3930 // Propagate undef/zero elements from LHS/RHS.
3931 for (unsigned i = 0; i != NumElts; ++i) {
3932 int M = ShuffleMask[i];
3933 if (M < 0) {
3934 KnownUndef.setBit(i);
3935 } else if (M < (int)NumElts) {
3936 if (UndefLHS[M])
3937 KnownUndef.setBit(i);
3938 if (ZeroLHS[M])
3939 KnownZero.setBit(i);
3940 } else {
3941 if (UndefRHS[M - NumElts])
3942 KnownUndef.setBit(i);
3943 if (ZeroRHS[M - NumElts])
3944 KnownZero.setBit(i);
3945 }
3946 }
3947 break;
3948 }
3952 APInt SrcUndef, SrcZero;
3953 SDValue Src = Op.getOperand(0);
3954 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3955 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3956 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3957 Depth + 1))
3958 return true;
3959 KnownZero = SrcZero.zextOrTrunc(NumElts);
3960 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3961
3962 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3963 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3964 DemandedSrcElts == 1) {
3965 // aext - if we just need the bottom element then we can bitcast.
3966 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3967 }
3968
3969 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3970 // zext(undef) upper bits are guaranteed to be zero.
3971 if (DemandedElts.isSubsetOf(KnownUndef))
3972 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3973 KnownUndef.clearAllBits();
3974
3975 // zext - if we just need the bottom element then we can mask:
3976 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3977 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3978 Op->isOnlyUserOf(Src.getNode()) &&
3979 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3980 SDLoc DL(Op);
3981 EVT SrcVT = Src.getValueType();
3982 EVT SrcSVT = SrcVT.getScalarType();
3983
3984 // If we're after type legalization and SrcSVT is not legal, use the
3985 // promoted type for creating constants to avoid creating nodes with
3986 // illegal types.
3987 if (TLO.LegalTypes())
3988 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
3989
3990 SmallVector<SDValue> MaskElts;
3991 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3992 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3993 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3994 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3995 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3996 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3997 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3998 }
3999 }
4000 }
4001 break;
4002 }
4003
4004 // TODO: There are more binop opcodes that could be handled here - MIN,
4005 // MAX, saturated math, etc.
4006 case ISD::ADD: {
4007 SDValue Op0 = Op.getOperand(0);
4008 SDValue Op1 = Op.getOperand(1);
4009 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
4010 APInt UndefLHS, ZeroLHS;
4011 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4012 Depth + 1, /*AssumeSingleUse*/ true))
4013 return true;
4014 }
4015 [[fallthrough]];
4016 }
4017 case ISD::AVGCEILS:
4018 case ISD::AVGCEILU:
4019 case ISD::AVGFLOORS:
4020 case ISD::AVGFLOORU:
4021 case ISD::AVGSUBFLOORS:
4022 case ISD::AVGSUBFLOORU:
4023 case ISD::OR:
4024 case ISD::XOR:
4025 case ISD::SUB:
4026 case ISD::FADD:
4027 case ISD::FSUB:
4028 case ISD::FMUL:
4029 case ISD::FDIV:
4030 case ISD::FREM:
4031 case ISD::PSEUDO_FMIN:
4032 case ISD::PSEUDO_FMAX: {
4033 SDValue Op0 = Op.getOperand(0);
4034 SDValue Op1 = Op.getOperand(1);
4035
4036 APInt UndefRHS, ZeroRHS;
4037 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4038 Depth + 1))
4039 return true;
4040 APInt UndefLHS, ZeroLHS;
4041 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4042 Depth + 1))
4043 return true;
4044
4045 KnownZero = ZeroLHS & ZeroRHS;
4046 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
4047
4048 // Attempt to avoid multi-use ops if we don't need anything from them.
4049 // TODO - use KnownUndef to relax the demandedelts?
4050 if (!DemandedElts.isAllOnes())
4051 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4052 return true;
4053 break;
4054 }
4055 case ISD::SHL:
4056 case ISD::SRL:
4057 case ISD::SRA:
4058 case ISD::ROTL:
4059 case ISD::ROTR: {
4060 SDValue Op0 = Op.getOperand(0);
4061 SDValue Op1 = Op.getOperand(1);
4062
4063 APInt UndefRHS, ZeroRHS;
4064 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4065 Depth + 1))
4066 return true;
4067 APInt UndefLHS, ZeroLHS;
4068 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4069 Depth + 1))
4070 return true;
4071
4072 KnownZero = ZeroLHS & ~UndefRHS;
4073 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
4074
4075 // Attempt to avoid multi-use ops if we don't need anything from them.
4076 // TODO - use KnownUndef to relax the demandedelts?
4077 if (!DemandedElts.isAllOnes())
4078 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4079 return true;
4080 break;
4081 }
4082 case ISD::MUL:
4083 case ISD::MULHU:
4084 case ISD::MULHS:
4085 case ISD::AND: {
4086 SDValue Op0 = Op.getOperand(0);
4087 SDValue Op1 = Op.getOperand(1);
4088
4089 APInt SrcUndef, SrcZero;
4090 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
4091 Depth + 1))
4092 return true;
4093 // FIXME: If we know that a demanded element was zero in Op1 we don't need
4094 // to demand it in Op0 - its guaranteed to be zero. There is however a
4095 // restriction, as we must not make any of the originally demanded elements
4096 // more poisonous. We could reduce amount of elements demanded, but then we
4097 // also need a to inform SimplifyDemandedVectorElts that some elements must
4098 // not be made more poisonous.
4099 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
4100 TLO, Depth + 1))
4101 return true;
4102
4103 KnownUndef &= DemandedElts;
4104 KnownZero &= DemandedElts;
4105
4106 // If every element pair has a zero/undef/poison then just fold to zero.
4107 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
4108 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
4109 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
4110 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4111
4112 // If either side has a zero element, then the result element is zero, even
4113 // if the other is an UNDEF.
4114 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
4115 // and then handle 'and' nodes with the rest of the binop opcodes.
4116 KnownZero |= SrcZero;
4117 KnownUndef &= SrcUndef;
4118 KnownUndef &= ~KnownZero;
4119
4120 // Attempt to avoid multi-use ops if we don't need anything from them.
4121 if (!DemandedElts.isAllOnes())
4122 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4123 return true;
4124 break;
4125 }
4126 case ISD::TRUNCATE:
4127 case ISD::SIGN_EXTEND:
4128 case ISD::ZERO_EXTEND:
4129 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4130 KnownZero, TLO, Depth + 1))
4131 return true;
4132
4133 if (!DemandedElts.isAllOnes())
4135 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
4136 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
4137
4138 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
4139 // zext(undef) upper bits are guaranteed to be zero.
4140 if (DemandedElts.isSubsetOf(KnownUndef))
4141 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4142 KnownUndef.clearAllBits();
4143 }
4144 break;
4145 case ISD::SINT_TO_FP:
4146 case ISD::UINT_TO_FP:
4147 case ISD::FP_TO_SINT:
4148 case ISD::FP_TO_UINT:
4149 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4150 KnownZero, TLO, Depth + 1))
4151 return true;
4152 // Don't fall through to generic undef -> undef handling.
4153 return false;
4154 default: {
4155 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
4156 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
4157 KnownZero, TLO, Depth))
4158 return true;
4159 } else {
4161 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
4162 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
4163 TLO, Depth, AssumeSingleUse))
4164 return true;
4165 }
4166 break;
4167 }
4168 }
4169
4170 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
4171
4172 // Constant fold all undef cases.
4173 // TODO: Handle zero cases as well.
4174 if (DemandedElts.isSubsetOf(KnownUndef))
4175 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
4176
4177 return false;
4178}
4179
4180/// Determine which of the bits specified in Mask are known to be either zero or
4181/// one and return them in the Known.
4184 const APInt &DemandedElts,
4185 const SelectionDAG &DAG,
4186 unsigned Depth) const {
4187 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4188 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4189 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4190 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4191 "Should use MaskedValueIsZero if you don't know whether Op"
4192 " is a target node!");
4193 Known.resetAll();
4194}
4195
4198 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4199 unsigned Depth) const {
4200 Known.resetAll();
4201}
4202
4205 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4206 unsigned Depth) const {
4207 Known.resetAll();
4208}
4209
4211 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4212 // The low bits are known zero if the pointer is aligned.
4213 Known.Zero.setLowBits(Log2(Alignment));
4214}
4215
4217 SelectionDAG &DAG,
4218 const SDLoc &DL,
4219 Align Alignment) const {
4220 // Materialize leading-zero stack object pointer facts as AssertZext.
4221 // Alignment-derived low zero bits are not represented on the returned DAG
4222 // value here.
4223 EVT PtrVT = Ptr.getValueType();
4224
4225 unsigned RegSize = PtrVT.getScalarSizeInBits();
4228 Alignment);
4229
4230 unsigned NumZeroBits = Known.countMinLeadingZeros();
4231 if (!NumZeroBits)
4232 return Ptr;
4233
4234 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4235 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4236}
4237
4243
4244/// This method can be implemented by targets that want to expose additional
4245/// information about sign bits to the DAG Combiner.
4247 const APInt &,
4248 const SelectionDAG &,
4249 unsigned Depth) const {
4250 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4251 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4252 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4253 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4254 "Should use ComputeNumSignBits if you don't know whether Op"
4255 " is a target node!");
4256 return 1;
4257}
4258
4260 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4261 const MachineRegisterInfo &MRI, unsigned Depth) const {
4262 return 1;
4263}
4264
4266 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4267 TargetLoweringOpt &TLO, unsigned Depth) const {
4268 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4269 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4270 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4271 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4272 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4273 " is a target node!");
4274 return false;
4275}
4276
4278 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4279 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4280 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4281 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4282 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4283 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4284 "Should use SimplifyDemandedBits if you don't know whether Op"
4285 " is a target node!");
4286 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4287 return false;
4288}
4289
4291 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4292 SelectionDAG &DAG, unsigned Depth) const {
4293 assert(
4294 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4295 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4296 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4297 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4298 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4299 " is a target node!");
4300 return SDValue();
4301}
4302
4303SDValue
4306 SelectionDAG &DAG) const {
4307 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4308 if (!LegalMask) {
4309 std::swap(N0, N1);
4311 LegalMask = isShuffleMaskLegal(Mask, VT);
4312 }
4313
4314 if (!LegalMask)
4315 return SDValue();
4316
4317 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4318}
4319
4321 return nullptr;
4322}
4323
4325 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4326 UndefPoisonKind Kind, unsigned Depth) const {
4327 assert(
4328 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4329 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4330 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4331 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4332 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4333 " is a target node!");
4334
4335 // If Op can't create undef/poison and none of its operands are undef/poison
4336 // then Op is never undef/poison.
4337 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4338 /*ConsiderFlags*/ true, Depth) &&
4339 all_of(Op->ops(), [&](SDValue V) {
4340 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4341 });
4342}
4343
4345 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4346 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4347 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4348 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4349 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4350 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4351 "Should use canCreateUndefOrPoison if you don't know whether Op"
4352 " is a target node!");
4353 // Be conservative and return true.
4354 return true;
4355}
4356
4359 const APInt &DemandedElts,
4360 const SelectionDAG &DAG,
4361 unsigned Depth) const {
4362 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4363 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4364 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4365 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4366 "Should use computeKnownFPClass if you don't know whether Op"
4367 " is a target node!");
4368}
4369
4371 const APInt &DemandedElts,
4372 const SelectionDAG &DAG,
4373 bool SNaN,
4374 unsigned Depth) const {
4375 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4376 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4377 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4378 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4379 "Should use isKnownNeverNaN if you don't know whether Op"
4380 " is a target node!");
4381 return false;
4382}
4383
4385 const APInt &DemandedElts,
4386 APInt &UndefElts,
4387 const SelectionDAG &DAG,
4388 unsigned Depth) const {
4389 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4390 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4391 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4392 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4393 "Should use isSplatValue if you don't know whether Op"
4394 " is a target node!");
4395 return false;
4396}
4397
4398// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4399// work with truncating build vectors and vectors with elements of less than
4400// 8 bits.
4402 if (!N)
4403 return false;
4404
4405 unsigned EltWidth;
4406 APInt CVal;
4407 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4408 /*AllowTruncation=*/true)) {
4409 CVal = CN->getAPIntValue();
4410 EltWidth = N.getValueType().getScalarSizeInBits();
4411 } else
4412 return false;
4413
4414 // If this is a truncating splat, truncate the splat value.
4415 // Otherwise, we may fail to match the expected values below.
4416 if (EltWidth < CVal.getBitWidth())
4417 CVal = CVal.trunc(EltWidth);
4418
4419 switch (getBooleanContents(N.getValueType())) {
4421 return CVal[0];
4423 return CVal.isOne();
4425 return CVal.isAllOnes();
4426 }
4427
4428 llvm_unreachable("Invalid boolean contents");
4429}
4430
4432 if (!N)
4433 return false;
4434
4436 if (!CN) {
4438 if (!BV)
4439 return false;
4440
4441 // Only interested in constant splats, we don't care about undef
4442 // elements in identifying boolean constants and getConstantSplatNode
4443 // returns NULL if all ops are undef;
4444 CN = BV->getConstantSplatNode();
4445 if (!CN)
4446 return false;
4447 }
4448
4449 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4450 return !CN->getAPIntValue()[0];
4451
4452 return CN->isZero();
4453}
4454
4456 bool SExt) const {
4457 if (VT == MVT::i1)
4458 return N->isOne();
4459
4461 switch (Cnt) {
4463 // An extended value of 1 is always true, unless its original type is i1,
4464 // in which case it will be sign extended to -1.
4465 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4468 return N->isAllOnes() && SExt;
4469 }
4470 llvm_unreachable("Unexpected enumeration.");
4471}
4472
4473/// This helper function of SimplifySetCC tries to optimize the comparison when
4474/// either operand of the SetCC node is a bitwise-and instruction.
4475SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4476 ISD::CondCode Cond, const SDLoc &DL,
4477 DAGCombinerInfo &DCI) const {
4478 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4479 std::swap(N0, N1);
4480
4481 SelectionDAG &DAG = DCI.DAG;
4482 EVT OpVT = N0.getValueType();
4483 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4484 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4485 return SDValue();
4486
4487 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4488 // iff everything but LSB is known zero:
4489 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4492 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4493 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4494 if (DAG.MaskedValueIsZero(N0, UpperBits))
4495 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4496 }
4497
4498 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4499 // test in a narrow type that we can truncate to with no cost. Examples:
4500 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4501 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4502 // TODO: This conservatively checks for type legality on the source and
4503 // destination types. That may inhibit optimizations, but it also
4504 // allows setcc->shift transforms that may be more beneficial.
4505 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4506 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4507 isTypeLegal(OpVT) && N0.hasOneUse()) {
4508 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4509 AndC->getAPIntValue().getActiveBits());
4510 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4511 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4512 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4513 return DAG.getSetCC(DL, VT, Trunc, Zero,
4515 }
4516 }
4517
4518 // Match these patterns in any of their permutations:
4519 // (X & Y) == Y
4520 // (X & Y) != Y
4521 SDValue X, Y;
4522 if (N0.getOperand(0) == N1) {
4523 X = N0.getOperand(1);
4524 Y = N0.getOperand(0);
4525 } else if (N0.getOperand(1) == N1) {
4526 X = N0.getOperand(0);
4527 Y = N0.getOperand(1);
4528 } else {
4529 return SDValue();
4530 }
4531
4532 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4533 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4534 // its liable to create and infinite loop.
4535 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4536 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4538 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4539 // Note that where Y is variable and is known to have at most one bit set
4540 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4541 // equivalent when Y == 0.
4542 assert(OpVT.isInteger());
4544 if (DCI.isBeforeLegalizeOps() ||
4546 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4547 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4548 // If the target supports an 'and-not' or 'and-complement' logic operation,
4549 // try to use that to make a comparison operation more efficient.
4550 // But don't do this transform if the mask is a single bit because there are
4551 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4552 // 'rlwinm' on PPC).
4553
4554 // Bail out if the compare operand that we want to turn into a zero is
4555 // already a zero (otherwise, infinite loop).
4556 if (isNullConstant(Y))
4557 return SDValue();
4558
4559 // Transform this into: ~X & Y == 0.
4560 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4561 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4562 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4563 }
4564
4565 return SDValue();
4566}
4567
4568/// This helper function of SimplifySetCC tries to optimize the comparison when
4569/// either operand of the SetCC node is a bitwise-or instruction.
4570/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4571SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4572 ISD::CondCode Cond, const SDLoc &DL,
4573 DAGCombinerInfo &DCI) const {
4574 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4575 std::swap(N0, N1);
4576
4577 SelectionDAG &DAG = DCI.DAG;
4578 EVT OpVT = N0.getValueType();
4579 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4580 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4581 return SDValue();
4582
4583 // (X | Y) == Y
4584 // (X | Y) != Y
4585 SDValue X;
4586 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4587 // If the target supports an 'and-not' or 'and-complement' logic operation,
4588 // try to use that to make a comparison operation more efficient.
4589
4590 // Bail out if the compare operand that we want to turn into a zero is
4591 // already a zero (otherwise, infinite loop).
4592 if (isNullConstant(N1))
4593 return SDValue();
4594
4595 // Transform this into: X & ~Y ==/!= 0.
4596 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4597 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4598 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4599 }
4600
4601 return SDValue();
4602}
4603
4604/// There are multiple IR patterns that could be checking whether certain
4605/// truncation of a signed number would be lossy or not. The pattern which is
4606/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4607/// We are looking for the following pattern: (KeptBits is a constant)
4608/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4609/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4610/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4611/// We will unfold it into the natural trunc+sext pattern:
4612/// ((%x << C) a>> C) dstcond %x
4613/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4614SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4615 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4616 const SDLoc &DL) const {
4617 // We must be comparing with a constant.
4618 ConstantSDNode *C1;
4619 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4620 return SDValue();
4621
4622 // N0 should be: add %x, (1 << (KeptBits-1))
4623 if (N0->getOpcode() != ISD::ADD)
4624 return SDValue();
4625
4626 // And we must be 'add'ing a constant.
4627 ConstantSDNode *C01;
4628 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4629 return SDValue();
4630
4631 SDValue X = N0->getOperand(0);
4632 EVT XVT = X.getValueType();
4633
4634 // Validate constants ...
4635
4636 APInt I1 = C1->getAPIntValue();
4637
4638 ISD::CondCode NewCond;
4639 if (Cond == ISD::CondCode::SETULT) {
4640 NewCond = ISD::CondCode::SETEQ;
4641 } else if (Cond == ISD::CondCode::SETULE) {
4642 NewCond = ISD::CondCode::SETEQ;
4643 // But need to 'canonicalize' the constant.
4644 I1 += 1;
4645 } else if (Cond == ISD::CondCode::SETUGT) {
4646 NewCond = ISD::CondCode::SETNE;
4647 // But need to 'canonicalize' the constant.
4648 I1 += 1;
4649 } else if (Cond == ISD::CondCode::SETUGE) {
4650 NewCond = ISD::CondCode::SETNE;
4651 } else
4652 return SDValue();
4653
4654 APInt I01 = C01->getAPIntValue();
4655
4656 auto checkConstants = [&I1, &I01]() -> bool {
4657 // Both of them must be power-of-two, and the constant from setcc is bigger.
4658 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4659 };
4660
4661 if (checkConstants()) {
4662 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4663 } else {
4664 // What if we invert constants? (and the target predicate)
4665 I1.negate();
4666 I01.negate();
4667 assert(XVT.isInteger());
4668 NewCond = getSetCCInverse(NewCond, XVT);
4669 if (!checkConstants())
4670 return SDValue();
4671 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4672 }
4673
4674 // They are power-of-two, so which bit is set?
4675 const unsigned KeptBits = I1.logBase2();
4676 const unsigned KeptBitsMinusOne = I01.logBase2();
4677
4678 // Magic!
4679 if (KeptBits != (KeptBitsMinusOne + 1))
4680 return SDValue();
4681 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4682
4683 // We don't want to do this in every single case.
4684 SelectionDAG &DAG = DCI.DAG;
4685 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4686 return SDValue();
4687
4688 // Unfold into: sext_inreg(%x) cond %x
4689 // Where 'cond' will be either 'eq' or 'ne'.
4690 SDValue SExtInReg = DAG.getNode(
4692 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4693 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4694}
4695
4696// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4697SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4698 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4699 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4701 "Should be a comparison with 0.");
4702 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4703 "Valid only for [in]equality comparisons.");
4704
4705 unsigned NewShiftOpcode;
4706 SDValue X, C, Y;
4707
4708 SelectionDAG &DAG = DCI.DAG;
4709
4710 // Look for '(C l>>/<< Y)'.
4711 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4712 // The shift should be one-use.
4713 if (!V.hasOneUse())
4714 return false;
4715 unsigned OldShiftOpcode = V.getOpcode();
4716 switch (OldShiftOpcode) {
4717 case ISD::SHL:
4718 NewShiftOpcode = ISD::SRL;
4719 break;
4720 case ISD::SRL:
4721 NewShiftOpcode = ISD::SHL;
4722 break;
4723 default:
4724 return false; // must be a logical shift.
4725 }
4726 // We should be shifting a constant.
4727 // FIXME: best to use isConstantOrConstantVector().
4728 C = V.getOperand(0);
4729 ConstantSDNode *CC =
4730 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4731 if (!CC)
4732 return false;
4733 Y = V.getOperand(1);
4734
4735 ConstantSDNode *XC =
4736 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4738 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4739 };
4740
4741 // LHS of comparison should be an one-use 'and'.
4742 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4743 return SDValue();
4744
4745 X = N0.getOperand(0);
4746 SDValue Mask = N0.getOperand(1);
4747
4748 // 'and' is commutative!
4749 if (!Match(Mask)) {
4750 std::swap(X, Mask);
4751 if (!Match(Mask))
4752 return SDValue();
4753 }
4754
4755 EVT VT = X.getValueType();
4756
4757 // Produce:
4758 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4759 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4760 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4761 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4762 return T2;
4763}
4764
4765/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4766/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4767/// handle the commuted versions of these patterns.
4768SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4769 ISD::CondCode Cond, const SDLoc &DL,
4770 DAGCombinerInfo &DCI) const {
4771 unsigned BOpcode = N0.getOpcode();
4772 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4773 "Unexpected binop");
4774 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4775
4776 // (X + Y) == X --> Y == 0
4777 // (X - Y) == X --> Y == 0
4778 // (X ^ Y) == X --> Y == 0
4779 SelectionDAG &DAG = DCI.DAG;
4780 EVT OpVT = N0.getValueType();
4781 SDValue X = N0.getOperand(0);
4782 SDValue Y = N0.getOperand(1);
4783 if (X == N1)
4784 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4785
4786 if (Y != N1)
4787 return SDValue();
4788
4789 // (X + Y) == Y --> X == 0
4790 // (X ^ Y) == Y --> X == 0
4791 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4792 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4793
4794 // The shift would not be valid if the operands are boolean (i1).
4795 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4796 return SDValue();
4797
4798 // (X - Y) == Y --> X == Y << 1
4799 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4800 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4801 if (!DCI.isCalledByLegalizer())
4802 DCI.AddToWorklist(YShl1.getNode());
4803 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4804}
4805
4807 SDValue N0, const APInt &C1,
4808 ISD::CondCode Cond, const SDLoc &dl,
4809 SelectionDAG &DAG) {
4810 // Look through truncs that don't change the value of a ctpop.
4811 // FIXME: Add vector support? Need to be careful with setcc result type below.
4812 SDValue CTPOP = N0;
4813 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4815 CTPOP = N0.getOperand(0);
4816
4817 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4818 return SDValue();
4819
4820 EVT CTVT = CTPOP.getValueType();
4821 SDValue CTOp = CTPOP.getOperand(0);
4822
4823 // Expand a power-of-2-or-zero comparison based on ctpop:
4824 // (ctpop x) u< 2 -> (x & x-1) == 0
4825 // (ctpop x) u> 1 -> (x & x-1) != 0
4826 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4827 // Keep the CTPOP if it is a cheap vector op.
4828 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4829 return SDValue();
4830
4831 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4832 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4833 return SDValue();
4834 if (C1 == 0 && (Cond == ISD::SETULT))
4835 return SDValue(); // This is handled elsewhere.
4836
4837 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4838
4839 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4840 SDValue Result = CTOp;
4841 for (unsigned i = 0; i < Passes; i++) {
4842 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4843 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4844 }
4846 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4847 }
4848
4849 // Expand a power-of-2 comparison based on ctpop
4850 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4851 // Keep the CTPOP if it is cheap.
4852 if (TLI.isCtpopFast(CTVT))
4853 return SDValue();
4854
4855 SDValue Zero = DAG.getConstant(0, dl, CTVT);
4856 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4857 assert(CTVT.isInteger());
4858 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4859
4860 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4861 // check before emitting a potentially unnecessary op.
4862 if (DAG.isKnownNeverZero(CTOp)) {
4863 // (ctpop x) == 1 --> (x & x-1) == 0
4864 // (ctpop x) != 1 --> (x & x-1) != 0
4865 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4866 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4867 return RHS;
4868 }
4869
4870 // (ctpop x) == 1 --> (x ^ x-1) > x-1
4871 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4872 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4874 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4875 }
4876
4877 return SDValue();
4878}
4879
4881 ISD::CondCode Cond, const SDLoc &dl,
4882 SelectionDAG &DAG) {
4883 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4884 return SDValue();
4885
4886 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4887 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
4888 return SDValue();
4889
4890 auto getRotateSource = [](SDValue X) {
4891 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
4892 return X.getOperand(0);
4893 return SDValue();
4894 };
4895
4896 // Peek through a rotated value compared against 0 or -1:
4897 // (rot X, Y) == 0/-1 --> X == 0/-1
4898 // (rot X, Y) != 0/-1 --> X != 0/-1
4899 if (SDValue R = getRotateSource(N0))
4900 return DAG.getSetCC(dl, VT, R, N1, Cond);
4901
4902 // Peek through an 'or' of a rotated value compared against 0:
4903 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
4904 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
4905 //
4906 // TODO: Add the 'and' with -1 sibling.
4907 // TODO: Recurse through a series of 'or' ops to find the rotate.
4908 EVT OpVT = N0.getValueType();
4909 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
4910 if (SDValue R = getRotateSource(N0.getOperand(0))) {
4911 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
4912 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4913 }
4914 if (SDValue R = getRotateSource(N0.getOperand(1))) {
4915 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
4916 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4917 }
4918 }
4919
4920 return SDValue();
4921}
4922
4924 ISD::CondCode Cond, const SDLoc &dl,
4925 SelectionDAG &DAG) {
4926 // If we are testing for all-bits-clear, we might be able to do that with
4927 // less shifting since bit-order does not matter.
4928 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4929 return SDValue();
4930
4931 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4932 if (!C1 || !C1->isZero())
4933 return SDValue();
4934
4935 if (!N0.hasOneUse() ||
4936 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
4937 return SDValue();
4938
4939 unsigned BitWidth = N0.getScalarValueSizeInBits();
4940 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
4941 if (!ShAmtC)
4942 return SDValue();
4943
4944 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
4945 if (ShAmt == 0)
4946 return SDValue();
4947
4948 // Canonicalize fshr as fshl to reduce pattern-matching.
4949 if (N0.getOpcode() == ISD::FSHR)
4950 ShAmt = BitWidth - ShAmt;
4951
4952 // Match an 'or' with a specific operand 'Other' in either commuted variant.
4953 SDValue X, Y;
4954 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
4955 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
4956 return false;
4957 if (Or.getOperand(0) == Other) {
4958 X = Or.getOperand(0);
4959 Y = Or.getOperand(1);
4960 return true;
4961 }
4962 if (Or.getOperand(1) == Other) {
4963 X = Or.getOperand(1);
4964 Y = Or.getOperand(0);
4965 return true;
4966 }
4967 return false;
4968 };
4969
4970 EVT OpVT = N0.getValueType();
4971 EVT ShAmtVT = N0.getOperand(2).getValueType();
4972 SDValue F0 = N0.getOperand(0);
4973 SDValue F1 = N0.getOperand(1);
4974 if (matchOr(F0, F1)) {
4975 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4976 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4977 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4978 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4979 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4980 }
4981 if (matchOr(F1, F0)) {
4982 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4983 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4984 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4985 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4986 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4987 }
4988
4989 return SDValue();
4990}
4991
4992/// Try to simplify a setcc built with the specified operands and cc. If it is
4993/// unable to simplify it, return a null SDValue.
4995 ISD::CondCode Cond, bool foldBooleans,
4996 DAGCombinerInfo &DCI,
4997 const SDLoc &dl) const {
4998 SelectionDAG &DAG = DCI.DAG;
4999 const DataLayout &Layout = DAG.getDataLayout();
5000 EVT OpVT = N0.getValueType();
5002
5003 // Constant fold or commute setcc.
5004 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
5005 return Fold;
5006
5007 bool N0ConstOrSplat =
5008 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5009 bool N1ConstOrSplat =
5010 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5011
5012 // Canonicalize toward having the constant on the RHS.
5013 // TODO: Handle non-splat vector constants. All undef causes trouble.
5014 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
5015 // infinite loop here when we encounter one.
5017 if (N0ConstOrSplat && !N1ConstOrSplat &&
5018 (DCI.isBeforeLegalizeOps() ||
5019 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
5020 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5021
5022 // If we have a subtract with the same 2 non-constant operands as this setcc
5023 // -- but in reverse order -- then try to commute the operands of this setcc
5024 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
5025 // instruction on some targets.
5026 if (!N0ConstOrSplat && !N1ConstOrSplat &&
5027 (DCI.isBeforeLegalizeOps() ||
5028 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
5029 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
5030 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
5031 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5032
5033 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
5034 return V;
5035
5036 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
5037 return V;
5038
5039 if (auto *N1C = isConstOrConstSplat(N1)) {
5040 const APInt &C1 = N1C->getAPIntValue();
5041
5042 // Optimize some CTPOP cases.
5043 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
5044 return V;
5045
5046 // For equality to 0 of a no-wrap multiply, decompose and test each op:
5047 // X * Y == 0 --> (X == 0) || (Y == 0)
5048 // X * Y != 0 --> (X != 0) && (Y != 0)
5049 // TODO: This bails out if minsize is set, but if the target doesn't have a
5050 // single instruction multiply for this type, it would likely be
5051 // smaller to decompose.
5052 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5053 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
5054 (N0->getFlags().hasNoUnsignedWrap() ||
5055 N0->getFlags().hasNoSignedWrap()) &&
5056 !Attr.hasFnAttr(Attribute::MinSize)) {
5057 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5058 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
5059 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
5060 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
5061 }
5062
5063 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
5064 // equality comparison, then we're just comparing whether X itself is
5065 // zero.
5066 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
5067 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
5069 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
5070 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5071 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
5072 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
5073 // (srl (ctlz x), 5) == 0 -> X != 0
5074 // (srl (ctlz x), 5) != 1 -> X != 0
5075 Cond = ISD::SETNE;
5076 } else {
5077 // (srl (ctlz x), 5) != 0 -> X == 0
5078 // (srl (ctlz x), 5) == 1 -> X == 0
5079 Cond = ISD::SETEQ;
5080 }
5081 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
5082 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
5083 Cond);
5084 }
5085 }
5086 }
5087 }
5088
5089 // setcc X, 0, setlt --> X (when X is all sign bits)
5090 // setcc X, 0, setne --> X (when X is all sign bits)
5091 //
5092 // When we know that X has 0 or -1 in each element (or scalar), this
5093 // comparison will produce X. This is only true when boolean contents are
5094 // represented via 0s and -1s.
5095 if (VT == OpVT &&
5096 // Check that the result of setcc is 0 and -1.
5098 // Match only for checks X < 0 and X != 0
5099 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
5100 // The identity holds iff we know all sign bits for all lanes.
5102 return N0;
5103
5104 // FIXME: Support vectors.
5105 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5106 const APInt &C1 = N1C->getAPIntValue();
5107
5108 // (zext x) == C --> x == (trunc C)
5109 // (sext x) == C --> x == (trunc C)
5110 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5111 DCI.isBeforeLegalize() && N0->hasOneUse()) {
5112 unsigned MinBits = N0.getValueSizeInBits();
5113 SDValue PreExt;
5114 bool Signed = false;
5115 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
5116 // ZExt
5117 MinBits = N0->getOperand(0).getValueSizeInBits();
5118 PreExt = N0->getOperand(0);
5119 } else if (N0->getOpcode() == ISD::AND) {
5120 // DAGCombine turns costly ZExts into ANDs
5121 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
5122 if ((C->getAPIntValue()+1).isPowerOf2()) {
5123 MinBits = C->getAPIntValue().countr_one();
5124 PreExt = N0->getOperand(0);
5125 }
5126 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
5127 // SExt
5128 MinBits = N0->getOperand(0).getValueSizeInBits();
5129 PreExt = N0->getOperand(0);
5130 Signed = true;
5131 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
5132 // ZEXTLOAD / SEXTLOAD
5133 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
5134 MinBits = LN0->getMemoryVT().getSizeInBits();
5135 PreExt = N0;
5136 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
5137 Signed = true;
5138 MinBits = LN0->getMemoryVT().getSizeInBits();
5139 PreExt = N0;
5140 }
5141 }
5142
5143 // Figure out how many bits we need to preserve this constant.
5144 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
5145
5146 // Make sure we're not losing bits from the constant.
5147 if (MinBits > 0 &&
5148 MinBits < C1.getBitWidth() &&
5149 MinBits >= ReqdBits) {
5150 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
5151 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
5152 // Will get folded away.
5153 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
5154 if (MinBits == 1 && C1 == 1)
5155 // Invert the condition.
5156 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
5158 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
5159 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
5160 }
5161
5162 // If truncating the setcc operands is not desirable, we can still
5163 // simplify the expression in some cases:
5164 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
5165 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
5166 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
5167 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
5168 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
5169 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
5170 SDValue TopSetCC = N0->getOperand(0);
5171 unsigned N0Opc = N0->getOpcode();
5172 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
5173 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
5174 TopSetCC.getOpcode() == ISD::SETCC &&
5175 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
5176 (isConstFalseVal(N1) ||
5177 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
5178
5179 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
5180 (!N1C->isZero() && Cond == ISD::SETNE);
5181
5182 if (!Inverse)
5183 return TopSetCC;
5184
5186 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
5187 TopSetCC.getOperand(0).getValueType());
5188 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
5189 TopSetCC.getOperand(1),
5190 InvCond);
5191 }
5192 }
5193 }
5194
5195 // If the LHS is '(and load, const)', the RHS is 0, the test is for
5196 // equality or unsigned, and all 1 bits of the const are in the same
5197 // partial word, see if we can shorten the load.
5198 if (DCI.isBeforeLegalize() &&
5200 N0.getOpcode() == ISD::AND && C1 == 0 &&
5201 N0.getNode()->hasOneUse() &&
5202 isa<LoadSDNode>(N0.getOperand(0)) &&
5203 N0.getOperand(0).getNode()->hasOneUse() &&
5205 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5206 APInt bestMask;
5207 unsigned bestWidth = 0, bestOffset = 0;
5208 if (Lod->isSimple() && Lod->isUnindexed() &&
5209 (Lod->getMemoryVT().isByteSized() ||
5210 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5211 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5212 unsigned origWidth = N0.getValueSizeInBits();
5213 unsigned maskWidth = origWidth;
5214 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5215 // 8 bits, but have to be careful...
5216 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5217 origWidth = Lod->getMemoryVT().getSizeInBits();
5218 const APInt &Mask = N0.getConstantOperandAPInt(1);
5219 // Only consider power-of-2 widths (and at least one byte) as candiates
5220 // for the narrowed load.
5221 for (unsigned width = 8; width < origWidth; width *= 2) {
5222 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5223 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5224 // Avoid accessing any padding here for now (we could use memWidth
5225 // instead of origWidth here otherwise).
5226 unsigned maxOffset = origWidth - width;
5227 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5228 if (Mask.isSubsetOf(newMask)) {
5229 unsigned ptrOffset =
5230 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5231 unsigned IsFast = 0;
5232 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5233 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5235 ptrOffset / 8) &&
5237 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5238 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5239 IsFast) {
5240 bestOffset = ptrOffset / 8;
5241 bestMask = Mask.lshr(offset);
5242 bestWidth = width;
5243 break;
5244 }
5245 }
5246 newMask <<= 8;
5247 }
5248 if (bestWidth)
5249 break;
5250 }
5251 }
5252 if (bestWidth) {
5253 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5254 SDValue Ptr = Lod->getBasePtr();
5255 if (bestOffset != 0)
5256 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5257 SDValue NewLoad =
5258 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5259 Lod->getPointerInfo().getWithOffset(bestOffset),
5260 Lod->getBaseAlign(), MachineMemOperand::MONone,
5261 Lod->getMMOMetadataForSubAccess());
5262 SDValue And =
5263 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5264 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5265 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5266 }
5267 }
5268
5269 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5270 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5271 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5272
5273 // If the comparison constant has bits in the upper part, the
5274 // zero-extended value could never match.
5275 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
5276 C1.getBitWidth() - InSize))) {
5277 switch (Cond) {
5278 case ISD::SETUGT:
5279 case ISD::SETUGE:
5280 case ISD::SETEQ:
5281 return DAG.getConstant(0, dl, VT);
5282 case ISD::SETULT:
5283 case ISD::SETULE:
5284 case ISD::SETNE:
5285 return DAG.getConstant(1, dl, VT);
5286 case ISD::SETGT:
5287 case ISD::SETGE:
5288 // True if the sign bit of C1 is set.
5289 return DAG.getConstant(C1.isNegative(), dl, VT);
5290 case ISD::SETLT:
5291 case ISD::SETLE:
5292 // True if the sign bit of C1 isn't set.
5293 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5294 default:
5295 break;
5296 }
5297 }
5298
5299 // Otherwise, we can perform the comparison with the low bits.
5300 switch (Cond) {
5301 case ISD::SETEQ:
5302 case ISD::SETNE:
5303 case ISD::SETUGT:
5304 case ISD::SETUGE:
5305 case ISD::SETULT:
5306 case ISD::SETULE: {
5307 EVT newVT = N0.getOperand(0).getValueType();
5308 // FIXME: Should use isNarrowingProfitable.
5309 if (DCI.isBeforeLegalizeOps() ||
5310 (isOperationLegal(ISD::SETCC, newVT) &&
5311 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5313 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5314 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5315
5316 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5317 NewConst, Cond);
5318 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5319 }
5320 break;
5321 }
5322 default:
5323 break; // todo, be more careful with signed comparisons
5324 }
5325 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5326 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5328 OpVT)) {
5329 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5330 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5331 EVT ExtDstTy = N0.getValueType();
5332 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5333
5334 // If the constant doesn't fit into the number of bits for the source of
5335 // the sign extension, it is impossible for both sides to be equal.
5336 if (C1.getSignificantBits() > ExtSrcTyBits)
5337 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5338
5339 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5340 ExtDstTy != ExtSrcTy && "Unexpected types!");
5341 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5342 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5343 DAG.getConstant(Imm, dl, ExtDstTy));
5344 if (!DCI.isCalledByLegalizer())
5345 DCI.AddToWorklist(ZextOp.getNode());
5346 // Otherwise, make this a use of a zext.
5347 return DAG.getSetCC(dl, VT, ZextOp,
5348 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5349 } else if ((N1C->isZero() || N1C->isOne()) &&
5350 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5351 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5352 // excluded as they are handled below whilst checking for foldBooleans.
5353 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5354 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5355 (N0.getValueType() == MVT::i1 ||
5359 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5360 if (TrueWhenTrue)
5361 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5362 // Invert the condition.
5363 if (N0.getOpcode() == ISD::SETCC) {
5366 if (DCI.isBeforeLegalizeOps() ||
5368 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5369 }
5370 }
5371
5372 if ((N0.getOpcode() == ISD::XOR ||
5373 (N0.getOpcode() == ISD::AND &&
5374 N0.getOperand(0).getOpcode() == ISD::XOR &&
5375 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5376 isOneConstant(N0.getOperand(1))) {
5377 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5378 // can only do this if the top bits are known zero.
5379 unsigned BitWidth = N0.getValueSizeInBits();
5380 if (DAG.MaskedValueIsZero(N0,
5382 BitWidth-1))) {
5383 // Okay, get the un-inverted input value.
5384 SDValue Val;
5385 if (N0.getOpcode() == ISD::XOR) {
5386 Val = N0.getOperand(0);
5387 } else {
5388 assert(N0.getOpcode() == ISD::AND &&
5389 N0.getOperand(0).getOpcode() == ISD::XOR);
5390 // ((X^1)&1)^1 -> X & 1
5391 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5392 N0.getOperand(0).getOperand(0),
5393 N0.getOperand(1));
5394 }
5395
5396 return DAG.getSetCC(dl, VT, Val, N1,
5398 }
5399 } else if (N1C->isOne()) {
5400 SDValue Op0 = N0;
5401 if (Op0.getOpcode() == ISD::TRUNCATE)
5402 Op0 = Op0.getOperand(0);
5403
5404 if ((Op0.getOpcode() == ISD::XOR) &&
5405 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5406 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5407 SDValue XorLHS = Op0.getOperand(0);
5408 SDValue XorRHS = Op0.getOperand(1);
5409 // Ensure that the input setccs return an i1 type or 0/1 value.
5410 if (Op0.getValueType() == MVT::i1 ||
5415 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5417 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5418 }
5419 }
5420 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5421 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5422 if (Op0.getValueType().bitsGT(VT))
5423 Op0 = DAG.getNode(ISD::AND, dl, VT,
5424 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5425 DAG.getConstant(1, dl, VT));
5426 else if (Op0.getValueType().bitsLT(VT))
5427 Op0 = DAG.getNode(ISD::AND, dl, VT,
5428 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5429 DAG.getConstant(1, dl, VT));
5430
5431 return DAG.getSetCC(dl, VT, Op0,
5432 DAG.getConstant(0, dl, Op0.getValueType()),
5434 }
5435 if (Op0.getOpcode() == ISD::AssertZext &&
5436 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5437 return DAG.getSetCC(dl, VT, Op0,
5438 DAG.getConstant(0, dl, Op0.getValueType()),
5440 }
5441 }
5442
5443 // Given:
5444 // icmp eq/ne (urem %x, %y), 0
5445 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5446 // icmp eq/ne %x, 0
5447 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5448 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5449 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5450 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5451 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5452 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5453 }
5454
5455 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5456 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5457 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5459 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5460 N1C->isAllOnes()) {
5461 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5462 DAG.getConstant(0, dl, OpVT),
5464 }
5465
5466 // fold (setcc (trunc x) c) -> (setcc x c)
5467 if (N0.getOpcode() == ISD::TRUNCATE &&
5469 (N0->getFlags().hasNoSignedWrap() &&
5472 EVT NewVT = N0.getOperand(0).getValueType();
5473 SDValue NewConst = DAG.getConstant(
5475 ? C1.sext(NewVT.getSizeInBits())
5476 : C1.zext(NewVT.getSizeInBits()),
5477 dl, NewVT);
5478 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5479 }
5480
5481 if (SDValue V =
5482 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5483 return V;
5484 }
5485
5486 // These simplifications apply to splat vectors as well.
5487 // TODO: Handle more splat vector cases.
5488 if (auto *N1C = isConstOrConstSplat(N1)) {
5489 const APInt &C1 = N1C->getAPIntValue();
5490
5491 APInt MinVal, MaxVal;
5492 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5494 MinVal = APInt::getSignedMinValue(OperandBitSize);
5495 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5496 } else {
5497 MinVal = APInt::getMinValue(OperandBitSize);
5498 MaxVal = APInt::getMaxValue(OperandBitSize);
5499 }
5500
5501 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5502 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5503 // X >= MIN --> true
5504 if (C1 == MinVal)
5505 return DAG.getBoolConstant(true, dl, VT, OpVT);
5506
5507 if (!VT.isVector()) { // TODO: Support this for vectors.
5508 // X >= C0 --> X > (C0 - 1)
5509 APInt C = C1 - 1;
5511 if ((DCI.isBeforeLegalizeOps() ||
5512 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5513 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5514 isLegalICmpImmediate(C.getSExtValue())))) {
5515 return DAG.getSetCC(dl, VT, N0,
5516 DAG.getConstant(C, dl, N1.getValueType()),
5517 NewCC);
5518 }
5519 }
5520 }
5521
5522 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5523 // X <= MAX --> true
5524 if (C1 == MaxVal)
5525 return DAG.getBoolConstant(true, dl, VT, OpVT);
5526
5527 // X <= C0 --> X < (C0 + 1)
5528 if (!VT.isVector()) { // TODO: Support this for vectors.
5529 APInt C = C1 + 1;
5531 if ((DCI.isBeforeLegalizeOps() ||
5532 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5533 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5534 isLegalICmpImmediate(C.getSExtValue())))) {
5535 return DAG.getSetCC(dl, VT, N0,
5536 DAG.getConstant(C, dl, N1.getValueType()),
5537 NewCC);
5538 }
5539 }
5540 }
5541
5542 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5543 if (C1 == MinVal)
5544 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5545
5546 // TODO: Support this for vectors after legalize ops.
5547 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5548 // Canonicalize setlt X, Max --> setne X, Max
5549 if (C1 == MaxVal)
5550 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5551
5552 // If we have setult X, 1, turn it into seteq X, 0
5553 if (C1 == MinVal+1)
5554 return DAG.getSetCC(dl, VT, N0,
5555 DAG.getConstant(MinVal, dl, N0.getValueType()),
5556 ISD::SETEQ);
5557 }
5558 }
5559
5560 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5561 if (C1 == MaxVal)
5562 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5563
5564 // TODO: Support this for vectors after legalize ops.
5565 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5566 // Canonicalize setgt X, Min --> setne X, Min
5567 if (C1 == MinVal)
5568 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5569
5570 // If we have setugt X, Max-1, turn it into seteq X, Max
5571 if (C1 == MaxVal-1)
5572 return DAG.getSetCC(dl, VT, N0,
5573 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5574 ISD::SETEQ);
5575 }
5576 }
5577
5578 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5579 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5580 if (C1.isZero())
5581 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5582 VT, N0, N1, Cond, DCI, dl))
5583 return CC;
5584
5585 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5586 // For example, when high 32-bits of i64 X are known clear:
5587 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5588 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5589 bool CmpZero = N1C->isZero();
5590 bool CmpNegOne = N1C->isAllOnes();
5591 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5592 // Match or(lo,shl(hi,bw/2)) pattern.
5593 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5594 unsigned EltBits = V.getScalarValueSizeInBits();
5595 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5596 return false;
5597 SDValue LHS = V.getOperand(0);
5598 SDValue RHS = V.getOperand(1);
5599 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5600 // Unshifted element must have zero upperbits.
5601 if (RHS.getOpcode() == ISD::SHL &&
5602 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5603 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5604 DAG.MaskedValueIsZero(LHS, HiBits)) {
5605 Lo = LHS;
5606 Hi = RHS.getOperand(0);
5607 return true;
5608 }
5609 if (LHS.getOpcode() == ISD::SHL &&
5610 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5611 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5612 DAG.MaskedValueIsZero(RHS, HiBits)) {
5613 Lo = RHS;
5614 Hi = LHS.getOperand(0);
5615 return true;
5616 }
5617 return false;
5618 };
5619
5620 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5621 unsigned EltBits = N0.getScalarValueSizeInBits();
5622 unsigned HalfBits = EltBits / 2;
5623 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5624 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5625 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5626 SDValue NewN0 =
5627 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5628 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5629 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5630 };
5631
5632 SDValue Lo, Hi;
5633 if (IsConcat(N0, Lo, Hi))
5634 return MergeConcat(Lo, Hi);
5635
5636 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5637 SDValue Lo0, Lo1, Hi0, Hi1;
5638 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5639 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5640 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5641 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5642 }
5643 }
5644 }
5645 }
5646
5647 // If we have "setcc X, C0", check to see if we can shrink the immediate
5648 // by changing cc.
5649 // TODO: Support this for vectors after legalize ops.
5650 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5651 // SETUGT X, SINTMAX -> SETLT X, 0
5652 // SETUGE X, SINTMIN -> SETLT X, 0
5653 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5654 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5655 return DAG.getSetCC(dl, VT, N0,
5656 DAG.getConstant(0, dl, N1.getValueType()),
5657 ISD::SETLT);
5658
5659 // SETULT X, SINTMIN -> SETGT X, -1
5660 // SETULE X, SINTMAX -> SETGT X, -1
5661 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5662 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5663 return DAG.getSetCC(dl, VT, N0,
5664 DAG.getAllOnesConstant(dl, N1.getValueType()),
5665 ISD::SETGT);
5666 }
5667 }
5668
5669 // Back to non-vector simplifications.
5670 // TODO: Can we do these for vector splats?
5671 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5672 const APInt &C1 = N1C->getAPIntValue();
5673 EVT ShValTy = N0.getValueType();
5674
5675 // Fold bit comparisons when we can. This will result in an
5676 // incorrect value when boolean false is negative one, unless
5677 // the bitsize is 1 in which case the false value is the same
5678 // in practice regardless of the representation.
5679 if ((VT.getSizeInBits() == 1 ||
5681 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5682 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5683 N0.getOpcode() == ISD::AND) {
5684 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5685 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5686 // Perform the xform if the AND RHS is a single bit.
5687 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5688 if (AndRHS->getAPIntValue().isPowerOf2() &&
5689 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5690 return DAG.getNode(
5691 ISD::TRUNCATE, dl, VT,
5692 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5693 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5694 }
5695 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5696 // (X & 8) == 8 --> (X & 8) >> 3
5697 // Perform the xform if C1 is a single bit.
5698 unsigned ShCt = C1.logBase2();
5699 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5700 return DAG.getNode(
5701 ISD::TRUNCATE, dl, VT,
5702 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5703 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5704 }
5705 }
5706 }
5707 }
5708
5709 if (C1.getSignificantBits() <= 64 &&
5710 !isLegalICmpImmediate(C1.getSExtValue())) {
5711 // (X & -256) == 256 -> (X >> 8) == 1
5712 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5713 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5714 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5715 const APInt &AndRHSC = AndRHS->getAPIntValue();
5716 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5717 unsigned ShiftBits = AndRHSC.countr_zero();
5718 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5719 // If using an unsigned shift doesn't yield a legal compare
5720 // immediate, try using sra instead.
5721 APInt NewC = C1.lshr(ShiftBits);
5722 if (NewC.getSignificantBits() <= 64 &&
5724 APInt SignedC = C1.ashr(ShiftBits);
5725 if (SignedC.getSignificantBits() <= 64 &&
5727 SDValue Shift = DAG.getNode(
5728 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5729 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5730 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5731 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5732 }
5733 }
5734 SDValue Shift = DAG.getNode(
5735 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5736 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5737 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5738 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5739 }
5740 }
5741 }
5742 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5743 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5744 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5745 // X < 0x100000000 -> (X >> 32) < 1
5746 // X >= 0x100000000 -> (X >> 32) >= 1
5747 // X <= 0x0ffffffff -> (X >> 32) < 1
5748 // X > 0x0ffffffff -> (X >> 32) >= 1
5749 unsigned ShiftBits;
5750 APInt NewC = C1;
5751 ISD::CondCode NewCond = Cond;
5752 if (AdjOne) {
5753 ShiftBits = C1.countr_one();
5754 NewC = NewC + 1;
5755 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5756 } else {
5757 ShiftBits = C1.countr_zero();
5758 }
5759 APInt RangeWidth = NewC;
5760 NewC.lshrInPlace(ShiftBits);
5761 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5763 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5764 // If this is an offset range check, try to move the offset after the
5765 // shift to avoid preserving the pre-shift add with a mask.
5766 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse()) {
5767 if (auto *AddC = isConstOrConstSplat(N0.getOperand(1))) {
5768 const APInt &AddVal = AddC->getAPIntValue();
5769 if (AddVal.countr_zero() >= ShiftBits) {
5770 APInt RangeLower = -AddVal;
5771 bool Overflow;
5772 (void)RangeLower.uadd_ov(RangeWidth, Overflow);
5773 if (!RangeWidth.isZero() && !Overflow) {
5774 SDValue Shift = DAG.getNode(
5775 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5776 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5777 APInt Offset = -RangeLower.lshr(ShiftBits);
5778 SDValue ShiftedAdd =
5779 DAG.getNode(ISD::ADD, dl, ShValTy, Shift,
5780 DAG.getConstant(Offset, dl, ShValTy));
5781 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5782 return DAG.getSetCC(dl, VT, ShiftedAdd, CmpRHS, NewCond);
5783 }
5784 }
5785 }
5786 }
5787 SDValue Shift =
5788 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5789 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5790 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5791 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5792 }
5793 }
5794 }
5795 }
5796
5798 auto *CFP = cast<ConstantFPSDNode>(N1);
5799 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5800
5801 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5802 // constant if knowing that the operand is non-nan is enough. We prefer to
5803 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5804 // materialize 0.0.
5805 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5806 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5807
5808 // setcc (fneg x), C -> setcc swap(pred) x, -C
5809 if (N0.getOpcode() == ISD::FNEG) {
5811 if (DCI.isBeforeLegalizeOps() ||
5812 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5813 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5814 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5815 }
5816 }
5817
5818 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5820 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5821 bool IsFabs = N0.getOpcode() == ISD::FABS;
5822 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5823 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5824 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5825 : (IsFabs ? fcInf : fcPosInf);
5826 if (Cond == ISD::SETUEQ)
5827 Flag |= fcNan;
5828 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5829 DAG.getTargetConstant(Flag, dl, MVT::i32));
5830 }
5831 }
5832
5833 // If the condition is not legal, see if we can find an equivalent one
5834 // which is legal.
5836 // If the comparison was an awkward floating-point == or != and one of
5837 // the comparison operands is infinity or negative infinity, convert the
5838 // condition to a less-awkward <= or >=.
5839 if (CFP->getValueAPF().isInfinity()) {
5840 bool IsNegInf = CFP->getValueAPF().isNegative();
5842 switch (Cond) {
5843 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5844 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5845 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5846 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5847 default: break;
5848 }
5849 if (NewCond != ISD::SETCC_INVALID &&
5850 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5851 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5852 }
5853 }
5854 }
5855
5856 if (N0 == N1) {
5857 // The sext(setcc()) => setcc() optimization relies on the appropriate
5858 // constant being emitted.
5859 assert(!N0.getValueType().isInteger() &&
5860 "Integer types should be handled by FoldSetCC");
5861
5862 bool EqTrue = ISD::isTrueWhenEqual(Cond);
5863 unsigned UOF = ISD::getUnorderedFlavor(Cond);
5864 if (UOF == 2) // FP operators that are undefined on NaNs.
5865 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5866 if (UOF == unsigned(EqTrue))
5867 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5868 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
5869 // if it is not already.
5870 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5871 if (NewCond != Cond &&
5872 (DCI.isBeforeLegalizeOps() ||
5873 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5874 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5875 }
5876
5877 // ~X > ~Y --> Y > X
5878 // ~X < ~Y --> Y < X
5879 // ~X < C --> X > ~C
5880 // ~X > C --> X < ~C
5881 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5882 N0.getValueType().isInteger()) {
5883 if (isBitwiseNot(N0)) {
5884 if (isBitwiseNot(N1))
5885 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
5886
5889 SDValue Not = DAG.getNOT(dl, N1, OpVT);
5890 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
5891 }
5892 }
5893 }
5894
5895 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5896 N0.getValueType().isInteger()) {
5897 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
5898 N0.getOpcode() == ISD::XOR) {
5899 // Simplify (X+Y) == (X+Z) --> Y == Z
5900 if (N0.getOpcode() == N1.getOpcode()) {
5901 if (N0.getOperand(0) == N1.getOperand(0))
5902 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
5903 if (N0.getOperand(1) == N1.getOperand(1))
5904 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5905 if (isCommutativeBinOp(N0.getOpcode())) {
5906 // If X op Y == Y op X, try other combinations.
5907 if (N0.getOperand(0) == N1.getOperand(1))
5908 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
5909 Cond);
5910 if (N0.getOperand(1) == N1.getOperand(0))
5911 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
5912 Cond);
5913 }
5914 }
5915
5916 // If RHS is a legal immediate value for a compare instruction, we need
5917 // to be careful about increasing register pressure needlessly.
5918 bool LegalRHSImm = false;
5919
5920 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
5921 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5922 // Turn (X+C1) == C2 --> X == C2-C1
5923 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
5924 return DAG.getSetCC(
5925 dl, VT, N0.getOperand(0),
5926 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
5927 dl, N0.getValueType()),
5928 Cond);
5929
5930 // Turn (X^C1) == C2 --> X == C1^C2
5931 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
5932 return DAG.getSetCC(
5933 dl, VT, N0.getOperand(0),
5934 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
5935 dl, N0.getValueType()),
5936 Cond);
5937 }
5938
5939 // Turn (C1-X) == C2 --> X == C1-C2
5940 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
5941 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
5942 return DAG.getSetCC(
5943 dl, VT, N0.getOperand(1),
5944 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
5945 dl, N0.getValueType()),
5946 Cond);
5947
5948 // Could RHSC fold directly into a compare?
5949 if (RHSC->getValueType(0).getSizeInBits() <= 64)
5950 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
5951 }
5952
5953 // (X+Y) == X --> Y == 0 and similar folds.
5954 // Don't do this if X is an immediate that can fold into a cmp
5955 // instruction and X+Y has other uses. It could be an induction variable
5956 // chain, and the transform would increase register pressure.
5957 if (!LegalRHSImm || N0.hasOneUse())
5958 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
5959 return V;
5960 }
5961
5962 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
5963 N1.getOpcode() == ISD::XOR)
5964 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
5965 return V;
5966
5967 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
5968 return V;
5969
5970 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
5971 return V;
5972 }
5973
5974 // Fold remainder of division by a constant.
5975 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
5976 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5977 // When division is cheap or optimizing for minimum size,
5978 // fall through to DIVREM creation by skipping this fold.
5979 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
5980 if (N0.getOpcode() == ISD::UREM) {
5981 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
5982 return Folded;
5983 } else if (N0.getOpcode() == ISD::SREM) {
5984 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
5985 return Folded;
5986 }
5987 }
5988 }
5989
5990 // Fold away ALL boolean setcc's.
5991 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
5992 SDValue Temp;
5993 switch (Cond) {
5994 default: llvm_unreachable("Unknown integer setcc!");
5995 case ISD::SETEQ: // X == Y -> ~(X^Y)
5996 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5997 N0 = DAG.getNOT(dl, Temp, OpVT);
5998 if (!DCI.isCalledByLegalizer())
5999 DCI.AddToWorklist(Temp.getNode());
6000 break;
6001 case ISD::SETNE: // X != Y --> (X^Y)
6002 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
6003 break;
6004 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
6005 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
6006 Temp = DAG.getNOT(dl, N0, OpVT);
6007 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
6008 if (!DCI.isCalledByLegalizer())
6009 DCI.AddToWorklist(Temp.getNode());
6010 break;
6011 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
6012 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
6013 Temp = DAG.getNOT(dl, N1, OpVT);
6014 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
6015 if (!DCI.isCalledByLegalizer())
6016 DCI.AddToWorklist(Temp.getNode());
6017 break;
6018 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
6019 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
6020 Temp = DAG.getNOT(dl, N0, OpVT);
6021 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
6022 if (!DCI.isCalledByLegalizer())
6023 DCI.AddToWorklist(Temp.getNode());
6024 break;
6025 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
6026 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
6027 Temp = DAG.getNOT(dl, N1, OpVT);
6028 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
6029 break;
6030 }
6031 if (VT.getScalarType() != MVT::i1) {
6032 if (!DCI.isCalledByLegalizer())
6033 DCI.AddToWorklist(N0.getNode());
6034 // FIXME: If running after legalize, we probably can't do this.
6036 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
6037 }
6038 return N0;
6039 }
6040
6041 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
6042 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
6043 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
6045 N1->getFlags().hasNoUnsignedWrap()) ||
6047 N1->getFlags().hasNoSignedWrap())) &&
6049 if (VT.getScalarType() == MVT::i1)
6050 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6051 // For (legal) non vXi1 cases - ensure we adjust the cmp and result types.
6052 EVT OldCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6053 N0.getValueType());
6054 if (VT == OldCCVT) {
6055 EVT NewCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6056 N0.getOperand(0).getValueType());
6057 return DAG.getBoolExtOrTrunc(
6058 DAG.getSetCC(dl, NewCCVT, N0.getOperand(0), N1.getOperand(0), Cond),
6059 dl, VT, N0.getOperand(0).getValueType());
6060 }
6061 }
6062
6063 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
6064 // TODO: Remove that .isVector() check
6065 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
6067 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
6068 }
6069
6070 // Could not fold it.
6071 return SDValue();
6072}
6073
6074/// Returns true (and the GlobalValue and the offset) if the node is a
6075/// GlobalAddress + offset.
6077 int64_t &Offset) const {
6078
6079 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
6080
6081 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
6082 GA = GASD->getGlobal();
6083 Offset += GASD->getOffset();
6084 return true;
6085 }
6086
6087 if (N->isAnyAdd()) {
6088 SDValue N1 = N->getOperand(0);
6089 SDValue N2 = N->getOperand(1);
6090 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
6091 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
6092 Offset += V->getSExtValue();
6093 return true;
6094 }
6095 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
6096 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
6097 Offset += V->getSExtValue();
6098 return true;
6099 }
6100 }
6101 }
6102
6103 return false;
6104}
6105
6107 DAGCombinerInfo &DCI) const {
6108 // Default implementation: no optimization.
6109 return SDValue();
6110}
6111
6112//===----------------------------------------------------------------------===//
6113// Inline Assembler Implementation Methods
6114//===----------------------------------------------------------------------===//
6115
6118 unsigned S = Constraint.size();
6119
6120 if (S == 1) {
6121 switch (Constraint[0]) {
6122 default: break;
6123 case 'r':
6124 return C_RegisterClass;
6125 case 'm': // memory
6126 case 'o': // offsetable
6127 case 'V': // not offsetable
6128 return C_Memory;
6129 case 'p': // Address.
6130 return C_Address;
6131 case 'n': // Simple Integer
6132 case 'E': // Floating Point Constant
6133 case 'F': // Floating Point Constant
6134 return C_Immediate;
6135 case 'i': // Simple Integer or Relocatable Constant
6136 case 's': // Relocatable Constant
6137 case 'X': // Allow ANY value.
6138 case 'I': // Target registers.
6139 case 'J':
6140 case 'K':
6141 case 'L':
6142 case 'M':
6143 case 'N':
6144 case 'O':
6145 case 'P':
6146 case '<':
6147 case '>':
6148 return C_Other;
6149 }
6150 }
6151
6152 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
6153 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
6154 return C_Memory;
6155 return C_Register;
6156 }
6157 return C_Unknown;
6158}
6159
6160/// Try to replace an X constraint, which matches anything, with another that
6161/// has more specific requirements based on the type of the corresponding
6162/// operand.
6163const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6164 if (ConstraintVT.isInteger())
6165 return "r";
6166 if (ConstraintVT.isFloatingPoint())
6167 return "f"; // works for many targets
6168 return nullptr;
6169}
6170
6172 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
6173 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
6174 return SDValue();
6175}
6176
6177/// Lower the specified operand into the Ops vector.
6178/// If it is invalid, don't add anything to Ops.
6180 StringRef Constraint,
6181 std::vector<SDValue> &Ops,
6182 SelectionDAG &DAG) const {
6183
6184 if (Constraint.size() > 1)
6185 return;
6186
6187 char ConstraintLetter = Constraint[0];
6188 switch (ConstraintLetter) {
6189 default: break;
6190 case 'X': // Allows any operand
6191 case 'i': // Simple Integer or Relocatable Constant
6192 case 'n': // Simple Integer
6193 case 's': { // Relocatable Constant
6194
6196 uint64_t Offset = 0;
6197
6198 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
6199 // etc., since getelementpointer is variadic. We can't use
6200 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
6201 // while in this case the GA may be furthest from the root node which is
6202 // likely an ISD::ADD.
6203 while (true) {
6204 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
6205 // gcc prints these as sign extended. Sign extend value to 64 bits
6206 // now; without this it would get ZExt'd later in
6207 // ScheduleDAGSDNodes::EmitNode, which is very generic.
6208 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
6209 BooleanContent BCont = getBooleanContents(MVT::i64);
6210 ISD::NodeType ExtOpc =
6211 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
6212 int64_t ExtVal =
6213 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
6214 Ops.push_back(
6215 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
6216 return;
6217 }
6218 if (ConstraintLetter != 'n') {
6219 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6220 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6221 GA->getValueType(0),
6222 Offset + GA->getOffset()));
6223 return;
6224 }
6225 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
6226 Ops.push_back(DAG.getTargetBlockAddress(
6227 BA->getBlockAddress(), BA->getValueType(0),
6228 Offset + BA->getOffset(), BA->getTargetFlags()));
6229 return;
6230 }
6232 Ops.push_back(Op);
6233 return;
6234 }
6235 }
6236 const unsigned OpCode = Op.getOpcode();
6237 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6238 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6239 Op = Op.getOperand(1);
6240 // Subtraction is not commutative.
6241 else if (OpCode == ISD::ADD &&
6242 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6243 Op = Op.getOperand(0);
6244 else
6245 return;
6246 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6247 continue;
6248 }
6249 return;
6250 }
6251 break;
6252 }
6253 }
6254}
6255
6259
6260std::pair<unsigned, const TargetRegisterClass *>
6262 StringRef Constraint,
6263 MVT VT) const {
6264 if (!Constraint.starts_with("{"))
6265 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6266 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6267
6268 // Remove the braces from around the name.
6269 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6270
6271 std::pair<unsigned, const TargetRegisterClass *> R =
6272 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6273
6274 // Figure out which register class contains this reg.
6275 for (const TargetRegisterClass &RC : RI->regclasses()) {
6276 // If none of the value types for this register class are valid, we
6277 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6278 if (!isLegalRC(*RI, RC))
6279 continue;
6280
6281 for (const MCPhysReg &PR : RC) {
6282 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6283 std::pair<unsigned, const TargetRegisterClass *> S =
6284 std::make_pair(PR, &RC);
6285
6286 // If this register class has the requested value type, return it,
6287 // otherwise keep searching and return the first class found
6288 // if no other is found which explicitly has the requested type.
6289 if (RI->isTypeLegalForClass(RC, VT))
6290 return S;
6291 if (!R.second)
6292 R = S;
6293 }
6294 }
6295 }
6296
6297 return R;
6298}
6299
6300//===----------------------------------------------------------------------===//
6301// Constraint Selection.
6302
6303/// Return true of this is an input operand that is a matching constraint like
6304/// "4".
6306 assert(!ConstraintCode.empty() && "No known constraint!");
6307 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6308}
6309
6310/// If this is an input matching constraint, this method returns the output
6311/// operand it matches.
6313 assert(!ConstraintCode.empty() && "No known constraint!");
6314 return atoi(ConstraintCode.c_str());
6315}
6316
6317/// Split up the constraint string from the inline assembly value into the
6318/// specific constraints and their prefixes, and also tie in the associated
6319/// operand values.
6320/// If this returns an empty vector, and if the constraint string itself
6321/// isn't empty, there was an error parsing.
6324 const TargetRegisterInfo *TRI,
6325 const CallBase &Call) const {
6326 /// Information about all of the constraints.
6327 AsmOperandInfoVector ConstraintOperands;
6328 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6329 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6330
6331 // Do a prepass over the constraints, canonicalizing them, and building up the
6332 // ConstraintOperands list.
6333 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6334 unsigned ResNo = 0; // ResNo - The result number of the next output.
6335 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6336
6337 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6338 ConstraintOperands.emplace_back(std::move(CI));
6339 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6340
6341 // Update multiple alternative constraint count.
6342 if (OpInfo.multipleAlternatives.size() > maCount)
6343 maCount = OpInfo.multipleAlternatives.size();
6344
6345 OpInfo.ConstraintVT = MVT::Other;
6346
6347 // Compute the value type for each operand.
6348 switch (OpInfo.Type) {
6349 case InlineAsm::isOutput: {
6350 // Indirect outputs just consume an argument.
6351 if (OpInfo.isIndirect) {
6352 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6353 break;
6354 }
6355
6356 // The return value of the call is this value. As such, there is no
6357 // corresponding argument.
6358 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6359 EVT VT;
6360 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6361 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6362 } else {
6363 assert(ResNo == 0 && "Asm only has one result!");
6364 VT = getAsmOperandValueType(DL, Call.getType());
6365 }
6366 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6367 ++ResNo;
6368 break;
6369 }
6370 case InlineAsm::isInput:
6371 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6372 break;
6373 case InlineAsm::isLabel:
6374 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6375 ++LabelNo;
6376 continue;
6378 // Nothing to do.
6379 break;
6380 }
6381
6382 if (OpInfo.CallOperandVal) {
6383 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6384 if (OpInfo.isIndirect) {
6385 OpTy = Call.getParamElementType(ArgNo);
6386 assert(OpTy && "Indirect operand must have elementtype attribute");
6387 }
6388
6389 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6391 if (STy->getNumElements() == 1)
6392 OpTy = STy->getElementType(0);
6393
6394 // If OpTy is not a single value, it may be a struct/union that we
6395 // can tile with integers.
6396 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6397 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6398 switch (BitSize) {
6399 default: break;
6400 case 1:
6401 case 8:
6402 case 16:
6403 case 32:
6404 case 64:
6405 case 128:
6406 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6407 break;
6408 }
6409 }
6410
6411 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6412 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6413 ArgNo++;
6414 }
6415 }
6416
6417 // If we have multiple alternative constraints, select the best alternative.
6418 if (!ConstraintOperands.empty()) {
6419 if (maCount) {
6420 unsigned bestMAIndex = 0;
6421 int bestWeight = -1;
6422 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6423 int weight = -1;
6424 unsigned maIndex;
6425 // Compute the sums of the weights for each alternative, keeping track
6426 // of the best (highest weight) one so far.
6427 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6428 int weightSum = 0;
6429 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6430 cIndex != eIndex; ++cIndex) {
6431 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6432 if (OpInfo.Type == InlineAsm::isClobber)
6433 continue;
6434
6435 // If this is an output operand with a matching input operand,
6436 // look up the matching input. If their types mismatch, e.g. one
6437 // is an integer, the other is floating point, or their sizes are
6438 // different, flag it as an maCantMatch.
6439 if (OpInfo.hasMatchingInput()) {
6440 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6441 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6442 if ((OpInfo.ConstraintVT.isInteger() !=
6443 Input.ConstraintVT.isInteger()) ||
6444 (OpInfo.ConstraintVT.getSizeInBits() !=
6445 Input.ConstraintVT.getSizeInBits())) {
6446 weightSum = -1; // Can't match.
6447 break;
6448 }
6449 }
6450 }
6451 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6452 if (weight == -1) {
6453 weightSum = -1;
6454 break;
6455 }
6456 weightSum += weight;
6457 }
6458 // Update best.
6459 if (weightSum > bestWeight) {
6460 bestWeight = weightSum;
6461 bestMAIndex = maIndex;
6462 }
6463 }
6464
6465 // Now select chosen alternative in each constraint.
6466 for (AsmOperandInfo &cInfo : ConstraintOperands)
6467 if (cInfo.Type != InlineAsm::isClobber)
6468 cInfo.selectAlternative(bestMAIndex);
6469 }
6470 }
6471
6472 // Check and hook up tied operands, choose constraint code to use.
6473 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6474 cIndex != eIndex; ++cIndex) {
6475 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6476
6477 // If this is an output operand with a matching input operand, look up the
6478 // matching input. If their types mismatch, e.g. one is an integer, the
6479 // other is floating point, or their sizes are different, flag it as an
6480 // error.
6481 if (OpInfo.hasMatchingInput()) {
6482 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6483
6484 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6485 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6486 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6487 OpInfo.ConstraintVT);
6488 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6489 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6490 Input.ConstraintVT);
6491 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6492 OpInfo.ConstraintVT.isFloatingPoint();
6493 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6494 Input.ConstraintVT.isFloatingPoint();
6495 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6496 (MatchRC.second != InputRC.second)) {
6497 report_fatal_error("Unsupported asm: input constraint"
6498 " with a matching output constraint of"
6499 " incompatible type!");
6500 }
6501 }
6502 }
6503 }
6504
6505 return ConstraintOperands;
6506}
6507
6508/// Return a number indicating our preference for chosing a type of constraint
6509/// over another, for the purpose of sorting them. Immediates are almost always
6510/// preferrable (when they can be emitted). A higher return value means a
6511/// stronger preference for one constraint type relative to another.
6512/// FIXME: We should prefer registers over memory but doing so may lead to
6513/// unrecoverable register exhaustion later.
6514/// https://github.com/llvm/llvm-project/issues/20571
6516 switch (CT) {
6519 return 4;
6522 return 3;
6524 return 2;
6526 return 1;
6528 return 0;
6529 }
6530 llvm_unreachable("Invalid constraint type");
6531}
6532
6533/// Examine constraint type and operand type and determine a weight value.
6534/// This object must already have been set up with the operand type
6535/// and the current alternative constraint selected.
6538 AsmOperandInfo &info, int maIndex) const {
6540 if (maIndex >= (int)info.multipleAlternatives.size())
6541 rCodes = &info.Codes;
6542 else
6543 rCodes = &info.multipleAlternatives[maIndex].Codes;
6544 ConstraintWeight BestWeight = CW_Invalid;
6545
6546 // Loop over the options, keeping track of the most general one.
6547 for (const std::string &rCode : *rCodes) {
6548 ConstraintWeight weight =
6549 getSingleConstraintMatchWeight(info, rCode.c_str());
6550 if (weight > BestWeight)
6551 BestWeight = weight;
6552 }
6553
6554 return BestWeight;
6555}
6556
6557/// Examine constraint type and operand type and determine a weight value.
6558/// This object must already have been set up with the operand type
6559/// and the current alternative constraint selected.
6562 AsmOperandInfo &info, const char *constraint) const {
6564 Value *CallOperandVal = info.CallOperandVal;
6565 // If we don't have a value, we can't do a match,
6566 // but allow it at the lowest weight.
6567 if (!CallOperandVal)
6568 return CW_Default;
6569 // Look at the constraint type.
6570 switch (*constraint) {
6571 case 'i': // immediate integer.
6572 case 'n': // immediate integer with a known value.
6573 if (isa<ConstantInt>(CallOperandVal))
6574 weight = CW_Constant;
6575 break;
6576 case 's': // non-explicit intregal immediate.
6577 if (isa<GlobalValue>(CallOperandVal))
6578 weight = CW_Constant;
6579 break;
6580 case 'E': // immediate float if host format.
6581 case 'F': // immediate float.
6582 if (isa<ConstantFP>(CallOperandVal))
6583 weight = CW_Constant;
6584 break;
6585 case '<': // memory operand with autodecrement.
6586 case '>': // memory operand with autoincrement.
6587 case 'm': // memory operand.
6588 case 'o': // offsettable memory operand
6589 case 'V': // non-offsettable memory operand
6590 weight = CW_Memory;
6591 break;
6592 case 'r': // general register.
6593 case 'g': // general register, memory operand or immediate integer.
6594 // note: Clang converts "g" to "imr".
6595 if (CallOperandVal->getType()->isIntegerTy())
6596 weight = CW_Register;
6597 break;
6598 case 'X': // any operand.
6599 default:
6600 weight = CW_Default;
6601 break;
6602 }
6603 return weight;
6604}
6605
6606/// If there are multiple different constraints that we could pick for this
6607/// operand (e.g. "imr") try to pick the 'best' one.
6608/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6609/// into seven classes:
6610/// Register -> one specific register
6611/// RegisterClass -> a group of regs
6612/// Memory -> memory
6613/// Address -> a symbolic memory reference
6614/// Immediate -> immediate values
6615/// Other -> magic values (such as "Flag Output Operands")
6616/// Unknown -> something we don't recognize yet and can't handle
6617/// Ideally, we would pick the most specific constraint possible: if we have
6618/// something that fits into a register, we would pick it. The problem here
6619/// is that if we have something that could either be in a register or in
6620/// memory that use of the register could cause selection of *other*
6621/// operands to fail: they might only succeed if we pick memory. Because of
6622/// this the heuristic we use is:
6623///
6624/// 1) If there is an 'other' constraint, and if the operand is valid for
6625/// that constraint, use it. This makes us take advantage of 'i'
6626/// constraints when available.
6627/// 2) Otherwise, pick the most general constraint present. This prefers
6628/// 'm' over 'r', for example.
6629///
6631 TargetLowering::AsmOperandInfo &OpInfo) const {
6632 ConstraintGroup Ret;
6633
6634 Ret.reserve(OpInfo.Codes.size());
6635 for (StringRef Code : OpInfo.Codes) {
6637
6638 // Indirect 'other' or 'immediate' constraints are not allowed.
6639 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6640 CType == TargetLowering::C_Register ||
6642 continue;
6643
6644 // Things with matching constraints can only be registers, per gcc
6645 // documentation. This mainly affects "g" constraints.
6646 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6647 continue;
6648
6649 Ret.emplace_back(Code, CType);
6650 }
6651
6653 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6654 });
6655
6656 return Ret;
6657}
6658
6659/// If we have an immediate, see if we can lower it. Return true if we can,
6660/// false otherwise.
6662 SDValue Op, SelectionDAG *DAG,
6663 const TargetLowering &TLI) {
6664
6665 assert((P.second == TargetLowering::C_Other ||
6666 P.second == TargetLowering::C_Immediate) &&
6667 "need immediate or other");
6668
6669 if (!Op.getNode())
6670 return false;
6671
6672 std::vector<SDValue> ResultOps;
6673 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6674 return !ResultOps.empty();
6675}
6676
6677/// Determines the constraint code and constraint type to use for the specific
6678/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6680 SDValue Op,
6681 SelectionDAG *DAG) const {
6682 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6683
6684 // Single-letter constraints ('r') are very common.
6685 if (OpInfo.Codes.size() == 1) {
6686 OpInfo.ConstraintCode = OpInfo.Codes[0];
6687 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6688 } else {
6690 if (G.empty())
6691 return;
6692
6693 unsigned BestIdx = 0;
6694 for (const unsigned E = G.size();
6695 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6696 G[BestIdx].second == TargetLowering::C_Immediate);
6697 ++BestIdx) {
6698 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6699 break;
6700 // If we're out of constraints, just pick the first one.
6701 if (BestIdx + 1 == E) {
6702 BestIdx = 0;
6703 break;
6704 }
6705 }
6706
6707 OpInfo.ConstraintCode = G[BestIdx].first;
6708 OpInfo.ConstraintType = G[BestIdx].second;
6709 }
6710
6711 // 'X' matches anything.
6712 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6713 // Constants are handled elsewhere. For Functions, the type here is the
6714 // type of the result, which is not what we want to look at; leave them
6715 // alone.
6716 Value *v = OpInfo.CallOperandVal;
6717 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6718 return;
6719 }
6720
6721 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6722 OpInfo.ConstraintCode = "i";
6723 return;
6724 }
6725
6726 // Otherwise, try to resolve it to something we know about by looking at
6727 // the actual operand type.
6728 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6729 OpInfo.ConstraintCode = Repl;
6730 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6731 }
6732 }
6733}
6734
6735/// Given an exact SDIV by a constant, create a multiplication
6736/// with the multiplicative inverse of the constant.
6737/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6739 const SDLoc &dl, SelectionDAG &DAG,
6740 SmallVectorImpl<SDNode *> &Created) {
6741 SDValue Op0 = N->getOperand(0);
6742 SDValue Op1 = N->getOperand(1);
6743 EVT VT = N->getValueType(0);
6744 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6745 EVT ShSVT = ShVT.getScalarType();
6746
6747 bool UseSRA = false;
6748 SmallVector<SDValue, 16> Shifts, Factors;
6749
6750 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6751 if (C->isZero())
6752 return false;
6753
6754 EVT CT = C->getValueType(0);
6755 APInt Divisor = C->getAPIntValue();
6756 unsigned Shift = Divisor.countr_zero();
6757 if (Shift) {
6758 Divisor.ashrInPlace(Shift);
6759 UseSRA = true;
6760 }
6761 APInt Factor = Divisor.multiplicativeInverse();
6762 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6763 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6764 return true;
6765 };
6766
6767 // Collect all magic values from the build vector.
6768 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6769 return SDValue();
6770
6771 SDValue Shift, Factor;
6772 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6773 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6774 Factor = DAG.getBuildVector(VT, dl, Factors);
6775 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6776 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6777 "Expected matchUnaryPredicate to return one element for scalable "
6778 "vectors");
6779 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6780 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6781 } else {
6782 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6783 Shift = Shifts[0];
6784 Factor = Factors[0];
6785 }
6786
6787 SDValue Res = Op0;
6788 if (UseSRA) {
6789 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6790 Created.push_back(Res.getNode());
6791 }
6792
6793 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6794}
6795
6796/// Given an exact UDIV by a constant, create a multiplication
6797/// with the multiplicative inverse of the constant.
6798/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6800 const SDLoc &dl, SelectionDAG &DAG,
6801 SmallVectorImpl<SDNode *> &Created) {
6802 EVT VT = N->getValueType(0);
6803 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6804 EVT ShSVT = ShVT.getScalarType();
6805
6806 bool UseSRL = false;
6807 SmallVector<SDValue, 16> Shifts, Factors;
6808
6809 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6810 if (C->isZero())
6811 return false;
6812
6813 EVT CT = C->getValueType(0);
6814 APInt Divisor = C->getAPIntValue();
6815 unsigned Shift = Divisor.countr_zero();
6816 if (Shift) {
6817 Divisor.lshrInPlace(Shift);
6818 UseSRL = true;
6819 }
6820 // Calculate the multiplicative inverse modulo BW.
6821 APInt Factor = Divisor.multiplicativeInverse();
6822 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6823 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6824 return true;
6825 };
6826
6827 SDValue Op1 = N->getOperand(1);
6828
6829 // Collect all magic values from the build vector.
6830 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6831 return SDValue();
6832
6833 SDValue Shift, Factor;
6834 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6835 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6836 Factor = DAG.getBuildVector(VT, dl, Factors);
6837 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6838 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6839 "Expected matchUnaryPredicate to return one element for scalable "
6840 "vectors");
6841 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6842 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6843 } else {
6844 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6845 Shift = Shifts[0];
6846 Factor = Factors[0];
6847 }
6848
6849 SDValue Res = N->getOperand(0);
6850 if (UseSRL) {
6851 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
6852 Created.push_back(Res.getNode());
6853 }
6854
6855 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6856}
6857
6859 SelectionDAG &DAG,
6860 SmallVectorImpl<SDNode *> &Created) const {
6862 if (isIntDivCheap(N->getValueType(0), Attr))
6863 return SDValue(N, 0); // Lower SDIV as SDIV
6864 return SDValue();
6865}
6866
6867SDValue
6869 SelectionDAG &DAG,
6870 SmallVectorImpl<SDNode *> &Created) const {
6872 if (isIntDivCheap(N->getValueType(0), Attr))
6873 return SDValue(N, 0); // Lower SREM as SREM
6874 return SDValue();
6875}
6876
6877/// Build sdiv by power-of-2 with conditional move instructions
6878/// Ref: "Hacker's Delight" by Henry Warren 10-1
6879/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6880/// bgez x, label
6881/// add x, x, 2**k-1
6882/// label:
6883/// sra res, x, k
6884/// neg res, res (when the divisor is negative)
6886 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
6887 SmallVectorImpl<SDNode *> &Created) const {
6888 unsigned Lg2 = Divisor.countr_zero();
6889 EVT VT = N->getValueType(0);
6890
6891 SDLoc DL(N);
6892 SDValue N0 = N->getOperand(0);
6893 SDValue Zero = DAG.getConstant(0, DL, VT);
6894 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
6895 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
6896
6897 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
6898 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6899 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
6900 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6901 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
6902
6903 Created.push_back(Cmp.getNode());
6904 Created.push_back(Add.getNode());
6905 Created.push_back(CMov.getNode());
6906
6907 // Divide by pow2.
6908 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
6909 DAG.getShiftAmountConstant(Lg2, VT, DL));
6910
6911 // If we're dividing by a positive value, we're done. Otherwise, we must
6912 // negate the result.
6913 if (Divisor.isNonNegative())
6914 return SRA;
6915
6916 Created.push_back(SRA.getNode());
6917 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
6918}
6919
6920/// Given an ISD::SDIV node expressing a divide by constant,
6921/// return a DAG expression to select that will generate the same value by
6922/// multiplying by a magic number.
6923/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6925 bool IsAfterLegalization,
6926 bool IsAfterLegalTypes,
6927 SmallVectorImpl<SDNode *> &Created) const {
6928 SDLoc dl(N);
6929
6930 // If the sdiv has an 'exact' bit we can use a simpler lowering.
6931 if (N->getFlags().hasExact())
6932 return BuildExactSDIV(*this, N, dl, DAG, Created);
6933
6934 EVT VT = N->getValueType(0);
6935 EVT SVT = VT.getScalarType();
6936 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6937 EVT ShSVT = ShVT.getScalarType();
6938 unsigned EltBits = VT.getScalarSizeInBits();
6939 EVT MulVT;
6940
6941 // Check to see if we can do this.
6942 // FIXME: We should be more aggressive here.
6943 EVT QueryVT = VT;
6944 if (VT.isVector()) {
6945 // If the vector type will be legalized to a vector type with the same
6946 // element type, allow the transform before type legalization if MULHS or
6947 // SMUL_LOHI are supported.
6948 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
6949 if (!QueryVT.isVector() ||
6951 return SDValue();
6952 } else if (!isTypeLegal(VT)) {
6953 // Limit this to simple scalars for now.
6954 if (!VT.isSimple())
6955 return SDValue();
6956
6957 // If this type will be promoted to a large enough type with a legal
6958 // multiply operation, we can go ahead and do this transform.
6960 return SDValue();
6961
6962 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6963 if (MulVT.getSizeInBits() < (2 * EltBits) ||
6964 !isOperationLegal(ISD::MUL, MulVT))
6965 return SDValue();
6966 }
6967
6968 bool HasMULHS =
6969 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
6970 bool HasSMUL_LOHI =
6971 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
6972
6973 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
6974 // If type twice as wide legal, widen and use a mul plus a shift.
6975 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
6976 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
6977 // custom lowered. This is very expensive so avoid it at all costs for
6978 // constant divisors.
6979 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
6982 MulVT = WideVT;
6983 }
6984
6985 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
6986 return SDValue();
6987
6988 // If we're after type legalization and SVT is not legal, use the
6989 // promoted type for creating constants to avoid creating nodes with
6990 // illegal types.
6991 if (IsAfterLegalTypes && VT.isVector()) {
6992 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
6993 if (SVT.bitsLT(VT.getScalarType()))
6994 return SDValue();
6995 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
6996 if (ShSVT.bitsLT(ShVT.getScalarType()))
6997 return SDValue();
6998 }
6999 const unsigned SVTBits = SVT.getSizeInBits();
7000
7001 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
7002
7003 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
7004 if (C->isZero())
7005 return false;
7006 // Truncate the divisor to the target scalar type in case it was promoted
7007 // during type legalization.
7008 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7010 int NumeratorFactor = 0;
7011 int ShiftMask = -1;
7012
7013 if (Divisor.isOne() || Divisor.isAllOnes()) {
7014 // If d is +1/-1, we just multiply the numerator by +1/-1.
7015 NumeratorFactor = Divisor.getSExtValue();
7016 magics.Magic = 0;
7017 magics.ShiftAmount = 0;
7018 ShiftMask = 0;
7019 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
7020 // If d > 0 and m < 0, add the numerator.
7021 NumeratorFactor = 1;
7022 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
7023 // If d < 0 and m > 0, subtract the numerator.
7024 NumeratorFactor = -1;
7025 }
7026
7027 MagicFactors.push_back(
7028 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
7029 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
7030 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
7031 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
7032 return true;
7033 };
7034
7035 SDValue N0 = N->getOperand(0);
7036 SDValue N1 = N->getOperand(1);
7037
7038 // Collect the shifts / magic values from each element.
7039 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
7040 /*AllowTruncation=*/true))
7041 return SDValue();
7042
7043 SDValue MagicFactor, Factor, Shift, ShiftMask;
7044 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7045 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7046 Factor = DAG.getBuildVector(VT, dl, Factors);
7047 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
7048 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
7049 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7050 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
7051 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
7052 "Expected matchUnaryPredicate to return one element for scalable "
7053 "vectors");
7054 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7055 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
7056 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
7057 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
7058 } else {
7059 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7060 MagicFactor = MagicFactors[0];
7061 Factor = Factors[0];
7062 Shift = Shifts[0];
7063 ShiftMask = ShiftMasks[0];
7064 }
7065
7066 // Multiply the numerator (operand 0) by the magic value.
7067 auto GetMULHS = [&](SDValue X, SDValue Y) {
7068 if (HasMULHS)
7069 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
7070 if (HasSMUL_LOHI) {
7071 SDValue LoHi =
7072 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7073 return LoHi.getValue(1);
7074 }
7075
7076 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
7077 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
7078 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7079 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7080 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7081 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7082 };
7083
7084 SDValue Q = GetMULHS(N0, MagicFactor);
7085 if (!Q)
7086 return SDValue();
7087
7088 Created.push_back(Q.getNode());
7089
7090 // (Optionally) Add/subtract the numerator using Factor.
7091 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
7092 Created.push_back(Factor.getNode());
7093 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
7094 Created.push_back(Q.getNode());
7095
7096 // Shift right algebraic by shift value.
7097 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
7098 Created.push_back(Q.getNode());
7099
7100 // Extract the sign bit, mask it and add it to the quotient.
7101 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
7102 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
7103 Created.push_back(T.getNode());
7104 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
7105 Created.push_back(T.getNode());
7106 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
7107}
7108
7109/// Given an ISD::UDIV node expressing a divide by constant,
7110/// return a DAG expression to select that will generate the same value by
7111/// multiplying by a magic number.
7112/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7114 bool IsAfterLegalization,
7115 bool IsAfterLegalTypes,
7116 SmallVectorImpl<SDNode *> &Created) const {
7117 SDLoc dl(N);
7118
7119 // If the udiv has an 'exact' bit we can use a simpler lowering.
7120 if (N->getFlags().hasExact())
7121 return BuildExactUDIV(*this, N, dl, DAG, Created);
7122
7123 EVT VT = N->getValueType(0);
7124 EVT SVT = VT.getScalarType();
7125 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7126 EVT ShSVT = ShVT.getScalarType();
7127 unsigned EltBits = VT.getScalarSizeInBits();
7128 EVT MulVT;
7129
7130 // Check to see if we can do this.
7131 // FIXME: We should be more aggressive here.
7132 EVT QueryVT = VT;
7133 if (VT.isVector()) {
7134 // If the vector type will be legalized to a vector type with the same
7135 // element type, allow the transform before type legalization if MULHU or
7136 // UMUL_LOHI are supported.
7137 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7138 if (!QueryVT.isVector() ||
7140 return SDValue();
7141 } else if (!isTypeLegal(VT)) {
7142 // Limit this to simple scalars for now.
7143 if (!VT.isSimple())
7144 return SDValue();
7145
7146 // If this type will be promoted to a large enough type with a legal
7147 // multiply operation, we can go ahead and do this transform.
7149 return SDValue();
7150
7151 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7152 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7153 !isOperationLegal(ISD::MUL, MulVT))
7154 return SDValue();
7155 }
7156
7157 bool HasMULHU =
7158 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
7159 bool HasUMUL_LOHI =
7160 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
7161
7162 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
7163 // If type twice as wide legal, widen and use a mul plus a shift.
7164 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7165 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
7166 // custom lowered. This is very expensive so avoid it at all costs for
7167 // constant divisors.
7168 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
7171 MulVT = WideVT;
7172 }
7173
7174 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
7175 return SDValue();
7176
7177 SDValue N0 = N->getOperand(0);
7178 SDValue N1 = N->getOperand(1);
7179
7180 // Try to use leading zeros of the dividend to reduce the multiplier and
7181 // avoid expensive fixups.
7182 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
7183
7184 // If we're after type legalization and SVT is not legal, use the
7185 // promoted type for creating constants to avoid creating nodes with
7186 // illegal types.
7187 if (IsAfterLegalTypes && VT.isVector()) {
7188 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7189 if (SVT.bitsLT(VT.getScalarType()))
7190 return SDValue();
7191 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7192 if (ShSVT.bitsLT(ShVT.getScalarType()))
7193 return SDValue();
7194 }
7195 const unsigned SVTBits = SVT.getSizeInBits();
7196
7197 // Allow i32 to be widened to i64 for uncooperative divisors if i64 MULHU or
7198 // UMUL_LOHI is supported.
7199 const EVT WideSVT = MVT::i64;
7200 const bool HasWideMULHU =
7201 VT == MVT::i32 &&
7202 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
7203 const bool HasWideUMUL_LOHI =
7204 VT == MVT::i32 &&
7205 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
7206 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
7207
7208 // For even divisors with a 33-bit magic number, the widened high-multiply
7209 // path is only worthwhile over the even-divisor rewrite on targets that
7210 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
7211 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
7212 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
7213
7214 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
7215 bool UseWiden = false;
7216 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
7217
7218 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
7219 if (C->isZero())
7220 return false;
7221 // Truncate the divisor to the target scalar type in case it was promoted
7222 // during type legalization.
7223 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7224
7225 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
7226
7227 // Magic algorithm doesn't work for division by 1. We need to emit a select
7228 // at the end.
7229 if (Divisor.isOne()) {
7230 PreShift = PostShift = DAG.getUNDEF(ShSVT);
7231 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
7232 } else {
7235 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7236 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7237 /*AllowWidenOptimization=*/AllowWiden);
7238
7239 if (magics.Widen) {
7240 UseWiden = true;
7241 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7242 } else {
7243 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7244 }
7245
7246 assert(magics.PreShift < Divisor.getBitWidth() &&
7247 "We shouldn't generate an undefined shift!");
7248 assert(magics.PostShift < Divisor.getBitWidth() &&
7249 "We shouldn't generate an undefined shift!");
7250 assert((!magics.IsAdd || magics.PreShift == 0) &&
7251 "Unexpected pre-shift");
7252 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7253 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7254 NPQFactor = DAG.getConstant(
7255 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7256 : APInt::getZero(SVTBits),
7257 dl, SVT);
7258 UseNPQ |= magics.IsAdd;
7259 UsePreShift |= magics.PreShift != 0;
7260 UsePostShift |= magics.PostShift != 0;
7261 }
7262
7263 PreShifts.push_back(PreShift);
7264 MagicFactors.push_back(MagicFactor);
7265 NPQFactors.push_back(NPQFactor);
7266 PostShifts.push_back(PostShift);
7267 return true;
7268 };
7269
7270 // Collect the shifts/magic values from each element.
7271 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7272 /*AllowTruncation=*/true))
7273 return SDValue();
7274
7275 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7276 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7277 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7278 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7279 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7280 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7281 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7282 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7283 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7284 "Expected matchUnaryPredicate to return one for scalable vectors");
7285 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7286 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7287 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7288 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7289 } else {
7290 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7291 PreShift = PreShifts[0];
7292 MagicFactor = MagicFactors[0];
7293 PostShift = PostShifts[0];
7294 }
7295
7296 if (UseWiden) {
7297 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7298 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7299
7300 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7301 // WideSVT bits
7302 SDValue High;
7303 if (HasWideMULHU) {
7304 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7305 } else {
7306 assert(HasWideUMUL_LOHI);
7307 SDValue LoHi =
7308 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7309 WideN0, MagicFactor);
7310 High = LoHi.getValue(1);
7311 }
7312
7313 Created.push_back(High.getNode());
7314 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7315 }
7316
7317 SDValue Q = N0;
7318 if (UsePreShift) {
7319 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7320 Created.push_back(Q.getNode());
7321 }
7322
7323 auto GetMULHU = [&](SDValue X, SDValue Y) {
7324 if (HasMULHU)
7325 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7326 if (HasUMUL_LOHI) {
7327 SDValue LoHi =
7328 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7329 return LoHi.getValue(1);
7330 }
7331
7332 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7333 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7334 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7335 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7336 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7337 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7338 };
7339
7340 // Multiply the numerator (operand 0) by the magic value.
7341 Q = GetMULHU(Q, MagicFactor);
7342 if (!Q)
7343 return SDValue();
7344
7345 Created.push_back(Q.getNode());
7346
7347 if (UseNPQ) {
7348 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7349 Created.push_back(NPQ.getNode());
7350
7351 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7352 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7353 if (VT.isVector())
7354 NPQ = GetMULHU(NPQ, NPQFactor);
7355 else
7356 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7357
7358 Created.push_back(NPQ.getNode());
7359
7360 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7361 Created.push_back(Q.getNode());
7362 }
7363
7364 if (UsePostShift) {
7365 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7366 Created.push_back(Q.getNode());
7367 }
7368
7369 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7370
7371 SDValue One = DAG.getConstant(1, dl, VT);
7372 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7373 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7374}
7375
7376/// If all values in Values that *don't* match the predicate are same 'splat'
7377/// value, then replace all values with that splat value.
7378/// Else, if AlternativeReplacement was provided, then replace all values that
7379/// do match predicate with AlternativeReplacement value.
7380static void
7382 std::function<bool(SDValue)> Predicate,
7383 SDValue AlternativeReplacement = SDValue()) {
7384 SDValue Replacement;
7385 // Is there a value for which the Predicate does *NOT* match? What is it?
7386 auto SplatValue = llvm::find_if_not(Values, Predicate);
7387 if (SplatValue != Values.end()) {
7388 // Does Values consist only of SplatValue's and values matching Predicate?
7389 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7390 return Value == *SplatValue || Predicate(Value);
7391 })) // Then we shall replace values matching predicate with SplatValue.
7392 Replacement = *SplatValue;
7393 }
7394 if (!Replacement) {
7395 // Oops, we did not find the "baseline" splat value.
7396 if (!AlternativeReplacement)
7397 return; // Nothing to do.
7398 // Let's replace with provided value then.
7399 Replacement = AlternativeReplacement;
7400 }
7401 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7402}
7403
7404/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7405/// where the divisor and comparison target are constants,
7406/// return a DAG expression that will generate the same comparison result
7407/// using only multiplications, additions and shifts/rotations.
7408/// Ref: "Hacker's Delight" 10-17.
7409SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7410 SDValue CompTargetNode,
7412 DAGCombinerInfo &DCI,
7413 const SDLoc &DL) const {
7415 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7416 DCI, DL, Built)) {
7417 for (SDNode *N : Built)
7418 DCI.AddToWorklist(N);
7419 return Folded;
7420 }
7421
7422 return SDValue();
7423}
7424
7425SDValue
7426TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7427 SDValue CompTargetNode, ISD::CondCode Cond,
7428 DAGCombinerInfo &DCI, const SDLoc &DL,
7429 SmallVectorImpl<SDNode *> &Created) const {
7430 // fold (seteq/ne (urem N, D), C) ->
7431 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7432 // - D must be constant, with D = D0 * 2^K where D0 is odd
7433 // - P is the multiplicative inverse of D0 modulo 2^W
7434 // - Q = floor(((2^W) - 1) / D)
7435 // where W is the width of the common type of N and D.
7436 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7437 "Only applicable for (in)equality comparisons.");
7438
7439 SelectionDAG &DAG = DCI.DAG;
7440
7441 EVT VT = REMNode.getValueType();
7442 EVT SVT = VT.getScalarType();
7443 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7444 EVT ShSVT = ShVT.getScalarType();
7445
7446 // If MUL is unavailable, we cannot proceed in any case.
7447 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7448 return SDValue();
7449
7450 bool ComparingWithAllZeros = true;
7451 bool AllComparisonsWithNonZerosAreTautological = true;
7452 bool HadTautologicalLanes = false;
7453 bool AllLanesAreTautological = true;
7454 bool HadEvenDivisor = false;
7455 bool AllDivisorsArePowerOfTwo = true;
7456 bool HadTautologicalInvertedLanes = false;
7457 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7458
7459 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7460 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7461 if (CDiv->isZero())
7462 return false;
7463
7464 const APInt &D = CDiv->getAPIntValue();
7465 const APInt &Cmp = CCmp->getAPIntValue();
7466
7467 ComparingWithAllZeros &= Cmp.isZero();
7468
7469 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7470 // if C2 is not less than C1, the comparison is always false.
7471 // But we will only be able to produce the comparison that will give the
7472 // opposive tautological answer. So this lane would need to be fixed up.
7473 bool TautologicalInvertedLane = D.ule(Cmp);
7474 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7475
7476 // If all lanes are tautological (either all divisors are ones, or divisor
7477 // is not greater than the constant we are comparing with),
7478 // we will prefer to avoid the fold.
7479 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7480 HadTautologicalLanes |= TautologicalLane;
7481 AllLanesAreTautological &= TautologicalLane;
7482
7483 // If we are comparing with non-zero, we need'll need to subtract said
7484 // comparison value from the LHS. But there is no point in doing that if
7485 // every lane where we are comparing with non-zero is tautological..
7486 if (!Cmp.isZero())
7487 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7488
7489 // Decompose D into D0 * 2^K
7490 unsigned K = D.countr_zero();
7491 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7492 APInt D0 = D.lshr(K);
7493
7494 // D is even if it has trailing zeros.
7495 HadEvenDivisor |= (K != 0);
7496 // D is a power-of-two if D0 is one.
7497 // If all divisors are power-of-two, we will prefer to avoid the fold.
7498 AllDivisorsArePowerOfTwo &= D0.isOne();
7499
7500 // P = inv(D0, 2^W)
7501 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7502 unsigned W = D.getBitWidth();
7503 APInt P = D0.multiplicativeInverse();
7504 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7505
7506 // Q = floor((2^W - 1) u/ D)
7507 // R = ((2^W - 1) u% D)
7508 APInt Q, R;
7510
7511 // If we are comparing with zero, then that comparison constant is okay,
7512 // else it may need to be one less than that.
7513 if (Cmp.ugt(R))
7514 Q -= 1;
7515
7517 "We are expecting that K is always less than all-ones for ShSVT");
7518
7519 // If the lane is tautological the result can be constant-folded.
7520 if (TautologicalLane) {
7521 // Set P and K amount to a bogus values so we can try to splat them.
7522 P = 0;
7523 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7524 // And ensure that comparison constant is tautological,
7525 // it will always compare true/false.
7526 Q.setAllBits();
7527 } else {
7528 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7529 }
7530
7531 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7532 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7533 return true;
7534 };
7535
7536 SDValue N = REMNode.getOperand(0);
7537 SDValue D = REMNode.getOperand(1);
7538
7539 // Collect the values from each element.
7540 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7541 return SDValue();
7542
7543 // If all lanes are tautological, the result can be constant-folded.
7544 if (AllLanesAreTautological)
7545 return SDValue();
7546
7547 // If this is a urem by a powers-of-two, avoid the fold since it can be
7548 // best implemented as a bit test.
7549 if (AllDivisorsArePowerOfTwo)
7550 return SDValue();
7551
7552 SDValue PVal, KVal, QVal;
7553 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7554 if (HadTautologicalLanes) {
7555 // Try to turn PAmts into a splat, since we don't care about the values
7556 // that are currently '0'. If we can't, just keep '0'`s.
7558 // Try to turn KAmts into a splat, since we don't care about the values
7559 // that are currently '-1'. If we can't, change them to '0'`s.
7561 DAG.getConstant(0, DL, ShSVT));
7562 }
7563
7564 PVal = DAG.getBuildVector(VT, DL, PAmts);
7565 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7566 QVal = DAG.getBuildVector(VT, DL, QAmts);
7567 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7568 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7569 "Expected matchBinaryPredicate to return one element for "
7570 "SPLAT_VECTORs");
7571 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7572 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7573 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7574 } else {
7575 PVal = PAmts[0];
7576 KVal = KAmts[0];
7577 QVal = QAmts[0];
7578 }
7579
7580 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7581 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7582 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7583 assert(CompTargetNode.getValueType() == N.getValueType() &&
7584 "Expecting that the types on LHS and RHS of comparisons match.");
7585 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7586 }
7587
7588 // (mul N, P)
7589 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7590 Created.push_back(Op0.getNode());
7591
7592 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7593 // divisors as a performance improvement, since rotating by 0 is a no-op.
7594 if (HadEvenDivisor) {
7595 // We need ROTR to do this.
7596 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7597 return SDValue();
7598 // UREM: (rotr (mul N, P), K)
7599 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7600 Created.push_back(Op0.getNode());
7601 }
7602
7603 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7604 SDValue NewCC =
7605 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7607 if (!HadTautologicalInvertedLanes)
7608 return NewCC;
7609
7610 // If any lanes previously compared always-false, the NewCC will give
7611 // always-true result for them, so we need to fixup those lanes.
7612 // Or the other way around for inequality predicate.
7613 assert(VT.isVector() && "Can/should only get here for vectors.");
7614 Created.push_back(NewCC.getNode());
7615
7616 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7617 // if C2 is not less than C1, the comparison is always false.
7618 // But we have produced the comparison that will give the
7619 // opposive tautological answer. So these lanes would need to be fixed up.
7620 SDValue TautologicalInvertedChannels =
7621 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7622 Created.push_back(TautologicalInvertedChannels.getNode());
7623
7624 // NOTE: we avoid letting illegal types through even if we're before legalize
7625 // ops – legalization has a hard time producing good code for this.
7626 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7627 // If we have a vector select, let's replace the comparison results in the
7628 // affected lanes with the correct tautological result.
7629 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7630 DL, SETCCVT, SETCCVT);
7631 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7632 Replacement, NewCC);
7633 }
7634
7635 // Else, we can just invert the comparison result in the appropriate lanes.
7636 //
7637 // NOTE: see the note above VSELECT above.
7638 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7639 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7640 TautologicalInvertedChannels);
7641
7642 return SDValue(); // Don't know how to lower.
7643}
7644
7645/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7646/// where the divisor is constant and the comparison target is zero,
7647/// return a DAG expression that will generate the same comparison result
7648/// using only multiplications, additions and shifts/rotations.
7649/// Ref: "Hacker's Delight" 10-17.
7650SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7651 SDValue CompTargetNode,
7653 DAGCombinerInfo &DCI,
7654 const SDLoc &DL) const {
7656 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7657 DCI, DL, Built)) {
7658 assert(Built.size() <= 7 && "Max size prediction failed.");
7659 for (SDNode *N : Built)
7660 DCI.AddToWorklist(N);
7661 return Folded;
7662 }
7663
7664 return SDValue();
7665}
7666
7667SDValue
7668TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7669 SDValue CompTargetNode, ISD::CondCode Cond,
7670 DAGCombinerInfo &DCI, const SDLoc &DL,
7671 SmallVectorImpl<SDNode *> &Created) const {
7672 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7673 // Fold:
7674 // (seteq/ne (srem N, D), 0)
7675 // To:
7676 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7677 //
7678 // - D must be constant, with D = D0 * 2^K where D0 is odd
7679 // - P is the multiplicative inverse of D0 modulo 2^W
7680 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7681 // - Q = floor((2 * A) / (2^K))
7682 // where W is the width of the common type of N and D.
7683 //
7684 // When D is a power of two (and thus D0 is 1), the normal
7685 // formula for A and Q don't apply, because the derivation
7686 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7687 // does not apply. This specifically fails when N = INT_MIN.
7688 //
7689 // Instead, for power-of-two D, we use:
7690 // - A = 0
7691 // | -> No offset needed. We're effectively treating it the same as urem.
7692 // - Q = 2^(W-K) - 1
7693 // |-> Test that the top K bits are zero after rotation
7694 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7695 "Only applicable for (in)equality comparisons.");
7696
7697 SelectionDAG &DAG = DCI.DAG;
7698
7699 EVT VT = REMNode.getValueType();
7700 EVT SVT = VT.getScalarType();
7701 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7702 EVT ShSVT = ShVT.getScalarType();
7703
7704 // If we are after ops legalization, and MUL is unavailable, we can not
7705 // proceed.
7706 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7707 return SDValue();
7708
7709 // TODO: Could support comparing with non-zero too.
7710 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7711 if (!CompTarget || !CompTarget->isZero())
7712 return SDValue();
7713
7714 bool HadOneDivisor = false;
7715 bool AllDivisorsAreOnes = true;
7716 bool HadEvenDivisor = false;
7717 bool AllDivisorsArePowerOfTwo = true;
7718 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7719
7720 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7721 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7722 if (C->isZero())
7723 return false;
7724
7725 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7726
7727 // WARNING: this fold is only valid for positive divisors!
7728 // `rem %X, -C` is equivalent to `rem %X, C`
7729 APInt D = C->getAPIntValue().abs();
7730
7731 // If all divisors are ones, we will prefer to avoid the fold.
7732 HadOneDivisor |= D.isOne();
7733 AllDivisorsAreOnes &= D.isOne();
7734
7735 // Decompose D into D0 * 2^K
7736 unsigned K = D.countr_zero();
7737 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7738 APInt D0 = D.lshr(K);
7739
7740 // D is even if it has trailing zeros.
7741 HadEvenDivisor |= (K != 0);
7742
7743 // D is a power-of-two if D0 is one. This includes INT_MIN.
7744 // If all divisors are power-of-two, we will prefer to avoid the fold.
7745 AllDivisorsArePowerOfTwo &= D0.isOne();
7746
7747 // P = inv(D0, 2^W)
7748 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7749 unsigned W = D.getBitWidth();
7750 APInt P = D0.multiplicativeInverse();
7751 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7752
7753 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7754 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7755 A.clearLowBits(K);
7756
7757 // Q = floor((2 * A) / (2^K))
7758 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7759
7761 "We are expecting that A is always less than all-ones for SVT");
7763 "We are expecting that K is always less than all-ones for ShSVT");
7764
7765 // If D was a power of two, apply the alternate constant derivation.
7766 if (D0.isOne()) {
7767 // A = 0
7768 A = APInt(W, 0);
7769 // - Q = 2^(W-K) - 1
7770 Q = APInt::getLowBitsSet(W, W - K);
7771 }
7772
7773 // If the divisor is 1 the result can be constant-folded.
7774 if (D.isOne()) {
7775 // Set P, A and K to a bogus values so we can try to splat them.
7776 P = 0;
7777 A.setAllBits();
7778 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7779
7780 // x ?% 1 == 0 <--> true <--> x u<= -1
7781 Q.setAllBits();
7782 } else {
7783 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7784 }
7785
7786 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7787 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7788 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7789 return true;
7790 };
7791
7792 SDValue N = REMNode.getOperand(0);
7793 SDValue D = REMNode.getOperand(1);
7794
7795 // Collect the values from each element.
7796 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7797 return SDValue();
7798
7799 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7800 if (AllDivisorsAreOnes)
7801 return SDValue();
7802
7803 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7804 // since it can be best implemented as a bit test.
7805 if (AllDivisorsArePowerOfTwo)
7806 return SDValue();
7807
7808 SDValue PVal, AVal, KVal, QVal;
7809 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7810 if (HadOneDivisor) {
7811 // Try to turn PAmts into a splat, since we don't care about the values
7812 // that are currently '0'. If we can't, just keep '0'`s.
7814 // Try to turn AAmts into a splat, since we don't care about the
7815 // values that are currently '-1'. If we can't, change them to '0'`s.
7817 DAG.getConstant(0, DL, SVT));
7818 // Try to turn KAmts into a splat, since we don't care about the values
7819 // that are currently '-1'. If we can't, change them to '0'`s.
7821 DAG.getConstant(0, DL, ShSVT));
7822 }
7823
7824 PVal = DAG.getBuildVector(VT, DL, PAmts);
7825 AVal = DAG.getBuildVector(VT, DL, AAmts);
7826 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7827 QVal = DAG.getBuildVector(VT, DL, QAmts);
7828 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7829 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7830 QAmts.size() == 1 &&
7831 "Expected matchUnaryPredicate to return one element for scalable "
7832 "vectors");
7833 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7834 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7835 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7836 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7837 } else {
7838 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7839 PVal = PAmts[0];
7840 AVal = AAmts[0];
7841 KVal = KAmts[0];
7842 QVal = QAmts[0];
7843 }
7844
7845 // (mul N, P)
7846 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7847 Created.push_back(Op0.getNode());
7848
7849 // We need ADD to do this.
7850 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
7851 return SDValue();
7852
7853 // (add (mul N, P), A)
7854 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
7855 Created.push_back(Op0.getNode());
7856
7857 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7858 // divisors as a performance improvement, since rotating by 0 is a no-op.
7859 if (HadEvenDivisor) {
7860 // We need ROTR to do this.
7861 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7862 return SDValue();
7863 // SREM: (rotr (add (mul N, P), A), K)
7864 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7865 Created.push_back(Op0.getNode());
7866 }
7867
7868 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
7869 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7871}
7872
7874 const DenormalMode &Mode,
7875 SDNodeFlags Flags) const {
7876 SDLoc DL(Op);
7877 EVT VT = Op.getValueType();
7878 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7879 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7880
7881 // This is specifically a check for the handling of denormal inputs, not the
7882 // result.
7883 if (Mode.Input == DenormalMode::PreserveSign ||
7884 Mode.Input == DenormalMode::PositiveZero) {
7885 // Test = X == 0.0
7886 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
7887 /*Signaling=*/false, Flags);
7888 }
7889
7890 // Testing it with denormal inputs to avoid wrong estimate.
7891 //
7892 // Test = fabs(X) < SmallestNormal
7893 const fltSemantics &FltSem = VT.getFltSemantics();
7894 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
7895 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
7896 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
7897 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
7898 /*Signaling=*/false, Flags);
7899}
7900
7902 bool LegalOps, bool OptForSize,
7904 unsigned Depth) const {
7905 // fneg is removable even if it has multiple uses.
7906 if (Op.getOpcode() == ISD::FNEG) {
7908 return Op.getOperand(0);
7909 }
7910
7911 // Don't recurse exponentially.
7913 return SDValue();
7914
7915 // Pre-increment recursion depth for use in recursive calls.
7916 ++Depth;
7917 const SDNodeFlags Flags = Op->getFlags();
7918 EVT VT = Op.getValueType();
7919 unsigned Opcode = Op.getOpcode();
7920
7921 // Don't allow anything with multiple uses unless we know it is free.
7922 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
7923 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
7924 isFPExtFree(VT, Op.getOperand(0).getValueType());
7925 if (!IsFreeExtend)
7926 return SDValue();
7927 }
7928
7929 auto RemoveDeadNode = [&](SDValue N) {
7930 if (N && N.getNode()->use_empty())
7931 DAG.RemoveDeadNode(N.getNode());
7932 };
7933
7934 SDLoc DL(Op);
7935
7936 // Because getNegatedExpression can delete nodes we need a handle to keep
7937 // temporary nodes alive in case the recursion manages to create an identical
7938 // node.
7939 std::list<HandleSDNode> Handles;
7940
7941 switch (Opcode) {
7942 case ISD::ConstantFP: {
7943 // Don't invert constant FP values after legalization unless the target says
7944 // the negated constant is legal.
7945 bool IsOpLegal =
7947 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
7948 OptForSize);
7949
7950 if (LegalOps && !IsOpLegal)
7951 break;
7952
7953 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
7954 V.changeSign();
7955 SDValue CFP = DAG.getConstantFP(V, DL, VT);
7956
7957 // If we already have the use of the negated floating constant, it is free
7958 // to negate it even it has multiple uses.
7959 if (!Op.hasOneUse() && CFP.use_empty())
7960 break;
7962 return CFP;
7963 }
7964 case ISD::SPLAT_VECTOR: {
7965 // fold splat_vector(fneg(X)) -> splat_vector(-X)
7966 SDValue X = Op.getOperand(0);
7968 break;
7969
7970 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
7971 if (!NegX)
7972 break;
7974 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
7975 }
7976 case ISD::BUILD_VECTOR: {
7977 // Only permit BUILD_VECTOR of constants.
7978 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
7979 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
7980 }))
7981 break;
7982
7983 bool IsOpLegal =
7986 llvm::all_of(Op->op_values(), [&](SDValue N) {
7987 return N.isUndef() ||
7988 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
7989 OptForSize);
7990 });
7991
7992 if (LegalOps && !IsOpLegal)
7993 break;
7994
7996 for (SDValue C : Op->op_values()) {
7997 if (C.isUndef()) {
7998 Ops.push_back(C);
7999 continue;
8000 }
8001 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
8002 V.changeSign();
8003 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
8004 }
8006 return DAG.getBuildVector(VT, DL, Ops);
8007 }
8008 case ISD::FADD: {
8009 if (!Flags.hasNoSignedZeros())
8010 break;
8011
8012 // After operation legalization, it might not be legal to create new FSUBs.
8013 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
8014 break;
8015 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8016
8017 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
8019 SDValue NegX =
8020 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8021 // Prevent this node from being deleted by the next call.
8022 if (NegX)
8023 Handles.emplace_back(NegX);
8024
8025 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
8027 SDValue NegY =
8028 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8029
8030 // We're done with the handles.
8031 Handles.clear();
8032
8033 // Negate the X if its cost is less or equal than Y.
8034 if (NegX && (CostX <= CostY)) {
8035 Cost = CostX;
8036 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
8037 if (NegY != N)
8038 RemoveDeadNode(NegY);
8039 return N;
8040 }
8041
8042 // Negate the Y if it is not expensive.
8043 if (NegY) {
8044 Cost = CostY;
8045 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
8046 if (NegX != N)
8047 RemoveDeadNode(NegX);
8048 return N;
8049 }
8050 break;
8051 }
8052 case ISD::FSUB: {
8053 // We can't turn -(A-B) into B-A when we honor signed zeros.
8054 if (!Flags.hasNoSignedZeros())
8055 break;
8056
8057 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8058 // fold (fneg (fsub 0, Y)) -> Y
8059 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
8060 if (C->isZero()) {
8062 return Y;
8063 }
8064
8065 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
8067 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
8068 }
8069 case ISD::FMUL:
8070 case ISD::FDIV: {
8071 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8072
8073 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
8075 SDValue NegX =
8076 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8077 // Prevent this node from being deleted by the next call.
8078 if (NegX)
8079 Handles.emplace_back(NegX);
8080
8081 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
8083 SDValue NegY =
8084 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8085
8086 // We're done with the handles.
8087 Handles.clear();
8088
8089 // Negate the X if its cost is less or equal than Y.
8090 if (NegX && (CostX <= CostY)) {
8091 Cost = CostX;
8092 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
8093 if (NegY != N)
8094 RemoveDeadNode(NegY);
8095 return N;
8096 }
8097
8098 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
8099 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
8100 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
8101 break;
8102
8103 // Negate the Y if it is not expensive.
8104 if (NegY) {
8105 Cost = CostY;
8106 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
8107 if (NegX != N)
8108 RemoveDeadNode(NegX);
8109 return N;
8110 }
8111 break;
8112 }
8113 case ISD::FMA:
8114 case ISD::FMULADD:
8115 case ISD::FMAD: {
8116 if (!Flags.hasNoSignedZeros())
8117 break;
8118
8119 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
8121 SDValue NegZ =
8122 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
8123 // Give up if fail to negate the Z.
8124 if (!NegZ)
8125 break;
8126
8127 // Prevent this node from being deleted by the next two calls.
8128 Handles.emplace_back(NegZ);
8129
8130 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
8132 SDValue NegX =
8133 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8134 // Prevent this node from being deleted by the next call.
8135 if (NegX)
8136 Handles.emplace_back(NegX);
8137
8138 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
8140 SDValue NegY =
8141 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8142
8143 // We're done with the handles.
8144 Handles.clear();
8145
8146 // Negate the X if its cost is less or equal than Y.
8147 if (NegX && (CostX <= CostY)) {
8148 Cost = std::min(CostX, CostZ);
8149 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
8150 if (NegY != N)
8151 RemoveDeadNode(NegY);
8152 return N;
8153 }
8154
8155 // Negate the Y if it is not expensive.
8156 if (NegY) {
8157 Cost = std::min(CostY, CostZ);
8158 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
8159 if (NegX != N)
8160 RemoveDeadNode(NegX);
8161 return N;
8162 }
8163 break;
8164 }
8165
8166 case ISD::FP_EXTEND:
8167 case ISD::FSIN:
8168 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8169 OptForSize, Cost, Depth))
8170 return DAG.getNode(Opcode, DL, VT, NegV);
8171 break;
8172 case ISD::FP_ROUND:
8173 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8174 OptForSize, Cost, Depth))
8175 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
8176 break;
8177 case ISD::SELECT:
8178 case ISD::VSELECT: {
8179 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
8180 // iff at least one cost is cheaper and the other is neutral/cheaper
8181 SDValue LHS = Op.getOperand(1);
8183 SDValue NegLHS =
8184 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
8185 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
8186 RemoveDeadNode(NegLHS);
8187 break;
8188 }
8189
8190 // Prevent this node from being deleted by the next call.
8191 Handles.emplace_back(NegLHS);
8192
8193 SDValue RHS = Op.getOperand(2);
8195 SDValue NegRHS =
8196 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
8197
8198 // We're done with the handles.
8199 Handles.clear();
8200
8201 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
8202 (CostLHS != NegatibleCost::Cheaper &&
8203 CostRHS != NegatibleCost::Cheaper)) {
8204 RemoveDeadNode(NegLHS);
8205 RemoveDeadNode(NegRHS);
8206 break;
8207 }
8208
8209 Cost = std::min(CostLHS, CostRHS);
8210 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
8211 }
8212 }
8213
8214 return SDValue();
8215}
8216
8217//===----------------------------------------------------------------------===//
8218// Legalization Utilities
8219//===----------------------------------------------------------------------===//
8220
8221bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
8222 SDValue LHS, SDValue RHS,
8224 EVT HiLoVT, SelectionDAG &DAG,
8225 MulExpansionKind Kind, SDValue LL,
8226 SDValue LH, SDValue RL, SDValue RH) const {
8227 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
8228 Opcode == ISD::SMUL_LOHI);
8229
8230 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
8232 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8234 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8236 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8238
8239 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8240 return false;
8241
8242 unsigned OuterBitSize = VT.getScalarSizeInBits();
8243 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8244
8245 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8246 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8247 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8248
8249 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8250 bool Signed) -> bool {
8251 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8252 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8253 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8254 Hi = Lo.getValue(1);
8255 return true;
8256 }
8257 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8258 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8259 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8260 return true;
8261 }
8262 return false;
8263 };
8264
8265 SDValue Lo, Hi;
8266
8267 if (!LL.getNode() && !RL.getNode() &&
8269 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8270 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8271 }
8272
8273 if (!LL.getNode())
8274 return false;
8275
8276 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8277 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8278 DAG.MaskedValueIsZero(RHS, HighMask)) {
8279 // The inputs are both zero-extended.
8280 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8281 Result.push_back(Lo);
8282 Result.push_back(Hi);
8283 if (Opcode != ISD::MUL) {
8284 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8285 Result.push_back(Zero);
8286 Result.push_back(Zero);
8287 }
8288 return true;
8289 }
8290 }
8291
8292 if (!VT.isVector() && Opcode == ISD::MUL &&
8293 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8294 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8295 // The input values are both sign-extended.
8296 // TODO non-MUL case?
8297 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8298 Result.push_back(Lo);
8299 Result.push_back(Hi);
8300 return true;
8301 }
8302 }
8303
8304 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8305 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8306
8307 if (!LH.getNode() && !RH.getNode() &&
8310 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8311 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8312 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8313 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8314 }
8315
8316 if (!LH.getNode())
8317 return false;
8318
8319 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8320 return false;
8321
8322 Result.push_back(Lo);
8323
8324 if (Opcode == ISD::MUL) {
8325 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8326 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8327 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8328 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8329 Result.push_back(Hi);
8330 return true;
8331 }
8332
8333 // Compute the full width result.
8334 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8335 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8336 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8337 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8338 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8339 };
8340
8341 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8342 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8343 return false;
8344
8345 // This is effectively the add part of a multiply-add of half-sized operands,
8346 // so it cannot overflow.
8347 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8348
8349 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8350 return false;
8351
8352 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8353 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8354
8355 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8357 if (UseGlue)
8358 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8359 Merge(Lo, Hi));
8360 else
8361 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8362 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8363
8364 SDValue Carry = Next.getValue(1);
8365 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8366 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8367
8368 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8369 return false;
8370
8371 if (UseGlue)
8372 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8373 Carry);
8374 else
8375 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8376 Zero, Carry);
8377
8378 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8379
8380 if (Opcode == ISD::SMUL_LOHI) {
8381 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8382 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8383 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8384
8385 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8386 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8387 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8388 }
8389
8390 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8391 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8392 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8393 return true;
8394}
8395
8397 SelectionDAG &DAG, MulExpansionKind Kind,
8398 SDValue LL, SDValue LH, SDValue RL,
8399 SDValue RH) const {
8401 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8402 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8403 DAG, Kind, LL, LH, RL, RH);
8404 if (Ok) {
8405 assert(Result.size() == 2);
8406 Lo = Result[0];
8407 Hi = Result[1];
8408 }
8409 return Ok;
8410}
8411
8412// Optimize unsigned division or remainder by constants for types twice as large
8413// as a legal VT.
8414//
8415// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8416// can be computed
8417// as:
8418// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8419// Remainder = Sum % Constant;
8420//
8421// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8422// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8423// High:Low into 3 chunks of W bits and compute remainder as
8424// Sum = Chunk0 + Chunk1 + Chunk2;
8425// Remainder = Sum % Constant;
8426//
8427// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8428//
8429// For division, we can compute the remainder using the algorithm described
8430// above, subtract it from the dividend to get an exact multiple of Constant.
8431// Then multiply that exact multiply by the multiplicative inverse modulo
8432// (1 << (BitWidth / 2)) to get the quotient.
8433
8434// If Constant is even, we can shift right the dividend and the divisor by the
8435// number of trailing zeros in Constant before applying the remainder algorithm.
8436// If we're after the quotient, we can subtract this value from the shifted
8437// dividend and multiply by the multiplicative inverse of the shifted divisor.
8438// If we want the remainder, we shift the value left by the number of trailing
8439// zeros and add the bits that were shifted out of the dividend.
8440bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8441 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8442 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8443 unsigned Opcode = N->getOpcode();
8444 EVT VT = N->getValueType(0);
8445
8446 unsigned BitWidth = Divisor.getBitWidth();
8447 unsigned HBitWidth = BitWidth / 2;
8449 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8450
8451 // If the divisor is even, shift it until it becomes odd.
8452 unsigned TrailingZeros = 0;
8453 if (!Divisor[0]) {
8454 TrailingZeros = Divisor.countr_zero();
8455 Divisor.lshrInPlace(TrailingZeros);
8456 }
8457
8458 // After removing trailing zeros, the divisor needs to be less than
8459 // (1 << HBitWidth).
8460 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8461 if (Divisor.uge(HalfMaxPlus1))
8462 return false;
8463
8464 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8465 // (1 << W) % Divisor == -1.
8466 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8467 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8468 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8469 if (I == HBitWidth - 1)
8470 continue;
8471
8472 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8473
8474 if (Mod.isOne()) {
8475 BestChunkWidth = I;
8476 break;
8477 }
8478
8479 // We have an alternate strategy for Remainder == Divisor - 1.
8480 // FIXME: Support HBitWidth.
8481 if (I != HBitWidth && Mod == Divisor - 1)
8482 AltChunkWidth = I;
8483 }
8484
8485 bool Alternate = false;
8486 if (!BestChunkWidth) {
8487 if (!AltChunkWidth)
8488 return false;
8489 Alternate = true;
8490 BestChunkWidth = AltChunkWidth;
8491 }
8492
8493 SDLoc dl(N);
8494
8495 assert(!LL == !LH && "Expected both input halves or no input halves!");
8496 if (!LL)
8497 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8498
8499 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8500
8501 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8502 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8503 if (HasFSHR)
8504 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8505 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8506 return DAG.getNode(
8507 ISD::OR, dl, HiLoVT,
8508 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8509 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8510 DAG.getNode(
8511 ISD::SHL, dl, HiLoVT, Hi,
8512 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8513 };
8514
8515 // Helper to perform a right shift on a 128-bit value split into two halves.
8516 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8517 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8518 if (ShiftAmt == 0)
8519 return;
8520 if (ShiftAmt < HBitWidth) {
8521 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8522 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8523 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8524 } else if (ShiftAmt == HBitWidth) {
8525 Lo = Hi;
8526 Hi = DAG.getConstant(0, dl, HiLoVT);
8527 } else {
8528 Lo = DAG.getNode(
8529 ISD::SRL, dl, HiLoVT, Hi,
8530 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8531 Hi = DAG.getConstant(0, dl, HiLoVT);
8532 }
8533 };
8534
8535 // Shift the input by the number of TrailingZeros in the divisor. The
8536 // shifted out bits will be added to the remainder later.
8537 SDValue PartialRemL, PartialRemH;
8538 if (TrailingZeros && Opcode != ISD::UDIV) {
8539 // Save the shifted off bits if we need the remainder.
8540 if (TrailingZeros < HBitWidth) {
8541 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8542 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8543 DAG.getConstant(Mask, dl, HiLoVT));
8544 } else if (TrailingZeros == HBitWidth) {
8545 // All of LL is part of the remainder.
8546 PartialRemL = LL;
8547 } else {
8548 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8549 PartialRemL = LL;
8550 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8551 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8552 DAG.getConstant(Mask, dl, HiLoVT));
8553 }
8554 }
8555
8556 SDValue Sum;
8557 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8558 // out, add that to the final sum.
8559 if (BestChunkWidth == HBitWidth) {
8560 assert(!Alternate);
8561 // Shift LH:LL right if there were trailing zeros in the divisor.
8562 ShiftRight(LL, LH, TrailingZeros);
8563
8564 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8565 EVT SetCCType =
8566 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8568 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8569 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8570 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8571 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8572 } else {
8573 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8574 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8575 // If the boolean for the target is 0 or 1, we can add the setcc result
8576 // directly.
8577 if (getBooleanContents(HiLoVT) ==
8579 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8580 else
8581 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8582 DAG.getConstant(0, dl, HiLoVT));
8583 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8584 }
8585 } else {
8586 // Otherwise split into multple chunks and add them together. We chose
8587 // BestChunkWidth so that the sum will not overflow.
8588 SDValue Mask = DAG.getConstant(
8589 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8590
8591 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8592 // If there were trailing zeros in the divisor, increase the shift amount.
8593 unsigned Shift = I + TrailingZeros;
8594 SDValue Chunk;
8595 if (Shift == 0)
8596 Chunk = LL;
8597 else if (Shift >= HBitWidth)
8598 Chunk = DAG.getNode(
8599 ISD::SRL, dl, HiLoVT, LH,
8600 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8601 else
8602 Chunk = GetFSHR(LL, LH, Shift);
8603 // If we're on the last chunk, we don't need an AND.
8604 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8605 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8606 if (!Sum) {
8607 Sum = Chunk;
8608 } else {
8609 // For Alternate, we need to subtract odd chunks.
8610 unsigned ChunkNum = I / BestChunkWidth;
8611 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8612 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8613 }
8614 }
8615
8616 // For Alternate, the sum may be negative, but we need a positive sum. We
8617 // can increase it by a multiple of the divisor to make it positive. For 3
8618 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8619 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8620 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8621 // positive.
8622 if (Alternate) {
8623 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8624 assert(NumChunks <= 4);
8625
8626 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8627 Adjust.setBit(0);
8628 // If there are 4 chunks, we need to adjust twice.
8629 if (NumChunks == 4)
8630 Adjust <<= 1;
8631 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8632 DAG.getConstant(Adjust, dl, HiLoVT));
8633 }
8634 }
8635
8636 // Perform a HiLoVT urem on the Sum using truncated divisor.
8637 SDValue RemL =
8638 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8639 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8640 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8641
8642 if (Opcode != ISD::UREM) {
8643 // If we didn't shift LH/LR earlier, do it now.
8644 if (BestChunkWidth != HBitWidth)
8645 ShiftRight(LL, LH, TrailingZeros);
8646
8647 // Subtract the remainder from the shifted dividend.
8648 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8649 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8650
8651 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8652
8653 // Multiply by the multiplicative inverse of the divisor modulo
8654 // (1 << BitWidth).
8655 APInt MulFactor = Divisor.multiplicativeInverse();
8656
8657 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8658 DAG.getConstant(MulFactor, dl, VT));
8659
8660 // Split the quotient into low and high parts.
8661 SDValue QuotL, QuotH;
8662 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8663 Result.push_back(QuotL);
8664 Result.push_back(QuotH);
8665 }
8666
8667 if (Opcode != ISD::UDIV) {
8668 // If we shifted the input, shift the remainder left and add the bits we
8669 // shifted off the input.
8670 if (TrailingZeros) {
8671 if (TrailingZeros < HBitWidth) {
8672 // Shift RemH:RemL left by TrailingZeros.
8673 // RemH gets the high bits shifted out of RemL.
8674 RemH = DAG.getNode(
8675 ISD::SRL, dl, HiLoVT, RemL,
8676 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8677 RemL =
8678 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8679 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8680 // OR in the partial remainder.
8681 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8683 } else if (TrailingZeros == HBitWidth) {
8684 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8685 // PartialRemL.
8686 RemH = RemL;
8687 RemL = PartialRemL;
8688 } else {
8689 // Shift left by more than HBitWidth.
8690 RemH = DAG.getNode(
8691 ISD::SHL, dl, HiLoVT, RemL,
8692 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8693 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8695 RemL = PartialRemL;
8696 }
8697 }
8698 Result.push_back(RemL);
8699 Result.push_back(RemH);
8700 }
8701
8702 return true;
8703}
8704
8705bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8706 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8707 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8708
8709 SDValue N0 = N->getOperand(0);
8710 EVT VT = N0->getValueType(0);
8711 SDLoc DL{N};
8712
8713 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8714
8715 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8716 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8717 const APInt &Const,
8718 SmallVectorImpl<SDValue> &Result) {
8719 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8720 SDValue RHS = DAG.getConstant(Const, DL, VT);
8721 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8722 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8724 LL, LH, RL, RH);
8725 };
8726
8727 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8728 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8729 SDValue RH) {
8730 SDValue AddSubNode =
8732 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8733 SDValue OutL = AddSubNode.getValue(0);
8734 SDValue Overflow = AddSubNode.getValue(1);
8735 SDValue AddSubWithOverflow =
8737 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8738 SDValue OutH = AddSubWithOverflow.getValue(0);
8739 return std::make_pair(OutL, OutH);
8740 };
8741
8742 // This helper creates a SRL of the pair (LL, LH) by Shift.
8743 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8744 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8745 if (Shift < HBitWidth) {
8746 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8747 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8748 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8749 return std::make_pair(ResL, ResH);
8750 }
8751 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8752 if (Shift == HBitWidth)
8753 return std::make_pair(LH, Zero);
8754 assert(Shift - HBitWidth < HBitWidth &&
8755 "We shouldn't generate an undefined shift");
8756 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8757 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8758 };
8759
8760 // Knowledge of leading zeros may help to reduce the multiplier.
8761 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8762
8763 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8764 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8765
8766 assert(!LL == !LH && "Expected both input halves or no input halves!");
8767 if (!LL)
8768 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8769 SDValue QL = LL;
8770 SDValue QH = LH;
8771 if (Magics.PreShift != 0)
8772 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8773
8774 SmallVector<SDValue, 4> UMulResult;
8775 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8776 return false;
8777
8778 QL = UMulResult[2];
8779 QH = UMulResult[3];
8780
8781 if (Magics.IsAdd) {
8782 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8783 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8784 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8785 }
8786
8787 if (Magics.PostShift != 0)
8788 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8789
8790 unsigned Opcode = N->getOpcode();
8791 if (Opcode != ISD::UREM) {
8792 Result.push_back(QL);
8793 Result.push_back(QH);
8794 }
8795
8796 if (Opcode != ISD::UDIV) {
8797 SmallVector<SDValue, 2> MulResult;
8798 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8799 return false;
8800
8801 assert(MulResult.size() == 2);
8802
8803 auto [RemL, RemH] =
8804 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8805
8806 Result.push_back(RemL);
8807 Result.push_back(RemH);
8808 }
8809
8810 return true;
8811}
8812
8815 EVT HiLoVT, SelectionDAG &DAG,
8816 SDValue LL, SDValue LH) const {
8817 unsigned Opcode = N->getOpcode();
8818
8819 // TODO: Support signed division/remainder.
8820 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8821 return false;
8822 assert(
8823 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8824 "Unexpected opcode");
8825
8826 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8827 if (!CN)
8828 return false;
8829
8830 APInt Divisor = CN->getAPIntValue();
8831
8832 // The generated half-width UREM is normally optimized using high multiply.
8833 // If the wide UREM libcall is unavailable, a legal or custom half-width
8834 // UDIVREM can lower it instead.
8835 bool CanDecomposeUREMWithoutMulHi =
8836 Opcode == ISD::UREM &&
8837 getLibcallImpl(RTLIB::getUREM(N->getValueType(0))) ==
8838 RTLIB::Unsupported &&
8840 if (!CanDecomposeUREMWithoutMulHi &&
8843 return false;
8844
8845 // Prefer the smaller libcall when one is available.
8846 if (DAG.shouldOptForSize() && !CanDecomposeUREMWithoutMulHi)
8847 return false;
8848
8849 // Early out for 0 or 1 divisors.
8850 if (Divisor.ule(1))
8851 return false;
8852
8853 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
8854 DAG, LL, LH))
8855 return true;
8856
8857 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
8858 LH))
8859 return true;
8860
8861 return false;
8862}
8863
8864// Check that (every element of) Z is undef or not an exact multiple of BW.
8865static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
8867 Z,
8868 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
8869 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
8870}
8871
8873 SelectionDAG &DAG) const {
8874 EVT VT = Node->getValueType(0);
8875
8876 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
8880 return SDValue();
8881
8882 SDValue X = Node->getOperand(0);
8883 SDValue Y = Node->getOperand(1);
8884 SDValue Z = Node->getOperand(2);
8885
8886 unsigned BW = VT.getScalarSizeInBits();
8887 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
8888 SDLoc DL(SDValue(Node, 0));
8889
8890 EVT ShVT = Z.getValueType();
8891
8892 // If a funnel shift in the other direction is more supported, use it.
8893 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
8894 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8895 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
8896 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8897 // fshl X, Y, Z -> fshr X, Y, -Z
8898 // fshr X, Y, Z -> fshl X, Y, -Z
8899 Z = DAG.getNegative(Z, DL, ShVT);
8900 } else {
8901 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
8902 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
8903 SDValue One = DAG.getConstant(1, DL, ShVT);
8904 if (IsFSHL) {
8905 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8906 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
8907 } else {
8908 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8909 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
8910 }
8911 Z = DAG.getNOT(DL, Z, ShVT);
8912 }
8913 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
8914 }
8915
8916 SDValue ShX, ShY;
8917 SDValue ShAmt, InvShAmt;
8918 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8919 // fshl: X << C | Y >> (BW - C)
8920 // fshr: X << (BW - C) | Y >> C
8921 // where C = Z % BW is not zero
8922 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8923 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8924 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
8925 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
8926 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
8927 } else {
8928 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
8929 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
8930 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
8931 if (isPowerOf2_32(BW)) {
8932 // Z % BW -> Z & (BW - 1)
8933 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
8934 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
8935 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
8936 } else {
8937 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8938 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8939 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
8940 }
8941
8942 SDValue One = DAG.getConstant(1, DL, ShVT);
8943 if (IsFSHL) {
8944 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
8945 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
8946 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
8947 } else {
8948 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
8949 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
8950 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
8951 }
8952 }
8953 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
8954}
8955
8956// TODO: Merge with expandFunnelShift.
8958 SelectionDAG &DAG) const {
8959 EVT VT = Node->getValueType(0);
8960 unsigned EltSizeInBits = VT.getScalarSizeInBits();
8961 bool IsLeft = Node->getOpcode() == ISD::ROTL;
8962 SDValue Op0 = Node->getOperand(0);
8963 SDValue Op1 = Node->getOperand(1);
8964 SDLoc DL(SDValue(Node, 0));
8965
8966 EVT ShVT = Op1.getValueType();
8967 SDValue Zero = DAG.getConstant(0, DL, ShVT);
8968
8969 // If a rotate in the other direction is more supported, use it.
8970 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
8971 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8972 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
8973 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8974 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
8975 }
8976
8977 if (!AllowVectorOps && VT.isVector() &&
8983 return SDValue();
8984
8985 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
8986 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
8987 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
8988 SDValue ShVal;
8989 SDValue HsVal;
8990 if (isPowerOf2_32(EltSizeInBits)) {
8991 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
8992 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
8993 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8994 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
8995 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8996 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
8997 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
8998 } else {
8999 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
9000 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
9001 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
9002 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
9003 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
9004 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
9005 SDValue One = DAG.getConstant(1, DL, ShVT);
9006 HsVal =
9007 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
9008 }
9009 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
9010}
9011
9012/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
9013/// a chain of halving decompositions (halving element width) and/or vector
9014/// widening (doubling element count). This guides expansion strategy selection:
9015/// if true, the halving/widening path produces better code than bit-by-bit.
9016///
9017/// HalveDepth tracks halving steps only (each creates ~4x more operations).
9018/// Widening steps are cheap (O(1) pad/extract) and don't count.
9019/// Limiting halvings to 2 prevents exponential blowup:
9020/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
9021/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
9022/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
9024 EVT VT, unsigned HalveDepth = 0,
9025 unsigned TotalDepth = 0) {
9026 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
9027 return false;
9029 return true;
9030 if (!TLI.isTypeLegal(VT))
9031 return false;
9032
9033 unsigned BW = VT.getScalarSizeInBits();
9034
9035 // Halve: halve element width, same element count.
9036 // This is the expensive step -- each halving creates ~4x more operations.
9037 if (BW % 2 == 0) {
9038 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
9039 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
9040 if (TLI.isTypeLegal(HalfVT) &&
9041 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
9042 return true;
9043 }
9044
9045 // Widen: double element count (fixed-width vectors only).
9046 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
9047 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
9048 if (TLI.isTypeLegal(WideVT) &&
9049 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
9050 return true;
9051
9052 return false;
9053}
9054
9056 SDLoc DL(Node);
9057 EVT VT = Node->getValueType(0);
9058 SDValue X = Node->getOperand(0);
9059 SDValue Y = Node->getOperand(1);
9060 unsigned BW = VT.getScalarSizeInBits();
9061 unsigned Opcode = Node->getOpcode();
9062 LLVMContext &Ctx = *DAG.getContext();
9063
9064 switch (Opcode) {
9065 case ISD::CLMUL: {
9066 // For vector types, try decomposition strategies that leverage legal
9067 // CLMUL on narrower or wider element types, avoiding the expensive
9068 // bit-by-bit expansion.
9069 if (VT.isVector()) {
9070 // Strategy 1: Halving decomposition to half-element-width CLMUL.
9071 // Applies ExpandIntRes_CLMUL's identity element-wise:
9072 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
9073 // where:
9074 // Lo = CLMUL(XLo, YLo)
9075 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9076 unsigned HalfBW = BW / 2;
9077 if (BW % 2 == 0) {
9078 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
9079 EVT HalfVT =
9080 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
9081 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
9082 /*HalveDepth=*/1)) {
9083 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
9084
9085 // Extract low and high halves of each element.
9086 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
9087 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9088 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
9089 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
9090 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9091 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
9092
9093 // Lo = CLMUL(XLo, YLo)
9094 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
9095
9096 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9097 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
9098 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
9099 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
9100 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
9101 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
9102
9103 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
9104 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
9105 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
9106 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
9107 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
9108 }
9109 }
9110
9111 // Strategy 2: Promote to double-element-width CLMUL.
9112 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
9113 {
9114 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9115 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
9116 // If CLMUL on ExtVT is Custom (not Legal), the target may
9117 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
9118 // fallback costs O(BW) vectorized iterations. Only widen when
9119 // element count is small enough that scalarization is cheaper.
9120 unsigned NumElts = VT.getVectorMinNumElements();
9121 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
9122 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
9123 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
9124 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9125 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
9126 }
9127 }
9128 }
9129
9130 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
9131 // vector, extract lower result). CLMUL is element-wise, so upper
9132 // (undef) lanes don't affect the lower results.
9133 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
9134 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
9135 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
9136 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
9137 SDValue Undef = DAG.getUNDEF(WideVT);
9138 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9139 X, DAG.getVectorIdxConstant(0, DL));
9140 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9141 Y, DAG.getVectorIdxConstant(0, DL));
9142 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
9143 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
9144 DAG.getVectorIdxConstant(0, DL));
9145 }
9146 }
9147 }
9148
9149 // Special case: clmul(X, Y) where Y is a known constant (splat) that forms
9150 // a contiguous block of trailing ones whose length N is a power of two
9151 // (e.g. i8 0xFF, i8 0x0F, ...) or equal to the operand width. In this
9152 // special case, clmul(X, Y) is equivalent to a "parallel prefix XOR" or
9153 // "bitwise parity" operation on X.
9154 //
9155 // Note: This special currently dose NOT apply when the mask is neither a
9156 // power of two nor equal to the operand width because the loop inside
9157 // behaves as if the mask was bit-ceiled, and "undoing" the XOR with parts
9158 // of that CLMUL is a recursive problem (e.g. CLMUL with a 20-bit mask
9159 // requires correction XOR with CLMUL with 12-bit mask).
9160 if (auto *C = isConstOrConstSplat(Y, /*AllowUndefs=*/true)) {
9161 const APInt &YVal = C->getAPIntValue();
9162 unsigned N = YVal.countr_one();
9163 if (YVal.isAllOnes() || (YVal.isMask() && isPowerOf2_32(N))) {
9164 SDValue R = X;
9165 for (unsigned I = 1; I < N; I <<= 1) {
9166 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
9167 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
9168 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
9169 }
9170 return R;
9171 }
9172 }
9173
9174 // NOTE: If you change this expansion, please update the cost model
9175 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
9176 // Intrinsic::clmul.
9177
9178 // Strategy 4: multiplication with holes.
9179 //
9180 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
9181 // do occur, they wind up in a "hole" and are subsequently masked out of the
9182 // result.
9183 //
9184 // https://www.bearssl.org/constanttime.html#ghash-for-gcm describes this
9185 // approach.
9186
9187 // Stride S handles operands up to S·2^S bits using S² multiplies.
9188 //
9189 // * BW <= 8 uses S = 2 (holes of 1 bit)
9190 // * BW <= 24 uses S = 3 (holes of 2 bits)
9191 // * BW <= 64 uses S = 4 (holes of 3 bits)
9192 // * BW <= 160 uses S = 5 (holes of 4 bits)
9193 // * BW <= 384 uses S = 6 (holes of 5 bits)
9194 //
9195 // We distribute the BW bits over S phases:
9196 //
9197 // phase 0 keeps bits: 0, S, 2S, ...
9198 // phase 1 keeps bits: 1, S + 1, 2S + 1, ...
9199 // ...
9200 //
9201 // Each phase has up to n = ceil(BW / S) bits set, and the holes are S-1
9202 // bits wide.
9203 //
9204 // Take BW = 4, S = 2, n = 2. The worst case is a fully populated phase (all
9205 // non-hole bits are set to 1) multiplied by itself, 0b0101 * 0b0101. Each
9206 // set bit of one operand shifts a copy of the other, and we add the copies:
9207 //
9208 // col: 4 3 2 1 0
9209 // 0b0101 << 0: 0 0 1 0 1
9210 // 0b0101 << 2: 1 0 1 0 0
9211 // ----------------- +
9212 // count: 1 0 2 0 1
9213 //
9214 // Counting the number of one-bits in each column gives a triangle: the
9215 // counts climb 1, 2, ..., n and back down (here 1, 2, 1 across the data
9216 // columns). So a column holds at most n one-bits, and that maximum n is
9217 // reached in only one column: the peak. Every other column holds at most n
9218 // - 1 one-bits.
9219 //
9220 // A stack of one-bits in a column turns into carries: column 2 above really
9221 // stores the value 1 + 1 = 2 = n. A column spans S bits, its kept bit
9222 // plus S-1 hole bits, and the count is written from the kept bit upward,
9223 // so any count <= 2^S - 1 stays within the column and never interferes with
9224 // the next data bit S positions up. Every non-peak column holds at most n -
9225 // 1, so they all fit as soon as n - 1 <= 2^S - 1.
9226 //
9227 // That leaves only the peak column. Because both operands set all data
9228 // bits, the triangle peaks at the top of the word at the highest data bit
9229 // still inside BW. Here the count reaches exactly n = 2^S and overflows.
9230 // But its carry lands at bit n*S >= BW, off the top, where it (and the
9231 // whole descending half of the triangle) is truncated.
9232 //
9233 // Hence the holes suffice exactly when n = ceil(BW / S) <= 2^S, i.e. BW <=
9234 // S*2^S.
9235 //
9236 // Here we find the smallest S that satisfies this inequality.
9237 unsigned S = 1;
9238 while (S < 32 && divideCeil(BW, S) > (1u << S))
9239 ++S;
9240
9241 // The "multiplication with holes" expansion emits S*S MULs, 3*S ANDs,
9242 // S*(S-1) XORs and S-1 ORs.
9243 unsigned HolesCost = S * S + 3 * S + S * (S - 1) + (S - 1);
9244
9245 // Estimate the cost of the naive algorithm.
9246 KnownBits KnownY = DAG.computeKnownBits(Y);
9247 unsigned NaiveCost = 0;
9248 for (unsigned I = 0; I < BW; ++I) {
9249 // The iteration folds away entirely and is free.
9250 if (KnownY.Zero[I])
9251 continue;
9252
9253 // On targets with a fast bit test instruction more instructions are used
9254 // to not need a (potentially expensive) multiplication. See also below.
9255 if (hasBitTest(Y, DAG.getShiftAmountConstant(I, VT, DL))) {
9256 // AND + SETCC + SHL + SELECT + XOR.
9257 NaiveCost += 5;
9258 } else {
9259 // AND + MUL + XOR.
9260 NaiveCost += 3;
9261 }
9262 }
9263
9264 // Only use multiplication with holes when it is cheaper, else use the naive
9265 // fallback below.
9266 if (HolesCost < NaiveCost &&
9268
9269 // Set a bit every S positions, e.g. for S = 4 this is equivalent to
9270 // 0b...00010001...0001.
9271 APInt MaskVal = APInt::getSplat(BW, APInt(S, 1));
9272
9273 // Create versions of X and Y that keep only the I-th bit of each S-bit
9274 // slice.
9275 SmallVector<SDValue, 4> M(S), Xp(S), Yp(S);
9276 for (unsigned I = 0; I < S; ++I) {
9277 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9278 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9279 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9280 }
9281
9282 // Codegens these expressions (S*S multiplications), e.g. for S=4:
9283 //
9284 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9285 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9286 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9287 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9288 SDValue Res = DAG.getConstant(0, DL, VT);
9289 for (unsigned I = 0; I < S; ++I) {
9290 SDValue Zi = DAG.getConstant(0, DL, VT);
9291 for (unsigned J = 0; J < S; ++J) {
9292 unsigned K = (I + S - J) % S;
9293 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9294 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9295 }
9296
9297 // Keep only the bits belonging to this iteration, and bitwise or it all
9298 // together.
9299 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9300 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9301 }
9302 return Res;
9303 }
9304
9305 // Strategy 5: the naive fallback.
9306 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9307
9308 SDValue Res = DAG.getConstant(0, DL, VT);
9309 for (unsigned I = 0; I < BW; ++I) {
9310 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9311 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9312 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9313
9314 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9315 // multiply, use a shift-based expansion to avoid expensive MUL
9316 // instructions.
9317 SDValue Part;
9318 if (!hasBitTest(Y, ShiftAmt) &&
9321 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9322 } else {
9323 // Canonical bit test: (Y & (1 << I)) != 0
9324 SDValue Zero = DAG.getConstant(0, DL, VT);
9325 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9326 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9327 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9328 }
9329 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9330 }
9331 return Res;
9332 }
9333 case ISD::CLMULR:
9334 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9337 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9338 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9339 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9340 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9341 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9342 DAG.getShiftAmountConstant(1, VT, DL));
9343 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9344 }
9345 [[fallthrough]];
9346 case ISD::CLMULH: {
9347 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9348 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9349 // when any of these hold:
9350 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9351 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9352 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9353 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9354 // path creates CLMUL(VT) which will be expanded efficiently. The
9355 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9356 // causing a cycle.
9357 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9358 // => trunc path is preferred over the bitreverse path, as it avoids the
9359 // cost of 3 bitreverse operations.
9364 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9365 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9366 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9367 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9368 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9369 if (Opcode == ISD::CLMULH)
9370 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9371 DAG.getShiftAmountConstant(1, VT, DL));
9372 return Res;
9373 }
9374 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9375 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9376 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9377 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9378 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9379 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9380 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9381 }
9382 }
9383 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9384}
9385
9388 SDLoc dl(Node);
9389 SDValue Val = Node->getOperand(0);
9390 EVT VT = Val.getValueType();
9391 SDNodeFlags Flags = Node->getFlags();
9392
9393 SDValue IntPart = DAG.getNode(ISD::FTRUNC, dl, VT, Val, Flags);
9394 SDValue FracPart = DAG.getNode(ISD::FSUB, dl, VT, Val, IntPart, Flags);
9395
9396 SDValue FracToUse = FracPart;
9397 if (!Flags.hasNoInfs()) {
9398 SDValue Abs = DAG.getNode(ISD::FABS, dl, VT, Val, Flags);
9399 SDValue Inf =
9401 EVT SetCCVT =
9402 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9403 SDValue IsInf = DAG.getSetCC(dl, SetCCVT, Abs, Inf, ISD::SETOEQ);
9404 SDValue Zero = DAG.getConstantFP(0.0, dl, VT);
9405 FracToUse = DAG.getSelect(dl, VT, IsInf, Zero, FracPart);
9406 }
9407
9408 SDValue ResultFrac =
9409 DAG.getNode(ISD::FCOPYSIGN, dl, VT, FracToUse, Val, Flags);
9410 Results.push_back(ResultFrac);
9411 Results.push_back(IntPart);
9412 return true;
9413}
9414
9416 SDLoc DL(Node);
9417 EVT VT = Node->getValueType(0);
9418 SDValue Val = Node->getOperand(0);
9419 SDValue Msk = Node->getOperand(1);
9420 unsigned BW = VT.getScalarSizeInBits();
9421
9422 // Just scalarize if scalar PEXT is legal
9424 return DAG.UnrollVectorOp(Node);
9425
9426 // Hacker's Delight §7-4: Compress, or Generalized Extract
9427 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9428 SDValue M = Msk;
9429 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9430 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9431
9432 // Repeatedly compute which bits would shift to the right by an odd amount,
9433 // shift all such bits in parallel using a mask, and double the shift amount.
9434 for (unsigned I = 1; I < BW; I *= 2) {
9435 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9436 SDValue Mp =
9437 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9438 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9439 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9440 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9441 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9443 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9444 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9445 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9447 if (I * 2 < BW)
9448 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9449 }
9450
9451 return X;
9452}
9453
9455 SDLoc DL(Node);
9456 EVT VT = Node->getValueType(0);
9457 SDValue Val = Node->getOperand(0);
9458 SDValue Msk = Node->getOperand(1);
9459 unsigned BW = VT.getScalarSizeInBits();
9460
9461 // Just scalarize if scalar PDEP is legal
9463 return DAG.UnrollVectorOp(Node);
9464
9465 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9466 unsigned LogBW = Log2_32_Ceil(BW);
9467 SmallVector<SDValue, 8> MvArray(LogBW);
9468 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9469 SDValue Mc = Msk;
9470 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9471
9472 // First pass: compute move masks for each power of two that a bit moves by.
9473 for (unsigned S = 0; S < LogBW; ++S) {
9474 unsigned ShiftS = 1u << S;
9475 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9476 SDValue Mp =
9477 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9478 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9479 MvArray[S] = Mv;
9480 if (S + 1 < LogBW) {
9481 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9482 SDValue MvShifted = DAG.getNode(
9483 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9484 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9486 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9487 }
9488 }
9489
9490 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9491 // Each pass handles half the shift amount of the previous pass.
9492 SDValue X = Val;
9493 for (int S = (int)LogBW - 1; S >= 0; --S) {
9494 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9495 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9496 SDValue UnshiftedBits =
9497 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9498 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9499 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9501 }
9502
9503 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9504}
9505
9507 SelectionDAG &DAG) const {
9508 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9509 EVT VT = Node->getValueType(0);
9510 unsigned VTBits = VT.getScalarSizeInBits();
9511 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9512
9513 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9514 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9515 SDValue ShOpLo = Node->getOperand(0);
9516 SDValue ShOpHi = Node->getOperand(1);
9517 SDValue ShAmt = Node->getOperand(2);
9518 EVT ShAmtVT = ShAmt.getValueType();
9519 EVT ShAmtCCVT =
9520 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9521 SDLoc dl(Node);
9522
9523 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9524 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9525 // away during isel.
9526 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9527 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9528 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9529 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9530 : DAG.getConstant(0, dl, VT);
9531
9532 SDValue Tmp2, Tmp3;
9533 if (IsSHL) {
9534 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9535 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9536 } else {
9537 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9538 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9539 }
9540
9541 // If the shift amount is larger or equal than the width of a part we don't
9542 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9543 // values for large shift amounts.
9544 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9545 DAG.getConstant(VTBits, dl, ShAmtVT));
9546 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9547 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9548
9549 if (IsSHL) {
9550 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9551 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9552 } else {
9553 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9554 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9555 }
9556}
9557
9559 SelectionDAG &DAG) const {
9560 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9561 // suggested in
9562 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9563 // It uses strict_fp operations even outside a strict_fp context in order
9564 // to guarantee that the canonicalization is not optimized away by later
9565 // passes. The result chain introduced by that is intentionally ignored
9566 // since no ordering requirement is intended here.
9567 EVT VT = Node->getValueType(0);
9568 SDLoc DL(Node);
9569 SDNodeFlags Flags = Node->getFlags();
9570 Flags.setNoFPExcept(true);
9571 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9572 SDValue Mul =
9573 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9574 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9575 return Mul;
9576}
9577
9579 SelectionDAG &DAG) const {
9580 // Expand conversion from a native IEEE float type to an arbitrary FP format
9581 // returning the result as an integer using bit manipulation.
9582 EVT ResVT = Node->getValueType(0);
9583 SDLoc dl(Node);
9584
9585 SDValue FloatVal = Node->getOperand(0);
9586 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9587 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9588 const auto RoundMode =
9589 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9590 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9591
9592 // Supported destination formats.
9593 switch (Sem) {
9600 break;
9601 default:
9602 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9603 "destination format (semantics enum " +
9604 Twine(SemEnum) + ")");
9605 return SDValue();
9606 }
9607
9608 // Supported rounding modes.
9609 switch (RoundMode) {
9615 break;
9616 default:
9617 DAG.getContext()->emitError(
9618 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9619 Twine(static_cast<int>(RoundMode)) + ")");
9620 return SDValue();
9621 }
9622
9623 // Destination format parameters.
9624 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9625 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9626 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9627 const unsigned DstMant = DstPrecision - 1;
9628 // Unsigned formats spend no bit on the sign.
9629 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9630 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9631 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9632 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9633 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9634 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9635 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9636
9637 // Compute the maximum normal exponent for the destination format.
9638 const unsigned DstExpMaxNormal =
9639 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9640 : DstExpMax;
9641
9642 // For NanOnly formats the max exponent field for finite values
9643 // is DstExpMax, but the encoding with exp = DstExpMax and
9644 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9645 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9646 // avoid the NaN encoding.
9647 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9648 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9649 DstNanEnc == fltNanEncoding::AllOnes)
9650 DstMaxMantAtMaxExp = DstMantMask - 1;
9651
9652 // Source format parameters.
9653 EVT SrcVT = FloatVal.getValueType();
9654 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9655 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9656 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9657 const unsigned SrcMant = SrcPrecision - 1;
9658 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9659
9660 // Work in the source integer type. Match the destination shape so the
9661 // expansion stays vector when ResVT is a vector.
9662 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9663 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9664 EVT SetCCVT =
9665 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9666 EVT FPSetCCVT =
9667 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9668
9669 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9670 SDValue One = DAG.getConstant(1, dl, IntVT);
9671
9672 // Bitcast source float to integer to extract the sign bit.
9673 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9674 SDValue SignBit =
9675 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9676 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9677
9678 // Classify the input.
9679 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9680 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9681 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9682 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9683 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9684 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9685
9686 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9687 // source denormals automatically. The result is unspecified for Inf/NaN, but
9688 // those inputs are detected above and override the final result.
9689 EVT FrexpExpScalarVT =
9691 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9692 SDValue Frexp =
9693 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9694 SDValue FrexpFrac = Frexp.getValue(0);
9695 SDValue FrexpExp = Frexp.getValue(1);
9696
9697 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9698 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9699 DAG.getConstant(SrcMantMask, dl, IntVT));
9700
9701 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9702 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9703 DAG.getConstant(DstBias - 1, dl, IntVT));
9704
9705 // Compute rounding increment given the round bit, sticky bits, and LSB
9706 // of the truncated mantissa.
9707 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9708 SDValue LSB) -> SDValue {
9709 switch (RoundMode) {
9711 // Round up if round_bit && (sticky || lsb)
9712 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9713 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9714 }
9716 return Zero;
9718 // Round up if positive and any truncated bits are set.
9719 SDValue AnyTruncBits =
9720 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9721 SDValue HasTruncBits =
9722 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9723 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9724 SDValue DoRound =
9725 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9726 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9727 }
9729 // Round up if negative and any truncated bits are set (to -Inf).
9730 SDValue AnyTruncBits =
9731 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9732 SDValue HasTruncBits =
9733 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9734 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9735 SDValue DoRound =
9736 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9737 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9738 }
9740 return RoundBit;
9741 default:
9742 llvm_unreachable("unsupported rounding mode");
9743 }
9744 };
9745
9746 // Round mantissa from SrcMant bits to DstMant bits.
9747 SDValue TruncMant;
9748 SDValue RoundUp;
9749 if (SrcMant > DstMant) {
9750 const unsigned Shift = SrcMant - DstMant;
9751 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9752 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9753
9754 // Check bit at position Shift - 1 aka the round bit.
9755 SDValue RoundBit;
9756 if (Shift >= 1) {
9757 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9758 SDValue ShiftedMant =
9759 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9760 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9761 } else {
9762 RoundBit = Zero;
9763 }
9764
9765 // OR of all bits below the round bit to get sticky bits.
9766 SDValue StickyBits;
9767 if (Shift >= 2) {
9768 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9769 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9770 DAG.getConstant(StickyMask, dl, IntVT));
9771 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9772 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9773 } else {
9774 StickyBits = Zero;
9775 }
9776
9777 // LSB of truncated mantissa.
9778 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9779
9780 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9781 } else {
9782 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9783 SDValue MantShift =
9784 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9785 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9786 RoundUp = Zero;
9787 }
9788
9789 // Apply rounding.
9790 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9791
9792 // Handle mantissa overflow from rounding.
9793 // If rounded_mant > DstMantMask, carry into exponent.
9794 SDValue MantOverflow =
9795 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9796 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9797 // On overflow: mant = 0, exp += 1.
9798 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9799 SDValue AdjExp =
9800 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9801 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9802
9803 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9804 // sign bit to merge in.
9805 SDValue SignShifted =
9806 DstHasSign
9807 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9808 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9809 : Zero;
9810
9811 // Destination denormal conversion (when new_exp <= 0).
9812 // Shift the mantissa right by 1 - new_exp additional bits and set the
9813 // exponent field to 0.
9814 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9815 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9816
9817 SDValue DenormResult;
9818 {
9819 // denorm_shift = 1 - NewExp.
9820 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9821
9822 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9823 SDValue ImplicitOne =
9824 DAG.getNode(ISD::SHL, dl, IntVT, One,
9825 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9826 SDValue FullSrcMant =
9827 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9828
9829 // Total right shift = DenormShift + (SrcMant - DstMant).
9830 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9831 SDValue TotalShift =
9832 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9833 DAG.getSignedConstant(MantDelta, dl, IntVT));
9834
9835 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9836 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9837 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9838 SDValue ClampedShift =
9839 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9840 SDValue DenormTruncMant =
9841 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9842 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9843
9844 // Rounding for denorm path.
9845 SDValue DenormRoundUp;
9846 {
9847 // Round bit is at position TotalShift - 1 of FullSrcMant.
9848 // Clamp to at least 1 so the subtraction doesn't underflow and create
9849 // shift nodes with invalid shift amounts.
9850 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
9851 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
9852 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
9853 SDValue DenormRoundBit = DAG.getNode(
9854 ISD::AND, dl, IntVT,
9855 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
9856
9857 // Sticky: all bits below round bit.
9858 // sticky_mask = (1 << RoundBitPos) - 1
9859 SDValue StickyMask = DAG.getNode(
9860 ISD::SUB, dl, IntVT,
9861 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
9862 SDValue DenormStickyBits =
9863 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
9864 SDValue HasSticky = DAG.getNode(
9865 ISD::ZERO_EXTEND, dl, IntVT,
9866 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
9867
9868 SDValue DenormLSB =
9869 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
9870
9871 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
9872
9873 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
9874 SDValue ShiftGEOne =
9875 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
9876 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
9877 }
9878
9879 SDValue DenormRoundedMant =
9880 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
9881
9882 // If rounding caused overflow into the normal range, then we get the
9883 // smallest normal number.
9884 SDValue DenormMantOF =
9885 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
9886 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9887 SDValue DenormFinalMant =
9888 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
9889 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
9890
9891 // Assemble: sign | (exp << DstMant) | mant
9892 SDValue DenormExpShifted =
9893 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
9894 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9895 DenormResult = DAG.getNode(
9896 ISD::OR, dl, IntVT,
9897 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
9898 DenormFinalMant);
9899 }
9900
9901 // Exponent overflow detection.
9902 SDValue ExpOF =
9903 DAG.getSetCC(dl, SetCCVT, AdjExp,
9904 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
9905
9906 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
9907 // a value that exceeds the max allowed mantissa at that exponent.
9908 SDValue ExpAtMax =
9909 DAG.getSetCC(dl, SetCCVT, AdjExp,
9910 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
9911 SDValue MantExceedsMax =
9912 DAG.getSetCC(dl, SetCCVT, AdjMant,
9913 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
9914 SDValue ExpMantOF =
9915 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
9916 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
9917
9918 // Build overflow result.
9920
9921 if (Saturate) {
9922 // Clamp to max finite value:
9923 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
9924 uint64_t MaxFinite =
9925 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9926 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9927 DAG.getConstant(MaxFinite, dl, IntVT));
9928 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9929 // Produce infinity.
9930 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9931 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9932 DAG.getConstant(InfBits, dl, IntVT));
9933 } else {
9934 // Emit poison if no Inf in format and not saturating.
9935 OverflowResult = DAG.getPOISON(IntVT);
9936 }
9937
9938 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
9939 SDValue NormExpShifted =
9940 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
9941 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9942 SDValue NormResult = DAG.getNode(
9943 ISD::OR, dl, IntVT,
9944 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
9945
9946 // Build special-value results.
9947 SDValue NaNResult;
9948 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9949 // Produce canonical NaN.
9950 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
9951 NaNResult =
9952 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
9953 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9954 DstNanEnc == fltNanEncoding::AllOnes) {
9955 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
9956 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
9957 dl, IntVT);
9958 } else {
9959 // NaN -> poison for finite only values.
9960 NaNResult = DAG.getPOISON(IntVT);
9961 }
9962
9963 // Inf handling.
9964 SDValue InfResult;
9965 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9966 // Produce signed infinity.
9967 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9968 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9969 DAG.getConstant(InfBits, dl, IntVT));
9970 } else if (Saturate) {
9971 // Inf saturates to max finite.
9972 uint64_t MaxFinite =
9973 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9974 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9975 DAG.getConstant(MaxFinite, dl, IntVT));
9976 } else {
9977 // No Inf and not saturating -> poison.
9978 InfResult = DAG.getPOISON(IntVT);
9979 }
9980
9981 SDValue ZeroResult = SignShifted;
9982
9983 // Final selection in an order: NaN takes priority, then Inf, then Zero.
9984 SDValue FiniteResult =
9985 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
9986 FiniteResult =
9987 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
9988
9989 SDValue Result = FiniteResult;
9990 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
9991 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
9992
9993 // Negative values are unrepresentable in an unsigned format: clamp to zero
9994 // when saturating, poison otherwise so no select is needed. -0.0 is handled
9995 // by IsZero above. Run before the NaN case so a negative NaN still yields
9996 // NaN.
9997 if (!DstHasSign && Saturate) {
9998 SDValue IsNegative =
9999 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
10000 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
10001 }
10002
10003 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10004
10005 // Truncate to destination integer type.
10006 return DAG.getZExtOrTrunc(Result, dl, ResVT);
10007}
10008
10009SDValue
10011 SelectionDAG &DAG) const {
10012 SDLoc dl(Node);
10013 EVT DstVT = Node->getValueType(0);
10014 EVT DstScalarVT = DstVT.getScalarType();
10015
10016 SDValue IntVal = Node->getOperand(0);
10017 const uint64_t SemEnum = Node->getConstantOperandVal(1);
10018 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
10019
10020 // Supported source formats.
10021 switch (Sem) {
10028 break;
10029 default:
10030 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
10031 "source format (semantics enum " +
10032 Twine(SemEnum) + ")");
10033 return SDValue();
10034 }
10035
10036 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
10037 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
10038 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
10039 const unsigned SrcMant = SrcPrecision - 1;
10040 // Unsigned formats spend no bit on the sign.
10041 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
10042 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
10043 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
10044 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
10045
10046 // Destination format parameters.
10047 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
10048 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
10049 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
10050 const unsigned DstExpBits = DstBits - DstMant - 1;
10051 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
10052 const int DstBias = 1 - DstMinExp;
10053 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
10054
10055 // Work in an integer type matching the destination float width.
10056 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
10057 EVT IntVT = IntScalarVT;
10058 if (DstVT.isVector()) {
10059 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
10060 DstVT.getVectorElementCount());
10061 } else if (!isTypeLegal(IntScalarVT)) {
10062 // Avoid generating illegal type as there is no other places that'll
10063 // legalize it. Vector types don't have this problem because they
10064 // are subject to LegalizeVectorOps and another type legalization phase
10065 // will follow.
10066 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
10067 // We only know how to handle situations where the legal type is wider.
10068 DAG.getContext()->emitError(
10069 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
10070 "legalization is not supported");
10071 return SDValue();
10072 }
10073 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
10074 }
10075
10076 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
10077
10078 EVT SetCCVT =
10079 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
10080
10081 SDValue Zero = DAG.getConstant(0, dl, IntVT);
10082 SDValue One = DAG.getConstant(1, dl, IntVT);
10083
10084 // Extract bit fields.
10085 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
10086 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
10087
10088 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
10089 DAG.getConstant(MantMask, dl, IntVT));
10090
10091 SDValue ExpField =
10092 DAG.getNode(ISD::AND, dl, IntVT,
10093 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10094 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
10095 DAG.getConstant(ExpMask, dl, IntVT));
10096
10097 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
10098 // exponent.
10099 SDValue SignShifted =
10100 SrcHasSign
10101 ? DAG.getNode(
10102 ISD::SHL, dl, IntVT,
10103 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10104 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
10105 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
10106 : Zero;
10107
10108 // Classify the input.
10109 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
10110 SDValue IsExpAllOnes =
10111 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
10112 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
10113 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
10114 SDValue IsMantNonZero =
10115 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
10116
10117 SDValue IsNaN;
10118 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
10119 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10120 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
10121 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
10122 } else {
10124 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
10125 SDValue IsMantAllOnes =
10126 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
10127 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
10128 }
10129
10130 SDValue IsInf;
10131 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
10132 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
10133 else
10134 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10135
10136 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
10137 SDValue IsDenorm =
10138 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
10139
10140 // Normal value conversion.
10141 const int BiasAdjust = DstBias - SrcBias;
10142 SDValue NormDstExp = DAG.getNode(
10143 ISD::ADD, dl, IntVT, ExpField,
10144 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
10145 IntVT));
10146
10147 SDValue NormDstMant;
10148 if (DstMant > SrcMant) {
10149 SDValue NormDstMantShift =
10150 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
10151 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
10152 } else {
10153 NormDstMant = MantField;
10154 }
10155
10156 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
10157 SDValue NormExpShifted =
10158 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
10159 SDValue NormResult =
10160 DAG.getNode(ISD::OR, dl, IntVT,
10161 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
10162 NormDstMant);
10163
10164 // With identical exponent biases, denormal values remain denormal and the
10165 // normal conversion's mantissa shift is sufficient.
10166 SDValue DenormResult = NormResult;
10167 if (BiasAdjust != 0) {
10168 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
10169 SDValue LeadingZeros =
10170 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
10171
10172 const int DenormExpConst =
10173 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
10174 SDValue DenormDstExp = DAG.getNode(
10175 ISD::SUB, dl, IntVT,
10176 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
10177 LeadingZeros);
10178
10179 SDValue MantMSB =
10180 DAG.getNode(ISD::SUB, dl, IntVT,
10181 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
10182
10183 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
10184 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
10185
10186 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
10187 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
10188 DAG.getConstant(ShiftSub, dl, IntVT));
10189
10190 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
10191
10192 SDValue DenormExpShifted =
10193 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
10194 DenormResult = DAG.getNode(
10195 ISD::OR, dl, IntVT,
10196 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10197 DenormDstMant);
10198 }
10199
10200 SDValue FiniteResult =
10201 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
10202
10203 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10204 SDValue NaNResult =
10205 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
10206
10207 SDValue InfResult =
10208 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10209 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
10210
10211 // A source format may have a larger finite exponent range despite having
10212 // fewer bits, as with Float8E5M3FNU converted to half. Its overflowing finite
10213 // values become infinity. The NaN selection below still takes precedence.
10214 if (APFloat::semanticsMaxExponent(SrcSem) >
10216 SDValue IsOverflow =
10217 DAG.getSetCC(dl, SetCCVT, NormDstExp,
10218 DAG.getConstant(DstExpAllOnes, dl, IntVT), ISD::SETUGE);
10219 FiniteResult =
10220 DAG.getSelect(dl, IntVT, IsOverflow, InfResult, FiniteResult);
10221 }
10222
10223 SDValue ZeroResult = SignShifted;
10224
10225 SDValue Result = FiniteResult;
10226 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10227 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10228 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10229
10230 if (!DstVT.bitsEq(IntVT)) {
10231 // Store to stack before loading it back.
10232 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
10233 // IntScalarVT is the original type that has the same width as DstVT.
10234 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
10235 SDValue StackPtr =
10236 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
10237 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10239 MachinePointerInfo PtrInfo =
10240 MachinePointerInfo::getFixedStack(MF, FrameIndex);
10241 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
10242 PtrInfo, IntScalarVT, Alignment);
10243
10244 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
10245 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
10246 }
10247
10248 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
10249}
10250
10252 SelectionDAG &DAG) const {
10253 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10254 SDValue Src = Node->getOperand(OpNo);
10255 EVT SrcVT = Src.getValueType();
10256 EVT DstVT = Node->getValueType(0);
10257 SDLoc dl(SDValue(Node, 0));
10258
10259 // FIXME: Only f32 to i64 conversions are supported.
10260 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
10261 return false;
10262
10263 if (Node->isStrictFPOpcode())
10264 // When a NaN is converted to an integer a trap is allowed. We can't
10265 // use this expansion here because it would eliminate that trap. Other
10266 // traps are also allowed and cannot be eliminated. See
10267 // IEEE 754-2008 sec 5.8.
10268 return false;
10269
10270 // Expand f32 -> i64 conversion
10271 // This algorithm comes from compiler-rt's implementation of fixsfdi:
10272 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
10273 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
10274 EVT IntVT = SrcVT.changeTypeToInteger();
10275 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
10276
10277 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
10278 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
10279 SDValue Bias = DAG.getConstant(127, dl, IntVT);
10280 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
10281 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
10282 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
10283
10284 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
10285
10286 SDValue ExponentBits = DAG.getNode(
10287 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
10288 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
10289 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
10290
10291 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
10292 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
10293 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
10294 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10295
10296 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10297 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10298 DAG.getConstant(0x00800000, dl, IntVT));
10299
10300 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10301
10302 R = DAG.getSelectCC(
10303 dl, Exponent, ExponentLoBit,
10304 DAG.getNode(ISD::SHL, dl, DstVT, R,
10305 DAG.getZExtOrTrunc(
10306 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10307 dl, IntShVT)),
10308 DAG.getNode(ISD::SRL, dl, DstVT, R,
10309 DAG.getZExtOrTrunc(
10310 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10311 dl, IntShVT)),
10312 ISD::SETGT);
10313
10314 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10315 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10316
10317 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10318 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10319 return true;
10320}
10321
10323 SDValue &Chain,
10324 SelectionDAG &DAG) const {
10325 SDLoc dl(SDValue(Node, 0));
10326 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10327 SDValue Src = Node->getOperand(OpNo);
10328
10329 EVT SrcVT = Src.getValueType();
10330 EVT DstVT = Node->getValueType(0);
10331 EVT SetCCVT =
10332 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10333 EVT DstSetCCVT =
10334 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10335
10336 // Only expand vector types if we have the appropriate vector bit operations.
10337 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10339 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10341 return false;
10342
10343 // If the maximum float value is smaller then the signed integer range,
10344 // the destination signmask can't be represented by the float, so we can
10345 // just use FP_TO_SINT directly.
10346 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10347 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10348 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10350 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10351 if (Node->isStrictFPOpcode()) {
10352 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10353 { Node->getOperand(0), Src });
10354 Chain = Result.getValue(1);
10355 } else
10356 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10357 return true;
10358 }
10359
10360 // Don't expand it if there isn't cheap fsub instruction.
10362 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10363 return false;
10364
10365 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10366 SDValue Sel;
10367
10368 if (Node->isStrictFPOpcode()) {
10369 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10370 Node->getOperand(0), /*IsSignaling*/ true);
10371 Chain = Sel.getValue(1);
10372 } else {
10373 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10374 }
10375
10376 bool Strict = Node->isStrictFPOpcode() ||
10377 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10378
10379 if (Strict) {
10380 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10381 // signmask then offset (the result of which should be fully representable).
10382 // Sel = Src < 0x8000000000000000
10383 // FltOfs = select Sel, 0, 0x8000000000000000
10384 // IntOfs = select Sel, 0, 0x8000000000000000
10385 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10386
10387 // TODO: Should any fast-math-flags be set for the FSUB?
10388 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10389 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10390 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10391 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10392 DAG.getConstant(0, dl, DstVT),
10393 DAG.getConstant(SignMask, dl, DstVT));
10394 SDValue SInt;
10395 if (Node->isStrictFPOpcode()) {
10396 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10397 { Chain, Src, FltOfs });
10398 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10399 { Val.getValue(1), Val });
10400 Chain = SInt.getValue(1);
10401 } else {
10402 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10403 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10404 }
10405 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10406 } else {
10407 // Expand based on maximum range of FP_TO_SINT:
10408 // True = fp_to_sint(Src)
10409 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10410 // Result = select (Src < 0x8000000000000000), True, False
10411
10412 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10413 // TODO: Should any fast-math-flags be set for the FSUB?
10414 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10415 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10416 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10417 DAG.getConstant(SignMask, dl, DstVT));
10418 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10419 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10420 }
10421 return true;
10422}
10423
10425 SDValue &Chain, SelectionDAG &DAG) const {
10426 // This transform is not correct for converting 0 when rounding mode is set
10427 // to round toward negative infinity which will produce -0.0. So disable
10428 // under strictfp.
10429 if (Node->isStrictFPOpcode())
10430 return false;
10431
10432 SDValue Src = Node->getOperand(0);
10433 EVT SrcVT = Src.getValueType();
10434 EVT DstVT = Node->getValueType(0);
10435
10436 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10437 // it.
10438 if (Node->getFlags().hasNonNeg() &&
10440 Result =
10441 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10442 return true;
10443 }
10444
10445 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10446 return false;
10447
10448 // Only expand vector types if we have the appropriate vector bit
10449 // operations.
10450 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10455 return false;
10456
10457 SDLoc dl(SDValue(Node, 0));
10458
10459 // Implementation of unsigned i64 to f64 following the algorithm in
10460 // __floatundidf in compiler_rt. This implementation performs rounding
10461 // correctly in all rounding modes with the exception of converting 0
10462 // when rounding toward negative infinity. In that case the fsub will
10463 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10464 // incorrect.
10465 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10466 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10467 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10468 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10469 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10470 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10471
10472 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10473 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10474 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10475 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10476 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10477 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10478 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10479 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10480 return true;
10481}
10482
10483SDValue
10485 SelectionDAG &DAG) const {
10486 unsigned Opcode = Node->getOpcode();
10487 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10488 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10489 "Wrong opcode");
10490
10491 if (Node->getFlags().hasNoNaNs()) {
10492 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10493 EVT VT = Node->getValueType(0);
10494 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10496 VT.isVector())
10497 return SDValue();
10498 SDValue Op1 = Node->getOperand(0);
10499 SDValue Op2 = Node->getOperand(1);
10500 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10501 Node->getFlags());
10502 }
10503
10504 return SDValue();
10505}
10506
10508 SelectionDAG &DAG) const {
10509 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10510 return Expanded;
10511
10512 EVT VT = Node->getValueType(0);
10513 if (VT.isScalableVector())
10515 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10516
10517 SDLoc dl(Node);
10518 unsigned NewOp =
10520
10521 if (isOperationLegalOrCustom(NewOp, VT)) {
10522 SDValue Quiet0 = Node->getOperand(0);
10523 SDValue Quiet1 = Node->getOperand(1);
10524
10525 if (!Node->getFlags().hasNoNaNs()) {
10526 // Insert canonicalizes if it's possible we need to quiet to get correct
10527 // sNaN behavior.
10528 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10529 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10530 Node->getFlags());
10531 }
10532 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10533 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10534 Node->getFlags());
10535 }
10536 }
10537
10538 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10539 }
10540
10541 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10542 // instead if there are no NaNs.
10543 if (Node->getFlags().hasNoNaNs() ||
10544 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10545 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10546 unsigned IEEE2018Op =
10547 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10548 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10549 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10550 Node->getOperand(1), Node->getFlags());
10551 }
10552
10554 return SelCC;
10555
10556 return SDValue();
10557}
10558
10560 const TargetLowering &TLI,
10561 const SDLoc &DL, SDValue Val,
10562 FPClassTest FPClass) {
10563 EVT VT = Val.getValueType();
10564 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10565 EVT IntVT = VT.changeTypeToInteger();
10566 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10567 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10568 if (!TLI.isTypeLegal(IntVT) &&
10570 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10571 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10572 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10573}
10574
10576 SelectionDAG &DAG) const {
10577 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10578 return Expanded;
10579
10580 SDLoc DL(N);
10581 SDValue LHS = N->getOperand(0);
10582 SDValue RHS = N->getOperand(1);
10583 unsigned Opc = N->getOpcode();
10584 EVT VT = N->getValueType(0);
10585 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10586 bool IsMax = Opc == ISD::FMAXIMUM;
10587 SDNodeFlags Flags = N->getFlags();
10588
10589 // First, implement comparison not propagating NaN. If no native fmin or fmax
10590 // available, use plain select with setcc instead.
10592 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10593 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10594
10595 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10596 // signed zero behavior.
10597 bool MinMaxMustRespectOrderedZero = false;
10598
10599 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10600 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10601 MinMaxMustRespectOrderedZero = true;
10602 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10603 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10604 } else {
10606 return DAG.UnrollVectorOp(N);
10607
10608 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10609 SDValue Compare =
10610 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10611 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10612 }
10613
10614 // Propagate any NaN of both operands
10615 if (!N->getFlags().hasNoNaNs() &&
10616 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10617 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10619 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10620 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10621 }
10622
10623 // fminimum/fmaximum requires -0.0 less than +0.0
10624 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10625 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10626 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10628 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10629 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10630 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10631 }
10632
10633 return MinMax;
10634}
10635
10637 SelectionDAG &DAG) const {
10638 SDLoc DL(Node);
10639 SDValue LHS = Node->getOperand(0);
10640 SDValue RHS = Node->getOperand(1);
10641 unsigned Opc = Node->getOpcode();
10642 EVT VT = Node->getValueType(0);
10643 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10644 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10645 SDNodeFlags Flags = Node->getFlags();
10646
10647 unsigned NewOp =
10649
10650 if (isOperationLegalOrCustom(NewOp, VT)) {
10651 if (!Flags.hasNoNaNs()) {
10652 // Insert canonicalizes if it's possible we need to quiet to get correct
10653 // sNaN behavior.
10654 if (!DAG.isKnownNeverSNaN(LHS)) {
10655 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10656 }
10657 if (!DAG.isKnownNeverSNaN(RHS)) {
10658 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10659 }
10660 }
10661
10662 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10663 }
10664
10665 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10666 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10667 if (Flags.hasNoNaNs() ||
10668 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10669 unsigned IEEE2019Op =
10671 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10672 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10673 }
10674
10675 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10676 // either one for +0.0 vs -0.0.
10677 if ((Flags.hasNoNaNs() ||
10678 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10679 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10680 DAG.isKnownNeverLogicalZero(RHS))) {
10681 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10682 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10683 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10684 }
10685
10686 if (VT.isVector() &&
10689 return DAG.UnrollVectorOp(Node);
10690
10691 // If only one operand is NaN, override it with another operand.
10692 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10693 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10694 }
10695 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10696 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10697 }
10698
10699 // Always prefer RHS if equal.
10700 SDValue MinMax =
10701 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10702
10703 // TODO: We need quiet sNaN if strictfp.
10704
10705 // Fixup signed zero behavior.
10706 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10707 DAG.isKnownNeverLogicalZero(RHS)) {
10708 return MinMax;
10709 }
10710 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10711 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10713 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10714 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10715 // we preferred RHS when generate MinMax, if the operands are equal.
10716 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10717 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10718}
10719
10720/// Returns a true value if if this FPClassTest can be performed with an ordered
10721/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10722/// std::nullopt if it cannot be performed as a compare with 0.
10723static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10724 const fltSemantics &Semantics,
10725 const MachineFunction &MF) {
10726 FPClassTest OrderedMask = Test & ~fcNan;
10727 FPClassTest NanTest = Test & fcNan;
10728 bool IsOrdered = NanTest == fcNone;
10729 bool IsUnordered = NanTest == fcNan;
10730
10731 // Skip cases that are testing for only a qnan or snan.
10732 if (!IsOrdered && !IsUnordered)
10733 return std::nullopt;
10734
10735 if (OrderedMask == fcZero &&
10736 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10737 return IsOrdered;
10738 if (OrderedMask == (fcZero | fcSubnormal) &&
10739 MF.getDenormalMode(Semantics).inputsAreZero())
10740 return IsOrdered;
10741 return std::nullopt;
10742}
10743
10745 const FPClassTest OrigTestMask,
10746 SDNodeFlags Flags, const SDLoc &DL,
10747 SelectionDAG &DAG) const {
10748 EVT OperandVT = Op.getValueType();
10749 assert(OperandVT.isFloatingPoint());
10750 FPClassTest Test = OrigTestMask;
10751
10752 // Degenerated cases.
10753 if (Test == fcNone)
10754 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10755 if (Test == fcAllFlags)
10756 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10757
10758 // PPC double double is a pair of doubles, of which the higher part determines
10759 // the value class.
10760 if (OperandVT == MVT::ppcf128) {
10761 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10762 DAG.getConstant(1, DL, MVT::i32));
10763 OperandVT = MVT::f64;
10764 }
10765
10766 // Floating-point type properties.
10767 EVT ScalarFloatVT = OperandVT.getScalarType();
10768 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10769 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10770 bool IsF80 = (ScalarFloatVT == MVT::f80);
10771
10772 // Some checks can be implemented using float comparisons, if floating point
10773 // exceptions are ignored.
10774 if (Flags.hasNoFPExcept() &&
10776 FPClassTest FPTestMask = Test;
10777 bool IsInvertedFP = false;
10778
10779 if (FPClassTest InvertedFPCheck =
10780 invertFPClassTestIfSimpler(FPTestMask, true)) {
10781 FPTestMask = InvertedFPCheck;
10782 IsInvertedFP = true;
10783 }
10784
10785 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10786 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10787
10788 // See if we can fold an | fcNan into an unordered compare.
10789 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10790
10791 // Can't fold the ordered check if we're only testing for snan or qnan
10792 // individually.
10793 if ((FPTestMask & fcNan) != fcNan)
10794 OrderedFPTestMask = FPTestMask;
10795
10796 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10797
10798 if (std::optional<bool> IsCmp0 =
10799 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10800 IsCmp0 && (isCondCodeLegalOrCustom(
10801 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10802 OperandVT.getScalarType().getSimpleVT()))) {
10803
10804 // If denormals could be implicitly treated as 0, this is not equivalent
10805 // to a compare with 0 since it will also be true for denormals.
10806 return DAG.getSetCC(DL, ResultVT, Op,
10807 DAG.getConstantFP(0.0, DL, OperandVT),
10808 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10809 }
10810
10811 if (FPTestMask == fcNan &&
10813 OperandVT.getScalarType().getSimpleVT()))
10814 return DAG.getSetCC(DL, ResultVT, Op, Op,
10815 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10816
10817 bool IsOrderedInf = FPTestMask == fcInf;
10818 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10819 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10820 : UnorderedCmpOpcode,
10821 OperandVT.getScalarType().getSimpleVT()) &&
10824 (OperandVT.isVector() &&
10826 // isinf(x) --> fabs(x) == inf
10827 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10828 SDValue Inf =
10829 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10830 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10831 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10832 }
10833
10834 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10835 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10836 : UnorderedCmpOpcode,
10837 OperandVT.getSimpleVT())) {
10838 // isposinf(x) --> x == inf
10839 // isneginf(x) --> x == -inf
10840 // isposinf(x) || nan --> x u== inf
10841 // isneginf(x) || nan --> x u== -inf
10842
10843 SDValue Inf = DAG.getConstantFP(
10844 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
10845 OperandVT);
10846 return DAG.getSetCC(DL, ResultVT, Op, Inf,
10847 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
10848 }
10849
10850 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
10851 // TODO: Could handle ordered case, but it produces worse code for
10852 // x86. Maybe handle ordered if fabs is free?
10853
10854 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10855 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
10856
10857 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
10858 OperandVT.getScalarType().getSimpleVT())) {
10859 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
10860
10861 // TODO: Maybe only makes sense if fabs is free. Integer test of
10862 // exponent bits seems better for x86.
10863 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10864 SDValue SmallestNormal = DAG.getConstantFP(
10865 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10866 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
10867 IsOrdered ? OrderedOp : UnorderedOp);
10868 }
10869 }
10870
10871 if (FPTestMask == fcNormal) {
10872 // TODO: Handle unordered
10873 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10874 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
10875
10876 if (isCondCodeLegalOrCustom(IsFiniteOp,
10877 OperandVT.getScalarType().getSimpleVT()) &&
10878 isCondCodeLegalOrCustom(IsNormalOp,
10879 OperandVT.getScalarType().getSimpleVT()) &&
10880 isFAbsFree(OperandVT)) {
10881 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
10882 SDValue Inf =
10883 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10884 SDValue SmallestNormal = DAG.getConstantFP(
10885 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10886
10887 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10888 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
10889 SDValue IsNormal =
10890 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
10891 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
10892 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
10893 }
10894 }
10895 }
10896
10897 // Some checks may be represented as inversion of simpler check, for example
10898 // "inf|normal|subnormal|zero" => !"nan".
10899 bool IsInverted = false;
10900
10901 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
10902 Test = InvertedCheck;
10903 IsInverted = true;
10904 }
10905
10906 // In the general case use integer operations.
10907 unsigned BitSize = OperandVT.getScalarSizeInBits();
10908 EVT IntVT = OperandVT.changeElementType(
10909 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
10910 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
10911
10912 // Various masks.
10913 APInt SignBit = APInt::getSignMask(BitSize);
10914 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
10915 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
10916 const unsigned ExplicitIntBitInF80 = 63;
10917 APInt ExpMask = Inf;
10918 if (IsF80)
10919 ExpMask.clearBit(ExplicitIntBitInF80);
10920 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
10921 APInt QNaNBitMask =
10922 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
10923 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
10924
10925 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
10926 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
10927 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
10928 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
10929 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
10930 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
10931
10932 SDValue Res;
10933 const auto appendResult = [&](SDValue PartialRes) {
10934 if (PartialRes) {
10935 if (Res)
10936 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
10937 else
10938 Res = PartialRes;
10939 }
10940 };
10941
10942 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
10943 const auto getIntBitIsSet = [&]() -> SDValue {
10944 if (!IntBitIsSetV) {
10945 APInt IntBitMask(BitSize, 0);
10946 IntBitMask.setBit(ExplicitIntBitInF80);
10947 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
10948 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
10949 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
10950 }
10951 return IntBitIsSetV;
10952 };
10953
10954 // Split the value into sign bit and absolute value.
10955 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
10956 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
10957 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
10958
10959 // Tests that involve more than one class should be processed first.
10960 SDValue PartialRes;
10961
10962 if (IsF80)
10963 ; // Detect finite numbers of f80 by checking individual classes because
10964 // they have different settings of the explicit integer bit.
10965 else if ((Test & fcFinite) == fcFinite) {
10966 // finite(V) ==> (a << 1) < (inf << 1)
10967 //
10968 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
10969 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
10970
10972 "finite check requires IEEE-like FP");
10973
10974 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
10975 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
10976 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
10977
10978 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
10979 Test &= ~fcFinite;
10980 } else if ((Test & fcFinite) == fcPosFinite) {
10981 // finite(V) && V > 0 ==> V < exp_mask
10982 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
10983 Test &= ~fcPosFinite;
10984 } else if ((Test & fcFinite) == fcNegFinite) {
10985 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
10986 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
10987 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10988 Test &= ~fcNegFinite;
10989 }
10990 appendResult(PartialRes);
10991
10992 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
10993 // fcZero | fcSubnormal => test all exponent bits are 0
10994 // TODO: Handle sign bit specific cases
10995 if (PartialCheck == (fcZero | fcSubnormal)) {
10996 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
10997 SDValue ExpIsZero =
10998 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10999 appendResult(ExpIsZero);
11000 Test &= ~PartialCheck & fcAllFlags;
11001 }
11002 }
11003
11004 // Check for individual classes.
11005
11006 if (unsigned PartialCheck = Test & fcZero) {
11007 if (PartialCheck == fcPosZero)
11008 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
11009 else if (PartialCheck == fcZero)
11010 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
11011 else // ISD::fcNegZero
11012 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
11013 appendResult(PartialRes);
11014 }
11015
11016 if (unsigned PartialCheck = Test & fcSubnormal) {
11017 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
11018 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
11019 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
11020 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
11021 SDValue VMinusOneV =
11022 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
11023 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
11024 if (PartialCheck == fcNegSubnormal)
11025 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11026 appendResult(PartialRes);
11027 }
11028
11029 if (unsigned PartialCheck = Test & fcInf) {
11030 if (PartialCheck == fcPosInf)
11031 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
11032 else if (PartialCheck == fcInf)
11033 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
11034 else { // ISD::fcNegInf
11035 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
11036 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
11037 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
11038 }
11039 appendResult(PartialRes);
11040 }
11041
11042 if (unsigned PartialCheck = Test & fcNan) {
11043 APInt InfWithQnanBit = Inf | QNaNBitMask;
11044 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
11045 if (PartialCheck == fcNan) {
11046 // isnan(V) ==> abs(V) > int(inf)
11047 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11048 if (IsF80) {
11049 // Recognize unsupported values as NaNs for compatibility with glibc.
11050 // In them (exp(V)==0) == int_bit.
11051 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
11052 SDValue ExpIsZero =
11053 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11054 SDValue IsPseudo =
11055 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
11056 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
11057 }
11058 } else if (PartialCheck == fcQNan) {
11059 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
11060 PartialRes =
11061 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
11062 } else { // ISD::fcSNan
11063 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
11064 // abs(V) < (unsigned(Inf) | quiet_bit)
11065 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11066 SDValue IsNotQnan =
11067 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
11068 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
11069 }
11070 appendResult(PartialRes);
11071 }
11072
11073 if (unsigned PartialCheck = Test & fcNormal) {
11074 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
11075 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
11076 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
11077 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
11078 APInt ExpLimit = ExpMask - ExpLSB;
11079 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
11080 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
11081 if (PartialCheck == fcNegNormal)
11082 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11083 else if (PartialCheck == fcPosNormal) {
11084 SDValue PosSignV =
11085 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
11086 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
11087 }
11088 if (IsF80)
11089 PartialRes =
11090 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
11091 appendResult(PartialRes);
11092 }
11093
11094 if (!Res)
11095 return DAG.getConstant(IsInverted, DL, ResultVT);
11096 if (IsInverted)
11097 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
11098 return Res;
11099}
11100
11101// Only expand vector types if we have the appropriate vector bit operations.
11102static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
11103 assert(VT.isVector() && "Expected vector type");
11104 unsigned Len = VT.getScalarSizeInBits();
11105 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
11108 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
11110}
11111
11113 SDLoc dl(Node);
11114 EVT VT = Node->getValueType(0);
11115 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11116 SDValue Op = Node->getOperand(0);
11117 unsigned Len = VT.getScalarSizeInBits();
11118
11119 // Compute effective bit width from known bits, allowing us to shift the
11120 // active bits down if necessary to fit into smaller specialized expansions.
11122 unsigned LZ = Known.countMinLeadingZeros();
11123 unsigned TZ = Known.countMinTrailingZeros();
11124 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
11125
11126 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
11127 unsigned EffectiveLen = Len;
11128 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
11129 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
11130
11131 assert(VT.isInteger() && "CTPOP not implemented for this type.");
11132
11133 // TODO: Add support for irregular type lengths.
11134 if (!(Len <= 128 && Len % 8 == 0))
11135 return SDValue();
11136
11137 // Only expand vector types if we have the appropriate vector bit operations.
11138 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
11139 return SDValue();
11140
11141 // If the active bits are not at the low end, shift them down
11142 if (EffectiveLen < Len && TZ > 0) {
11143 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
11144 DAG.getShiftAmountConstant(TZ, VT, dl));
11145 }
11146
11147 // This is the "best" algorithm from
11148 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
11149 SDValue Mask55 =
11150 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
11151 SDValue Mask33 =
11152 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
11153 SDValue Mask0F =
11154 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
11155
11156 // v = v - ((v >> 1) & 0x55555555...)
11157 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
11158 DAG.getNode(ISD::AND, dl, VT,
11159 DAG.getNode(ISD::SRL, dl, VT, Op,
11160 DAG.getConstant(1, dl, ShVT)),
11161 Mask55));
11162 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
11163 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
11164 DAG.getNode(ISD::AND, dl, VT,
11165 DAG.getNode(ISD::SRL, dl, VT, Op,
11166 DAG.getConstant(2, dl, ShVT)),
11167 Mask33));
11168 // v = (v + (v >> 4)) & 0x0F0F0F0F...
11169 Op = DAG.getNode(ISD::AND, dl, VT,
11170 DAG.getNode(ISD::ADD, dl, VT, Op,
11171 DAG.getNode(ISD::SRL, dl, VT, Op,
11172 DAG.getConstant(4, dl, ShVT))),
11173 Mask0F);
11174
11175 if (EffectiveLen <= 8)
11176 return Op;
11177
11178 // Avoid the multiply if we only have 2 bytes to add.
11179 // TODO: Only doing this for scalars because vectors weren't as obviously
11180 // improved.
11181 if (EffectiveLen == 16 && !VT.isVector()) {
11182 // v = (v + (v >> 8)) & 0x00FF;
11183 return DAG.getNode(ISD::AND, dl, VT,
11184 DAG.getNode(ISD::ADD, dl, VT, Op,
11185 DAG.getNode(ISD::SRL, dl, VT, Op,
11186 DAG.getConstant(8, dl, ShVT))),
11187 DAG.getConstant(0xFF, dl, VT));
11188 }
11189
11190 // v = (v * 0x01010101...) >> (Len - 8)
11191 SDValue V;
11194 SDValue Mask01 =
11195 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
11196 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
11197 } else {
11198 V = Op;
11199 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
11200 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
11201 V = DAG.getNode(ISD::ADD, dl, VT, V,
11202 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
11203 }
11204 }
11205 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
11206}
11207
11209 SDLoc dl(Node);
11210 EVT VT = Node->getValueType(0);
11211 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11212 SDValue Op = Node->getOperand(0);
11213 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11214
11215 // If the non-ZERO_POISON version is supported we can use that instead.
11216 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
11218 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
11219
11220 // If the ZERO_POISON version is supported use that and handle the zero case.
11222 EVT SetCCVT =
11223 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11224 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
11225 SDValue Zero = DAG.getConstant(0, dl, VT);
11226 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11227 return DAG.getSelect(dl, VT, SrcIsZero,
11228 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
11229 }
11230
11231 // Only expand vector types if we have the appropriate vector bit operations.
11232 // This includes the operations needed to expand CTPOP if it isn't supported.
11233 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11235 !canExpandVectorCTPOP(*this, VT)) ||
11238 return SDValue();
11239
11240 // for now, we do this:
11241 // x = x | (x >> 1);
11242 // x = x | (x >> 2);
11243 // ...
11244 // x = x | (x >>16);
11245 // x = x | (x >>32); // for 64-bit input
11246 // return popcount(~x);
11247 //
11248 // Ref: "Hacker's Delight" by Henry Warren
11249 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
11250 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
11251 Op = DAG.getNode(ISD::OR, dl, VT, Op,
11252 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
11253 }
11254 Op = DAG.getNOT(dl, Op, VT);
11255 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
11256}
11257
11259 SDLoc dl(Node);
11260 EVT VT = Node->getValueType(0);
11261 SDValue Op = DAG.getFreeze(Node->getOperand(0));
11262 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11263
11264 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
11265 // This transforms the sign bits into leading zeros that can be counted.
11266 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
11267 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
11268 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
11269 SDValue Shl =
11270 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11271 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
11272 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
11273}
11274
11276 const SDLoc &DL, EVT VT, SDValue Op,
11277 unsigned BitWidth) const {
11278 if (BitWidth != 32 && BitWidth != 64)
11279 return SDValue();
11280
11281 const DataLayout &TD = DAG.getDataLayout();
11283 return SDValue();
11284
11285 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
11286 : APInt(64, 0x0218A392CD3D5DBFULL);
11287 MachinePointerInfo PtrInfo =
11289 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
11290 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11291 SDValue Lookup = DAG.getNode(
11292 ISD::SRL, DL, VT,
11293 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
11294 DAG.getConstant(DeBruijn, DL, VT)),
11295 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11297
11299 for (unsigned i = 0; i < BitWidth; i++) {
11300 APInt Shl = DeBruijn.shl(i);
11301 APInt Lshr = Shl.lshr(ShiftAmt);
11302 Table[Lshr.getZExtValue()] = i;
11303 }
11304
11305 // Create a ConstantArray in Constant Pool
11306 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11307 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11308 TD.getPrefTypeAlign(CA->getType()));
11309 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11310 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11311 PtrInfo, MVT::i8);
11312 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11313 return ExtLoad;
11314
11315 EVT SetCCVT =
11316 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11317 SDValue Zero = DAG.getConstant(0, DL, VT);
11318 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11319 return DAG.getSelect(DL, VT, SrcIsZero,
11320 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11321}
11322
11324 SDLoc dl(Node);
11325 EVT VT = Node->getValueType(0);
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::CTTZ_ZERO_POISON &&
11332 return DAG.getNode(ISD::CTTZ, 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 CTTZ = DAG.getNode(ISD::CTTZ_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), CTTZ);
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) ||
11350 !canExpandVectorCTPOP(*this, VT)) ||
11354 return SDValue();
11355
11356 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11357 // to be expanded or converted to a libcall.
11360 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11361 return V;
11362
11363 bool UseCTLZ =
11365
11366 // When only ctlz is available and the operand is nonzero we can use:
11367 // { return nlz(x & -x) ^ 31; }
11368 // which is more efficient than:
11369 // { return 32 - nlz(~x & (x - 1)); }.
11370 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11371 SDValue LowestBit =
11372 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11373 return DAG.getNode(ISD::XOR, dl, VT,
11374 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11375 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11376 }
11377
11378 // If ctpop is available, we use:
11379 // { return popcount(~x & (x-1)); }
11380 // If the target has ctlz but not ctpop, we use:
11381 // { return 32 - nlz(~x & (x-1)); }
11382 // Ref: "Hacker's Delight" by Henry Warren
11383 SDValue Tmp = DAG.getNode(
11384 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11385 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11386
11387 if (UseCTLZ)
11388 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11389 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11390
11391 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11392}
11393
11395 SelectionDAG &DAG) const {
11396 // %cond = to_bool_vec %source
11397 // %splat = splat /*val=*/VL
11398 // %tz = step_vector
11399 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11400 // %r = vp.reduce.umin %v
11401 SDLoc DL(N);
11402 SDValue Source = N->getOperand(0);
11403 SDValue Mask = N->getOperand(1);
11404 SDValue EVL = N->getOperand(2);
11405 EVT SrcVT = Source.getValueType();
11406 EVT ResVT = N->getValueType(0);
11407 EVT ResVecVT =
11408 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11409
11410 // Convert to boolean vector.
11411 if (SrcVT.getScalarType() != MVT::i1) {
11412 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11413 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11414 SrcVT.getVectorElementCount());
11415 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11416 }
11417
11418 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11419 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11420 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11421 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11422 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11423}
11424
11425/// Returns a type-legalized version of \p Mask as the first item in the
11426/// pair. The second item contains a type-legalized step vector that's
11427/// guaranteed to fit the number of elements in \p Mask.
11428/// If the stepvector would require splitting, returns an empty SDValue
11429/// as the second item to signal that the operation should be split instead.
11430static std::pair<SDValue, SDValue>
11432 SelectionDAG &DAG) {
11433 EVT MaskVT = Mask.getValueType();
11434 EVT BoolVT = MaskVT.getScalarType();
11435
11436 // Find a suitable type for a stepvector.
11437 // If zero is poison, we can assume the upper limit of the result is VF-1.
11438 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11439 if (MaskVT.isScalableVector())
11440 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11441 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11442 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11443 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11444 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11445 // If the step vector element type is smaller than the mask element type,
11446 // use the mask type directly to avoid widening issues.
11447 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11448 EVT StepVT = MVT::getIntegerVT(EltWidth);
11449 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11450
11451 // If promotion or widening is required to make the type legal, do it here.
11452 // Promotion of integers within LegalizeVectorOps is looking for types of
11453 // the same size but with a smaller number of larger elements, not the usual
11454 // larger size with the same number of larger elements.
11456 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11457 SDValue StepVec;
11458 if (TypeAction == TargetLowering::TypePromoteInteger) {
11459 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11460 StepVec = DAG.getStepVector(DL, StepVecVT);
11461 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11462 // For widening, the element count changes. Create a step vector with only
11463 // the original elements valid and zeros for padding. Also widen the mask.
11464 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11465 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11466
11467 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11468 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11469 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11470 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11471
11472 // Widen mask: pad with zeros.
11473 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11474 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11475 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11476 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11477 // The stepvector type would require splitting. Signal to the caller
11478 // that the operation should be split instead of expanded.
11479 return {Mask, SDValue()};
11480 } else {
11481 StepVec = DAG.getStepVector(DL, StepVecVT);
11482 }
11483
11484 return {Mask, StepVec};
11485}
11486
11488 SelectionDAG &DAG) const {
11489 SDLoc DL(N);
11490 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11491 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11492
11493 // If StepVec is empty, the stepvector would require splitting.
11494 // Split the operation instead and let it be recursively legalized.
11495 if (!StepVec) {
11496 EVT MaskVT = N->getOperand(0).getValueType();
11497 EVT ResVT = N->getValueType(0);
11498
11499 // Split the mask
11500 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11501 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11502
11503 // Create split VECTOR_FIND_LAST_ACTIVE operations
11504 SDValue LoResult =
11505 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11506 SDValue HiResult =
11507 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11508
11509 // Check if any lane is active in the high mask.
11510 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11512 AnyHiActive, DL,
11513 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11514 MVT::i1);
11515
11516 // Adjust HiResult by adding the number of elements in Lo
11517 SDValue LoNumElts =
11518 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11519 SDValue AdjustedHiResult =
11520 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11521
11522 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11523 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11524 LoResult);
11525 }
11526
11527 EVT StepVecVT = StepVec.getValueType();
11528 EVT StepVT = StepVec.getValueType().getVectorElementType();
11529
11530 // Zero out lanes with inactive elements, then find the highest remaining
11531 // value from the stepvector.
11532 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11533 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11534 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11535 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11536}
11537
11539 SelectionDAG &DAG) const {
11540 SDLoc DL(N);
11541
11542 SDValue Start = N->getOperand(0);
11543 SDValue End = N->getOperand(1);
11544 EVT VT = N->getValueType(0);
11545 EVT OpVT = Start.getValueType();
11546
11547 auto [Mask, StepVector] = getLegalMaskAndStepVector(
11548 DAG.getPOISON(VT), /*ZeroIsPoison=*/false, DL, DAG);
11549
11550 // No legal step vector: split the mask in half and recombine the results.
11551 // Lo = get_active_lane_mask Start, End
11552 // Hi = get_active_lane_mask (uaddsat Start, LoNumElts), End
11553 if (!StepVector) {
11554 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
11555 SDValue Lo = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, LoVT, Start, End);
11556 SDValue LoNumElts =
11557 DAG.getElementCount(DL, OpVT, LoVT.getVectorElementCount());
11558 SDValue HiStart = DAG.getNode(ISD::UADDSAT, DL, OpVT, Start, LoNumElts);
11559 SDValue Hi = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, HiVT, HiStart, End);
11560 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
11561 }
11562
11563 // Rebase and saturate the termination value.
11564 SDValue Max =
11565 DAG.getConstant(maxUIntN(std::min(StepVector.getScalarValueSizeInBits(),
11566 OpVT.getScalarSizeInBits())),
11567 DL, OpVT);
11568 End = DAG.getNode(ISD::USUBSAT, DL, OpVT, End, Start);
11569 End = DAG.getNode(ISD::UMIN, DL, OpVT, End, Max);
11570 End = DAG.getZExtOrTrunc(End, DL, StepVector.getValueType().getScalarType());
11571
11572 // cmp <0, 1, 2, 3...>, End
11573 SDValue EndV = DAG.getSplat(StepVector.getValueType(), DL, End);
11574 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11575 StepVector.getValueType());
11576 SDValue Cmp = DAG.getSetCC(DL, CCVT, StepVector, EndV, ISD::SETULT);
11577 SDValue Res = DAG.getBoolExtOrTrunc(Cmp, DL, Mask.getValueType(),
11578 StepVector.getValueType());
11579 if (Mask.getValueType() != VT)
11580 Res = DAG.getExtractSubvector(DL, VT, Res, 0);
11581 return Res;
11582}
11583
11585 SelectionDAG &DAG) const {
11586 SDLoc DL(N);
11587 EVT VT = N->getValueType(0);
11588 SDValue SourceValue = N->getOperand(0);
11589 SDValue SinkValue = N->getOperand(1);
11590 SDValue EltSizeInBytes = N->getOperand(2);
11591
11592 // Note: The lane offset is scalable if the mask is scalable.
11593 ElementCount LaneOffsetEC =
11594 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11595
11596 EVT AddrVT = SourceValue->getValueType(0);
11597 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11598
11599 EVT CmpVT =
11600 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11601
11602 // Unsigned compare: Source >= Sink.
11603 SDValue SourceAheadOfOrEqualToSink =
11604 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11605
11606 // Take the difference between the pointers and divided by the element size,
11607 // to see how many lanes separate them.
11608 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11609
11610 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11611 if (IsReadAfterWrite)
11612 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11613 DAG.getNegative(Diff, DL, AddrVT), Diff);
11614
11615 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11616
11617 // The pointers do not alias if:
11618 // - Source >= Sink (WAR_MASK)
11619 // - Source == Sink (RAW_MASK)
11620 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11621 if (IsReadAfterWrite)
11622 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11623
11624 // The pointers do not alias if:
11625 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11626 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11627 SDValue MaskN = DAG.getSelect(
11628 DL, AddrVT, NoAlias,
11630 AddrVT),
11631 Diff);
11632
11633 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11634}
11635
11637 bool IsNegative) const {
11638 SDLoc dl(N);
11639 EVT VT = N->getValueType(0);
11640 SDValue Op = N->getOperand(0);
11641
11642 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11643 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11645 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11646 if (IsNegative)
11647 return DAG.getNegative(AbsVal, dl, VT);
11648 return AbsVal;
11649 }
11650
11651 // abs(x) -> smax(x,sub(0,x))
11652 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11654 SDValue Zero = DAG.getConstant(0, dl, VT);
11655 Op = DAG.getFreeze(Op);
11656 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11657 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11658 }
11659
11660 // abs(x) -> umin(x,sub(0,x))
11661 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11663 SDValue Zero = DAG.getConstant(0, dl, VT);
11664 Op = DAG.getFreeze(Op);
11665 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11666 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11667 }
11668
11669 // 0 - abs(x) -> smin(x, sub(0,x))
11670 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11672 SDValue Zero = DAG.getConstant(0, dl, VT);
11673 Op = DAG.getFreeze(Op);
11674 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11675 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11676 }
11677
11678 // Only expand vector types if we have the appropriate vector operations.
11679 if (VT.isVector() &&
11681 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11682 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11684 return SDValue();
11685
11686 Op = DAG.getFreeze(Op);
11687 SDValue Shift = DAG.getNode(
11688 ISD::SRA, dl, VT, Op,
11689 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11690 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11691
11692 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11693 if (!IsNegative)
11694 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11695
11696 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11697 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11698}
11699
11701 SDLoc dl(N);
11702 EVT VT = N->getValueType(0);
11703 SDValue LHS = N->getOperand(0);
11704 SDValue RHS = N->getOperand(1);
11705 bool IsSigned = N->getOpcode() == ISD::ABDS;
11706
11707 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11708 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11709 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11710 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11711 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11712 LHS = DAG.getFreeze(LHS);
11713 RHS = DAG.getFreeze(RHS);
11714 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11715 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11716 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11717 }
11718
11719 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11720 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11721 LHS = DAG.getFreeze(LHS);
11722 RHS = DAG.getFreeze(RHS);
11723 return DAG.getNode(ISD::OR, dl, VT,
11724 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11725 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11726 }
11727
11728 // abds, or abdu with non-negative operands: if the sub is nsw, abs(sub).
11729 // Otherwise abdu: if the sub is nuw then lhs >= rhs, so just sub.
11730 bool UseSigned =
11731 IsSigned || (DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS));
11732
11733 if (DAG.willNotOverflowSub(UseSigned, LHS, RHS)) {
11734 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11735 return UseSigned ? DAG.getNode(ISD::ABS, dl, VT, Sub) : Sub;
11736 }
11737
11738 if (DAG.willNotOverflowSub(UseSigned, RHS, LHS)) {
11739 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, RHS, LHS);
11740 return UseSigned ? DAG.getNode(ISD::ABS, dl, VT, Sub) : Sub;
11741 }
11742
11743 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11745 LHS = DAG.getFreeze(LHS);
11746 RHS = DAG.getFreeze(RHS);
11747 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11748
11749 // Branchless expansion iff cmp result is allbits:
11750 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11751 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11752 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11753 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11754 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11755 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11756 }
11757
11758 // Similar to the branchless expansion, if we don't prefer selects, use the
11759 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11760 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11761 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11762 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11764 SDValue USubO =
11765 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11766 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11767 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11768 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11769 }
11770
11771 // FIXME: Should really try to split the vector in case it's legal on a
11772 // subvector.
11774 return DAG.UnrollVectorOp(N);
11775
11776 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11777 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11778 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11779 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11780}
11781
11783 SDLoc dl(N);
11784 EVT VT = N->getValueType(0);
11785 SDValue LHS = N->getOperand(0);
11786 SDValue RHS = N->getOperand(1);
11787
11788 unsigned Opc = N->getOpcode();
11789 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11790 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11791 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11792 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11793 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11794 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11796 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11797 "Unknown AVG node");
11798
11799 // If the operands are already extended, we can add+shift.
11800 bool IsExt =
11801 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11802 DAG.ComputeNumSignBits(RHS) >= 2) ||
11803 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11804 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11805 if (IsExt) {
11806 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11807 if (!IsFloor)
11808 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11809 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11810 DAG.getShiftAmountConstant(1, VT, dl));
11811 }
11812
11813 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11814 if (VT.isScalarInteger()) {
11815 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11816 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11817 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11818 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11819 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11820 if (!IsFloor)
11821 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11822 DAG.getConstant(1, dl, ExtVT));
11823 // Just use SRL as we will be truncating away the extended sign bits.
11824 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11825 DAG.getShiftAmountConstant(1, ExtVT, dl));
11826 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11827 }
11828 }
11829
11830 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11831 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11834 SDValue UAddWithOverflow =
11835 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11836
11837 SDValue Sum = UAddWithOverflow.getValue(0);
11838 SDValue Overflow = UAddWithOverflow.getValue(1);
11839
11840 // Right shift the sum by 1
11841 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
11842 DAG.getShiftAmountConstant(1, VT, dl));
11843
11844 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
11845 SDValue OverflowShl = DAG.getNode(
11846 ISD::SHL, dl, VT, ZeroExtOverflow,
11847 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11848
11849 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
11850 }
11851
11852 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
11853 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
11854 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
11855 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
11856 LHS = DAG.getFreeze(LHS);
11857 RHS = DAG.getFreeze(RHS);
11858 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
11859 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
11860 SDValue Shift =
11861 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11862 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
11863}
11864
11866 SDLoc dl(N);
11867 EVT VT = N->getValueType(0);
11868 SDValue Op = N->getOperand(0);
11869
11870 if (!VT.isSimple())
11871 return SDValue();
11872
11873 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11874 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11875 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11876 default:
11877 return SDValue();
11878 case MVT::i16:
11879 // Use a rotate by 8. This can be further expanded if necessary.
11880 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11881 case MVT::i32:
11882 // This is meant for ARM specifically, which has ROTR but no ROTL.
11883 // t = x ^ rotr(x, 16)
11884 // t = bic(t, 0x00ff0000)
11885 // t = lshr(t, 8)
11886 // x = t ^ rotr(x, 8)
11888 SDValue Rotr16 =
11889 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
11890 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
11891 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
11892 DAG.getConstant(0xFF00FFFF, dl, VT));
11893 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
11894 SDValue Rotr8 =
11895 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11896 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
11897 }
11898 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11899 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
11900 DAG.getConstant(0xFF00, dl, VT));
11901 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
11902 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11903 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
11904 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11905 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11906 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11907 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11908 case MVT::i64:
11909 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11910 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
11911 DAG.getConstant(255ULL<<8, dl, VT));
11912 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
11913 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
11914 DAG.getConstant(255ULL<<16, dl, VT));
11915 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
11916 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
11917 DAG.getConstant(255ULL<<24, dl, VT));
11918 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
11919 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11920 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
11921 DAG.getConstant(255ULL<<24, dl, VT));
11922 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11923 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
11924 DAG.getConstant(255ULL<<16, dl, VT));
11925 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
11926 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
11927 DAG.getConstant(255ULL<<8, dl, VT));
11928 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11929 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
11930 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
11931 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11932 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11933 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
11934 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11935 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
11936 }
11937}
11938
11940 SDLoc dl(N);
11941 EVT VT = N->getValueType(0);
11942 SDValue Op = N->getOperand(0);
11943 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11944 unsigned Sz = VT.getScalarSizeInBits();
11945
11946 SDValue Tmp, Tmp2, Tmp3;
11947
11948 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
11949 // and finally the i1 pairs.
11950 // TODO: We can easily support i4/i2 legal types if any target ever does.
11951 if (Sz >= 8 && isPowerOf2_32(Sz)) {
11952 // Create the masks - repeating the pattern every byte.
11953 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
11954 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
11955 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
11956
11957 // BSWAP if the type is wider than a single byte.
11958 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
11959
11960 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
11961 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
11962 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
11963 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
11964 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
11965 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11966
11967 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
11968 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
11969 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
11970 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
11971 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
11972 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11973
11974 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
11975 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
11976 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
11977 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
11978 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
11979 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11980 return Tmp;
11981 }
11982
11983 Tmp = DAG.getConstant(0, dl, VT);
11984 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
11985 if (I < J)
11986 Tmp2 =
11987 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
11988 else
11989 Tmp2 =
11990 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
11991
11992 APInt Shift = APInt::getOneBitSet(Sz, J);
11993 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
11994 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
11995 }
11996
11997 return Tmp;
11998}
11999
12000std::pair<SDValue, SDValue>
12002 SelectionDAG &DAG) const {
12003 SDLoc SL(LD);
12004 SDValue Chain = LD->getChain();
12005 SDValue BasePTR = LD->getBasePtr();
12006 EVT SrcVT = LD->getMemoryVT();
12007 EVT DstVT = LD->getValueType(0);
12008 ISD::LoadExtType ExtType = LD->getExtensionType();
12009
12010 if (SrcVT.isScalableVector())
12011 report_fatal_error("Cannot scalarize scalable vector loads");
12012
12013 unsigned NumElem = SrcVT.getVectorNumElements();
12014
12015 EVT SrcEltVT = SrcVT.getScalarType();
12016 EVT DstEltVT = DstVT.getScalarType();
12017
12018 // A vector must always be stored in memory as-is, i.e. without any padding
12019 // between the elements, since various code depend on it, e.g. in the
12020 // handling of a bitcast of a vector type to int, which may be done with a
12021 // vector store followed by an integer load. A vector that does not have
12022 // elements that are byte-sized must therefore be stored as an integer
12023 // built out of the extracted vector elements.
12024 if (!SrcEltVT.isByteSized()) {
12025 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
12026 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
12027
12028 unsigned NumSrcBits = SrcVT.getSizeInBits();
12029 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
12030
12031 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
12032 SDValue SrcEltBitMask = DAG.getConstant(
12033 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
12034
12035 // Load the whole vector and avoid masking off the top bits as it makes
12036 // the codegen worse.
12037 SDValue Load = DAG.getExtLoad(
12038 ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, LD->getPointerInfo(),
12039 SrcIntVT, LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12040 LD->getMMOMetadataForSubAccess());
12041
12043 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12044 unsigned ShiftIntoIdx =
12045 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12046 SDValue ShiftAmount = DAG.getShiftAmountConstant(
12047 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
12048 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
12049 SDValue Elt =
12050 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
12051 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
12052
12053 if (ExtType != ISD::NON_EXTLOAD) {
12054 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
12055 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
12056 }
12057
12058 Vals.push_back(Scalar);
12059 }
12060
12061 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12062 return std::make_pair(Value, Load.getValue(1));
12063 }
12064
12065 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
12066 assert(SrcEltVT.isByteSized());
12067
12069 SmallVector<SDValue, 8> LoadChains;
12070
12071 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12072 SDValue ScalarLoad = DAG.getExtLoad(
12073 ExtType, SL, DstEltVT, Chain, BasePTR,
12074 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
12075 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12076 LD->getMMOMetadataForSubAccess());
12077
12078 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
12079
12080 Vals.push_back(ScalarLoad.getValue(0));
12081 LoadChains.push_back(ScalarLoad.getValue(1));
12082 }
12083
12084 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
12085 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12086
12087 return std::make_pair(Value, NewChain);
12088}
12089
12091 SelectionDAG &DAG) const {
12092 SDLoc SL(ST);
12093
12094 SDValue Chain = ST->getChain();
12095 SDValue BasePtr = ST->getBasePtr();
12096 SDValue Value = ST->getValue();
12097 EVT StVT = ST->getMemoryVT();
12098
12099 if (StVT.isScalableVector())
12100 report_fatal_error("Cannot scalarize scalable vector stores");
12101
12102 // The type of the data we want to save
12103 EVT RegVT = Value.getValueType();
12104 EVT RegSclVT = RegVT.getScalarType();
12105
12106 // The type of data as saved in memory.
12107 EVT MemSclVT = StVT.getScalarType();
12108
12109 unsigned NumElem = StVT.getVectorNumElements();
12110
12111 // A vector must always be stored in memory as-is, i.e. without any padding
12112 // between the elements, since various code depend on it, e.g. in the
12113 // handling of a bitcast of a vector type to int, which may be done with a
12114 // vector store followed by an integer load. A vector that does not have
12115 // elements that are byte-sized must therefore be stored as an integer
12116 // built out of the extracted vector elements.
12117 if (!MemSclVT.isByteSized()) {
12118 unsigned NumBits = StVT.getSizeInBits();
12119 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
12120
12121 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
12122
12123 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12124 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12125 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
12126 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
12127 unsigned ShiftIntoIdx =
12128 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12129 SDValue ShiftAmount =
12130 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
12131 SDValue ShiftedElt =
12132 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
12133 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
12134 }
12135
12136 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
12137 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12138 ST->getMMOMetadataForSubAccess());
12139 }
12140
12141 // Store Stride in bytes
12142 unsigned Stride = MemSclVT.getSizeInBits() / 8;
12143 assert(Stride && "Zero stride!");
12144 // Extract each of the elements from the original vector and save them into
12145 // memory individually.
12147 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12148 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12149
12150 SDValue Ptr =
12151 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
12152
12153 // This scalar TruncStore may be illegal, but we legalize it later.
12155 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
12156 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12157 ST->getMMOMetadataForSubAccess());
12158
12159 Stores.push_back(Store);
12160 }
12161
12162 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
12163}
12164
12165std::pair<SDValue, SDValue>
12167 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
12168 "unaligned indexed loads not implemented!");
12169 SDValue Chain = LD->getChain();
12170 SDValue Ptr = LD->getBasePtr();
12171 EVT VT = LD->getValueType(0);
12172 EVT LoadedVT = LD->getMemoryVT();
12173 SDLoc dl(LD);
12174 auto &MF = DAG.getMachineFunction();
12175
12176 if (VT.isFloatingPoint() || VT.isVector()) {
12177 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
12178 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
12179 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
12180 LoadedVT.isVector()) {
12181 // Scalarize the load and let the individual components be handled.
12182 return scalarizeVectorLoad(LD, DAG);
12183 }
12184
12185 // Expand to a (misaligned) integer load of the same size,
12186 // then bitconvert to floating point or vector.
12187 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
12188 LD->getMemOperand());
12189 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
12190 if (LoadedVT != VT)
12191 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
12192 ISD::ANY_EXTEND, dl, VT, Result);
12193
12194 return std::make_pair(Result, newLoad.getValue(1));
12195 }
12196
12197 // Copy the value to a (aligned) stack slot using (unaligned) integer
12198 // loads and stores, then do a (aligned) load from the stack slot.
12199 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
12200 unsigned LoadedBytes = LoadedVT.getStoreSize();
12201 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12202 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
12203
12204 // Make sure the stack slot is also aligned for the register type.
12205 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
12206 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
12208 SDValue StackPtr = StackBase;
12209 unsigned Offset = 0;
12210
12211 EVT PtrVT = Ptr.getValueType();
12212 EVT StackPtrVT = StackPtr.getValueType();
12213
12214 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12215 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12216
12217 // Do all but one copies using the full register width.
12218 for (unsigned i = 1; i < NumRegs; i++) {
12219 // Load one integer register's worth from the original location.
12220 SDValue Load = DAG.getLoad(
12221 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12222 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12223 LD->getMMOMetadataForSubAccess());
12224 // Follow the load with a store to the stack slot. Remember the store.
12225 Stores.push_back(DAG.getStore(
12226 Load.getValue(1), dl, Load, StackPtr,
12227 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12228 // Increment the pointers.
12229 Offset += RegBytes;
12230
12231 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12232 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12233 }
12234
12235 // The last copy may be partial. Do an extending load.
12236 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12237 8 * (LoadedBytes - Offset));
12238 SDValue Load = DAG.getExtLoad(
12239 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12240 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12241 LD->getMemOperand()->getFlags(), LD->getMMOMetadataForSubAccess());
12242 // Follow the load with a store to the stack slot. Remember the store.
12243 // On big-endian machines this requires a truncating store to ensure
12244 // that the bits end up in the right place.
12245 Stores.push_back(DAG.getTruncStore(
12246 Load.getValue(1), dl, Load, StackPtr,
12247 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12248
12249 // The order of the stores doesn't matter - say it with a TokenFactor.
12250 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12251
12252 // Finally, perform the original load only redirected to the stack slot.
12253 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12254 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12255 LoadedVT);
12256
12257 // Callers expect a MERGE_VALUES node.
12258 return std::make_pair(Load, TF);
12259 }
12260
12261 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12262 "Unaligned load of unsupported type.");
12263
12264 // Compute the new VT that is half the size of the old one. This is an
12265 // integer MVT.
12266 unsigned NumBits = LoadedVT.getSizeInBits();
12267 EVT NewLoadedVT;
12268 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12269 NumBits >>= 1;
12270
12271 Align Alignment = LD->getBaseAlign();
12272 unsigned IncrementSize = NumBits / 8;
12273 ISD::LoadExtType HiExtType = LD->getExtensionType();
12274
12275 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12276 if (HiExtType == ISD::NON_EXTLOAD)
12277 HiExtType = ISD::ZEXTLOAD;
12278
12279 // Load the value in two parts
12280 SDValue Lo, Hi;
12281 if (DAG.getDataLayout().isLittleEndian()) {
12282 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12283 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12284 LD->getMMOMetadataForSubAccess());
12285
12286 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12287 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12288 LD->getPointerInfo().getWithOffset(IncrementSize),
12289 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12290 LD->getMMOMetadataForSubAccess());
12291 } else {
12292 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12293 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12294 LD->getMMOMetadataForSubAccess());
12295
12296 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12297 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12298 LD->getPointerInfo().getWithOffset(IncrementSize),
12299 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12300 LD->getMMOMetadataForSubAccess());
12301 }
12302
12303 // aggregate the two parts
12304 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12305 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12306 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12307
12308 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12309 Hi.getValue(1));
12310
12311 return std::make_pair(Result, TF);
12312}
12313
12315 SelectionDAG &DAG) const {
12316 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12317 "unaligned indexed stores not implemented!");
12318 SDValue Chain = ST->getChain();
12319 SDValue Ptr = ST->getBasePtr();
12320 SDValue Val = ST->getValue();
12321 EVT VT = Val.getValueType();
12322 Align Alignment = ST->getBaseAlign();
12323 auto &MF = DAG.getMachineFunction();
12324 EVT StoreMemVT = ST->getMemoryVT();
12325
12326 SDLoc dl(ST);
12327 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12328 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12329 if (isTypeLegal(intVT)) {
12330 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12331 StoreMemVT.isVector()) {
12332 // Scalarize the store and let the individual components be handled.
12333 SDValue Result = scalarizeVectorStore(ST, DAG);
12334 return Result;
12335 }
12336 // Expand to a bitconvert of the value to the integer type of the
12337 // same size, then a (misaligned) int store.
12338 // FIXME: Does not handle truncating floating point stores!
12339 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12340 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12341 Alignment, ST->getMemOperand()->getFlags(),
12342 ST->getMMOMetadataForSubAccess());
12343 return Result;
12344 }
12345 // Do a (aligned) store to a stack slot, then copy from the stack slot
12346 // to the final destination using (unaligned) integer loads and stores.
12347 MVT RegVT = getRegisterType(
12348 *DAG.getContext(),
12349 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12350 EVT PtrVT = Ptr.getValueType();
12351 unsigned StoredBytes = StoreMemVT.getStoreSize();
12352 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12353 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12354
12355 // Make sure the stack slot is also aligned for the register type.
12356 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12357 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12358
12359 // Perform the original store, only redirected to the stack slot.
12361 Chain, dl, Val, StackPtr,
12362 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12363
12364 EVT StackPtrVT = StackPtr.getValueType();
12365
12366 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12367 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12369 unsigned Offset = 0;
12370
12371 // Do all but one copies using the full register width.
12372 for (unsigned i = 1; i < NumRegs; i++) {
12373 // Load one integer register's worth from the stack slot.
12374 SDValue Load = DAG.getLoad(
12375 RegVT, dl, Store, StackPtr,
12376 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12377 // Store it to the final location. Remember the store.
12378 Stores.push_back(DAG.getStore(
12379 Load.getValue(1), dl, Load, Ptr,
12380 ST->getPointerInfo().getWithOffset(Offset), ST->getBaseAlign(),
12381 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess()));
12382 // Increment the pointers.
12383 Offset += RegBytes;
12384 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12385 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12386 }
12387
12388 // The last store may be partial. Do a truncating store. On big-endian
12389 // machines this requires an extending load from the stack slot to ensure
12390 // that the bits are in the right place.
12391 EVT LoadMemVT =
12392 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12393
12394 // Load from the stack slot.
12395 SDValue Load = DAG.getExtLoad(
12396 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12397 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12398
12399 Stores.push_back(
12400 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
12401 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12402 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12403 ST->getMMOMetadataForSubAccess()));
12404 // The order of the stores doesn't matter - say it with a TokenFactor.
12405 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12406 return Result;
12407 }
12408
12409 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12410 "Unaligned store of unknown type.");
12411 // Get the half-size VT
12412 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12413 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12414 unsigned IncrementSize = NumBits / 8;
12415
12416 // Divide the stored value in two parts.
12417 SDValue ShiftAmount =
12418 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12419 SDValue Lo = Val;
12420 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12421 // fold and not use the upper bits. A smaller constant may be easier to
12422 // materialize.
12423 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12424 Lo = DAG.getNode(
12425 ISD::AND, dl, VT, Lo,
12426 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12427 VT));
12428 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12429
12430 // Store the two parts
12431 SDValue Store1, Store2;
12432 Store1 = DAG.getTruncStore(
12433 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Lo : Hi, Ptr,
12434 ST->getPointerInfo(), NewStoredVT, Alignment,
12435 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12436
12437 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12438 Store2 = DAG.getTruncStore(
12439 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12440 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12441 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12442
12443 SDValue Result =
12444 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12445 return Result;
12446}
12447
12448SDValue
12450 const SDLoc &DL, EVT DataVT,
12451 SelectionDAG &DAG,
12452 bool IsCompressedMemory) const {
12454 EVT AddrVT = Addr.getValueType();
12455 EVT MaskVT = Mask.getValueType();
12456 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12457 "Incompatible types of Data and Mask");
12458 if (IsCompressedMemory) {
12459 // Incrementing the pointer according to number of '1's in the mask.
12460 if (DataVT.isScalableVector()) {
12461 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12462 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12463 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12464 } else {
12465 EVT MaskIntVT =
12466 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12467 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12468 if (MaskIntVT.getSizeInBits() < 32) {
12469 MaskInIntReg =
12470 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12471 MaskIntVT = MVT::i32;
12472 }
12473 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12474 }
12475 // Scale is an element size in bytes.
12476 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12477 AddrVT);
12478 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12479 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12480 } else
12481 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12482
12483 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12484}
12485
12487 EVT VecVT, const SDLoc &DL,
12488 ElementCount SubEC) {
12489 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12490 "Cannot index a scalable vector within a fixed-width vector");
12491 ElementCount NElts = VecVT.getVectorElementCount();
12492 EVT IdxVT = Idx.getValueType();
12493
12494 // Attempt to prove all accessed lanes sit within VecVT.
12495 ElementCount IdxAsEC;
12496 if (sd_match(Idx, m_ElementCount(IdxAsEC))) {
12497 if (SubEC.isScalar() && ElementCount::isKnownLT(IdxAsEC, NElts))
12498 return Idx;
12499 // Calculate end index as TypeSize to remove possibility of overflow.
12500 if (IdxAsEC.isScalable() == SubEC.isScalable() &&
12501 TypeSize::isKnownLE(TypeSize(IdxAsEC) + TypeSize(SubEC),
12502 TypeSize(NElts)))
12503 return Idx;
12504 }
12505
12506 // Can we mask Idx rather than clamp it.
12507 if (SubEC.isScalar() && NElts.isPowerOf2()) {
12508 SDValue EC = DAG.getElementCount(DL, IdxVT, NElts);
12509 SDValue Mask =
12510 DAG.getNode(ISD::SUB, DL, IdxVT, EC, DAG.getConstant(1, DL, IdxVT));
12511 return DAG.getNode(ISD::AND, DL, IdxVT, Idx, Mask);
12512 }
12513
12514 unsigned SubOpcode =
12516 SDValue MaxSafeIndex =
12517 DAG.getNode(SubOpcode, DL, IdxVT, DAG.getElementCount(DL, IdxVT, NElts),
12518 DAG.getElementCount(DL, IdxVT, SubEC));
12519 return DAG.getNode(ISD::UMIN, DL, IdxVT, Idx, MaxSafeIndex);
12520}
12521
12522SDValue
12524 EVT VecVT, SDValue Index,
12525 const SDNodeFlags PtrArithFlags) const {
12527 DAG, VecPtr, VecVT,
12529 Index, PtrArithFlags);
12530}
12531
12532SDValue
12534 EVT VecVT, EVT SubVecVT, SDValue Index,
12535 const SDNodeFlags PtrArithFlags) const {
12536 SDLoc dl(Index);
12537 // Make sure the index type is big enough to compute in.
12538 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12539
12540 EVT EltVT = VecVT.getVectorElementType();
12541
12542 // Calculate the element offset and add it to the pointer.
12543 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12544 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12545 "Converting bits to bytes lost precision");
12546 assert(SubVecVT.getVectorElementType() == EltVT &&
12547 "Sub-vector must be a vector with matching element type");
12548 assert((SubVecVT.getVectorElementCount().isScalar() ||
12549 isa<ConstantSDNode>(Index)) &&
12550 "Subvector Index must be constant!");
12551
12552 // An out-of-range index only makes the vector operation return poison, but
12553 // a load/store through the pointer computed below would be immediate UB, so
12554 // freeze the index before clamping it into range.
12555 if (!DAG.isGuaranteedNotToBePoison(Index))
12556 Index = DAG.getFreeze(Index);
12557
12558 EVT IdxVT = Index.getValueType();
12559 if (SubVecVT.isScalableVector())
12560 Index =
12561 DAG.getVScale(dl, IdxVT, cast<ConstantSDNode>(Index)->getAPIntValue());
12562
12563 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12564 SubVecVT.getVectorElementCount());
12565 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12566 DAG.getConstant(EltSize, dl, IdxVT));
12567 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12568}
12569
12570//===----------------------------------------------------------------------===//
12571// Implementation of Emulated TLS Model
12572//===----------------------------------------------------------------------===//
12573
12575 SelectionDAG &DAG) const {
12576 // Access to address of TLS varialbe xyz is lowered to a function call:
12577 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12578 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12579 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12580 SDLoc dl(GA);
12581
12582 ArgListTy Args;
12583 const GlobalValue *GV =
12585 SmallString<32> NameString("__emutls_v.");
12586 NameString += GV->getName();
12587 StringRef EmuTlsVarName(NameString);
12588 const GlobalVariable *EmuTlsVar =
12589 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12590 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12591 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12592
12593 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12594
12596 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12597 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12598 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12599
12600 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12601 // At last for X86 targets, maybe good for other targets too?
12603 MFI.setAdjustsStack(true); // Is this only for X86 target?
12604 MFI.setHasCalls(true);
12605
12606 assert((GA->getOffset() == 0) &&
12607 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12608 return CallResult.first;
12609}
12610
12612 SelectionDAG &DAG) const {
12613 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12614 if (!isCtlzFast())
12615 return SDValue();
12616 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12617 SDLoc dl(Op);
12618 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12619 EVT VT = Op.getOperand(0).getValueType();
12620 SDValue Zext = Op.getOperand(0);
12621 if (VT.bitsLT(MVT::i32)) {
12622 VT = MVT::i32;
12623 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12624 }
12625 unsigned Log2b = Log2_32(VT.getSizeInBits());
12626 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12627 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12628 DAG.getConstant(Log2b, dl, MVT::i32));
12629 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12630 }
12631 return SDValue();
12632}
12633
12635 SDValue Op0 = Node->getOperand(0);
12636 SDValue Op1 = Node->getOperand(1);
12637 EVT VT = Op0.getValueType();
12638 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12639 unsigned Opcode = Node->getOpcode();
12640 SDLoc DL(Node);
12641
12642 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12643 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12644 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12645 DAG.SignBitIsZero(Op1))
12646 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12647
12648 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12649 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12651 Op0 = DAG.getFreeze(Op0);
12652 SDValue Zero = DAG.getConstant(0, DL, VT);
12653 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12654 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12655 }
12656
12657 // umin(x,y) -> sub(x,usubsat(x,y))
12658 // TODO: Missing freeze(Op0)?
12659 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12661 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12662 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12663 }
12664
12665 // umax(x,y) -> add(x,usubsat(y,x))
12666 // TODO: Missing freeze(Op0)?
12667 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12669 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12670 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12671 }
12672
12673 // FIXME: Should really try to split the vector in case it's legal on a
12674 // subvector.
12676 return DAG.UnrollVectorOp(Node);
12677
12678 // Attempt to find an existing SETCC node that we can reuse.
12679 // TODO: Do we need a generic doesSETCCNodeExist?
12680 // TODO: Missing freeze(Op0)/freeze(Op1)?
12681 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12682 ISD::CondCode PrefCommuteCC,
12683 ISD::CondCode AltCommuteCC) {
12684 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12685 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12686 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12687 {Op0, Op1, DAG.getCondCode(CC)})) {
12688 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12689 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12690 }
12691 }
12692 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12693 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12694 {Op0, Op1, DAG.getCondCode(CC)})) {
12695 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12696 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12697 }
12698 }
12699 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12700 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12701 };
12702
12703 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12704 // -> Y = (A < B) ? B : A
12705 // -> Y = (A >= B) ? A : B
12706 // -> Y = (A <= B) ? B : A
12707 switch (Opcode) {
12708 case ISD::SMAX:
12709 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12710 case ISD::SMIN:
12711 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12712 case ISD::UMAX:
12713 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12714 case ISD::UMIN:
12715 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12716 }
12717
12718 llvm_unreachable("How did we get here?");
12719}
12720
12722 unsigned Opcode = Node->getOpcode();
12723 SDValue LHS = Node->getOperand(0);
12724 SDValue RHS = Node->getOperand(1);
12725 EVT VT = LHS.getValueType();
12726 SDLoc dl(Node);
12727
12728 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12729 assert(VT.isInteger() && "Expected operands to be integers");
12730
12731 // usub.sat(a, b) -> umax(a, b) - b
12732 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12733 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12734 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12735 }
12736
12737 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12738 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12739 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12741 LHS = DAG.getFreeze(LHS);
12742 SDValue Zero = DAG.getConstant(0, dl, VT);
12743 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12744 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12745 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12746 Subtrahend =
12747 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12748 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12749 }
12750
12751 // uadd.sat(a, b) -> umin(a, ~b) + b
12752 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12753 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12754 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12755 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12756 }
12757
12758 unsigned OverflowOp;
12759 switch (Opcode) {
12760 case ISD::SADDSAT:
12761 OverflowOp = ISD::SADDO;
12762 break;
12763 case ISD::UADDSAT:
12764 OverflowOp = ISD::UADDO;
12765 break;
12766 case ISD::SSUBSAT:
12767 OverflowOp = ISD::SSUBO;
12768 break;
12769 case ISD::USUBSAT:
12770 OverflowOp = ISD::USUBO;
12771 break;
12772 default:
12773 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12774 "addition or subtraction node.");
12775 }
12776
12777 // FIXME: Should really try to split the vector in case it's legal on a
12778 // subvector.
12780 return DAG.UnrollVectorOp(Node);
12781
12782 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12783 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12784 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12785 SDValue SumDiff = Result.getValue(0);
12786 SDValue Overflow = Result.getValue(1);
12787 SDValue Zero = DAG.getConstant(0, dl, VT);
12788 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12789
12790 if (Opcode == ISD::UADDSAT) {
12792 // (LHS + RHS) | OverflowMask
12793 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12794 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12795 }
12796 // Overflow ? 0xffff.... : (LHS + RHS)
12797 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12798 }
12799
12800 if (Opcode == ISD::USUBSAT) {
12802 // (LHS - RHS) & ~OverflowMask
12803 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12804 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12805 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12806 }
12807 // Overflow ? 0 : (LHS - RHS)
12808 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12809 }
12810
12811 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12812 "Expected signed saturating add/sub opcode");
12813
12814 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12815 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12816
12817 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12818 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12819
12820 // If either of the operand signs are known, then they are guaranteed to
12821 // only saturate in one direction. If non-negative they will saturate
12822 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12823 //
12824 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12825 // sign of 'y' has to be flipped.
12826
12827 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12828 bool RHSIsNonNegative =
12829 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12830 if (LHSIsNonNegative || RHSIsNonNegative) {
12831 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12832 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12833 }
12834
12835 bool LHSIsNegative = KnownLHS.isNegative();
12836 bool RHSIsNegative =
12837 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12838 if (LHSIsNegative || RHSIsNegative) {
12839 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12840 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
12841 }
12842
12843 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
12844 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12845 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
12846 DAG.getConstant(BitWidth - 1, dl, VT));
12847 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
12848 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
12849}
12850
12852 unsigned Opcode = Node->getOpcode();
12853 SDValue LHS = Node->getOperand(0);
12854 SDValue RHS = Node->getOperand(1);
12855 EVT VT = LHS.getValueType();
12856 EVT ResVT = Node->getValueType(0);
12857 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12858 SDLoc dl(Node);
12859
12860 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
12861 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
12862 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
12863 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
12864
12865 // We can't perform arithmetic on i1 values. Extending them would
12866 // probably result in worse codegen, so let's just use two selects instead.
12867 // Some targets are also just better off using selects rather than subtraction
12868 // because one of the conditions can be merged with one of the selects.
12869 // And finally, if we don't know the contents of high bits of a boolean value
12870 // we can't perform any arithmetic either.
12872 BoolVT.getScalarSizeInBits() == 1 ||
12874 SDValue SelectZeroOrOne =
12875 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
12876 DAG.getConstant(0, dl, ResVT));
12877 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
12878 SelectZeroOrOne);
12879 }
12880
12882 std::swap(IsGT, IsLT);
12883 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
12884 ResVT);
12885}
12886
12888 unsigned Opcode = Node->getOpcode();
12889 bool IsSigned = Opcode == ISD::SSHLSAT;
12890 SDValue LHS = Node->getOperand(0);
12891 SDValue RHS = Node->getOperand(1);
12892 EVT VT = LHS.getValueType();
12893 SDLoc dl(Node);
12894
12895 assert((Node->getOpcode() == ISD::SSHLSAT ||
12896 Node->getOpcode() == ISD::USHLSAT) &&
12897 "Expected a SHLSAT opcode");
12898 assert(VT.isInteger() && "Expected operands to be integers");
12899
12901 return DAG.UnrollVectorOp(Node);
12902
12903 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
12904
12905 unsigned BW = VT.getScalarSizeInBits();
12906 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12907 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
12908 SDValue Orig =
12909 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
12910
12911 SDValue SatVal;
12912 if (IsSigned) {
12913 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
12914 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
12915 SDValue Cond =
12916 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
12917 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
12918 } else {
12919 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
12920 }
12921 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
12922 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
12923}
12924
12926 bool Signed, SDValue &Lo, SDValue &Hi,
12927 SDValue LHS, SDValue RHS,
12928 SDValue HiLHS, SDValue HiRHS) const {
12929 EVT VT = LHS.getValueType();
12930 assert(RHS.getValueType() == VT && "Mismatching operand types");
12931
12932 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
12933 assert((!Signed || !HiLHS) &&
12934 "Signed flag should only be set when HiLHS and RiRHS are null");
12935
12936 // We'll expand the multiplication by brute force because we have no other
12937 // options. This is a trivially-generalized version of the code from
12938 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
12939 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
12940 // sign bits while calculating the Hi half.
12941 unsigned Bits = VT.getScalarSizeInBits();
12942 unsigned HalfBits = Bits / 2;
12943 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
12944 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
12945 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
12946
12947 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
12948 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
12949
12950 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
12951 // This is always an unsigned shift.
12952 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
12953
12954 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
12955 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
12956 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
12957
12958 SDValue U =
12959 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
12960 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
12961 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
12962
12963 SDValue V =
12964 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
12965 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
12966
12967 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
12968 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
12969
12970 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
12971 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
12972
12973 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
12974 // the products to Hi.
12975 if (HiLHS) {
12976 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
12977 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
12978 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
12979 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
12980 }
12981}
12982
12984 bool Signed, const SDValue LHS,
12985 const SDValue RHS, SDValue &Lo,
12986 SDValue &Hi) const {
12987 EVT VT = LHS.getValueType();
12988 assert(RHS.getValueType() == VT && "Mismatching operand types");
12989 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12990 // We can fall back to a libcall with an illegal type for the MUL if we
12991 // have a libcall big enough.
12992 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
12993 if (WideVT == MVT::i16)
12994 LC = RTLIB::MUL_I16;
12995 else if (WideVT == MVT::i32)
12996 LC = RTLIB::MUL_I32;
12997 else if (WideVT == MVT::i64)
12998 LC = RTLIB::MUL_I64;
12999 else if (WideVT == MVT::i128)
13000 LC = RTLIB::MUL_I128;
13001
13002 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
13003 if (LibcallImpl == RTLIB::Unsupported) {
13004 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
13005 return;
13006 }
13007
13008 // The libcall takes and returns WideVT values as packed VT halves. This only
13009 // works if VT is legal and WideVT isn't. Otherwise, emit a wide multiply and
13010 // let it legalise normally, possibly into a wider libcall.
13011 if (isTypeLegal(WideVT) || !isTypeLegal(VT)) {
13012 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT,
13013 DAG.getExtOrTrunc(Signed, LHS, dl, WideVT),
13014 DAG.getExtOrTrunc(Signed, RHS, dl, WideVT));
13015 SDValue Shift =
13016 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13017 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13018 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT,
13019 DAG.getNode(ISD::SRL, dl, WideVT, Mul, Shift));
13020 return;
13021 }
13022
13023 SDValue HiLHS, HiRHS;
13024 if (Signed) {
13025 // The high part is obtained by SRA'ing all but one of the bits of low
13026 // part.
13027 unsigned LoSize = VT.getFixedSizeInBits();
13028 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
13029 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
13030 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
13031 } else {
13032 HiLHS = DAG.getConstant(0, dl, VT);
13033 HiRHS = DAG.getConstant(0, dl, VT);
13034 }
13035
13036 // Attempt a libcall.
13037 SDValue Ret;
13039 CallOptions.setIsSigned(Signed);
13040 CallOptions.setIsPostTypeLegalization(true);
13042 // Halves of WideVT are packed into registers in different order
13043 // depending on platform endianness. This is usually handled by
13044 // the C calling convention, but we can't defer to it in
13045 // the legalizer.
13046 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
13047 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13048 } else {
13049 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
13050 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13051 }
13053 "Ret value is a collection of constituent nodes holding result.");
13054 if (DAG.getDataLayout().isLittleEndian()) {
13055 // Same as above.
13056 Lo = Ret.getOperand(0);
13057 Hi = Ret.getOperand(1);
13058 } else {
13059 Lo = Ret.getOperand(1);
13060 Hi = Ret.getOperand(0);
13061 }
13062}
13063
13064SDValue
13066 assert((Node->getOpcode() == ISD::SMULFIX ||
13067 Node->getOpcode() == ISD::UMULFIX ||
13068 Node->getOpcode() == ISD::SMULFIXSAT ||
13069 Node->getOpcode() == ISD::UMULFIXSAT) &&
13070 "Expected a fixed point multiplication opcode");
13071
13072 SDLoc dl(Node);
13073 SDValue LHS = Node->getOperand(0);
13074 SDValue RHS = Node->getOperand(1);
13075 EVT VT = LHS.getValueType();
13076 unsigned Scale = Node->getConstantOperandVal(2);
13077 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
13078 Node->getOpcode() == ISD::UMULFIXSAT);
13079 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
13080 Node->getOpcode() == ISD::SMULFIXSAT);
13081 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13082 unsigned VTSize = VT.getScalarSizeInBits();
13083
13084 if (!Scale) {
13085 // [us]mul.fix(a, b, 0) -> mul(a, b)
13086 if (!Saturating) {
13088 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13089 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
13090 SDValue Result =
13091 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13092 SDValue Product = Result.getValue(0);
13093 SDValue Overflow = Result.getValue(1);
13094 SDValue Zero = DAG.getConstant(0, dl, VT);
13095
13096 APInt MinVal = APInt::getSignedMinValue(VTSize);
13097 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
13098 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13099 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13100 // Xor the inputs, if resulting sign bit is 0 the product will be
13101 // positive, else negative.
13102 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
13103 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
13104 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
13105 return DAG.getSelect(dl, VT, Overflow, Result, Product);
13106 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
13107 SDValue Result =
13108 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13109 SDValue Product = Result.getValue(0);
13110 SDValue Overflow = Result.getValue(1);
13111
13112 APInt MaxVal = APInt::getMaxValue(VTSize);
13113 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13114 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
13115 }
13116 }
13117
13118 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
13119 "Expected scale to be less than the number of bits if signed or at "
13120 "most the number of bits if unsigned.");
13121 assert(LHS.getValueType() == RHS.getValueType() &&
13122 "Expected both operands to be the same type");
13123
13124 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
13125 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
13126 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
13127 SDValue Val, ISD::CondCode CC) {
13128 if (VT.isVector())
13129 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
13130 Sat, Val);
13131 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
13132 };
13133
13134 // Get the upper and lower bits of the result.
13135 SDValue Lo, Hi;
13136 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13137 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
13138 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13139 if (isOperationLegalOrCustom(LoHiOp, VT)) {
13140 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
13141 Lo = Result.getValue(0);
13142 Hi = Result.getValue(1);
13143 } else if (isOperationLegalOrCustom(HiOp, VT)) {
13144 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13145 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
13146 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13147 // Try for a multiplication using a wider type.
13148 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13149 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
13150 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
13151 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
13152 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
13153 SDValue Shifted =
13154 DAG.getNode(ISD::SRA, dl, WideVT, Res,
13155 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
13156 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
13157 } else if (VT.isVector()) {
13158 return SDValue();
13159 } else {
13160 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
13161 }
13162
13163 if (Scale == VTSize)
13164 // Result is just the top half since we'd be shifting by the width of the
13165 // operand. Overflow impossible so this works for both UMULFIX and
13166 // UMULFIXSAT.
13167 return Hi;
13168
13169 // The result will need to be shifted right by the scale since both operands
13170 // are scaled. The result is given to us in 2 halves, so we only want part of
13171 // both in the result.
13172 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
13173 DAG.getShiftAmountConstant(Scale, VT, dl));
13174 if (!Saturating)
13175 return Result;
13176
13177 if (!Signed) {
13178 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
13179 // widened multiplication) aren't all zeroes.
13180
13181 // Saturate to max if ((Hi >> Scale) != 0),
13182 // which is the same as if (Hi > ((1 << Scale) - 1))
13183 APInt MaxVal = APInt::getMaxValue(VTSize);
13184 SDValue LowMask =
13185 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
13186 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
13187 Result, ISD::SETUGT);
13188 }
13189
13190 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
13191 // widened multiplication) aren't all ones or all zeroes.
13192
13193 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
13194 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
13195
13196 if (Scale == 0) {
13197 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
13198 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
13199 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
13200 // Saturated to SatMin if wide product is negative, and SatMax if wide
13201 // product is positive ...
13202 SDValue Zero = DAG.getConstant(0, dl, VT);
13203 SDValue ResultIfOverflow =
13204 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
13205 // ... but only if we overflowed.
13206 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
13207 }
13208
13209 // We handled Scale==0 above so all the bits to examine is in Hi.
13210
13211 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
13212 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
13213 SDValue LowMask =
13214 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
13215 // Saturate to min if (Hi >> (Scale - 1)) < -1),
13216 // which is the same as if (HI < (-1 << (Scale - 1))
13217 SDValue HighMask = DAG.getConstant(
13218 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
13219 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
13220 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
13221 return Result;
13222}
13223
13224SDValue
13226 SDValue LHS, SDValue RHS,
13227 unsigned Scale, SelectionDAG &DAG) const {
13228 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
13229 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
13230 "Expected a fixed point division opcode");
13231
13232 EVT VT = LHS.getValueType();
13233 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
13234 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
13235 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13236
13237 // If there is enough room in the type to upscale the LHS or downscale the
13238 // RHS before the division, we can perform it in this type without having to
13239 // resize. For signed operations, the LHS headroom is the number of
13240 // redundant sign bits, and for unsigned ones it is the number of zeroes.
13241 // The headroom for the RHS is the number of trailing zeroes.
13242 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
13244 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
13245
13246 // For signed saturating operations, we need to be able to detect true integer
13247 // division overflow; that is, when you have MIN / -EPS. However, this
13248 // is undefined behavior and if we emit divisions that could take such
13249 // values it may cause undesired behavior (arithmetic exceptions on x86, for
13250 // example).
13251 // Avoid this by requiring an extra bit so that we never get this case.
13252 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13253 // signed saturating division, we need to emit a whopping 32-bit division.
13254 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13255 return SDValue();
13256
13257 unsigned LHSShift = std::min(LHSLead, Scale);
13258 unsigned RHSShift = Scale - LHSShift;
13259
13260 // At this point, we know that if we shift the LHS up by LHSShift and the
13261 // RHS down by RHSShift, we can emit a regular division with a final scaling
13262 // factor of Scale.
13263
13264 if (LHSShift)
13265 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13266 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13267 if (RHSShift)
13268 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13269 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13270
13271 SDValue Quot;
13272 if (Signed) {
13273 // For signed operations, if the resulting quotient is negative and the
13274 // remainder is nonzero, subtract 1 from the quotient to round towards
13275 // negative infinity.
13276 SDValue Rem;
13277 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13278 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13279 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13280 if (isTypeLegal(VT) &&
13282 Quot = DAG.getNode(ISD::SDIVREM, dl,
13283 DAG.getVTList(VT, VT),
13284 LHS, RHS);
13285 Rem = Quot.getValue(1);
13286 Quot = Quot.getValue(0);
13287 } else {
13288 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13289 LHS, RHS);
13290 Rem = DAG.getNode(ISD::SREM, dl, VT,
13291 LHS, RHS);
13292 }
13293 SDValue Zero = DAG.getConstant(0, dl, VT);
13294 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13295 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13296 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13297 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13298 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13299 DAG.getConstant(1, dl, VT));
13300 Quot = DAG.getSelect(dl, VT,
13301 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13302 Sub1, Quot);
13303 } else
13304 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13305 LHS, RHS);
13306
13307 return Quot;
13308}
13309
13311 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13312 SDLoc dl(Node);
13313 SDValue LHS = Node->getOperand(0);
13314 SDValue RHS = Node->getOperand(1);
13315 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13316
13317 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13318 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13319 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13320 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13321 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13322 { LHS, RHS, CarryIn });
13323 Result = SDValue(NodeCarry.getNode(), 0);
13324 Overflow = SDValue(NodeCarry.getNode(), 1);
13325 return;
13326 }
13327
13328 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13329 LHS.getValueType(), LHS, RHS);
13330
13331 EVT ResultType = Node->getValueType(1);
13332 EVT SetCCType = getSetCCResultType(
13333 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13334 SDValue SetCC;
13335 if (IsAdd && isOneConstant(RHS)) {
13336 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13337 // the live range of X. We assume comparing with 0 is cheap.
13338 // The general case (X + C) < C is not necessarily beneficial. Although we
13339 // reduce the live range of X, we may introduce the materialization of
13340 // constant C.
13341 SetCC =
13342 DAG.getSetCC(dl, SetCCType, Result,
13343 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13344 } else if (IsAdd && isAllOnesConstant(RHS)) {
13345 // Special case: uaddo X, -1 overflows if X != 0.
13346 SetCC =
13347 DAG.getSetCC(dl, SetCCType, LHS,
13348 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13349 } else {
13351 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13352 }
13353 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13354}
13355
13357 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13358 SDLoc dl(Node);
13359 SDValue LHS = Node->getOperand(0);
13360 SDValue RHS = Node->getOperand(1);
13361 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13362
13363 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13364 LHS.getValueType(), LHS, RHS);
13365
13366 EVT ResultType = Node->getValueType(1);
13367 EVT OType = getSetCCResultType(
13368 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13369
13370 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13371 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13372 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13373 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13374 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13375 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13376 return;
13377 }
13378
13379 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13380
13381 if (IsAdd) {
13382 // For an addition, the result should be less than one of the operands (LHS)
13383 // if and only if the other operand (RHS) is negative, otherwise there will
13384 // be overflow.
13385 SDValue ResultLowerThanLHS =
13386 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13387 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13388 Overflow = DAG.getBoolExtOrTrunc(
13389 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13390 ResultType, ResultType);
13391 } else {
13392 // For subtraction, overflow occurs when the signed comparison of operands
13393 // doesn't match the sign of the result.
13394 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13395 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13396 Overflow = DAG.getBoolExtOrTrunc(
13397 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13398 ResultType, ResultType);
13399 }
13400}
13401
13403 SDValue &Overflow, SelectionDAG &DAG) const {
13404 SDLoc dl(Node);
13405 EVT VT = Node->getValueType(0);
13406 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13407 SDValue LHS = Node->getOperand(0);
13408 SDValue RHS = Node->getOperand(1);
13409 bool isSigned = Node->getOpcode() == ISD::SMULO;
13410
13411 // For power-of-two multiplications we can use a simpler shift expansion.
13412 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13413 const APInt &C = RHSC->getAPIntValue();
13414 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13415 if (C.isPowerOf2()) {
13416 // smulo(x, signed_min) is same as umulo(x, signed_min).
13417 bool UseArithShift = isSigned && !C.isMinSignedValue();
13418 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13419 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13420 Overflow = DAG.getSetCC(dl, SetCCVT,
13421 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13422 dl, VT, Result, ShiftAmt),
13423 LHS, ISD::SETNE);
13424 return true;
13425 }
13426 }
13427
13428 SDValue BottomHalf;
13429 SDValue TopHalf;
13430 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13431
13432 static const unsigned Ops[2][3] =
13435 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13436 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13437 RHS);
13438 TopHalf = BottomHalf.getValue(1);
13439 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13440 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13441 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13442 } else if (isTypeLegal(WideVT)) {
13443 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13444 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13445 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13446 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13447 SDValue ShiftAmt =
13448 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13449 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13450 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13451 } else {
13452 if (VT.isVector())
13453 return false;
13454
13455 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13456 }
13457
13458 Result = BottomHalf;
13459 if (isSigned) {
13460 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13461 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13462 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13463 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13464 } else {
13465 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13466 DAG.getConstant(0, dl, VT), ISD::SETNE);
13467 }
13468
13469 // Truncate the result if SetCC returns a larger type than needed.
13470 EVT RType = Node->getValueType(1);
13471 if (RType.bitsLT(Overflow.getValueType()))
13472 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13473
13474 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13475 "Unexpected result type for S/UMULO legalization");
13476 return true;
13477}
13478
13480 SDLoc dl(Node);
13481 EVT VT = Node->getValueType(0);
13482 SDValue LHS = Node->getOperand(0);
13483 SDValue RHS = Node->getOperand(1);
13484 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13485
13486 // Use MUL_LOHI if legal/custom for the original type.
13487 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13488 if (isOperationLegalOrCustom(LoHiOp, VT))
13489 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13490
13491 // Use a wide multiply if available.
13492 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13493 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13494 unsigned BW = VT.getScalarSizeInBits();
13495 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13496 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13497 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13498 DAG.getNode(ISD::SRL, dl, WideVT,
13499 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13500 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13501 }
13502
13503 // Let fixed-length vectors be scalarised by the caller.
13504 // Expand everything else with a wide multiply.
13505 if (!VT.isFixedLengthVector()) {
13506 SDValue Lo, Hi;
13507 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13508 return Hi;
13509 }
13510
13511 return SDValue();
13512}
13513
13515 SDLoc dl(Node);
13516 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13517 SDValue Op = Node->getOperand(0);
13518 SDNodeFlags Flags = Node->getFlags();
13519 EVT VT = Op.getValueType();
13520
13521 // Try to use a shuffle reduction for power of two vectors.
13522 if (VT.isPow2VectorType()) {
13523 // See if the reduction opcode is safe to use with widened types.
13524 bool WidenSrc = false;
13525 switch (Node->getOpcode()) {
13528 case ISD::VECREDUCE_ADD:
13529 case ISD::VECREDUCE_MUL:
13530 case ISD::VECREDUCE_AND:
13531 case ISD::VECREDUCE_OR:
13532 case ISD::VECREDUCE_XOR:
13537 WidenSrc = VT.isFixedLengthVector();
13538 break;
13539 }
13540
13542 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13543 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13544 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13545 // Attempt to widen the source vectors to a legal op.
13546 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13547 if (WideVT.isVector() &&
13548 WideVT.getScalarType() == HalfVT.getScalarType() &&
13549 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13550 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13551 SDValue Lo, Hi;
13552 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13553 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13554 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13555 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13556 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13557 VT = HalfVT;
13558 continue;
13559 }
13560 }
13561 break;
13562 }
13563
13564 SDValue Lo, Hi;
13565 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13566 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13567 VT = HalfVT;
13568
13569 // Stop if splitting is enough to make the reduction legal.
13570 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13571 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13572 Flags);
13573 }
13574 }
13575
13576 if (VT.isScalableVector())
13578 "Expanding reductions for scalable vectors is undefined.");
13579
13580 EVT EltVT = VT.getVectorElementType();
13581 unsigned NumElts = VT.getVectorNumElements();
13582
13584 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13585
13586 SDValue Res = Ops[0];
13587 for (unsigned i = 1; i < NumElts; i++)
13588 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13589
13590 // Result type may be wider than element type.
13591 if (EltVT != Node->getValueType(0))
13592 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13593 return Res;
13594}
13595
13597 SDLoc dl(Node);
13598 SDValue AccOp = Node->getOperand(0);
13599 SDValue VecOp = Node->getOperand(1);
13600 SDNodeFlags Flags = Node->getFlags();
13601
13602 EVT VT = VecOp.getValueType();
13603 EVT EltVT = VT.getVectorElementType();
13604
13605 if (VT.isScalableVector())
13607 "Expanding reductions for scalable vectors is undefined.");
13608
13609 unsigned NumElts = VT.getVectorNumElements();
13610
13612 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13613
13614 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13615
13616 SDValue Res = AccOp;
13617 for (unsigned i = 0; i < NumElts; i++)
13618 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13619
13620 return Res;
13621}
13622
13624 SelectionDAG &DAG) const {
13625 EVT VT = Node->getValueType(0);
13626 SDLoc dl(Node);
13627 bool isSigned = Node->getOpcode() == ISD::SREM;
13628 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13629 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13630 SDValue Dividend = Node->getOperand(0);
13631 SDValue Divisor = Node->getOperand(1);
13632 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13633 SDVTList VTs = DAG.getVTList(VT, VT);
13634 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13635 return true;
13636 }
13637 if (isOperationLegalOrCustom(DivOpc, VT)) {
13638 // X % Y -> X-X/Y*Y
13639 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13640 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13641 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13642 return true;
13643 }
13644 return false;
13645}
13646
13648 SelectionDAG &DAG) const {
13649 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13650 SDLoc dl(SDValue(Node, 0));
13651 SDValue Src = Node->getOperand(0);
13652
13653 // DstVT is the result type, while SatVT is the size to which we saturate
13654 EVT SrcVT = Src.getValueType();
13655 EVT DstVT = Node->getValueType(0);
13656
13657 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13658 unsigned SatWidth = SatVT.getScalarSizeInBits();
13659 unsigned DstWidth = DstVT.getScalarSizeInBits();
13660 assert(SatWidth <= DstWidth &&
13661 "Expected saturation width smaller than result width");
13662
13663 // Determine minimum and maximum integer values and their corresponding
13664 // floating-point values.
13665 APInt MinInt, MaxInt;
13666 if (IsSigned) {
13667 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13668 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13669 } else {
13670 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13671 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13672 }
13673
13674 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13675 // libcall emission cannot handle this. Large result types will fail.
13676 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13677 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13678 SrcVT = Src.getValueType();
13679 }
13680
13681 const fltSemantics &Sem = SrcVT.getFltSemantics();
13682 APFloat MinFloat(Sem);
13683 APFloat MaxFloat(Sem);
13684
13685 APFloat::opStatus MinStatus =
13686 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13687 APFloat::opStatus MaxStatus =
13688 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13689 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13690 !(MaxStatus & APFloat::opStatus::opInexact);
13691
13692 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13693 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13694
13695 // If the integer bounds are exactly representable as floats and min/max are
13696 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13697 // of comparisons and selects.
13698 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13699 bool MayPropagateNaN) {
13700 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13701 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13702 if (!MinMaxLegal)
13703 return SDValue();
13704
13705 SDValue Clamped = Src;
13706
13707 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13708 // then the result is MinFloat.
13709 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13710 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13711 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13712 // Convert clamped value to integer.
13713 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13714 dl, DstVT, Clamped);
13715
13716 // If !MayPropagateNan and the conversion is unsigned case we're done,
13717 // because we mapped NaN to MinFloat, which will cast to zero.
13718 if (!MayPropagateNaN && !IsSigned)
13719 return FpToInt;
13720
13721 // Otherwise, select 0 if Src is NaN.
13722 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13723 EVT SetCCVT =
13724 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13725 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13726 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13727 };
13728 if (AreExactFloatBounds) {
13729 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13730 /*MayPropagateNaN=*/false))
13731 return Res;
13732 // These may propagate NaN for sNaN operands.
13733 if (SDValue Res =
13734 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13735 return Res;
13736 // These always propagate NaN.
13737 if (SDValue Res =
13738 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13739 return Res;
13740 }
13741
13742 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13743 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13744
13745 // Result of direct conversion. The assumption here is that the operation is
13746 // non-trapping and it's fine to apply it to an out-of-range value if we
13747 // select it away later.
13748 SDValue FpToInt =
13749 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13750
13751 SDValue Select = FpToInt;
13752
13753 EVT SetCCVT =
13754 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13755
13756 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13757 // MinInt if Src is NaN.
13758 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13759 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13760 // If Src OGT MaxFloat, select MaxInt.
13761 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13762 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13763
13764 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13765 // is already zero.
13766 if (!IsSigned)
13767 return Select;
13768
13769 // Otherwise, select 0 if Src is NaN.
13770 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13771 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13772 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13773}
13774
13776 const SDLoc &dl,
13777 SelectionDAG &DAG) const {
13778 EVT OperandVT = Op.getValueType();
13779 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13780 return Op;
13781 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13782 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13783 // can induce double-rounding which may alter the results. We can
13784 // correct for this using a trick explained in: Boldo, Sylvie, and
13785 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13786 // World Congress. 2005.
13787 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13788 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13789
13790 // We can keep the narrow value as-is if narrowing was exact (no
13791 // rounding error), the wide value was NaN (the narrow value is also
13792 // NaN and should be preserved) or if we rounded to the odd value.
13793 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13794 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13795 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13796 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13797 EVT ResultIntVTCCVT = getSetCCResultType(
13798 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13799 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13800 // The result is already odd so we don't need to do anything.
13801 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13802
13803 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13804 Op.getValueType());
13805 // We keep results which are exact, odd or NaN.
13806 SDValue KeepNarrow =
13807 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13808 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13809 // We morally performed a round-down if AbsNarrow is smaller than
13810 // AbsWide.
13811 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13812 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13813 SDValue NarrowIsRd =
13814 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13815 // If the narrow value is odd or exact, pick it.
13816 // Otherwise, narrow is even and corresponds to either the rounded-up
13817 // or rounded-down value. If narrow is the rounded-down value, we want
13818 // the rounded-up value as it will be odd.
13819 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13820 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13821 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13822 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13823}
13824
13826 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13827 SDValue Op = Node->getOperand(0);
13828 EVT VT = Node->getValueType(0);
13829 SDLoc dl(Node);
13830 if (VT.getScalarType() == MVT::bf16) {
13831 if (Node->getConstantOperandVal(1) == 1) {
13832 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13833 }
13834 EVT OperandVT = Op.getValueType();
13835 SDValue IsNaN = DAG.getSetCC(
13836 dl,
13837 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
13838 Op, Op, ISD::SETUO);
13839
13840 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13841 // can induce double-rounding which may alter the results. We can
13842 // correct for this using a trick explained in: Boldo, Sylvie, and
13843 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13844 // World Congress. 2005.
13845 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
13846 EVT I32 = F32.changeTypeToInteger();
13847 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
13848 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
13849
13850 // Conversions should set NaN's quiet bit. This also prevents NaNs from
13851 // turning into infinities.
13852 SDValue NaN =
13853 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
13854
13855 // Factor in the contribution of the low 16 bits.
13856 SDValue One = DAG.getConstant(1, dl, I32);
13857 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
13858 DAG.getShiftAmountConstant(16, I32, dl));
13859 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
13860 SDValue RoundingBias =
13861 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
13862 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
13863
13864 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
13865 // 0x80000000.
13866 Op = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
13867
13868 // Now that we have rounded, shift the bits into position.
13869 Op = DAG.getNode(ISD::SRL, dl, I32, Op,
13870 DAG.getShiftAmountConstant(16, I32, dl));
13871 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
13872 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
13873 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13874 }
13875 return SDValue();
13876}
13877
13880 SelectionDAG &DAG) const {
13881 assert(Node->getOpcode() == ISD::VECTOR_INTERLEAVE && "Unexpected opcode");
13882 EVT VT = Node->getValueType(0);
13883 unsigned Factor = Node->getNumOperands();
13884 SDLoc DL(Node);
13885
13886 if (Factor > 2 && Factor % 2 == 0) {
13887 SmallVector<EVT> HalfVTs(Factor / 2, VT);
13888 SmallVector<SDValue, 8> LOps, ROps;
13889 // Interleave so we have 2 factors per result:
13890 // a0a1 b0b1 c0c1 d0d1 -> [a0c0 b0d0] [a1c1 b1d1]
13891 for (unsigned I = 0; I < Factor / 2; I++) {
13892 SDValue Interleave =
13893 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, {VT, VT},
13894 {Node->getOperand(I), Node->getOperand(I + Factor / 2)});
13895 LOps.push_back(Interleave.getValue(0));
13896 ROps.push_back(Interleave.getValue(1));
13897 }
13898 // Interleave at Factor/2:
13899 // [a0c0 b0d0] [a1c1 b1d1] -> a0b0 c0d0 a1b1 c1d1
13900 SDValue L = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, LOps);
13901 SDValue R = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, ROps);
13902 for (unsigned I = 0; I < Factor / 2; I++)
13903 Results.push_back(L.getValue(I));
13904 for (unsigned I = 0; I < Factor / 2; I++)
13905 Results.push_back(R.getValue(I));
13906 return;
13907 }
13908
13909 if (!VT.isFixedLengthVector())
13910 return;
13911
13912 unsigned NumElts = VT.getVectorNumElements();
13913 EVT EltVT = VT.getVectorElementType();
13914
13915 // A factor of two needs only same-width, two-input shuffles.
13916 if (Factor == 2) {
13917 SmallVector<int, 8> Mask = createInterleaveMask(NumElts, Factor);
13918 for (unsigned I = 0; I != Factor; ++I)
13919 Results.push_back(DAG.getVectorShuffle(
13920 VT, DL, Node->getOperand(0), Node->getOperand(1),
13921 ArrayRef<int>(Mask).slice(I * NumElts, NumElts)));
13922 return;
13923 }
13924
13925 SmallVector<SDValue> InterleavedElts;
13926 InterleavedElts.reserve(Factor * NumElts);
13927 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
13928 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
13929 InterleavedElts.push_back(DAG.getExtractVectorElt(
13930 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
13931
13932 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx)
13933 Results.push_back(DAG.getBuildVector(
13934 VT, DL, ArrayRef(InterleavedElts).slice(ResultIdx * NumElts, NumElts)));
13935}
13936
13939 SelectionDAG &DAG) const {
13940 assert(Node->getOpcode() == ISD::VECTOR_DEINTERLEAVE && "Unexpected opcode");
13941 EVT VT = Node->getValueType(0);
13942 unsigned Factor = Node->getNumOperands();
13943 SDLoc DL(Node);
13944
13945 if (Factor > 2 && Factor % 2 == 0) {
13947 SmallVector<EVT> HalfVTs(Factor / 2, VT);
13948 // Deinterleave at Factor/2 so each result contains two factors interleaved:
13949 // a0b0 c0d0 a1b1 c1d1 -> [a0c0 b0d0] [a1c1 b1d1]
13950 SDValue L = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
13951 ArrayRef(Ops).take_front(Factor / 2));
13952 SDValue R = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
13953 ArrayRef(Ops).take_back(Factor / 2));
13954 Results.resize(Factor);
13955 // Deinterleave the 2 factors out:
13956 // [a0c0 a1c1] [b0d0 b1d1] -> a0a1 b0b1 c0c1 d0d1
13957 for (unsigned I = 0; I < Factor / 2; ++I) {
13959 {L.getValue(I), R.getValue(I)});
13960 Results[I] = Deinterleave.getValue(0);
13961 Results[I + Factor / 2] = Deinterleave.getValue(1);
13962 }
13963 return;
13964 }
13965
13966 if (!VT.isFixedLengthVector())
13967 return;
13968
13969 unsigned NumElts = VT.getVectorNumElements();
13970 EVT EltVT = VT.getVectorElementType();
13971
13972 // A factor of two needs only same-width, two-input shuffles.
13973 if (Factor == 2) {
13974 for (unsigned I = 0; I != Factor; ++I)
13975 Results.push_back(
13976 DAG.getVectorShuffle(VT, DL, Node->getOperand(0), Node->getOperand(1),
13977 createStrideMask(I, Factor, NumElts)));
13978 return;
13979 }
13980
13981 SmallVector<SDValue> ConcatElts;
13982 ConcatElts.reserve(Factor * NumElts);
13983 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
13984 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
13985 ConcatElts.push_back(DAG.getExtractVectorElt(
13986 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
13987
13988 SmallVector<SDValue> DeinterleavedElts;
13989 DeinterleavedElts.reserve(Factor * NumElts);
13990 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx) {
13991 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
13992 DeinterleavedElts.push_back(ConcatElts[ResultIdx + EltIdx * Factor]);
13993 Results.push_back(DAG.getBuildVector(
13994 VT, DL,
13995 ArrayRef(DeinterleavedElts).slice(ResultIdx * NumElts, NumElts)));
13996 }
13997}
13998
14000 SelectionDAG &DAG) const {
14001 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
14002 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
14003 "Unexpected opcode!");
14004 assert((Node->getValueType(0).isScalableVector() ||
14005 !isa<ConstantSDNode>(Node->getOperand(2))) &&
14006 "Fixed length vector types with constant offsets expected to use "
14007 "SHUFFLE_VECTOR!");
14008
14009 EVT VT = Node->getValueType(0);
14010 SDValue V1 = Node->getOperand(0);
14011 SDValue V2 = Node->getOperand(1);
14012 SDValue Offset = Node->getOperand(2);
14013 SDLoc DL(Node);
14014
14015 // Expand through memory thusly:
14016 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
14017 // Store V1, Ptr
14018 // Store V2, Ptr + sizeof(V1)
14019 // if (VECTOR_SPLICE_LEFT)
14020 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
14021 // else
14022 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
14023 // Res = Load Ptr
14024
14025 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
14026
14028 VT.getVectorElementCount() * 2);
14029 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
14030 EVT PtrVT = StackPtr.getValueType();
14031 auto &MF = DAG.getMachineFunction();
14032 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14033 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
14034
14035 // Store the lo part of CONCAT_VECTORS(V1, V2)
14036 SDValue StoreV1 =
14037 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
14038 // Store the hi part of CONCAT_VECTORS(V1, V2)
14039 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
14040 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
14041 SDValue StoreV2 =
14042 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
14043
14044 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
14045 SDValue EltByteSize =
14046 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
14047 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
14048 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
14049
14050 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
14051
14052 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
14053 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
14054 else
14055 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
14056
14057 // Load the spliced result
14058 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
14060}
14061
14063 SelectionDAG &DAG) const {
14064 SDLoc DL(Node);
14065 SDValue Vec = Node->getOperand(0);
14066 SDValue Mask = Node->getOperand(1);
14067 SDValue Passthru = Node->getOperand(2);
14068
14069 EVT VecVT = Vec.getValueType();
14070 EVT ScalarVT = VecVT.getScalarType();
14071 EVT MaskVT = Mask.getValueType();
14072 EVT MaskScalarVT = MaskVT.getScalarType();
14073
14074 // Needs to be handled by targets that have scalable vector types.
14075 if (VecVT.isScalableVector())
14076 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
14077
14078 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
14079 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
14080 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14081 MachinePointerInfo PtrInfo =
14083
14084 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
14085 SDValue Chain = DAG.getEntryNode();
14086 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
14087
14088 bool HasPassthru = !Passthru.isUndef();
14089
14090 // If we have a passthru vector, store it on the stack, overwrite the matching
14091 // positions and then re-write the last element that was potentially
14092 // overwritten even though mask[i] = false.
14093 if (HasPassthru)
14094 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
14095
14096 SDValue LastWriteVal;
14097 APInt PassthruSplatVal;
14098 bool IsSplatPassthru =
14099 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal);
14100
14101 if (IsSplatPassthru) {
14102 // As we do not know which position we wrote to last, we cannot simply
14103 // access that index from the passthru vector. So we first check if passthru
14104 // is a splat vector, to use any element ...
14105 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
14106 } else if (HasPassthru) {
14107 // ... if it is not a splat vector, we need to get the passthru value at
14108 // position = popcount(mask) and re-load it from the stack before it is
14109 // overwritten in the loop below.
14110 EVT PopcountVT = ScalarVT.changeTypeToInteger();
14111 SDValue Popcount = DAG.getNode(
14113 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
14114 Popcount = DAG.getNode(
14116 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
14117 Popcount);
14118 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
14119 SDValue LastElmtPtr =
14120 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
14121 LastWriteVal = DAG.getLoad(
14122 ScalarVT, DL, Chain, LastElmtPtr,
14124 Chain = LastWriteVal.getValue(1);
14125 }
14126
14127 unsigned NumElms = VecVT.getVectorNumElements();
14128 for (unsigned I = 0; I < NumElms; I++) {
14129 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
14130 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14131 Chain = DAG.getStore(
14132 Chain, DL, ValI, OutPtr,
14134
14135 // Get the mask value and add it to the current output position. This
14136 // either increments by 1 if MaskI is true or adds 0 otherwise.
14137 // Freeze in case we have poison/undef mask entries.
14138 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
14139 MaskI = DAG.getFreeze(MaskI);
14140 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
14141 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
14142 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
14143
14144 if (HasPassthru && I == NumElms - 1) {
14145 SDValue EndOfVector =
14146 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
14147 SDValue AllLanesSelected =
14148 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
14149 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
14150 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14151
14152 // Re-write the last ValI if all lanes were selected. Otherwise,
14153 // overwrite the last write it with the passthru value.
14154 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
14155 LastWriteVal, SDNodeFlags::Unpredictable);
14156 Chain = DAG.getStore(
14157 Chain, DL, LastWriteVal, OutPtr,
14159 }
14160 }
14161
14162 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
14163}
14164
14166 SDLoc DL(Node);
14167 EVT VT = Node->getValueType(0);
14168 SDValue Op = Node->getOperand(0);
14169 ElementCount EC = Op.getValueType().getVectorElementCount();
14170
14171 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
14172 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
14173
14174 // No legal step vector: split mask in half and recombine results.
14175 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
14176 // (== LoNumElts when no active lane), allowing the SETNE comparison.
14177 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
14178 if (!StepVec) {
14179 EVT ResVT = Node->getValueType(0);
14180 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
14181 SDValue LoNumElts = DAG.getElementCount(
14182 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
14183 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
14184 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
14185 SDValue ResLoNotNumElts = DAG.getSetCC(
14186 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
14187 ResLo, LoNumElts, ISD::SETNE);
14188 // Per LangRef, ResVT must be wide enough to hold the total element count,
14189 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
14190 // the count is only required to fit unsigned.
14191 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
14193 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
14194 }
14195
14196 EVT StepVecVT = StepVec.getValueType();
14197 EVT StepVT = StepVecVT.getVectorElementType();
14198
14199 // Promote the scalar result type early to avoid redundant zexts.
14201 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
14202
14203 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
14204 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
14205 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
14206 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
14207 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
14209 StepVecVT.getVectorElementType(), Select);
14210 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
14211 DAG.getZExtOrTrunc(Max, DL, StepVT));
14212
14213 return DAG.getZExtOrTrunc(Sub, DL, VT);
14214}
14215
14217 SDLoc DL(N);
14218 SDValue Source = N->getOperand(0);
14219 SDValue Needle = N->getOperand(1);
14220 SDValue Mask = N->getOperand(2);
14221 EVT SourceVT = Source.getValueType();
14222 EVT NeedleVT = Needle.getValueType();
14223 EVT ResVT = N->getValueType(0);
14224 EVT CmpVT =
14225 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
14226
14227 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
14228
14229 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
14230 EVT NeedleEltVT = NeedleVT.getVectorElementType();
14231 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
14232 SDValue Splat;
14233 if (NeedleVT == SourceVT) {
14234 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
14235 Splat = DAG.getVectorShuffle(
14236 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
14238 } else {
14239 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
14240 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
14241 }
14242 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
14243 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
14244 }
14245
14246 EVT UseVT = ResVT;
14247 // If the result is immediately truncated, only extend to that type (to avoid
14248 // unnecessary sign/zero extends).
14249 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
14250 UseVT = N->user_begin()->getValueType(0);
14251
14252 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
14253 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
14254
14255 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
14256 if (UseVT != ResVT)
14257 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
14258 return Ret;
14259}
14260
14262 SelectionDAG &DAG) const {
14263 SDLoc DL(N);
14264 SDValue Acc = N->getOperand(0);
14265 SDValue MulLHS = N->getOperand(1);
14266 SDValue MulRHS = N->getOperand(2);
14267 EVT AccVT = Acc.getValueType();
14268 EVT MulOpVT = MulLHS.getValueType();
14269
14270 EVT ExtMulOpVT =
14272 MulOpVT.getVectorElementCount());
14273
14274 unsigned ExtOpcLHS, ExtOpcRHS;
14275 switch (N->getOpcode()) {
14276 default:
14277 llvm_unreachable("Unexpected opcode");
14279 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
14280 break;
14282 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
14283 break;
14285 ExtOpcLHS = ISD::SIGN_EXTEND;
14286 ExtOpcRHS = ISD::ZERO_EXTEND;
14287 break;
14289 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
14290 break;
14291 }
14292
14293 // A wide partial reduction is built from a ladder of narrower ones, a rung
14294 // at a time, each halving the element count and doubling the width.
14295 unsigned Opc = N->getOpcode();
14296 ElementCount MulEC = MulOpVT.getVectorElementCount();
14297 ElementCount AccEC = AccVT.getVectorElementCount();
14298 unsigned CountRatio =
14299 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
14300 unsigned WidthRatio =
14301 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
14302 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
14303 LLVMContext &Ctx = *DAG.getContext();
14304 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
14305
14306 // A pure reduction peels one rung and re-enters.
14307 if (llvm::isOneOrOneSplat(MulRHS)) {
14308 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
14309 return DAG.getNode(Opc, DL, AccVT, Acc,
14310 DAG.getNode(Opc, DL, RungVT,
14311 DAG.getConstant(0, DL, RungVT), MulLHS,
14312 MulRHS),
14313 DAG.getConstant(1, DL, RungVT));
14314 }
14315
14316 // A multiply widens the products by one rung, which legalizes back into a
14317 // widening multiply per half, and the ladder re-enters as a plain sum.
14318 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
14319 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
14320 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
14321 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
14322 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
14323
14324 // The halves meet at the narrowest rung, so the accumulator is added once.
14325 EVT MidVT = Lo.getValueType()
14326 .widenIntegerVectorElementType(Ctx)
14327 .getHalfNumVectorElementsVT(Ctx);
14329 return DAG.getNode(Opc, DL, AccVT,
14330 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
14331 SDValue Mid =
14332 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
14333 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
14334 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
14335 }
14336
14337 if (ExtMulOpVT != MulOpVT) {
14338 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
14339 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
14340 }
14341 SDValue Input = MulLHS;
14342 // Maintain the FP flags (if any).
14343 SDNodeFlags Flags = N->getFlags();
14344 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
14345 if (!llvm::isOneOrOneSplatFP(MulRHS))
14346 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS, Flags);
14347 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
14348 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14349 }
14350
14351 unsigned Stride = AccVT.getVectorMinNumElements();
14352 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
14353
14354 // Collect all of the subvectors
14355 std::deque<SDValue> Subvectors = {Acc};
14356 for (unsigned I = 0; I < ScaleFactor; I++)
14357 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
14358
14359 unsigned FlatNode =
14360 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
14361
14362 // Flatten the subvector tree
14363 while (Subvectors.size() > 1) {
14364 Subvectors.push_back(DAG.getNode(FlatNode, DL, AccVT,
14365 {Subvectors[0], Subvectors[1]}, Flags));
14366 Subvectors.pop_front();
14367 Subvectors.pop_front();
14368 }
14369
14370 assert(Subvectors.size() == 1 &&
14371 "There should only be one subvector after tree flattening");
14372
14373 return Subvectors[0];
14374}
14375
14376/// Given a store node \p StoreNode, return true if it is safe to fold that node
14377/// into \p FPNode, which expands to a library call with output pointers.
14379 SDNode *FPNode) {
14381 SmallVector<const SDNode *, 8> DeferredNodes;
14383
14384 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
14385 for (SDValue Op : StoreNode->ops())
14386 if (Op.getNode() != FPNode)
14387 Worklist.push_back(Op.getNode());
14388
14390 while (!Worklist.empty()) {
14391 const SDNode *Node = Worklist.pop_back_val();
14392 auto [_, Inserted] = Visited.insert(Node);
14393 if (!Inserted)
14394 continue;
14395
14396 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
14397 return false;
14398
14399 // Reached the FPNode (would result in a cycle).
14400 // OR Reached CALLSEQ_START (would result in nested call sequences).
14401 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
14402 return false;
14403
14404 if (Node->getOpcode() == ISD::CALLSEQ_END) {
14405 // Defer looking into call sequences (so we can check we're outside one).
14406 // We still need to look through these for the predecessor check.
14407 DeferredNodes.push_back(Node);
14408 continue;
14409 }
14410
14411 for (SDValue Op : Node->ops())
14412 Worklist.push_back(Op.getNode());
14413 }
14414
14415 // True if we're outside a call sequence and don't have the FPNode as a
14416 // predecessor. No cycles or nested call sequences possible.
14417 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
14418 MaxSteps);
14419}
14420
14422 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
14424 std::optional<unsigned> CallRetResNo) const {
14425 if (LC == RTLIB::UNKNOWN_LIBCALL)
14426 return false;
14427
14428 RTLIB::LibcallImpl LibcallImpl =
14430 if (LibcallImpl == RTLIB::Unsupported)
14431 return false;
14432
14433 LLVMContext &Ctx = *DAG.getContext();
14434 EVT VT = Node->getValueType(0);
14435 unsigned NumResults = Node->getNumValues();
14436
14437 // Find users of the node that store the results (and share input chains). The
14438 // destination pointers can be used instead of creating stack allocations.
14439 SDValue StoresInChain;
14440 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
14441 for (SDNode *User : Node->users()) {
14443 continue;
14444 auto *ST = cast<StoreSDNode>(User);
14445 SDValue StoreValue = ST->getValue();
14446 unsigned ResNo = StoreValue.getResNo();
14447 // Ensure the store corresponds to an output pointer.
14448 if (CallRetResNo == ResNo)
14449 continue;
14450 // Ensure the store to the default address space and not atomic or volatile.
14451 if (!ST->isSimple() || ST->getAddressSpace() != 0)
14452 continue;
14453 // Ensure all store chains are the same (so they don't alias).
14454 if (StoresInChain && ST->getChain() != StoresInChain)
14455 continue;
14456 // Ensure the store is properly aligned.
14457 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
14458 if (ST->getAlign() <
14459 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
14460 continue;
14461 // Avoid:
14462 // 1. Creating cyclic dependencies.
14463 // 2. Expanding the node to a call within a call sequence.
14465 continue;
14466 ResultStores[ResNo] = ST;
14467 StoresInChain = ST->getChain();
14468 }
14469
14470 ArgListTy Args;
14471
14472 // Pass the arguments.
14473 for (const SDValue &Op : Node->op_values()) {
14474 EVT ArgVT = Op.getValueType();
14475 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
14476 Args.emplace_back(Op, ArgTy);
14477 }
14478
14479 // Pass the output pointers.
14480 SmallVector<SDValue, 2> ResultPtrs(NumResults);
14482 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
14483 if (ResNo == CallRetResNo)
14484 continue;
14485 EVT ResVT = Node->getValueType(ResNo);
14486 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
14487 ResultPtrs[ResNo] = ResultPtr;
14488 Args.emplace_back(ResultPtr, PointerTy);
14489 }
14490
14491 SDLoc DL(Node);
14492
14494 // Pass the vector mask (if required).
14495 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
14496 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
14497 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14498 }
14499
14500 Type *RetType = CallRetResNo.has_value()
14501 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14502 : Type::getVoidTy(Ctx);
14503 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14504 SDValue Callee =
14505 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14507 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14508 getLibcallImplCallingConv(LibcallImpl), RetType, Callee, std::move(Args));
14509
14510 auto [Call, CallChain] = LowerCallTo(CLI);
14511
14512 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14513 if (ResNo == CallRetResNo) {
14514 Results.push_back(Call);
14515 continue;
14516 }
14517 MachinePointerInfo PtrInfo;
14518 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14519 ResultPtr, PtrInfo);
14520 SDValue OutChain = LoadResult.getValue(1);
14521
14522 if (StoreSDNode *ST = ResultStores[ResNo]) {
14523 // Replace store with the library call.
14524 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14525 PtrInfo = ST->getPointerInfo();
14526 } else {
14528 DAG.getMachineFunction(),
14529 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14530 }
14531
14532 Results.push_back(LoadResult);
14533 }
14534
14535 return true;
14536}
14537
14539 SDValue &LHS, SDValue &RHS,
14540 SDValue &CC, bool &NeedInvert,
14541 const SDLoc &dl, SDValue &Chain,
14542 bool IsSignaling) const {
14543 MVT OpVT = LHS.getSimpleValueType();
14544 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14545 NeedInvert = false;
14546 switch (getCondCodeAction(CCCode, OpVT)) {
14547 default:
14548 llvm_unreachable("Unknown condition code action!");
14550 // Nothing to do.
14551 break;
14554 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14555 std::swap(LHS, RHS);
14556 CC = DAG.getCondCode(InvCC);
14557 return true;
14558 }
14559 // Swapping operands didn't work. Try inverting the condition.
14560 bool NeedSwap = false;
14561 InvCC = getSetCCInverse(CCCode, OpVT);
14562 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14563 // If inverting the condition is not enough, try swapping operands
14564 // on top of it.
14565 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14566 NeedSwap = true;
14567 }
14568 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14569 CC = DAG.getCondCode(InvCC);
14570 NeedInvert = true;
14571 if (NeedSwap)
14572 std::swap(LHS, RHS);
14573 return true;
14574 }
14575
14576 // Special case: expand i1 comparisons using logical operations.
14577 if (OpVT == MVT::i1) {
14578 SDValue Ret;
14579 switch (CCCode) {
14580 default:
14581 llvm_unreachable("Unknown integer setcc!");
14582 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14583 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14584 MVT::i1);
14585 break;
14586 case ISD::SETNE: // X != Y --> (X ^ Y)
14587 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14588 break;
14589 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14590 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14591 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14592 DAG.getNOT(dl, LHS, MVT::i1));
14593 break;
14594 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14595 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14596 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14597 DAG.getNOT(dl, RHS, MVT::i1));
14598 break;
14599 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14600 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14601 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14602 DAG.getNOT(dl, LHS, MVT::i1));
14603 break;
14604 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14605 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14606 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14607 DAG.getNOT(dl, RHS, MVT::i1));
14608 break;
14609 }
14610
14611 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14612 RHS = SDValue();
14613 CC = SDValue();
14614 return true;
14615 }
14616
14618 unsigned Opc = 0;
14619 switch (CCCode) {
14620 default:
14621 llvm_unreachable("Don't know how to expand this condition!");
14622 case ISD::SETUO:
14623 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14624 CC1 = ISD::SETUNE;
14625 CC2 = ISD::SETUNE;
14626 Opc = ISD::OR;
14627 break;
14628 }
14630 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14631 NeedInvert = true;
14632 [[fallthrough]];
14633 case ISD::SETO:
14635 "If SETO is expanded, SETOEQ must be legal!");
14636 CC1 = ISD::SETOEQ;
14637 CC2 = ISD::SETOEQ;
14638 Opc = ISD::AND;
14639 break;
14640 case ISD::SETONE:
14641 case ISD::SETUEQ:
14642 // If the SETUO or SETO CC isn't legal, we might be able to use
14643 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14644 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14645 // the operands.
14646 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14647 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14648 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14649 CC1 = ISD::SETOGT;
14650 CC2 = ISD::SETOLT;
14651 Opc = ISD::OR;
14652 NeedInvert = ((unsigned)CCCode & 0x8U);
14653 break;
14654 }
14655 [[fallthrough]];
14656 case ISD::SETOEQ:
14657 case ISD::SETOGT:
14658 case ISD::SETOGE:
14659 case ISD::SETOLT:
14660 case ISD::SETOLE:
14661 case ISD::SETUNE:
14662 case ISD::SETUGT:
14663 case ISD::SETUGE:
14664 case ISD::SETULT:
14665 case ISD::SETULE:
14666 // If we are floating point, assign and break, otherwise fall through.
14667 if (!OpVT.isInteger()) {
14668 // We can use the 4th bit to tell if we are the unordered
14669 // or ordered version of the opcode.
14670 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14671 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14672 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14673 break;
14674 }
14675 // Fallthrough if we are unsigned integer.
14676 [[fallthrough]];
14677 case ISD::SETLE:
14678 case ISD::SETGT:
14679 case ISD::SETGE:
14680 case ISD::SETLT:
14681 case ISD::SETNE:
14682 case ISD::SETEQ:
14683 // If all combinations of inverting the condition and swapping operands
14684 // didn't work then we have no means to expand the condition.
14685 llvm_unreachable("Don't know how to expand this condition!");
14686 }
14687
14688 SDValue SetCC1, SetCC2;
14689 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14690 // If we aren't the ordered or unorder operation,
14691 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14692 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14693 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14694 } else {
14695 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14696 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14697 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14698 }
14699 if (Chain)
14700 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14701 SetCC2.getValue(1));
14702 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14703 RHS = SDValue();
14704 CC = SDValue();
14705 return true;
14706 }
14707 }
14708 return false;
14709}
14710
14712 SelectionDAG &DAG) const {
14713 EVT VT = Node->getValueType(0);
14714 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14715 // split into two equal parts.
14716 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14717 return SDValue();
14718
14719 // Restrict expansion to cases where both parts can be concatenated.
14720 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14721 if (LoVT != HiVT || !isTypeLegal(LoVT))
14722 return SDValue();
14723
14724 SDLoc DL(Node);
14725 unsigned Opcode = Node->getOpcode();
14726
14727 // Don't expand if the result is likely to be unrolled anyway.
14728 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14729 return SDValue();
14730
14731 SmallVector<SDValue, 4> LoOps, HiOps;
14732 for (const SDValue &V : Node->op_values()) {
14733 if (!V.getValueType().isVector()) {
14734 // Scalar operands pass through to both halves unchanged.
14735 LoOps.push_back(V);
14736 HiOps.push_back(V);
14737 continue;
14738 }
14739 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14740 LoOps.push_back(Lo);
14741 HiOps.push_back(Hi);
14742 }
14743
14744 bool IsStrict = Node->isStrictFPOpcode();
14745 SDVTList LoVTs =
14746 IsStrict ? DAG.getVTList(LoVT, MVT::Other) : DAG.getVTList(LoVT);
14747 SDVTList HiVTs =
14748 IsStrict ? DAG.getVTList(HiVT, MVT::Other) : DAG.getVTList(HiVT);
14749 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVTs, LoOps, Node->getFlags());
14750 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVTs, HiOps, Node->getFlags());
14751 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14752
14753 if (!IsStrict)
14754 return Res;
14755
14756 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14757 SplitOpLo.getValue(1), SplitOpHi.getValue(1));
14758 return DAG.getMergeValues({Res, Chain}, DL);
14759}
14760
14762 const SDLoc &DL,
14763 EVT InVecVT, SDValue EltNo,
14764 LoadSDNode *OriginalLoad,
14765 SelectionDAG &DAG) const {
14766 assert(OriginalLoad->isSimple());
14767
14768 EVT VecEltVT = InVecVT.getVectorElementType();
14769
14770 // If the vector element type is not a multiple of a byte then we are unable
14771 // to correctly compute an address to load only the extracted element as a
14772 // scalar.
14773 if (!VecEltVT.isByteSized())
14774 return SDValue();
14775
14776 ISD::LoadExtType ExtTy =
14777 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14778 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14779 return SDValue();
14780
14781 std::optional<unsigned> ByteOffset;
14782 Align Alignment = OriginalLoad->getAlign();
14784 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14785 int Elt = ConstEltNo->getZExtValue();
14786 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14787 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14788 Alignment = commonAlignment(Alignment, *ByteOffset);
14789 } else {
14790 // Discard the pointer info except the address space because the memory
14791 // operand can't represent this new access since the offset is variable.
14792 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14793 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14794 }
14795
14796 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14797 return SDValue();
14798
14799 unsigned IsFast = 0;
14800 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14801 OriginalLoad->getAddressSpace(), Alignment,
14802 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14803 !IsFast)
14804 return SDValue();
14805
14806 // The original DAG loaded the entire vector from memory, so arithmetic
14807 // within it must be inbounds.
14809 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
14810
14811 // We are replacing a vector load with a scalar load. The new load must have
14812 // identical memory op ordering to the original.
14813 SDValue Load;
14814 if (ResultVT.bitsGT(VecEltVT)) {
14815 // If the result type of vextract is wider than the load, then issue an
14816 // extending load instead.
14817 ISD::LoadExtType ExtType =
14818 isLoadLegal(ResultVT, VecEltVT, Alignment,
14819 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
14821 : ISD::EXTLOAD;
14822 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
14823 NewPtr, MPI, VecEltVT, Alignment,
14824 OriginalLoad->getMemOperand()->getFlags(),
14825 OriginalLoad->getMMOMetadataForSubAccess());
14826 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14827 } else {
14828 // The result type is narrower or the same width as the vector element
14829 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
14830 Alignment, OriginalLoad->getMemOperand()->getFlags(),
14831 OriginalLoad->getMMOMetadataForSubAccess());
14832 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14833 if (ResultVT.bitsLT(VecEltVT))
14834 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
14835 else
14836 Load = DAG.getBitcast(ResultVT, Load);
14837 }
14838
14839 return Load;
14840}
14841
14842// Set type id for call site info and metadata 'call_target'.
14843// We are filtering for:
14844// a) The call-graph-section use case that wants to know about indirect
14845// calls, or
14846// b) We want to annotate indirect calls.
14848 const CallBase *CB, MachineFunction &MF,
14849 MachineFunction::CallSiteInfo &CSInfo) const {
14850 if (CB && CB->isIndirectCall() &&
14853 CSInfo = MachineFunction::CallSiteInfo(*CB);
14854}
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 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 unsigned getConstraintPiority(TargetLowering::ConstraintType CT)
Return a number indicating our preference for chosing a type of constraint over another,...
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:135
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:342
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:363
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:398
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:338
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:334
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:375
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.
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
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...
unsigned getBitWidthForCttzElements(EVT RetVT, ElementCount EC, bool ZeroIsPoison, const ConstantRange *VScaleRange) const
Return the minimum number of bits required to hold the maximum possible number of trailing zero vecto...
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 isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
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.
const LibcallLoweringInfo & getLibcallLoweringInfo() const
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...
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall implementation.
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 unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const
Return the maximum number of "x & (x - 1)" operations that can be done instead of deferring to a cust...
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.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Get the libcall impl routine name for the specified libcall.
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:712
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
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:1558
@ 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:1540
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:1727
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:267
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:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
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:129
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
EVT getDoubleNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:494
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:266
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
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:453
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:501
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:435
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:339
std::string getEVTString() const
This function returns value type as a string, e.g. "i32".
Definition ValueTypes.h:524
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:404
EVT widenIntegerVectorElementType(LLVMContext &Context) const
Return a VT for an integer vector type with the size of the elements doubled.
Definition ValueTypes.h:475
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:210
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:279
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:467
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
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:121
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
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:359
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:484
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
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