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.
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 &&
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
9387 SDLoc DL(Node);
9388 EVT VT = Node->getValueType(0);
9389 SDValue Val = Node->getOperand(0);
9390 SDValue Msk = Node->getOperand(1);
9391 unsigned BW = VT.getScalarSizeInBits();
9392
9393 // Just scalarize if scalar PEXT is legal
9395 return DAG.UnrollVectorOp(Node);
9396
9397 // Hacker's Delight §7-4: Compress, or Generalized Extract
9398 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9399 SDValue M = Msk;
9400 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9401 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9402
9403 // Repeatedly compute which bits would shift to the right by an odd amount,
9404 // shift all such bits in parallel using a mask, and double the shift amount.
9405 for (unsigned I = 1; I < BW; I *= 2) {
9406 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9407 SDValue Mp =
9408 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9409 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9410 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9411 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9412 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9414 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9415 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9416 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9418 if (I * 2 < BW)
9419 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9420 }
9421
9422 return X;
9423}
9424
9426 SDLoc DL(Node);
9427 EVT VT = Node->getValueType(0);
9428 SDValue Val = Node->getOperand(0);
9429 SDValue Msk = Node->getOperand(1);
9430 unsigned BW = VT.getScalarSizeInBits();
9431
9432 // Just scalarize if scalar PDEP is legal
9434 return DAG.UnrollVectorOp(Node);
9435
9436 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9437 unsigned LogBW = Log2_32_Ceil(BW);
9438 SmallVector<SDValue, 8> MvArray(LogBW);
9439 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9440 SDValue Mc = Msk;
9441 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9442
9443 // First pass: compute move masks for each power of two that a bit moves by.
9444 for (unsigned S = 0; S < LogBW; ++S) {
9445 unsigned ShiftS = 1u << S;
9446 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9447 SDValue Mp =
9448 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9449 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9450 MvArray[S] = Mv;
9451 if (S + 1 < LogBW) {
9452 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9453 SDValue MvShifted = DAG.getNode(
9454 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9455 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9457 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9458 }
9459 }
9460
9461 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9462 // Each pass handles half the shift amount of the previous pass.
9463 SDValue X = Val;
9464 for (int S = (int)LogBW - 1; S >= 0; --S) {
9465 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9466 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9467 SDValue UnshiftedBits =
9468 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9469 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9470 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9472 }
9473
9474 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9475}
9476
9478 SelectionDAG &DAG) const {
9479 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9480 EVT VT = Node->getValueType(0);
9481 unsigned VTBits = VT.getScalarSizeInBits();
9482 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9483
9484 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9485 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9486 SDValue ShOpLo = Node->getOperand(0);
9487 SDValue ShOpHi = Node->getOperand(1);
9488 SDValue ShAmt = Node->getOperand(2);
9489 EVT ShAmtVT = ShAmt.getValueType();
9490 EVT ShAmtCCVT =
9491 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9492 SDLoc dl(Node);
9493
9494 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9495 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9496 // away during isel.
9497 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9498 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9499 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9500 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9501 : DAG.getConstant(0, dl, VT);
9502
9503 SDValue Tmp2, Tmp3;
9504 if (IsSHL) {
9505 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9506 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9507 } else {
9508 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9509 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9510 }
9511
9512 // If the shift amount is larger or equal than the width of a part we don't
9513 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9514 // values for large shift amounts.
9515 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9516 DAG.getConstant(VTBits, dl, ShAmtVT));
9517 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9518 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9519
9520 if (IsSHL) {
9521 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9522 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9523 } else {
9524 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9525 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9526 }
9527}
9528
9530 SelectionDAG &DAG) const {
9531 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9532 // suggested in
9533 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9534 // It uses strict_fp operations even outside a strict_fp context in order
9535 // to guarantee that the canonicalization is not optimized away by later
9536 // passes. The result chain introduced by that is intentionally ignored
9537 // since no ordering requirement is intended here.
9538 EVT VT = Node->getValueType(0);
9539 SDLoc DL(Node);
9540 SDNodeFlags Flags = Node->getFlags();
9541 Flags.setNoFPExcept(true);
9542 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9543 SDValue Mul =
9544 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9545 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9546 return Mul;
9547}
9548
9550 SelectionDAG &DAG) const {
9551 // Expand conversion from a native IEEE float type to an arbitrary FP format
9552 // returning the result as an integer using bit manipulation.
9553 EVT ResVT = Node->getValueType(0);
9554 SDLoc dl(Node);
9555
9556 SDValue FloatVal = Node->getOperand(0);
9557 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9558 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9559 const auto RoundMode =
9560 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9561 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9562
9563 // Supported destination formats.
9564 switch (Sem) {
9571 break;
9572 default:
9573 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9574 "destination format (semantics enum " +
9575 Twine(SemEnum) + ")");
9576 return SDValue();
9577 }
9578
9579 // Supported rounding modes.
9580 switch (RoundMode) {
9586 break;
9587 default:
9588 DAG.getContext()->emitError(
9589 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9590 Twine(static_cast<int>(RoundMode)) + ")");
9591 return SDValue();
9592 }
9593
9594 // Destination format parameters.
9595 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9596 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9597 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9598 const unsigned DstMant = DstPrecision - 1;
9599 // Unsigned formats spend no bit on the sign.
9600 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9601 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9602 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9603 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9604 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9605 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9606 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9607
9608 // Compute the maximum normal exponent for the destination format.
9609 const unsigned DstExpMaxNormal =
9610 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9611 : DstExpMax;
9612
9613 // For NanOnly formats the max exponent field for finite values
9614 // is DstExpMax, but the encoding with exp = DstExpMax and
9615 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9616 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9617 // avoid the NaN encoding.
9618 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9619 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9620 DstNanEnc == fltNanEncoding::AllOnes)
9621 DstMaxMantAtMaxExp = DstMantMask - 1;
9622
9623 // Source format parameters.
9624 EVT SrcVT = FloatVal.getValueType();
9625 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9626 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9627 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9628 const unsigned SrcMant = SrcPrecision - 1;
9629 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9630
9631 // Work in the source integer type. Match the destination shape so the
9632 // expansion stays vector when ResVT is a vector.
9633 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9634 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9635 EVT SetCCVT =
9636 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9637 EVT FPSetCCVT =
9638 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9639
9640 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9641 SDValue One = DAG.getConstant(1, dl, IntVT);
9642
9643 // Bitcast source float to integer to extract the sign bit.
9644 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9645 SDValue SignBit =
9646 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9647 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9648
9649 // Classify the input.
9650 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9651 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9652 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9653 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9654 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9655 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9656
9657 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9658 // source denormals automatically. The result is unspecified for Inf/NaN, but
9659 // those inputs are detected above and override the final result.
9660 EVT FrexpExpScalarVT =
9662 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9663 SDValue Frexp =
9664 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9665 SDValue FrexpFrac = Frexp.getValue(0);
9666 SDValue FrexpExp = Frexp.getValue(1);
9667
9668 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9669 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9670 DAG.getConstant(SrcMantMask, dl, IntVT));
9671
9672 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9673 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9674 DAG.getConstant(DstBias - 1, dl, IntVT));
9675
9676 // Compute rounding increment given the round bit, sticky bits, and LSB
9677 // of the truncated mantissa.
9678 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9679 SDValue LSB) -> SDValue {
9680 switch (RoundMode) {
9682 // Round up if round_bit && (sticky || lsb)
9683 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9684 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9685 }
9687 return Zero;
9689 // Round up if positive and any truncated bits are set.
9690 SDValue AnyTruncBits =
9691 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9692 SDValue HasTruncBits =
9693 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9694 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9695 SDValue DoRound =
9696 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9697 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9698 }
9700 // Round up if negative and any truncated bits are set (to -Inf).
9701 SDValue AnyTruncBits =
9702 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9703 SDValue HasTruncBits =
9704 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9705 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9706 SDValue DoRound =
9707 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9708 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9709 }
9711 return RoundBit;
9712 default:
9713 llvm_unreachable("unsupported rounding mode");
9714 }
9715 };
9716
9717 // Round mantissa from SrcMant bits to DstMant bits.
9718 SDValue TruncMant;
9719 SDValue RoundUp;
9720 if (SrcMant > DstMant) {
9721 const unsigned Shift = SrcMant - DstMant;
9722 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9723 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9724
9725 // Check bit at position Shift - 1 aka the round bit.
9726 SDValue RoundBit;
9727 if (Shift >= 1) {
9728 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9729 SDValue ShiftedMant =
9730 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9731 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9732 } else {
9733 RoundBit = Zero;
9734 }
9735
9736 // OR of all bits below the round bit to get sticky bits.
9737 SDValue StickyBits;
9738 if (Shift >= 2) {
9739 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9740 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9741 DAG.getConstant(StickyMask, dl, IntVT));
9742 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9743 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9744 } else {
9745 StickyBits = Zero;
9746 }
9747
9748 // LSB of truncated mantissa.
9749 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9750
9751 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9752 } else {
9753 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9754 SDValue MantShift =
9755 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9756 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9757 RoundUp = Zero;
9758 }
9759
9760 // Apply rounding.
9761 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9762
9763 // Handle mantissa overflow from rounding.
9764 // If rounded_mant > DstMantMask, carry into exponent.
9765 SDValue MantOverflow =
9766 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9767 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9768 // On overflow: mant = 0, exp += 1.
9769 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9770 SDValue AdjExp =
9771 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9772 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9773
9774 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9775 // sign bit to merge in.
9776 SDValue SignShifted =
9777 DstHasSign
9778 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9779 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9780 : Zero;
9781
9782 // Destination denormal conversion (when new_exp <= 0).
9783 // Shift the mantissa right by 1 - new_exp additional bits and set the
9784 // exponent field to 0.
9785 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9786 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9787
9788 SDValue DenormResult;
9789 {
9790 // denorm_shift = 1 - NewExp.
9791 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9792
9793 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9794 SDValue ImplicitOne =
9795 DAG.getNode(ISD::SHL, dl, IntVT, One,
9796 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9797 SDValue FullSrcMant =
9798 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9799
9800 // Total right shift = DenormShift + (SrcMant - DstMant).
9801 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9802 SDValue TotalShift =
9803 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9804 DAG.getSignedConstant(MantDelta, dl, IntVT));
9805
9806 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9807 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9808 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9809 SDValue ClampedShift =
9810 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9811 SDValue DenormTruncMant =
9812 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9813 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9814
9815 // Rounding for denorm path.
9816 SDValue DenormRoundUp;
9817 {
9818 // Round bit is at position TotalShift - 1 of FullSrcMant.
9819 // Clamp to at least 1 so the subtraction doesn't underflow and create
9820 // shift nodes with invalid shift amounts.
9821 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
9822 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
9823 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
9824 SDValue DenormRoundBit = DAG.getNode(
9825 ISD::AND, dl, IntVT,
9826 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
9827
9828 // Sticky: all bits below round bit.
9829 // sticky_mask = (1 << RoundBitPos) - 1
9830 SDValue StickyMask = DAG.getNode(
9831 ISD::SUB, dl, IntVT,
9832 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
9833 SDValue DenormStickyBits =
9834 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
9835 SDValue HasSticky = DAG.getNode(
9836 ISD::ZERO_EXTEND, dl, IntVT,
9837 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
9838
9839 SDValue DenormLSB =
9840 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
9841
9842 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
9843
9844 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
9845 SDValue ShiftGEOne =
9846 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
9847 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
9848 }
9849
9850 SDValue DenormRoundedMant =
9851 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
9852
9853 // If rounding caused overflow into the normal range, then we get the
9854 // smallest normal number.
9855 SDValue DenormMantOF =
9856 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
9857 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9858 SDValue DenormFinalMant =
9859 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
9860 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
9861
9862 // Assemble: sign | (exp << DstMant) | mant
9863 SDValue DenormExpShifted =
9864 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
9865 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9866 DenormResult = DAG.getNode(
9867 ISD::OR, dl, IntVT,
9868 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
9869 DenormFinalMant);
9870 }
9871
9872 // Exponent overflow detection.
9873 SDValue ExpOF =
9874 DAG.getSetCC(dl, SetCCVT, AdjExp,
9875 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
9876
9877 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
9878 // a value that exceeds the max allowed mantissa at that exponent.
9879 SDValue ExpAtMax =
9880 DAG.getSetCC(dl, SetCCVT, AdjExp,
9881 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
9882 SDValue MantExceedsMax =
9883 DAG.getSetCC(dl, SetCCVT, AdjMant,
9884 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
9885 SDValue ExpMantOF =
9886 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
9887 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
9888
9889 // Build overflow result.
9891
9892 if (Saturate) {
9893 // Clamp to max finite value:
9894 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
9895 uint64_t MaxFinite =
9896 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9897 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9898 DAG.getConstant(MaxFinite, dl, IntVT));
9899 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9900 // Produce infinity.
9901 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9902 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9903 DAG.getConstant(InfBits, dl, IntVT));
9904 } else {
9905 // Emit poison if no Inf in format and not saturating.
9906 OverflowResult = DAG.getPOISON(IntVT);
9907 }
9908
9909 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
9910 SDValue NormExpShifted =
9911 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
9912 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9913 SDValue NormResult = DAG.getNode(
9914 ISD::OR, dl, IntVT,
9915 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
9916
9917 // Build special-value results.
9918 SDValue NaNResult;
9919 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9920 // Produce canonical NaN.
9921 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
9922 NaNResult =
9923 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
9924 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9925 DstNanEnc == fltNanEncoding::AllOnes) {
9926 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
9927 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
9928 dl, IntVT);
9929 } else {
9930 // NaN -> poison for finite only values.
9931 NaNResult = DAG.getPOISON(IntVT);
9932 }
9933
9934 // Inf handling.
9935 SDValue InfResult;
9936 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9937 // Produce signed infinity.
9938 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9939 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9940 DAG.getConstant(InfBits, dl, IntVT));
9941 } else if (Saturate) {
9942 // Inf saturates to max finite.
9943 uint64_t MaxFinite =
9944 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9945 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9946 DAG.getConstant(MaxFinite, dl, IntVT));
9947 } else {
9948 // No Inf and not saturating -> poison.
9949 InfResult = DAG.getPOISON(IntVT);
9950 }
9951
9952 SDValue ZeroResult = SignShifted;
9953
9954 // Final selection in an order: NaN takes priority, then Inf, then Zero.
9955 SDValue FiniteResult =
9956 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
9957 FiniteResult =
9958 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
9959
9960 SDValue Result = FiniteResult;
9961 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
9962 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
9963
9964 // Negative values are unrepresentable in an unsigned format: clamp to zero
9965 // when saturating, poison otherwise so no select is needed. -0.0 is handled
9966 // by IsZero above. Run before the NaN case so a negative NaN still yields
9967 // NaN.
9968 if (!DstHasSign && Saturate) {
9969 SDValue IsNegative =
9970 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
9971 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
9972 }
9973
9974 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
9975
9976 // Truncate to destination integer type.
9977 return DAG.getZExtOrTrunc(Result, dl, ResVT);
9978}
9979
9980SDValue
9982 SelectionDAG &DAG) const {
9983 SDLoc dl(Node);
9984 EVT DstVT = Node->getValueType(0);
9985 EVT DstScalarVT = DstVT.getScalarType();
9986
9987 SDValue IntVal = Node->getOperand(0);
9988 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9989 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9990
9991 // Supported source formats.
9992 switch (Sem) {
9999 break;
10000 default:
10001 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
10002 "source format (semantics enum " +
10003 Twine(SemEnum) + ")");
10004 return SDValue();
10005 }
10006
10007 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
10008 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
10009 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
10010 const unsigned SrcMant = SrcPrecision - 1;
10011 // Unsigned formats spend no bit on the sign.
10012 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
10013 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
10014 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
10015 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
10016
10017 // Destination format parameters.
10018 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
10019 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
10020 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
10021 const unsigned DstExpBits = DstBits - DstMant - 1;
10022 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
10023 const int DstBias = 1 - DstMinExp;
10024 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
10025
10026 // Work in an integer type matching the destination float width.
10027 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
10028 EVT IntVT = IntScalarVT;
10029 if (DstVT.isVector()) {
10030 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
10031 DstVT.getVectorElementCount());
10032 } else if (!isTypeLegal(IntScalarVT)) {
10033 // Avoid generating illegal type as there is no other places that'll
10034 // legalize it. Vector types don't have this problem because they
10035 // are subject to LegalizeVectorOps and another type legalization phase
10036 // will follow.
10037 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
10038 // We only know how to handle situations where the legal type is wider.
10039 DAG.getContext()->emitError(
10040 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
10041 "legalization is not supported");
10042 return SDValue();
10043 }
10044 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
10045 }
10046
10047 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
10048
10049 EVT SetCCVT =
10050 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
10051
10052 SDValue Zero = DAG.getConstant(0, dl, IntVT);
10053 SDValue One = DAG.getConstant(1, dl, IntVT);
10054
10055 // Extract bit fields.
10056 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
10057 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
10058
10059 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
10060 DAG.getConstant(MantMask, dl, IntVT));
10061
10062 SDValue ExpField =
10063 DAG.getNode(ISD::AND, dl, IntVT,
10064 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10065 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
10066 DAG.getConstant(ExpMask, dl, IntVT));
10067
10068 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
10069 // exponent.
10070 SDValue SignShifted =
10071 SrcHasSign
10072 ? DAG.getNode(
10073 ISD::SHL, dl, IntVT,
10074 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10075 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
10076 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
10077 : Zero;
10078
10079 // Classify the input.
10080 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
10081 SDValue IsExpAllOnes =
10082 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
10083 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
10084 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
10085 SDValue IsMantNonZero =
10086 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
10087
10088 SDValue IsNaN;
10089 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
10090 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10091 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
10092 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
10093 } else {
10095 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
10096 SDValue IsMantAllOnes =
10097 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
10098 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
10099 }
10100
10101 SDValue IsInf;
10102 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
10103 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
10104 else
10105 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10106
10107 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
10108 SDValue IsDenorm =
10109 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
10110
10111 // Normal value conversion.
10112 const int BiasAdjust = DstBias - SrcBias;
10113 SDValue NormDstExp = DAG.getNode(
10114 ISD::ADD, dl, IntVT, ExpField,
10115 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
10116 IntVT));
10117
10118 SDValue NormDstMant;
10119 if (DstMant > SrcMant) {
10120 SDValue NormDstMantShift =
10121 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
10122 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
10123 } else {
10124 NormDstMant = MantField;
10125 }
10126
10127 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
10128 SDValue NormExpShifted =
10129 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
10130 SDValue NormResult =
10131 DAG.getNode(ISD::OR, dl, IntVT,
10132 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
10133 NormDstMant);
10134
10135 // With identical exponent biases, denormal values remain denormal and the
10136 // normal conversion's mantissa shift is sufficient.
10137 SDValue DenormResult = NormResult;
10138 if (BiasAdjust != 0) {
10139 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
10140 SDValue LeadingZeros =
10141 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
10142
10143 const int DenormExpConst =
10144 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
10145 SDValue DenormDstExp = DAG.getNode(
10146 ISD::SUB, dl, IntVT,
10147 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
10148 LeadingZeros);
10149
10150 SDValue MantMSB =
10151 DAG.getNode(ISD::SUB, dl, IntVT,
10152 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
10153
10154 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
10155 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
10156
10157 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
10158 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
10159 DAG.getConstant(ShiftSub, dl, IntVT));
10160
10161 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
10162
10163 SDValue DenormExpShifted =
10164 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
10165 DenormResult = DAG.getNode(
10166 ISD::OR, dl, IntVT,
10167 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10168 DenormDstMant);
10169 }
10170
10171 SDValue FiniteResult =
10172 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
10173
10174 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10175 SDValue NaNResult =
10176 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
10177
10178 SDValue InfResult =
10179 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10180 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
10181
10182 // A source format may have a larger finite exponent range despite having
10183 // fewer bits, as with Float8E5M3FNU converted to half. Its overflowing finite
10184 // values become infinity. The NaN selection below still takes precedence.
10185 if (APFloat::semanticsMaxExponent(SrcSem) >
10187 SDValue IsOverflow =
10188 DAG.getSetCC(dl, SetCCVT, NormDstExp,
10189 DAG.getConstant(DstExpAllOnes, dl, IntVT), ISD::SETUGE);
10190 FiniteResult =
10191 DAG.getSelect(dl, IntVT, IsOverflow, InfResult, FiniteResult);
10192 }
10193
10194 SDValue ZeroResult = SignShifted;
10195
10196 SDValue Result = FiniteResult;
10197 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10198 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10199 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10200
10201 if (!DstVT.bitsEq(IntVT)) {
10202 // Store to stack before loading it back.
10203 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
10204 // IntScalarVT is the original type that has the same width as DstVT.
10205 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
10206 SDValue StackPtr =
10207 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
10208 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10210 MachinePointerInfo PtrInfo =
10211 MachinePointerInfo::getFixedStack(MF, FrameIndex);
10212 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
10213 PtrInfo, IntScalarVT, Alignment);
10214
10215 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
10216 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
10217 }
10218
10219 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
10220}
10221
10223 SelectionDAG &DAG) const {
10224 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10225 SDValue Src = Node->getOperand(OpNo);
10226 EVT SrcVT = Src.getValueType();
10227 EVT DstVT = Node->getValueType(0);
10228 SDLoc dl(SDValue(Node, 0));
10229
10230 // FIXME: Only f32 to i64 conversions are supported.
10231 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
10232 return false;
10233
10234 if (Node->isStrictFPOpcode())
10235 // When a NaN is converted to an integer a trap is allowed. We can't
10236 // use this expansion here because it would eliminate that trap. Other
10237 // traps are also allowed and cannot be eliminated. See
10238 // IEEE 754-2008 sec 5.8.
10239 return false;
10240
10241 // Expand f32 -> i64 conversion
10242 // This algorithm comes from compiler-rt's implementation of fixsfdi:
10243 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
10244 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
10245 EVT IntVT = SrcVT.changeTypeToInteger();
10246 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
10247
10248 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
10249 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
10250 SDValue Bias = DAG.getConstant(127, dl, IntVT);
10251 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
10252 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
10253 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
10254
10255 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
10256
10257 SDValue ExponentBits = DAG.getNode(
10258 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
10259 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
10260 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
10261
10262 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
10263 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
10264 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
10265 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10266
10267 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10268 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10269 DAG.getConstant(0x00800000, dl, IntVT));
10270
10271 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10272
10273 R = DAG.getSelectCC(
10274 dl, Exponent, ExponentLoBit,
10275 DAG.getNode(ISD::SHL, dl, DstVT, R,
10276 DAG.getZExtOrTrunc(
10277 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10278 dl, IntShVT)),
10279 DAG.getNode(ISD::SRL, dl, DstVT, R,
10280 DAG.getZExtOrTrunc(
10281 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10282 dl, IntShVT)),
10283 ISD::SETGT);
10284
10285 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10286 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10287
10288 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10289 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10290 return true;
10291}
10292
10294 SDValue &Chain,
10295 SelectionDAG &DAG) const {
10296 SDLoc dl(SDValue(Node, 0));
10297 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10298 SDValue Src = Node->getOperand(OpNo);
10299
10300 EVT SrcVT = Src.getValueType();
10301 EVT DstVT = Node->getValueType(0);
10302 EVT SetCCVT =
10303 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10304 EVT DstSetCCVT =
10305 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10306
10307 // Only expand vector types if we have the appropriate vector bit operations.
10308 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10310 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10312 return false;
10313
10314 // If the maximum float value is smaller then the signed integer range,
10315 // the destination signmask can't be represented by the float, so we can
10316 // just use FP_TO_SINT directly.
10317 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10318 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10319 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10321 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10322 if (Node->isStrictFPOpcode()) {
10323 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10324 { Node->getOperand(0), Src });
10325 Chain = Result.getValue(1);
10326 } else
10327 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10328 return true;
10329 }
10330
10331 // Don't expand it if there isn't cheap fsub instruction.
10333 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10334 return false;
10335
10336 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10337 SDValue Sel;
10338
10339 if (Node->isStrictFPOpcode()) {
10340 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10341 Node->getOperand(0), /*IsSignaling*/ true);
10342 Chain = Sel.getValue(1);
10343 } else {
10344 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10345 }
10346
10347 bool Strict = Node->isStrictFPOpcode() ||
10348 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10349
10350 if (Strict) {
10351 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10352 // signmask then offset (the result of which should be fully representable).
10353 // Sel = Src < 0x8000000000000000
10354 // FltOfs = select Sel, 0, 0x8000000000000000
10355 // IntOfs = select Sel, 0, 0x8000000000000000
10356 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10357
10358 // TODO: Should any fast-math-flags be set for the FSUB?
10359 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10360 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10361 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10362 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10363 DAG.getConstant(0, dl, DstVT),
10364 DAG.getConstant(SignMask, dl, DstVT));
10365 SDValue SInt;
10366 if (Node->isStrictFPOpcode()) {
10367 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10368 { Chain, Src, FltOfs });
10369 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10370 { Val.getValue(1), Val });
10371 Chain = SInt.getValue(1);
10372 } else {
10373 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10374 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10375 }
10376 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10377 } else {
10378 // Expand based on maximum range of FP_TO_SINT:
10379 // True = fp_to_sint(Src)
10380 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10381 // Result = select (Src < 0x8000000000000000), True, False
10382
10383 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10384 // TODO: Should any fast-math-flags be set for the FSUB?
10385 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10386 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10387 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10388 DAG.getConstant(SignMask, dl, DstVT));
10389 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10390 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10391 }
10392 return true;
10393}
10394
10396 SDValue &Chain, SelectionDAG &DAG) const {
10397 // This transform is not correct for converting 0 when rounding mode is set
10398 // to round toward negative infinity which will produce -0.0. So disable
10399 // under strictfp.
10400 if (Node->isStrictFPOpcode())
10401 return false;
10402
10403 SDValue Src = Node->getOperand(0);
10404 EVT SrcVT = Src.getValueType();
10405 EVT DstVT = Node->getValueType(0);
10406
10407 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10408 // it.
10409 if (Node->getFlags().hasNonNeg() &&
10411 Result =
10412 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10413 return true;
10414 }
10415
10416 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10417 return false;
10418
10419 // Only expand vector types if we have the appropriate vector bit
10420 // operations.
10421 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10426 return false;
10427
10428 SDLoc dl(SDValue(Node, 0));
10429
10430 // Implementation of unsigned i64 to f64 following the algorithm in
10431 // __floatundidf in compiler_rt. This implementation performs rounding
10432 // correctly in all rounding modes with the exception of converting 0
10433 // when rounding toward negative infinity. In that case the fsub will
10434 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10435 // incorrect.
10436 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10437 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10438 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10439 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10440 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10441 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10442
10443 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10444 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10445 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10446 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10447 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10448 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10449 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10450 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10451 return true;
10452}
10453
10454SDValue
10456 SelectionDAG &DAG) const {
10457 unsigned Opcode = Node->getOpcode();
10458 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10459 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10460 "Wrong opcode");
10461
10462 if (Node->getFlags().hasNoNaNs()) {
10463 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10464 EVT VT = Node->getValueType(0);
10465 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10467 VT.isVector())
10468 return SDValue();
10469 SDValue Op1 = Node->getOperand(0);
10470 SDValue Op2 = Node->getOperand(1);
10471 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10472 Node->getFlags());
10473 }
10474
10475 return SDValue();
10476}
10477
10479 SelectionDAG &DAG) const {
10480 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10481 return Expanded;
10482
10483 EVT VT = Node->getValueType(0);
10484 if (VT.isScalableVector())
10486 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10487
10488 SDLoc dl(Node);
10489 unsigned NewOp =
10491
10492 if (isOperationLegalOrCustom(NewOp, VT)) {
10493 SDValue Quiet0 = Node->getOperand(0);
10494 SDValue Quiet1 = Node->getOperand(1);
10495
10496 if (!Node->getFlags().hasNoNaNs()) {
10497 // Insert canonicalizes if it's possible we need to quiet to get correct
10498 // sNaN behavior.
10499 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10500 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10501 Node->getFlags());
10502 }
10503 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10504 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10505 Node->getFlags());
10506 }
10507 }
10508
10509 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10510 }
10511
10512 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10513 // instead if there are no NaNs.
10514 if (Node->getFlags().hasNoNaNs() ||
10515 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10516 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10517 unsigned IEEE2018Op =
10518 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10519 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10520 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10521 Node->getOperand(1), Node->getFlags());
10522 }
10523
10525 return SelCC;
10526
10527 return SDValue();
10528}
10529
10531 const TargetLowering &TLI,
10532 const SDLoc &DL, SDValue Val,
10533 FPClassTest FPClass) {
10534 EVT VT = Val.getValueType();
10535 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10536 EVT IntVT = VT.changeTypeToInteger();
10537 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10538 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10539 if (!TLI.isTypeLegal(IntVT) &&
10541 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10542 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10543 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10544}
10545
10547 SelectionDAG &DAG) const {
10548 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10549 return Expanded;
10550
10551 SDLoc DL(N);
10552 SDValue LHS = N->getOperand(0);
10553 SDValue RHS = N->getOperand(1);
10554 unsigned Opc = N->getOpcode();
10555 EVT VT = N->getValueType(0);
10556 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10557 bool IsMax = Opc == ISD::FMAXIMUM;
10558 SDNodeFlags Flags = N->getFlags();
10559
10560 // First, implement comparison not propagating NaN. If no native fmin or fmax
10561 // available, use plain select with setcc instead.
10563 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10564 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10565
10566 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10567 // signed zero behavior.
10568 bool MinMaxMustRespectOrderedZero = false;
10569
10570 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10571 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10572 MinMaxMustRespectOrderedZero = true;
10573 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10574 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10575 } else {
10577 return DAG.UnrollVectorOp(N);
10578
10579 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10580 SDValue Compare =
10581 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10582 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10583 }
10584
10585 // Propagate any NaN of both operands
10586 if (!N->getFlags().hasNoNaNs() &&
10587 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10588 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10590 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10591 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10592 }
10593
10594 // fminimum/fmaximum requires -0.0 less than +0.0
10595 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10596 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10597 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10599 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10600 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10601 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10602 }
10603
10604 return MinMax;
10605}
10606
10608 SelectionDAG &DAG) const {
10609 SDLoc DL(Node);
10610 SDValue LHS = Node->getOperand(0);
10611 SDValue RHS = Node->getOperand(1);
10612 unsigned Opc = Node->getOpcode();
10613 EVT VT = Node->getValueType(0);
10614 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10615 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10616 SDNodeFlags Flags = Node->getFlags();
10617
10618 unsigned NewOp =
10620
10621 if (isOperationLegalOrCustom(NewOp, VT)) {
10622 if (!Flags.hasNoNaNs()) {
10623 // Insert canonicalizes if it's possible we need to quiet to get correct
10624 // sNaN behavior.
10625 if (!DAG.isKnownNeverSNaN(LHS)) {
10626 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10627 }
10628 if (!DAG.isKnownNeverSNaN(RHS)) {
10629 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10630 }
10631 }
10632
10633 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10634 }
10635
10636 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10637 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10638 if (Flags.hasNoNaNs() ||
10639 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10640 unsigned IEEE2019Op =
10642 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10643 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10644 }
10645
10646 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10647 // either one for +0.0 vs -0.0.
10648 if ((Flags.hasNoNaNs() ||
10649 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10650 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10651 DAG.isKnownNeverLogicalZero(RHS))) {
10652 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10653 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10654 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10655 }
10656
10657 if (VT.isVector() &&
10660 return DAG.UnrollVectorOp(Node);
10661
10662 // If only one operand is NaN, override it with another operand.
10663 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10664 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10665 }
10666 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10667 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10668 }
10669
10670 // Always prefer RHS if equal.
10671 SDValue MinMax =
10672 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10673
10674 // TODO: We need quiet sNaN if strictfp.
10675
10676 // Fixup signed zero behavior.
10677 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10678 DAG.isKnownNeverLogicalZero(RHS)) {
10679 return MinMax;
10680 }
10681 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10682 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10684 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10685 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10686 // we preferred RHS when generate MinMax, if the operands are equal.
10687 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10688 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10689}
10690
10691/// Returns a true value if if this FPClassTest can be performed with an ordered
10692/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10693/// std::nullopt if it cannot be performed as a compare with 0.
10694static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10695 const fltSemantics &Semantics,
10696 const MachineFunction &MF) {
10697 FPClassTest OrderedMask = Test & ~fcNan;
10698 FPClassTest NanTest = Test & fcNan;
10699 bool IsOrdered = NanTest == fcNone;
10700 bool IsUnordered = NanTest == fcNan;
10701
10702 // Skip cases that are testing for only a qnan or snan.
10703 if (!IsOrdered && !IsUnordered)
10704 return std::nullopt;
10705
10706 if (OrderedMask == fcZero &&
10707 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10708 return IsOrdered;
10709 if (OrderedMask == (fcZero | fcSubnormal) &&
10710 MF.getDenormalMode(Semantics).inputsAreZero())
10711 return IsOrdered;
10712 return std::nullopt;
10713}
10714
10716 const FPClassTest OrigTestMask,
10717 SDNodeFlags Flags, const SDLoc &DL,
10718 SelectionDAG &DAG) const {
10719 EVT OperandVT = Op.getValueType();
10720 assert(OperandVT.isFloatingPoint());
10721 FPClassTest Test = OrigTestMask;
10722
10723 // Degenerated cases.
10724 if (Test == fcNone)
10725 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10726 if (Test == fcAllFlags)
10727 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10728
10729 // PPC double double is a pair of doubles, of which the higher part determines
10730 // the value class.
10731 if (OperandVT == MVT::ppcf128) {
10732 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10733 DAG.getConstant(1, DL, MVT::i32));
10734 OperandVT = MVT::f64;
10735 }
10736
10737 // Floating-point type properties.
10738 EVT ScalarFloatVT = OperandVT.getScalarType();
10739 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10740 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10741 bool IsF80 = (ScalarFloatVT == MVT::f80);
10742
10743 // Some checks can be implemented using float comparisons, if floating point
10744 // exceptions are ignored.
10745 if (Flags.hasNoFPExcept() &&
10747 FPClassTest FPTestMask = Test;
10748 bool IsInvertedFP = false;
10749
10750 if (FPClassTest InvertedFPCheck =
10751 invertFPClassTestIfSimpler(FPTestMask, true)) {
10752 FPTestMask = InvertedFPCheck;
10753 IsInvertedFP = true;
10754 }
10755
10756 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10757 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10758
10759 // See if we can fold an | fcNan into an unordered compare.
10760 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10761
10762 // Can't fold the ordered check if we're only testing for snan or qnan
10763 // individually.
10764 if ((FPTestMask & fcNan) != fcNan)
10765 OrderedFPTestMask = FPTestMask;
10766
10767 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10768
10769 if (std::optional<bool> IsCmp0 =
10770 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10771 IsCmp0 && (isCondCodeLegalOrCustom(
10772 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10773 OperandVT.getScalarType().getSimpleVT()))) {
10774
10775 // If denormals could be implicitly treated as 0, this is not equivalent
10776 // to a compare with 0 since it will also be true for denormals.
10777 return DAG.getSetCC(DL, ResultVT, Op,
10778 DAG.getConstantFP(0.0, DL, OperandVT),
10779 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10780 }
10781
10782 if (FPTestMask == fcNan &&
10784 OperandVT.getScalarType().getSimpleVT()))
10785 return DAG.getSetCC(DL, ResultVT, Op, Op,
10786 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10787
10788 bool IsOrderedInf = FPTestMask == fcInf;
10789 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10790 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10791 : UnorderedCmpOpcode,
10792 OperandVT.getScalarType().getSimpleVT()) &&
10795 (OperandVT.isVector() &&
10797 // isinf(x) --> fabs(x) == inf
10798 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10799 SDValue Inf =
10800 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10801 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10802 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10803 }
10804
10805 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10806 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10807 : UnorderedCmpOpcode,
10808 OperandVT.getSimpleVT())) {
10809 // isposinf(x) --> x == inf
10810 // isneginf(x) --> x == -inf
10811 // isposinf(x) || nan --> x u== inf
10812 // isneginf(x) || nan --> x u== -inf
10813
10814 SDValue Inf = DAG.getConstantFP(
10815 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
10816 OperandVT);
10817 return DAG.getSetCC(DL, ResultVT, Op, Inf,
10818 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
10819 }
10820
10821 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
10822 // TODO: Could handle ordered case, but it produces worse code for
10823 // x86. Maybe handle ordered if fabs is free?
10824
10825 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10826 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
10827
10828 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
10829 OperandVT.getScalarType().getSimpleVT())) {
10830 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
10831
10832 // TODO: Maybe only makes sense if fabs is free. Integer test of
10833 // exponent bits seems better for x86.
10834 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10835 SDValue SmallestNormal = DAG.getConstantFP(
10836 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10837 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
10838 IsOrdered ? OrderedOp : UnorderedOp);
10839 }
10840 }
10841
10842 if (FPTestMask == fcNormal) {
10843 // TODO: Handle unordered
10844 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10845 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
10846
10847 if (isCondCodeLegalOrCustom(IsFiniteOp,
10848 OperandVT.getScalarType().getSimpleVT()) &&
10849 isCondCodeLegalOrCustom(IsNormalOp,
10850 OperandVT.getScalarType().getSimpleVT()) &&
10851 isFAbsFree(OperandVT)) {
10852 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
10853 SDValue Inf =
10854 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10855 SDValue SmallestNormal = DAG.getConstantFP(
10856 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10857
10858 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10859 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
10860 SDValue IsNormal =
10861 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
10862 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
10863 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
10864 }
10865 }
10866 }
10867
10868 // Some checks may be represented as inversion of simpler check, for example
10869 // "inf|normal|subnormal|zero" => !"nan".
10870 bool IsInverted = false;
10871
10872 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
10873 Test = InvertedCheck;
10874 IsInverted = true;
10875 }
10876
10877 // In the general case use integer operations.
10878 unsigned BitSize = OperandVT.getScalarSizeInBits();
10879 EVT IntVT = OperandVT.changeElementType(
10880 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
10881 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
10882
10883 // Various masks.
10884 APInt SignBit = APInt::getSignMask(BitSize);
10885 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
10886 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
10887 const unsigned ExplicitIntBitInF80 = 63;
10888 APInt ExpMask = Inf;
10889 if (IsF80)
10890 ExpMask.clearBit(ExplicitIntBitInF80);
10891 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
10892 APInt QNaNBitMask =
10893 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
10894 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
10895
10896 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
10897 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
10898 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
10899 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
10900 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
10901 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
10902
10903 SDValue Res;
10904 const auto appendResult = [&](SDValue PartialRes) {
10905 if (PartialRes) {
10906 if (Res)
10907 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
10908 else
10909 Res = PartialRes;
10910 }
10911 };
10912
10913 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
10914 const auto getIntBitIsSet = [&]() -> SDValue {
10915 if (!IntBitIsSetV) {
10916 APInt IntBitMask(BitSize, 0);
10917 IntBitMask.setBit(ExplicitIntBitInF80);
10918 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
10919 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
10920 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
10921 }
10922 return IntBitIsSetV;
10923 };
10924
10925 // Split the value into sign bit and absolute value.
10926 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
10927 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
10928 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
10929
10930 // Tests that involve more than one class should be processed first.
10931 SDValue PartialRes;
10932
10933 if (IsF80)
10934 ; // Detect finite numbers of f80 by checking individual classes because
10935 // they have different settings of the explicit integer bit.
10936 else if ((Test & fcFinite) == fcFinite) {
10937 // finite(V) ==> (a << 1) < (inf << 1)
10938 //
10939 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
10940 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
10941
10943 "finite check requires IEEE-like FP");
10944
10945 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
10946 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
10947 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
10948
10949 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
10950 Test &= ~fcFinite;
10951 } else if ((Test & fcFinite) == fcPosFinite) {
10952 // finite(V) && V > 0 ==> V < exp_mask
10953 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
10954 Test &= ~fcPosFinite;
10955 } else if ((Test & fcFinite) == fcNegFinite) {
10956 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
10957 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
10958 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10959 Test &= ~fcNegFinite;
10960 }
10961 appendResult(PartialRes);
10962
10963 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
10964 // fcZero | fcSubnormal => test all exponent bits are 0
10965 // TODO: Handle sign bit specific cases
10966 if (PartialCheck == (fcZero | fcSubnormal)) {
10967 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
10968 SDValue ExpIsZero =
10969 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10970 appendResult(ExpIsZero);
10971 Test &= ~PartialCheck & fcAllFlags;
10972 }
10973 }
10974
10975 // Check for individual classes.
10976
10977 if (unsigned PartialCheck = Test & fcZero) {
10978 if (PartialCheck == fcPosZero)
10979 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
10980 else if (PartialCheck == fcZero)
10981 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
10982 else // ISD::fcNegZero
10983 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
10984 appendResult(PartialRes);
10985 }
10986
10987 if (unsigned PartialCheck = Test & fcSubnormal) {
10988 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
10989 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
10990 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
10991 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
10992 SDValue VMinusOneV =
10993 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
10994 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
10995 if (PartialCheck == fcNegSubnormal)
10996 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10997 appendResult(PartialRes);
10998 }
10999
11000 if (unsigned PartialCheck = Test & fcInf) {
11001 if (PartialCheck == fcPosInf)
11002 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
11003 else if (PartialCheck == fcInf)
11004 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
11005 else { // ISD::fcNegInf
11006 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
11007 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
11008 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
11009 }
11010 appendResult(PartialRes);
11011 }
11012
11013 if (unsigned PartialCheck = Test & fcNan) {
11014 APInt InfWithQnanBit = Inf | QNaNBitMask;
11015 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
11016 if (PartialCheck == fcNan) {
11017 // isnan(V) ==> abs(V) > int(inf)
11018 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11019 if (IsF80) {
11020 // Recognize unsupported values as NaNs for compatibility with glibc.
11021 // In them (exp(V)==0) == int_bit.
11022 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
11023 SDValue ExpIsZero =
11024 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11025 SDValue IsPseudo =
11026 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
11027 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
11028 }
11029 } else if (PartialCheck == fcQNan) {
11030 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
11031 PartialRes =
11032 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
11033 } else { // ISD::fcSNan
11034 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
11035 // abs(V) < (unsigned(Inf) | quiet_bit)
11036 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11037 SDValue IsNotQnan =
11038 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
11039 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
11040 }
11041 appendResult(PartialRes);
11042 }
11043
11044 if (unsigned PartialCheck = Test & fcNormal) {
11045 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
11046 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
11047 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
11048 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
11049 APInt ExpLimit = ExpMask - ExpLSB;
11050 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
11051 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
11052 if (PartialCheck == fcNegNormal)
11053 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11054 else if (PartialCheck == fcPosNormal) {
11055 SDValue PosSignV =
11056 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
11057 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
11058 }
11059 if (IsF80)
11060 PartialRes =
11061 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
11062 appendResult(PartialRes);
11063 }
11064
11065 if (!Res)
11066 return DAG.getConstant(IsInverted, DL, ResultVT);
11067 if (IsInverted)
11068 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
11069 return Res;
11070}
11071
11072// Only expand vector types if we have the appropriate vector bit operations.
11073static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
11074 assert(VT.isVector() && "Expected vector type");
11075 unsigned Len = VT.getScalarSizeInBits();
11076 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
11079 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
11081}
11082
11084 SDLoc dl(Node);
11085 EVT VT = Node->getValueType(0);
11086 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11087 SDValue Op = Node->getOperand(0);
11088 unsigned Len = VT.getScalarSizeInBits();
11089
11090 // Compute effective bit width from known bits, allowing us to shift the
11091 // active bits down if necessary to fit into smaller specialized expansions.
11093 unsigned LZ = Known.countMinLeadingZeros();
11094 unsigned TZ = Known.countMinTrailingZeros();
11095 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
11096
11097 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
11098 unsigned EffectiveLen = Len;
11099 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
11100 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
11101
11102 assert(VT.isInteger() && "CTPOP not implemented for this type.");
11103
11104 // TODO: Add support for irregular type lengths.
11105 if (!(Len <= 128 && Len % 8 == 0))
11106 return SDValue();
11107
11108 // Only expand vector types if we have the appropriate vector bit operations.
11109 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
11110 return SDValue();
11111
11112 // If the active bits are not at the low end, shift them down
11113 if (EffectiveLen < Len && TZ > 0) {
11114 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
11115 DAG.getShiftAmountConstant(TZ, VT, dl));
11116 }
11117
11118 // This is the "best" algorithm from
11119 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
11120 SDValue Mask55 =
11121 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
11122 SDValue Mask33 =
11123 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
11124 SDValue Mask0F =
11125 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
11126
11127 // v = v - ((v >> 1) & 0x55555555...)
11128 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
11129 DAG.getNode(ISD::AND, dl, VT,
11130 DAG.getNode(ISD::SRL, dl, VT, Op,
11131 DAG.getConstant(1, dl, ShVT)),
11132 Mask55));
11133 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
11134 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
11135 DAG.getNode(ISD::AND, dl, VT,
11136 DAG.getNode(ISD::SRL, dl, VT, Op,
11137 DAG.getConstant(2, dl, ShVT)),
11138 Mask33));
11139 // v = (v + (v >> 4)) & 0x0F0F0F0F...
11140 Op = DAG.getNode(ISD::AND, dl, VT,
11141 DAG.getNode(ISD::ADD, dl, VT, Op,
11142 DAG.getNode(ISD::SRL, dl, VT, Op,
11143 DAG.getConstant(4, dl, ShVT))),
11144 Mask0F);
11145
11146 if (EffectiveLen <= 8)
11147 return Op;
11148
11149 // Avoid the multiply if we only have 2 bytes to add.
11150 // TODO: Only doing this for scalars because vectors weren't as obviously
11151 // improved.
11152 if (EffectiveLen == 16 && !VT.isVector()) {
11153 // v = (v + (v >> 8)) & 0x00FF;
11154 return DAG.getNode(ISD::AND, dl, VT,
11155 DAG.getNode(ISD::ADD, dl, VT, Op,
11156 DAG.getNode(ISD::SRL, dl, VT, Op,
11157 DAG.getConstant(8, dl, ShVT))),
11158 DAG.getConstant(0xFF, dl, VT));
11159 }
11160
11161 // v = (v * 0x01010101...) >> (Len - 8)
11162 SDValue V;
11165 SDValue Mask01 =
11166 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
11167 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
11168 } else {
11169 V = Op;
11170 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
11171 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
11172 V = DAG.getNode(ISD::ADD, dl, VT, V,
11173 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
11174 }
11175 }
11176 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
11177}
11178
11180 SDLoc dl(Node);
11181 EVT VT = Node->getValueType(0);
11182 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11183 SDValue Op = Node->getOperand(0);
11184 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11185
11186 // If the non-ZERO_POISON version is supported we can use that instead.
11187 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
11189 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
11190
11191 // If the ZERO_POISON version is supported use that and handle the zero case.
11193 EVT SetCCVT =
11194 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11195 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
11196 SDValue Zero = DAG.getConstant(0, dl, VT);
11197 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11198 return DAG.getSelect(dl, VT, SrcIsZero,
11199 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
11200 }
11201
11202 // Only expand vector types if we have the appropriate vector bit operations.
11203 // This includes the operations needed to expand CTPOP if it isn't supported.
11204 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11206 !canExpandVectorCTPOP(*this, VT)) ||
11209 return SDValue();
11210
11211 // for now, we do this:
11212 // x = x | (x >> 1);
11213 // x = x | (x >> 2);
11214 // ...
11215 // x = x | (x >>16);
11216 // x = x | (x >>32); // for 64-bit input
11217 // return popcount(~x);
11218 //
11219 // Ref: "Hacker's Delight" by Henry Warren
11220 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
11221 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
11222 Op = DAG.getNode(ISD::OR, dl, VT, Op,
11223 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
11224 }
11225 Op = DAG.getNOT(dl, Op, VT);
11226 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
11227}
11228
11230 SDLoc dl(Node);
11231 EVT VT = Node->getValueType(0);
11232 SDValue Op = DAG.getFreeze(Node->getOperand(0));
11233 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11234
11235 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
11236 // This transforms the sign bits into leading zeros that can be counted.
11237 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
11238 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
11239 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
11240 SDValue Shl =
11241 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11242 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
11243 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
11244}
11245
11247 const SDLoc &DL, EVT VT, SDValue Op,
11248 unsigned BitWidth) const {
11249 if (BitWidth != 32 && BitWidth != 64)
11250 return SDValue();
11251
11252 const DataLayout &TD = DAG.getDataLayout();
11254 return SDValue();
11255
11256 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
11257 : APInt(64, 0x0218A392CD3D5DBFULL);
11258 MachinePointerInfo PtrInfo =
11260 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
11261 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11262 SDValue Lookup = DAG.getNode(
11263 ISD::SRL, DL, VT,
11264 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
11265 DAG.getConstant(DeBruijn, DL, VT)),
11266 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11268
11270 for (unsigned i = 0; i < BitWidth; i++) {
11271 APInt Shl = DeBruijn.shl(i);
11272 APInt Lshr = Shl.lshr(ShiftAmt);
11273 Table[Lshr.getZExtValue()] = i;
11274 }
11275
11276 // Create a ConstantArray in Constant Pool
11277 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11278 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11279 TD.getPrefTypeAlign(CA->getType()));
11280 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11281 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11282 PtrInfo, MVT::i8);
11283 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11284 return ExtLoad;
11285
11286 EVT SetCCVT =
11287 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11288 SDValue Zero = DAG.getConstant(0, DL, VT);
11289 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11290 return DAG.getSelect(DL, VT, SrcIsZero,
11291 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11292}
11293
11295 SDLoc dl(Node);
11296 EVT VT = Node->getValueType(0);
11297 SDValue Op = Node->getOperand(0);
11298 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11299
11300 // If the non-ZERO_POISON version is supported we can use that instead.
11301 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11303 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11304
11305 // If the ZERO_POISON version is supported use that and handle the zero case.
11307 EVT SetCCVT =
11308 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11309 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11310 SDValue Zero = DAG.getConstant(0, dl, VT);
11311 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11312 return DAG.getSelect(dl, VT, SrcIsZero,
11313 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11314 }
11315
11316 // Only expand vector types if we have the appropriate vector bit operations.
11317 // This includes the operations needed to expand CTPOP if it isn't supported.
11318 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11321 !canExpandVectorCTPOP(*this, VT)) ||
11325 return SDValue();
11326
11327 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11328 // to be expanded or converted to a libcall.
11331 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11332 return V;
11333
11334 bool UseCTLZ =
11336
11337 // When only ctlz is available and the operand is nonzero we can use:
11338 // { return nlz(x & -x) ^ 31; }
11339 // which is more efficient than:
11340 // { return 32 - nlz(~x & (x - 1)); }.
11341 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11342 SDValue LowestBit =
11343 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11344 return DAG.getNode(ISD::XOR, dl, VT,
11345 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11346 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11347 }
11348
11349 // If ctpop is available, we use:
11350 // { return popcount(~x & (x-1)); }
11351 // If the target has ctlz but not ctpop, we use:
11352 // { return 32 - nlz(~x & (x-1)); }
11353 // Ref: "Hacker's Delight" by Henry Warren
11354 SDValue Tmp = DAG.getNode(
11355 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11356 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11357
11358 if (UseCTLZ)
11359 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11360 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11361
11362 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11363}
11364
11366 SelectionDAG &DAG) const {
11367 // %cond = to_bool_vec %source
11368 // %splat = splat /*val=*/VL
11369 // %tz = step_vector
11370 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11371 // %r = vp.reduce.umin %v
11372 SDLoc DL(N);
11373 SDValue Source = N->getOperand(0);
11374 SDValue Mask = N->getOperand(1);
11375 SDValue EVL = N->getOperand(2);
11376 EVT SrcVT = Source.getValueType();
11377 EVT ResVT = N->getValueType(0);
11378 EVT ResVecVT =
11379 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11380
11381 // Convert to boolean vector.
11382 if (SrcVT.getScalarType() != MVT::i1) {
11383 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11384 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11385 SrcVT.getVectorElementCount());
11386 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11387 }
11388
11389 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11390 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11391 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11392 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11393 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11394}
11395
11396/// Returns a type-legalized version of \p Mask as the first item in the
11397/// pair. The second item contains a type-legalized step vector that's
11398/// guaranteed to fit the number of elements in \p Mask.
11399/// If the stepvector would require splitting, returns an empty SDValue
11400/// as the second item to signal that the operation should be split instead.
11401static std::pair<SDValue, SDValue>
11403 SelectionDAG &DAG) {
11404 EVT MaskVT = Mask.getValueType();
11405 EVT BoolVT = MaskVT.getScalarType();
11406
11407 // Find a suitable type for a stepvector.
11408 // If zero is poison, we can assume the upper limit of the result is VF-1.
11409 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11410 if (MaskVT.isScalableVector())
11411 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11412 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11413 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11414 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11415 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11416 // If the step vector element type is smaller than the mask element type,
11417 // use the mask type directly to avoid widening issues.
11418 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11419 EVT StepVT = MVT::getIntegerVT(EltWidth);
11420 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11421
11422 // If promotion or widening is required to make the type legal, do it here.
11423 // Promotion of integers within LegalizeVectorOps is looking for types of
11424 // the same size but with a smaller number of larger elements, not the usual
11425 // larger size with the same number of larger elements.
11427 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11428 SDValue StepVec;
11429 if (TypeAction == TargetLowering::TypePromoteInteger) {
11430 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11431 StepVec = DAG.getStepVector(DL, StepVecVT);
11432 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11433 // For widening, the element count changes. Create a step vector with only
11434 // the original elements valid and zeros for padding. Also widen the mask.
11435 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11436 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11437
11438 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11439 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11440 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11441 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11442
11443 // Widen mask: pad with zeros.
11444 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11445 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11446 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11447 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11448 // The stepvector type would require splitting. Signal to the caller
11449 // that the operation should be split instead of expanded.
11450 return {Mask, SDValue()};
11451 } else {
11452 StepVec = DAG.getStepVector(DL, StepVecVT);
11453 }
11454
11455 return {Mask, StepVec};
11456}
11457
11459 SelectionDAG &DAG) const {
11460 SDLoc DL(N);
11461 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11462 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11463
11464 // If StepVec is empty, the stepvector would require splitting.
11465 // Split the operation instead and let it be recursively legalized.
11466 if (!StepVec) {
11467 EVT MaskVT = N->getOperand(0).getValueType();
11468 EVT ResVT = N->getValueType(0);
11469
11470 // Split the mask
11471 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11472 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11473
11474 // Create split VECTOR_FIND_LAST_ACTIVE operations
11475 SDValue LoResult =
11476 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11477 SDValue HiResult =
11478 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11479
11480 // Check if any lane is active in the high mask.
11481 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11483 AnyHiActive, DL,
11484 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11485 MVT::i1);
11486
11487 // Adjust HiResult by adding the number of elements in Lo
11488 SDValue LoNumElts =
11489 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11490 SDValue AdjustedHiResult =
11491 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11492
11493 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11494 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11495 LoResult);
11496 }
11497
11498 EVT StepVecVT = StepVec.getValueType();
11499 EVT StepVT = StepVec.getValueType().getVectorElementType();
11500
11501 // Zero out lanes with inactive elements, then find the highest remaining
11502 // value from the stepvector.
11503 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11504 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11505 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11506 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11507}
11508
11510 SelectionDAG &DAG) const {
11511 SDLoc DL(N);
11512
11513 SDValue Start = N->getOperand(0);
11514 SDValue End = N->getOperand(1);
11515 EVT VT = N->getValueType(0);
11516 EVT OpVT = Start.getValueType();
11517
11518 auto [Mask, StepVector] = getLegalMaskAndStepVector(
11519 DAG.getPOISON(VT), /*ZeroIsPoison=*/false, DL, DAG);
11520
11521 // No legal step vector: split the mask in half and recombine the results.
11522 // Lo = get_active_lane_mask Start, End
11523 // Hi = get_active_lane_mask (uaddsat Start, LoNumElts), End
11524 if (!StepVector) {
11525 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
11526 SDValue Lo = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, LoVT, Start, End);
11527 SDValue LoNumElts =
11528 DAG.getElementCount(DL, OpVT, LoVT.getVectorElementCount());
11529 SDValue HiStart = DAG.getNode(ISD::UADDSAT, DL, OpVT, Start, LoNumElts);
11530 SDValue Hi = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, HiVT, HiStart, End);
11531 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
11532 }
11533
11534 // Rebase and saturate the termination value.
11535 SDValue Max =
11536 DAG.getConstant(maxUIntN(std::min(StepVector.getScalarValueSizeInBits(),
11537 OpVT.getScalarSizeInBits())),
11538 DL, OpVT);
11539 End = DAG.getNode(ISD::USUBSAT, DL, OpVT, End, Start);
11540 End = DAG.getNode(ISD::UMIN, DL, OpVT, End, Max);
11541 End = DAG.getZExtOrTrunc(End, DL, StepVector.getValueType().getScalarType());
11542
11543 // cmp <0, 1, 2, 3...>, End
11544 SDValue EndV = DAG.getSplat(StepVector.getValueType(), DL, End);
11545 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11546 StepVector.getValueType());
11547 SDValue Cmp = DAG.getSetCC(DL, CCVT, StepVector, EndV, ISD::SETULT);
11548 SDValue Res = DAG.getBoolExtOrTrunc(Cmp, DL, Mask.getValueType(),
11549 StepVector.getValueType());
11550 if (Mask.getValueType() != VT)
11551 Res = DAG.getExtractSubvector(DL, VT, Res, 0);
11552 return Res;
11553}
11554
11556 SelectionDAG &DAG) const {
11557 SDLoc DL(N);
11558 EVT VT = N->getValueType(0);
11559 SDValue SourceValue = N->getOperand(0);
11560 SDValue SinkValue = N->getOperand(1);
11561 SDValue EltSizeInBytes = N->getOperand(2);
11562
11563 // Note: The lane offset is scalable if the mask is scalable.
11564 ElementCount LaneOffsetEC =
11565 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11566
11567 EVT AddrVT = SourceValue->getValueType(0);
11568 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11569
11570 EVT CmpVT =
11571 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11572
11573 // Unsigned compare: Source >= Sink.
11574 SDValue SourceAheadOfOrEqualToSink =
11575 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11576
11577 // Take the difference between the pointers and divided by the element size,
11578 // to see how many lanes separate them.
11579 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11580
11581 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11582 if (IsReadAfterWrite)
11583 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11584 DAG.getNegative(Diff, DL, AddrVT), Diff);
11585
11586 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11587
11588 // The pointers do not alias if:
11589 // - Source >= Sink (WAR_MASK)
11590 // - Source == Sink (RAW_MASK)
11591 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11592 if (IsReadAfterWrite)
11593 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11594
11595 // The pointers do not alias if:
11596 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11597 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11598 SDValue MaskN = DAG.getSelect(
11599 DL, AddrVT, NoAlias,
11601 AddrVT),
11602 Diff);
11603
11604 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11605}
11606
11608 bool IsNegative) const {
11609 SDLoc dl(N);
11610 EVT VT = N->getValueType(0);
11611 SDValue Op = N->getOperand(0);
11612
11613 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11614 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11616 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11617 if (IsNegative)
11618 return DAG.getNegative(AbsVal, dl, VT);
11619 return AbsVal;
11620 }
11621
11622 // abs(x) -> smax(x,sub(0,x))
11623 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11625 SDValue Zero = DAG.getConstant(0, dl, VT);
11626 Op = DAG.getFreeze(Op);
11627 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11628 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11629 }
11630
11631 // abs(x) -> umin(x,sub(0,x))
11632 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11634 SDValue Zero = DAG.getConstant(0, dl, VT);
11635 Op = DAG.getFreeze(Op);
11636 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11637 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11638 }
11639
11640 // 0 - abs(x) -> smin(x, sub(0,x))
11641 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11643 SDValue Zero = DAG.getConstant(0, dl, VT);
11644 Op = DAG.getFreeze(Op);
11645 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11646 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11647 }
11648
11649 // Only expand vector types if we have the appropriate vector operations.
11650 if (VT.isVector() &&
11652 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11653 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11655 return SDValue();
11656
11657 Op = DAG.getFreeze(Op);
11658 SDValue Shift = DAG.getNode(
11659 ISD::SRA, dl, VT, Op,
11660 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11661 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11662
11663 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11664 if (!IsNegative)
11665 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11666
11667 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11668 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11669}
11670
11672 SDLoc dl(N);
11673 EVT VT = N->getValueType(0);
11674 SDValue LHS = N->getOperand(0);
11675 SDValue RHS = N->getOperand(1);
11676 bool IsSigned = N->getOpcode() == ISD::ABDS;
11677
11678 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11679 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11680 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11681 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11682 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11683 LHS = DAG.getFreeze(LHS);
11684 RHS = DAG.getFreeze(RHS);
11685 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11686 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11687 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11688 }
11689
11690 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11691 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11692 LHS = DAG.getFreeze(LHS);
11693 RHS = DAG.getFreeze(RHS);
11694 return DAG.getNode(ISD::OR, dl, VT,
11695 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11696 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11697 }
11698
11699 // abds, or abdu with non-negative operands: if the sub is nsw, abs(sub).
11700 // Otherwise abdu: if the sub is nuw then lhs >= rhs, so just sub.
11701 bool IsNonNegative = DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS);
11702 bool UseSigned = IsSigned || IsNonNegative;
11703
11704 if (DAG.willNotOverflowSub(UseSigned, LHS, RHS)) {
11705 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11706 return UseSigned ? DAG.getNode(ISD::ABS, dl, VT, Sub) : Sub;
11707 }
11708
11709 if (DAG.willNotOverflowSub(UseSigned, RHS, LHS)) {
11710 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, RHS, LHS);
11711 return UseSigned ? DAG.getNode(ISD::ABS, dl, VT, Sub) : Sub;
11712 }
11713
11714 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11716 LHS = DAG.getFreeze(LHS);
11717 RHS = DAG.getFreeze(RHS);
11718 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11719
11720 // Branchless expansion iff cmp result is allbits:
11721 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11722 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11723 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11724 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11725 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11726 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11727 }
11728
11729 // Similar to the branchless expansion, if we don't prefer selects, use the
11730 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11731 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11732 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11733 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11735 SDValue USubO =
11736 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11737 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11738 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11739 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11740 }
11741
11742 // FIXME: Should really try to split the vector in case it's legal on a
11743 // subvector.
11745 return DAG.UnrollVectorOp(N);
11746
11747 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11748 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11749 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11750 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11751}
11752
11754 SDLoc dl(N);
11755 EVT VT = N->getValueType(0);
11756 SDValue LHS = N->getOperand(0);
11757 SDValue RHS = N->getOperand(1);
11758
11759 unsigned Opc = N->getOpcode();
11760 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11761 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11762 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11763 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11764 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11765 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11767 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11768 "Unknown AVG node");
11769
11770 // If the operands are already extended, we can add+shift.
11771 bool IsExt =
11772 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11773 DAG.ComputeNumSignBits(RHS) >= 2) ||
11774 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11775 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11776 if (IsExt) {
11777 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11778 if (!IsFloor)
11779 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11780 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11781 DAG.getShiftAmountConstant(1, VT, dl));
11782 }
11783
11784 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11785 if (VT.isScalarInteger()) {
11786 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11787 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11788 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11789 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11790 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11791 if (!IsFloor)
11792 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11793 DAG.getConstant(1, dl, ExtVT));
11794 // Just use SRL as we will be truncating away the extended sign bits.
11795 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11796 DAG.getShiftAmountConstant(1, ExtVT, dl));
11797 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11798 }
11799 }
11800
11801 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11802 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11805 SDValue UAddWithOverflow =
11806 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11807
11808 SDValue Sum = UAddWithOverflow.getValue(0);
11809 SDValue Overflow = UAddWithOverflow.getValue(1);
11810
11811 // Right shift the sum by 1
11812 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
11813 DAG.getShiftAmountConstant(1, VT, dl));
11814
11815 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
11816 SDValue OverflowShl = DAG.getNode(
11817 ISD::SHL, dl, VT, ZeroExtOverflow,
11818 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11819
11820 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
11821 }
11822
11823 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
11824 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
11825 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
11826 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
11827 LHS = DAG.getFreeze(LHS);
11828 RHS = DAG.getFreeze(RHS);
11829 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
11830 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
11831 SDValue Shift =
11832 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11833 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
11834}
11835
11837 SDLoc dl(N);
11838 EVT VT = N->getValueType(0);
11839 SDValue Op = N->getOperand(0);
11840
11841 if (!VT.isSimple())
11842 return SDValue();
11843
11844 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11845 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11846 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11847 default:
11848 return SDValue();
11849 case MVT::i16:
11850 // Use a rotate by 8. This can be further expanded if necessary.
11851 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11852 case MVT::i32:
11853 // This is meant for ARM specifically, which has ROTR but no ROTL.
11854 // t = x ^ rotr(x, 16)
11855 // t = bic(t, 0x00ff0000)
11856 // t = lshr(t, 8)
11857 // x = t ^ rotr(x, 8)
11859 SDValue Rotr16 =
11860 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
11861 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
11862 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
11863 DAG.getConstant(0xFF00FFFF, dl, VT));
11864 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
11865 SDValue Rotr8 =
11866 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11867 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
11868 }
11869 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11870 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
11871 DAG.getConstant(0xFF00, dl, VT));
11872 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
11873 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11874 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
11875 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11876 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11877 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11878 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11879 case MVT::i64:
11880 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11881 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
11882 DAG.getConstant(255ULL<<8, dl, VT));
11883 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
11884 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
11885 DAG.getConstant(255ULL<<16, dl, VT));
11886 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
11887 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
11888 DAG.getConstant(255ULL<<24, dl, VT));
11889 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
11890 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11891 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
11892 DAG.getConstant(255ULL<<24, dl, VT));
11893 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11894 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
11895 DAG.getConstant(255ULL<<16, dl, VT));
11896 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
11897 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
11898 DAG.getConstant(255ULL<<8, dl, VT));
11899 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11900 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
11901 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
11902 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11903 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11904 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
11905 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11906 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
11907 }
11908}
11909
11911 SDLoc dl(N);
11912 EVT VT = N->getValueType(0);
11913 SDValue Op = N->getOperand(0);
11914 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11915 unsigned Sz = VT.getScalarSizeInBits();
11916
11917 SDValue Tmp, Tmp2, Tmp3;
11918
11919 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
11920 // and finally the i1 pairs.
11921 // TODO: We can easily support i4/i2 legal types if any target ever does.
11922 if (Sz >= 8 && isPowerOf2_32(Sz)) {
11923 // Create the masks - repeating the pattern every byte.
11924 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
11925 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
11926 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
11927
11928 // BSWAP if the type is wider than a single byte.
11929 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
11930
11931 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
11932 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
11933 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
11934 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
11935 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
11936 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11937
11938 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
11939 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
11940 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
11941 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
11942 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
11943 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11944
11945 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
11946 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
11947 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
11948 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
11949 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
11950 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11951 return Tmp;
11952 }
11953
11954 Tmp = DAG.getConstant(0, dl, VT);
11955 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
11956 if (I < J)
11957 Tmp2 =
11958 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
11959 else
11960 Tmp2 =
11961 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
11962
11963 APInt Shift = APInt::getOneBitSet(Sz, J);
11964 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
11965 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
11966 }
11967
11968 return Tmp;
11969}
11970
11971std::pair<SDValue, SDValue>
11973 SelectionDAG &DAG) const {
11974 SDLoc SL(LD);
11975 SDValue Chain = LD->getChain();
11976 SDValue BasePTR = LD->getBasePtr();
11977 EVT SrcVT = LD->getMemoryVT();
11978 EVT DstVT = LD->getValueType(0);
11979 ISD::LoadExtType ExtType = LD->getExtensionType();
11980
11981 if (SrcVT.isScalableVector())
11982 report_fatal_error("Cannot scalarize scalable vector loads");
11983
11984 unsigned NumElem = SrcVT.getVectorNumElements();
11985
11986 EVT SrcEltVT = SrcVT.getScalarType();
11987 EVT DstEltVT = DstVT.getScalarType();
11988
11989 // A vector must always be stored in memory as-is, i.e. without any padding
11990 // between the elements, since various code depend on it, e.g. in the
11991 // handling of a bitcast of a vector type to int, which may be done with a
11992 // vector store followed by an integer load. A vector that does not have
11993 // elements that are byte-sized must therefore be stored as an integer
11994 // built out of the extracted vector elements.
11995 if (!SrcEltVT.isByteSized()) {
11996 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
11997 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
11998
11999 unsigned NumSrcBits = SrcVT.getSizeInBits();
12000 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
12001
12002 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
12003 SDValue SrcEltBitMask = DAG.getConstant(
12004 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
12005
12006 // Load the whole vector and avoid masking off the top bits as it makes
12007 // the codegen worse.
12008 SDValue Load = DAG.getExtLoad(
12009 ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, LD->getPointerInfo(),
12010 SrcIntVT, LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12011 LD->getMMOMetadataForSubAccess());
12012
12014 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12015 unsigned ShiftIntoIdx =
12016 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12017 SDValue ShiftAmount = DAG.getShiftAmountConstant(
12018 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
12019 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
12020 SDValue Elt =
12021 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
12022 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
12023
12024 if (ExtType != ISD::NON_EXTLOAD) {
12025 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
12026 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
12027 }
12028
12029 Vals.push_back(Scalar);
12030 }
12031
12032 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12033 return std::make_pair(Value, Load.getValue(1));
12034 }
12035
12036 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
12037 assert(SrcEltVT.isByteSized());
12038
12040 SmallVector<SDValue, 8> LoadChains;
12041
12042 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12043 SDValue ScalarLoad = DAG.getExtLoad(
12044 ExtType, SL, DstEltVT, Chain, BasePTR,
12045 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
12046 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12047 LD->getMMOMetadataForSubAccess());
12048
12049 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
12050
12051 Vals.push_back(ScalarLoad.getValue(0));
12052 LoadChains.push_back(ScalarLoad.getValue(1));
12053 }
12054
12055 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
12056 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12057
12058 return std::make_pair(Value, NewChain);
12059}
12060
12062 SelectionDAG &DAG) const {
12063 SDLoc SL(ST);
12064
12065 SDValue Chain = ST->getChain();
12066 SDValue BasePtr = ST->getBasePtr();
12067 SDValue Value = ST->getValue();
12068 EVT StVT = ST->getMemoryVT();
12069
12070 if (StVT.isScalableVector())
12071 report_fatal_error("Cannot scalarize scalable vector stores");
12072
12073 // The type of the data we want to save
12074 EVT RegVT = Value.getValueType();
12075 EVT RegSclVT = RegVT.getScalarType();
12076
12077 // The type of data as saved in memory.
12078 EVT MemSclVT = StVT.getScalarType();
12079
12080 unsigned NumElem = StVT.getVectorNumElements();
12081
12082 // A vector must always be stored in memory as-is, i.e. without any padding
12083 // between the elements, since various code depend on it, e.g. in the
12084 // handling of a bitcast of a vector type to int, which may be done with a
12085 // vector store followed by an integer load. A vector that does not have
12086 // elements that are byte-sized must therefore be stored as an integer
12087 // built out of the extracted vector elements.
12088 if (!MemSclVT.isByteSized()) {
12089 unsigned NumBits = StVT.getSizeInBits();
12090 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
12091
12092 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
12093
12094 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12095 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12096 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
12097 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
12098 unsigned ShiftIntoIdx =
12099 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12100 SDValue ShiftAmount =
12101 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
12102 SDValue ShiftedElt =
12103 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
12104 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
12105 }
12106
12107 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
12108 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12109 ST->getMMOMetadataForSubAccess());
12110 }
12111
12112 // Store Stride in bytes
12113 unsigned Stride = MemSclVT.getSizeInBits() / 8;
12114 assert(Stride && "Zero stride!");
12115 // Extract each of the elements from the original vector and save them into
12116 // memory individually.
12118 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12119 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12120
12121 SDValue Ptr =
12122 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
12123
12124 // This scalar TruncStore may be illegal, but we legalize it later.
12126 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
12127 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12128 ST->getMMOMetadataForSubAccess());
12129
12130 Stores.push_back(Store);
12131 }
12132
12133 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
12134}
12135
12136std::pair<SDValue, SDValue>
12138 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
12139 "unaligned indexed loads not implemented!");
12140 SDValue Chain = LD->getChain();
12141 SDValue Ptr = LD->getBasePtr();
12142 EVT VT = LD->getValueType(0);
12143 EVT LoadedVT = LD->getMemoryVT();
12144 SDLoc dl(LD);
12145 auto &MF = DAG.getMachineFunction();
12146
12147 if (VT.isFloatingPoint() || VT.isVector()) {
12148 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
12149 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
12150 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
12151 LoadedVT.isVector()) {
12152 // Scalarize the load and let the individual components be handled.
12153 return scalarizeVectorLoad(LD, DAG);
12154 }
12155
12156 // Expand to a (misaligned) integer load of the same size,
12157 // then bitconvert to floating point or vector.
12158 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
12159 LD->getMemOperand());
12160 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
12161 if (LoadedVT != VT)
12162 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
12163 ISD::ANY_EXTEND, dl, VT, Result);
12164
12165 return std::make_pair(Result, newLoad.getValue(1));
12166 }
12167
12168 // Copy the value to a (aligned) stack slot using (unaligned) integer
12169 // loads and stores, then do a (aligned) load from the stack slot.
12170 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
12171 unsigned LoadedBytes = LoadedVT.getStoreSize();
12172 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12173 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
12174
12175 // Make sure the stack slot is also aligned for the register type.
12176 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
12177 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
12179 SDValue StackPtr = StackBase;
12180 unsigned Offset = 0;
12181
12182 EVT PtrVT = Ptr.getValueType();
12183 EVT StackPtrVT = StackPtr.getValueType();
12184
12185 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12186 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12187
12188 // Do all but one copies using the full register width.
12189 for (unsigned i = 1; i < NumRegs; i++) {
12190 // Load one integer register's worth from the original location.
12191 SDValue Load = DAG.getLoad(
12192 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12193 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12194 LD->getMMOMetadataForSubAccess());
12195 // Follow the load with a store to the stack slot. Remember the store.
12196 Stores.push_back(DAG.getStore(
12197 Load.getValue(1), dl, Load, StackPtr,
12198 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12199 // Increment the pointers.
12200 Offset += RegBytes;
12201
12202 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12203 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12204 }
12205
12206 // The last copy may be partial. Do an extending load.
12207 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12208 8 * (LoadedBytes - Offset));
12209 SDValue Load = DAG.getExtLoad(
12210 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12211 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12212 LD->getMemOperand()->getFlags(), LD->getMMOMetadataForSubAccess());
12213 // Follow the load with a store to the stack slot. Remember the store.
12214 // On big-endian machines this requires a truncating store to ensure
12215 // that the bits end up in the right place.
12216 Stores.push_back(DAG.getTruncStore(
12217 Load.getValue(1), dl, Load, StackPtr,
12218 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12219
12220 // The order of the stores doesn't matter - say it with a TokenFactor.
12221 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12222
12223 // Finally, perform the original load only redirected to the stack slot.
12224 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12225 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12226 LoadedVT);
12227
12228 // Callers expect a MERGE_VALUES node.
12229 return std::make_pair(Load, TF);
12230 }
12231
12232 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12233 "Unaligned load of unsupported type.");
12234
12235 // Compute the new VT that is half the size of the old one. This is an
12236 // integer MVT.
12237 unsigned NumBits = LoadedVT.getSizeInBits();
12238 EVT NewLoadedVT;
12239 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12240 NumBits >>= 1;
12241
12242 Align Alignment = LD->getBaseAlign();
12243 unsigned IncrementSize = NumBits / 8;
12244 ISD::LoadExtType HiExtType = LD->getExtensionType();
12245
12246 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12247 if (HiExtType == ISD::NON_EXTLOAD)
12248 HiExtType = ISD::ZEXTLOAD;
12249
12250 // Load the value in two parts
12251 SDValue Lo, Hi;
12252 if (DAG.getDataLayout().isLittleEndian()) {
12253 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12254 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12255 LD->getMMOMetadataForSubAccess());
12256
12257 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12258 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12259 LD->getPointerInfo().getWithOffset(IncrementSize),
12260 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12261 LD->getMMOMetadataForSubAccess());
12262 } else {
12263 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12264 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12265 LD->getMMOMetadataForSubAccess());
12266
12267 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12268 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12269 LD->getPointerInfo().getWithOffset(IncrementSize),
12270 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12271 LD->getMMOMetadataForSubAccess());
12272 }
12273
12274 // aggregate the two parts
12275 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12276 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12277 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12278
12279 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12280 Hi.getValue(1));
12281
12282 return std::make_pair(Result, TF);
12283}
12284
12286 SelectionDAG &DAG) const {
12287 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12288 "unaligned indexed stores not implemented!");
12289 SDValue Chain = ST->getChain();
12290 SDValue Ptr = ST->getBasePtr();
12291 SDValue Val = ST->getValue();
12292 EVT VT = Val.getValueType();
12293 Align Alignment = ST->getBaseAlign();
12294 auto &MF = DAG.getMachineFunction();
12295 EVT StoreMemVT = ST->getMemoryVT();
12296
12297 SDLoc dl(ST);
12298 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12299 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12300 if (isTypeLegal(intVT)) {
12301 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12302 StoreMemVT.isVector()) {
12303 // Scalarize the store and let the individual components be handled.
12304 SDValue Result = scalarizeVectorStore(ST, DAG);
12305 return Result;
12306 }
12307 // Expand to a bitconvert of the value to the integer type of the
12308 // same size, then a (misaligned) int store.
12309 // FIXME: Does not handle truncating floating point stores!
12310 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12311 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12312 Alignment, ST->getMemOperand()->getFlags(),
12313 ST->getMMOMetadataForSubAccess());
12314 return Result;
12315 }
12316 // Do a (aligned) store to a stack slot, then copy from the stack slot
12317 // to the final destination using (unaligned) integer loads and stores.
12318 MVT RegVT = getRegisterType(
12319 *DAG.getContext(),
12320 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12321 EVT PtrVT = Ptr.getValueType();
12322 unsigned StoredBytes = StoreMemVT.getStoreSize();
12323 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12324 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12325
12326 // Make sure the stack slot is also aligned for the register type.
12327 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12328 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12329
12330 // Perform the original store, only redirected to the stack slot.
12332 Chain, dl, Val, StackPtr,
12333 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12334
12335 EVT StackPtrVT = StackPtr.getValueType();
12336
12337 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12338 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12340 unsigned Offset = 0;
12341
12342 // Do all but one copies using the full register width.
12343 for (unsigned i = 1; i < NumRegs; i++) {
12344 // Load one integer register's worth from the stack slot.
12345 SDValue Load = DAG.getLoad(
12346 RegVT, dl, Store, StackPtr,
12347 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12348 // Store it to the final location. Remember the store.
12349 Stores.push_back(DAG.getStore(
12350 Load.getValue(1), dl, Load, Ptr,
12351 ST->getPointerInfo().getWithOffset(Offset), ST->getBaseAlign(),
12352 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess()));
12353 // Increment the pointers.
12354 Offset += RegBytes;
12355 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12356 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12357 }
12358
12359 // The last store may be partial. Do a truncating store. On big-endian
12360 // machines this requires an extending load from the stack slot to ensure
12361 // that the bits are in the right place.
12362 EVT LoadMemVT =
12363 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12364
12365 // Load from the stack slot.
12366 SDValue Load = DAG.getExtLoad(
12367 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12368 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12369
12370 Stores.push_back(
12371 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
12372 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12373 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12374 ST->getMMOMetadataForSubAccess()));
12375 // The order of the stores doesn't matter - say it with a TokenFactor.
12376 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12377 return Result;
12378 }
12379
12380 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12381 "Unaligned store of unknown type.");
12382 // Get the half-size VT
12383 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12384 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12385 unsigned IncrementSize = NumBits / 8;
12386
12387 // Divide the stored value in two parts.
12388 SDValue ShiftAmount =
12389 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12390 SDValue Lo = Val;
12391 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12392 // fold and not use the upper bits. A smaller constant may be easier to
12393 // materialize.
12394 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12395 Lo = DAG.getNode(
12396 ISD::AND, dl, VT, Lo,
12397 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12398 VT));
12399 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12400
12401 // Store the two parts
12402 SDValue Store1, Store2;
12403 Store1 = DAG.getTruncStore(
12404 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Lo : Hi, Ptr,
12405 ST->getPointerInfo(), NewStoredVT, Alignment,
12406 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12407
12408 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12409 Store2 = DAG.getTruncStore(
12410 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12411 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12412 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12413
12414 SDValue Result =
12415 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12416 return Result;
12417}
12418
12419SDValue
12421 const SDLoc &DL, EVT DataVT,
12422 SelectionDAG &DAG,
12423 bool IsCompressedMemory) const {
12425 EVT AddrVT = Addr.getValueType();
12426 EVT MaskVT = Mask.getValueType();
12427 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12428 "Incompatible types of Data and Mask");
12429 if (IsCompressedMemory) {
12430 // Incrementing the pointer according to number of '1's in the mask.
12431 if (DataVT.isScalableVector()) {
12432 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12433 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12434 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12435 } else {
12436 EVT MaskIntVT =
12437 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12438 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12439 if (MaskIntVT.getSizeInBits() < 32) {
12440 MaskInIntReg =
12441 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12442 MaskIntVT = MVT::i32;
12443 }
12444 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12445 }
12446 // Scale is an element size in bytes.
12447 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12448 AddrVT);
12449 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12450 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12451 } else
12452 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12453
12454 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12455}
12456
12458 EVT VecVT, const SDLoc &dl,
12459 ElementCount SubEC) {
12460 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12461 "Cannot index a scalable vector within a fixed-width vector");
12462
12463 unsigned NElts = VecVT.getVectorMinNumElements();
12464 unsigned NumSubElts = SubEC.getKnownMinValue();
12465 EVT IdxVT = Idx.getValueType();
12466
12467 if (VecVT.isScalableVector() && !SubEC.isScalable()) {
12468 // If this is a constant index and we know the value plus the number of the
12469 // elements in the subvector minus one is less than the minimum number of
12470 // elements then it's safe to return Idx.
12471 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
12472 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
12473 return Idx;
12474 SDValue VS =
12475 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
12476 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
12477 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
12478 DAG.getConstant(NumSubElts, dl, IdxVT));
12479 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
12480 }
12481 if (isPowerOf2_32(NElts) && NumSubElts == 1) {
12483 return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
12484 DAG.getConstant(Imm, dl, IdxVT));
12485 }
12486 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
12487 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
12488 DAG.getConstant(MaxIndex, dl, IdxVT));
12489}
12490
12491SDValue
12493 EVT VecVT, SDValue Index,
12494 const SDNodeFlags PtrArithFlags) const {
12496 DAG, VecPtr, VecVT,
12498 Index, PtrArithFlags);
12499}
12500
12501SDValue
12503 EVT VecVT, EVT SubVecVT, SDValue Index,
12504 const SDNodeFlags PtrArithFlags) const {
12505 SDLoc dl(Index);
12506 // Make sure the index type is big enough to compute in.
12507 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12508
12509 EVT EltVT = VecVT.getVectorElementType();
12510
12511 // Calculate the element offset and add it to the pointer.
12512 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12513 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12514 "Converting bits to bytes lost precision");
12515 assert(SubVecVT.getVectorElementType() == EltVT &&
12516 "Sub-vector must be a vector with matching element type");
12517
12518 // An out-of-range index only makes the vector operation return poison, but
12519 // a load/store through the pointer computed below would be immediate UB, so
12520 // freeze the index before clamping it into range.
12521 if (!DAG.isGuaranteedNotToBePoison(Index))
12522 Index = DAG.getFreeze(Index);
12523
12524 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12525 SubVecVT.getVectorElementCount());
12526
12527 EVT IdxVT = Index.getValueType();
12528 if (SubVecVT.isScalableVector())
12529 Index =
12530 DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12531 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
12532
12533 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12534 DAG.getConstant(EltSize, dl, IdxVT));
12535 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12536}
12537
12538//===----------------------------------------------------------------------===//
12539// Implementation of Emulated TLS Model
12540//===----------------------------------------------------------------------===//
12541
12543 SelectionDAG &DAG) const {
12544 // Access to address of TLS varialbe xyz is lowered to a function call:
12545 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12546 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12547 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12548 SDLoc dl(GA);
12549
12550 ArgListTy Args;
12551 const GlobalValue *GV =
12553 SmallString<32> NameString("__emutls_v.");
12554 NameString += GV->getName();
12555 StringRef EmuTlsVarName(NameString);
12556 const GlobalVariable *EmuTlsVar =
12557 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12558 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12559 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12560
12561 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12562
12564 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12565 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12566 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12567
12568 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12569 // At last for X86 targets, maybe good for other targets too?
12571 MFI.setAdjustsStack(true); // Is this only for X86 target?
12572 MFI.setHasCalls(true);
12573
12574 assert((GA->getOffset() == 0) &&
12575 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12576 return CallResult.first;
12577}
12578
12580 SelectionDAG &DAG) const {
12581 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12582 if (!isCtlzFast())
12583 return SDValue();
12584 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12585 SDLoc dl(Op);
12586 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12587 EVT VT = Op.getOperand(0).getValueType();
12588 SDValue Zext = Op.getOperand(0);
12589 if (VT.bitsLT(MVT::i32)) {
12590 VT = MVT::i32;
12591 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12592 }
12593 unsigned Log2b = Log2_32(VT.getSizeInBits());
12594 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12595 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12596 DAG.getConstant(Log2b, dl, MVT::i32));
12597 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12598 }
12599 return SDValue();
12600}
12601
12603 SDValue Op0 = Node->getOperand(0);
12604 SDValue Op1 = Node->getOperand(1);
12605 EVT VT = Op0.getValueType();
12606 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12607 unsigned Opcode = Node->getOpcode();
12608 SDLoc DL(Node);
12609
12610 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12611 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12612 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12613 DAG.SignBitIsZero(Op1))
12614 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12615
12616 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12617 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12619 Op0 = DAG.getFreeze(Op0);
12620 SDValue Zero = DAG.getConstant(0, DL, VT);
12621 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12622 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12623 }
12624
12625 // umin(x,y) -> sub(x,usubsat(x,y))
12626 // TODO: Missing freeze(Op0)?
12627 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12629 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12630 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12631 }
12632
12633 // umax(x,y) -> add(x,usubsat(y,x))
12634 // TODO: Missing freeze(Op0)?
12635 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12637 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12638 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12639 }
12640
12641 // FIXME: Should really try to split the vector in case it's legal on a
12642 // subvector.
12644 return DAG.UnrollVectorOp(Node);
12645
12646 // Attempt to find an existing SETCC node that we can reuse.
12647 // TODO: Do we need a generic doesSETCCNodeExist?
12648 // TODO: Missing freeze(Op0)/freeze(Op1)?
12649 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12650 ISD::CondCode PrefCommuteCC,
12651 ISD::CondCode AltCommuteCC) {
12652 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12653 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12654 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12655 {Op0, Op1, DAG.getCondCode(CC)})) {
12656 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12657 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12658 }
12659 }
12660 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12661 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12662 {Op0, Op1, DAG.getCondCode(CC)})) {
12663 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12664 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12665 }
12666 }
12667 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12668 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12669 };
12670
12671 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12672 // -> Y = (A < B) ? B : A
12673 // -> Y = (A >= B) ? A : B
12674 // -> Y = (A <= B) ? B : A
12675 switch (Opcode) {
12676 case ISD::SMAX:
12677 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12678 case ISD::SMIN:
12679 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12680 case ISD::UMAX:
12681 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12682 case ISD::UMIN:
12683 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12684 }
12685
12686 llvm_unreachable("How did we get here?");
12687}
12688
12690 unsigned Opcode = Node->getOpcode();
12691 SDValue LHS = Node->getOperand(0);
12692 SDValue RHS = Node->getOperand(1);
12693 EVT VT = LHS.getValueType();
12694 SDLoc dl(Node);
12695
12696 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12697 assert(VT.isInteger() && "Expected operands to be integers");
12698
12699 // usub.sat(a, b) -> umax(a, b) - b
12700 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12701 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12702 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12703 }
12704
12705 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12706 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12707 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12709 LHS = DAG.getFreeze(LHS);
12710 SDValue Zero = DAG.getConstant(0, dl, VT);
12711 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12712 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12713 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12714 Subtrahend =
12715 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12716 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12717 }
12718
12719 // uadd.sat(a, b) -> umin(a, ~b) + b
12720 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12721 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12722 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12723 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12724 }
12725
12726 unsigned OverflowOp;
12727 switch (Opcode) {
12728 case ISD::SADDSAT:
12729 OverflowOp = ISD::SADDO;
12730 break;
12731 case ISD::UADDSAT:
12732 OverflowOp = ISD::UADDO;
12733 break;
12734 case ISD::SSUBSAT:
12735 OverflowOp = ISD::SSUBO;
12736 break;
12737 case ISD::USUBSAT:
12738 OverflowOp = ISD::USUBO;
12739 break;
12740 default:
12741 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12742 "addition or subtraction node.");
12743 }
12744
12745 // FIXME: Should really try to split the vector in case it's legal on a
12746 // subvector.
12748 return DAG.UnrollVectorOp(Node);
12749
12750 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12751 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12752 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12753 SDValue SumDiff = Result.getValue(0);
12754 SDValue Overflow = Result.getValue(1);
12755 SDValue Zero = DAG.getConstant(0, dl, VT);
12756 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12757
12758 if (Opcode == ISD::UADDSAT) {
12760 // (LHS + RHS) | OverflowMask
12761 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12762 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12763 }
12764 // Overflow ? 0xffff.... : (LHS + RHS)
12765 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12766 }
12767
12768 if (Opcode == ISD::USUBSAT) {
12770 // (LHS - RHS) & ~OverflowMask
12771 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12772 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12773 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12774 }
12775 // Overflow ? 0 : (LHS - RHS)
12776 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12777 }
12778
12779 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12780 "Expected signed saturating add/sub opcode");
12781
12782 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12783 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12784
12785 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12786 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12787
12788 // If either of the operand signs are known, then they are guaranteed to
12789 // only saturate in one direction. If non-negative they will saturate
12790 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12791 //
12792 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12793 // sign of 'y' has to be flipped.
12794
12795 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12796 bool RHSIsNonNegative =
12797 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12798 if (LHSIsNonNegative || RHSIsNonNegative) {
12799 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12800 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12801 }
12802
12803 bool LHSIsNegative = KnownLHS.isNegative();
12804 bool RHSIsNegative =
12805 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12806 if (LHSIsNegative || RHSIsNegative) {
12807 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12808 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
12809 }
12810
12811 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
12812 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12813 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
12814 DAG.getConstant(BitWidth - 1, dl, VT));
12815 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
12816 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
12817}
12818
12820 unsigned Opcode = Node->getOpcode();
12821 SDValue LHS = Node->getOperand(0);
12822 SDValue RHS = Node->getOperand(1);
12823 EVT VT = LHS.getValueType();
12824 EVT ResVT = Node->getValueType(0);
12825 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12826 SDLoc dl(Node);
12827
12828 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
12829 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
12830 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
12831 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
12832
12833 // We can't perform arithmetic on i1 values. Extending them would
12834 // probably result in worse codegen, so let's just use two selects instead.
12835 // Some targets are also just better off using selects rather than subtraction
12836 // because one of the conditions can be merged with one of the selects.
12837 // And finally, if we don't know the contents of high bits of a boolean value
12838 // we can't perform any arithmetic either.
12840 BoolVT.getScalarSizeInBits() == 1 ||
12842 SDValue SelectZeroOrOne =
12843 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
12844 DAG.getConstant(0, dl, ResVT));
12845 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
12846 SelectZeroOrOne);
12847 }
12848
12850 std::swap(IsGT, IsLT);
12851 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
12852 ResVT);
12853}
12854
12856 unsigned Opcode = Node->getOpcode();
12857 bool IsSigned = Opcode == ISD::SSHLSAT;
12858 SDValue LHS = Node->getOperand(0);
12859 SDValue RHS = Node->getOperand(1);
12860 EVT VT = LHS.getValueType();
12861 SDLoc dl(Node);
12862
12863 assert((Node->getOpcode() == ISD::SSHLSAT ||
12864 Node->getOpcode() == ISD::USHLSAT) &&
12865 "Expected a SHLSAT opcode");
12866 assert(VT.isInteger() && "Expected operands to be integers");
12867
12869 return DAG.UnrollVectorOp(Node);
12870
12871 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
12872
12873 unsigned BW = VT.getScalarSizeInBits();
12874 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12875 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
12876 SDValue Orig =
12877 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
12878
12879 SDValue SatVal;
12880 if (IsSigned) {
12881 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
12882 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
12883 SDValue Cond =
12884 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
12885 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
12886 } else {
12887 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
12888 }
12889 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
12890 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
12891}
12892
12894 bool Signed, SDValue &Lo, SDValue &Hi,
12895 SDValue LHS, SDValue RHS,
12896 SDValue HiLHS, SDValue HiRHS) const {
12897 EVT VT = LHS.getValueType();
12898 assert(RHS.getValueType() == VT && "Mismatching operand types");
12899
12900 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
12901 assert((!Signed || !HiLHS) &&
12902 "Signed flag should only be set when HiLHS and RiRHS are null");
12903
12904 // We'll expand the multiplication by brute force because we have no other
12905 // options. This is a trivially-generalized version of the code from
12906 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
12907 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
12908 // sign bits while calculating the Hi half.
12909 unsigned Bits = VT.getScalarSizeInBits();
12910 unsigned HalfBits = Bits / 2;
12911 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
12912 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
12913 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
12914
12915 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
12916 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
12917
12918 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
12919 // This is always an unsigned shift.
12920 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
12921
12922 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
12923 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
12924 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
12925
12926 SDValue U =
12927 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
12928 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
12929 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
12930
12931 SDValue V =
12932 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
12933 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
12934
12935 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
12936 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
12937
12938 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
12939 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
12940
12941 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
12942 // the products to Hi.
12943 if (HiLHS) {
12944 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
12945 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
12946 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
12947 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
12948 }
12949}
12950
12952 bool Signed, const SDValue LHS,
12953 const SDValue RHS, SDValue &Lo,
12954 SDValue &Hi) const {
12955 EVT VT = LHS.getValueType();
12956 assert(RHS.getValueType() == VT && "Mismatching operand types");
12957 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12958 // We can fall back to a libcall with an illegal type for the MUL if we
12959 // have a libcall big enough.
12960 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
12961 if (WideVT == MVT::i16)
12962 LC = RTLIB::MUL_I16;
12963 else if (WideVT == MVT::i32)
12964 LC = RTLIB::MUL_I32;
12965 else if (WideVT == MVT::i64)
12966 LC = RTLIB::MUL_I64;
12967 else if (WideVT == MVT::i128)
12968 LC = RTLIB::MUL_I128;
12969
12970 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
12971 if (LibcallImpl == RTLIB::Unsupported) {
12972 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
12973 return;
12974 }
12975
12976 // The libcall takes and returns WideVT values as packed VT halves. This only
12977 // works if VT is legal and WideVT isn't. Otherwise, emit a wide multiply and
12978 // let it legalise normally, possibly into a wider libcall.
12979 if (isTypeLegal(WideVT) || !isTypeLegal(VT)) {
12980 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT,
12981 DAG.getExtOrTrunc(Signed, LHS, dl, WideVT),
12982 DAG.getExtOrTrunc(Signed, RHS, dl, WideVT));
12983 SDValue Shift =
12984 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
12985 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
12986 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT,
12987 DAG.getNode(ISD::SRL, dl, WideVT, Mul, Shift));
12988 return;
12989 }
12990
12991 SDValue HiLHS, HiRHS;
12992 if (Signed) {
12993 // The high part is obtained by SRA'ing all but one of the bits of low
12994 // part.
12995 unsigned LoSize = VT.getFixedSizeInBits();
12996 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
12997 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
12998 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
12999 } else {
13000 HiLHS = DAG.getConstant(0, dl, VT);
13001 HiRHS = DAG.getConstant(0, dl, VT);
13002 }
13003
13004 // Attempt a libcall.
13005 SDValue Ret;
13007 CallOptions.setIsSigned(Signed);
13008 CallOptions.setIsPostTypeLegalization(true);
13010 // Halves of WideVT are packed into registers in different order
13011 // depending on platform endianness. This is usually handled by
13012 // the C calling convention, but we can't defer to it in
13013 // the legalizer.
13014 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
13015 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13016 } else {
13017 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
13018 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13019 }
13021 "Ret value is a collection of constituent nodes holding result.");
13022 if (DAG.getDataLayout().isLittleEndian()) {
13023 // Same as above.
13024 Lo = Ret.getOperand(0);
13025 Hi = Ret.getOperand(1);
13026 } else {
13027 Lo = Ret.getOperand(1);
13028 Hi = Ret.getOperand(0);
13029 }
13030}
13031
13032SDValue
13034 assert((Node->getOpcode() == ISD::SMULFIX ||
13035 Node->getOpcode() == ISD::UMULFIX ||
13036 Node->getOpcode() == ISD::SMULFIXSAT ||
13037 Node->getOpcode() == ISD::UMULFIXSAT) &&
13038 "Expected a fixed point multiplication opcode");
13039
13040 SDLoc dl(Node);
13041 SDValue LHS = Node->getOperand(0);
13042 SDValue RHS = Node->getOperand(1);
13043 EVT VT = LHS.getValueType();
13044 unsigned Scale = Node->getConstantOperandVal(2);
13045 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
13046 Node->getOpcode() == ISD::UMULFIXSAT);
13047 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
13048 Node->getOpcode() == ISD::SMULFIXSAT);
13049 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13050 unsigned VTSize = VT.getScalarSizeInBits();
13051
13052 if (!Scale) {
13053 // [us]mul.fix(a, b, 0) -> mul(a, b)
13054 if (!Saturating) {
13056 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13057 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
13058 SDValue Result =
13059 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13060 SDValue Product = Result.getValue(0);
13061 SDValue Overflow = Result.getValue(1);
13062 SDValue Zero = DAG.getConstant(0, dl, VT);
13063
13064 APInt MinVal = APInt::getSignedMinValue(VTSize);
13065 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
13066 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13067 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13068 // Xor the inputs, if resulting sign bit is 0 the product will be
13069 // positive, else negative.
13070 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
13071 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
13072 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
13073 return DAG.getSelect(dl, VT, Overflow, Result, Product);
13074 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
13075 SDValue Result =
13076 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13077 SDValue Product = Result.getValue(0);
13078 SDValue Overflow = Result.getValue(1);
13079
13080 APInt MaxVal = APInt::getMaxValue(VTSize);
13081 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13082 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
13083 }
13084 }
13085
13086 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
13087 "Expected scale to be less than the number of bits if signed or at "
13088 "most the number of bits if unsigned.");
13089 assert(LHS.getValueType() == RHS.getValueType() &&
13090 "Expected both operands to be the same type");
13091
13092 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
13093 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
13094 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
13095 SDValue Val, ISD::CondCode CC) {
13096 if (VT.isVector())
13097 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
13098 Sat, Val);
13099 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
13100 };
13101
13102 // Get the upper and lower bits of the result.
13103 SDValue Lo, Hi;
13104 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13105 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
13106 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13107 if (isOperationLegalOrCustom(LoHiOp, VT)) {
13108 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
13109 Lo = Result.getValue(0);
13110 Hi = Result.getValue(1);
13111 } else if (isOperationLegalOrCustom(HiOp, VT)) {
13112 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13113 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
13114 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13115 // Try for a multiplication using a wider type.
13116 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13117 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
13118 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
13119 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
13120 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
13121 SDValue Shifted =
13122 DAG.getNode(ISD::SRA, dl, WideVT, Res,
13123 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
13124 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
13125 } else if (VT.isVector()) {
13126 return SDValue();
13127 } else {
13128 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
13129 }
13130
13131 if (Scale == VTSize)
13132 // Result is just the top half since we'd be shifting by the width of the
13133 // operand. Overflow impossible so this works for both UMULFIX and
13134 // UMULFIXSAT.
13135 return Hi;
13136
13137 // The result will need to be shifted right by the scale since both operands
13138 // are scaled. The result is given to us in 2 halves, so we only want part of
13139 // both in the result.
13140 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
13141 DAG.getShiftAmountConstant(Scale, VT, dl));
13142 if (!Saturating)
13143 return Result;
13144
13145 if (!Signed) {
13146 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
13147 // widened multiplication) aren't all zeroes.
13148
13149 // Saturate to max if ((Hi >> Scale) != 0),
13150 // which is the same as if (Hi > ((1 << Scale) - 1))
13151 APInt MaxVal = APInt::getMaxValue(VTSize);
13152 SDValue LowMask =
13153 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
13154 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
13155 Result, ISD::SETUGT);
13156 }
13157
13158 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
13159 // widened multiplication) aren't all ones or all zeroes.
13160
13161 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
13162 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
13163
13164 if (Scale == 0) {
13165 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
13166 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
13167 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
13168 // Saturated to SatMin if wide product is negative, and SatMax if wide
13169 // product is positive ...
13170 SDValue Zero = DAG.getConstant(0, dl, VT);
13171 SDValue ResultIfOverflow =
13172 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
13173 // ... but only if we overflowed.
13174 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
13175 }
13176
13177 // We handled Scale==0 above so all the bits to examine is in Hi.
13178
13179 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
13180 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
13181 SDValue LowMask =
13182 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
13183 // Saturate to min if (Hi >> (Scale - 1)) < -1),
13184 // which is the same as if (HI < (-1 << (Scale - 1))
13185 SDValue HighMask = DAG.getConstant(
13186 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
13187 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
13188 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
13189 return Result;
13190}
13191
13192SDValue
13194 SDValue LHS, SDValue RHS,
13195 unsigned Scale, SelectionDAG &DAG) const {
13196 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
13197 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
13198 "Expected a fixed point division opcode");
13199
13200 EVT VT = LHS.getValueType();
13201 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
13202 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
13203 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13204
13205 // If there is enough room in the type to upscale the LHS or downscale the
13206 // RHS before the division, we can perform it in this type without having to
13207 // resize. For signed operations, the LHS headroom is the number of
13208 // redundant sign bits, and for unsigned ones it is the number of zeroes.
13209 // The headroom for the RHS is the number of trailing zeroes.
13210 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
13212 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
13213
13214 // For signed saturating operations, we need to be able to detect true integer
13215 // division overflow; that is, when you have MIN / -EPS. However, this
13216 // is undefined behavior and if we emit divisions that could take such
13217 // values it may cause undesired behavior (arithmetic exceptions on x86, for
13218 // example).
13219 // Avoid this by requiring an extra bit so that we never get this case.
13220 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13221 // signed saturating division, we need to emit a whopping 32-bit division.
13222 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13223 return SDValue();
13224
13225 unsigned LHSShift = std::min(LHSLead, Scale);
13226 unsigned RHSShift = Scale - LHSShift;
13227
13228 // At this point, we know that if we shift the LHS up by LHSShift and the
13229 // RHS down by RHSShift, we can emit a regular division with a final scaling
13230 // factor of Scale.
13231
13232 if (LHSShift)
13233 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13234 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13235 if (RHSShift)
13236 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13237 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13238
13239 SDValue Quot;
13240 if (Signed) {
13241 // For signed operations, if the resulting quotient is negative and the
13242 // remainder is nonzero, subtract 1 from the quotient to round towards
13243 // negative infinity.
13244 SDValue Rem;
13245 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13246 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13247 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13248 if (isTypeLegal(VT) &&
13250 Quot = DAG.getNode(ISD::SDIVREM, dl,
13251 DAG.getVTList(VT, VT),
13252 LHS, RHS);
13253 Rem = Quot.getValue(1);
13254 Quot = Quot.getValue(0);
13255 } else {
13256 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13257 LHS, RHS);
13258 Rem = DAG.getNode(ISD::SREM, dl, VT,
13259 LHS, RHS);
13260 }
13261 SDValue Zero = DAG.getConstant(0, dl, VT);
13262 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13263 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13264 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13265 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13266 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13267 DAG.getConstant(1, dl, VT));
13268 Quot = DAG.getSelect(dl, VT,
13269 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13270 Sub1, Quot);
13271 } else
13272 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13273 LHS, RHS);
13274
13275 return Quot;
13276}
13277
13279 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13280 SDLoc dl(Node);
13281 SDValue LHS = Node->getOperand(0);
13282 SDValue RHS = Node->getOperand(1);
13283 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13284
13285 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13286 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13287 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13288 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13289 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13290 { LHS, RHS, CarryIn });
13291 Result = SDValue(NodeCarry.getNode(), 0);
13292 Overflow = SDValue(NodeCarry.getNode(), 1);
13293 return;
13294 }
13295
13296 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13297 LHS.getValueType(), LHS, RHS);
13298
13299 EVT ResultType = Node->getValueType(1);
13300 EVT SetCCType = getSetCCResultType(
13301 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13302 SDValue SetCC;
13303 if (IsAdd && isOneConstant(RHS)) {
13304 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13305 // the live range of X. We assume comparing with 0 is cheap.
13306 // The general case (X + C) < C is not necessarily beneficial. Although we
13307 // reduce the live range of X, we may introduce the materialization of
13308 // constant C.
13309 SetCC =
13310 DAG.getSetCC(dl, SetCCType, Result,
13311 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13312 } else if (IsAdd && isAllOnesConstant(RHS)) {
13313 // Special case: uaddo X, -1 overflows if X != 0.
13314 SetCC =
13315 DAG.getSetCC(dl, SetCCType, LHS,
13316 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13317 } else {
13318 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
13319 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13320 }
13321 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13322}
13323
13325 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13326 SDLoc dl(Node);
13327 SDValue LHS = Node->getOperand(0);
13328 SDValue RHS = Node->getOperand(1);
13329 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13330
13331 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13332 LHS.getValueType(), LHS, RHS);
13333
13334 EVT ResultType = Node->getValueType(1);
13335 EVT OType = getSetCCResultType(
13336 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13337
13338 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13339 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13340 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13341 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13342 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13343 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13344 return;
13345 }
13346
13347 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13348
13349 if (IsAdd) {
13350 // For an addition, the result should be less than one of the operands (LHS)
13351 // if and only if the other operand (RHS) is negative, otherwise there will
13352 // be overflow.
13353 SDValue ResultLowerThanLHS =
13354 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13355 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13356 Overflow = DAG.getBoolExtOrTrunc(
13357 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13358 ResultType, ResultType);
13359 } else {
13360 // For subtraction, overflow occurs when the signed comparison of operands
13361 // doesn't match the sign of the result.
13362 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13363 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13364 Overflow = DAG.getBoolExtOrTrunc(
13365 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13366 ResultType, ResultType);
13367 }
13368}
13369
13371 SDValue &Overflow, SelectionDAG &DAG) const {
13372 SDLoc dl(Node);
13373 EVT VT = Node->getValueType(0);
13374 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13375 SDValue LHS = Node->getOperand(0);
13376 SDValue RHS = Node->getOperand(1);
13377 bool isSigned = Node->getOpcode() == ISD::SMULO;
13378
13379 // For power-of-two multiplications we can use a simpler shift expansion.
13380 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13381 const APInt &C = RHSC->getAPIntValue();
13382 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13383 if (C.isPowerOf2()) {
13384 // smulo(x, signed_min) is same as umulo(x, signed_min).
13385 bool UseArithShift = isSigned && !C.isMinSignedValue();
13386 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13387 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13388 Overflow = DAG.getSetCC(dl, SetCCVT,
13389 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13390 dl, VT, Result, ShiftAmt),
13391 LHS, ISD::SETNE);
13392 return true;
13393 }
13394 }
13395
13396 SDValue BottomHalf;
13397 SDValue TopHalf;
13398 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13399
13400 static const unsigned Ops[2][3] =
13403 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13404 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13405 RHS);
13406 TopHalf = BottomHalf.getValue(1);
13407 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13408 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13409 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13410 } else if (isTypeLegal(WideVT)) {
13411 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13412 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13413 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13414 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13415 SDValue ShiftAmt =
13416 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13417 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13418 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13419 } else {
13420 if (VT.isVector())
13421 return false;
13422
13423 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13424 }
13425
13426 Result = BottomHalf;
13427 if (isSigned) {
13428 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13429 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13430 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13431 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13432 } else {
13433 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13434 DAG.getConstant(0, dl, VT), ISD::SETNE);
13435 }
13436
13437 // Truncate the result if SetCC returns a larger type than needed.
13438 EVT RType = Node->getValueType(1);
13439 if (RType.bitsLT(Overflow.getValueType()))
13440 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13441
13442 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13443 "Unexpected result type for S/UMULO legalization");
13444 return true;
13445}
13446
13448 SDLoc dl(Node);
13449 EVT VT = Node->getValueType(0);
13450 SDValue LHS = Node->getOperand(0);
13451 SDValue RHS = Node->getOperand(1);
13452 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13453
13454 // Use MUL_LOHI if legal/custom for the original type.
13455 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13456 if (isOperationLegalOrCustom(LoHiOp, VT))
13457 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13458
13459 // Use a wide multiply if available.
13460 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13461 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13462 unsigned BW = VT.getScalarSizeInBits();
13463 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13464 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13465 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13466 DAG.getNode(ISD::SRL, dl, WideVT,
13467 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13468 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13469 }
13470
13471 // Let fixed-length vectors be scalarised by the caller.
13472 // Expand everything else with a wide multiply.
13473 if (!VT.isFixedLengthVector()) {
13474 SDValue Lo, Hi;
13475 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13476 return Hi;
13477 }
13478
13479 return SDValue();
13480}
13481
13483 SDLoc dl(Node);
13484 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13485 SDValue Op = Node->getOperand(0);
13486 SDNodeFlags Flags = Node->getFlags();
13487 EVT VT = Op.getValueType();
13488
13489 // Try to use a shuffle reduction for power of two vectors.
13490 if (VT.isPow2VectorType()) {
13491 // See if the reduction opcode is safe to use with widened types.
13492 bool WidenSrc = false;
13493 switch (Node->getOpcode()) {
13496 case ISD::VECREDUCE_ADD:
13497 case ISD::VECREDUCE_MUL:
13498 case ISD::VECREDUCE_AND:
13499 case ISD::VECREDUCE_OR:
13500 case ISD::VECREDUCE_XOR:
13505 WidenSrc = VT.isFixedLengthVector();
13506 break;
13507 }
13508
13510 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13511 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13512 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13513 // Attempt to widen the source vectors to a legal op.
13514 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13515 if (WideVT.isVector() &&
13516 WideVT.getScalarType() == HalfVT.getScalarType() &&
13517 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13518 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13519 SDValue Lo, Hi;
13520 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13521 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13522 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13523 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13524 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13525 VT = HalfVT;
13526 continue;
13527 }
13528 }
13529 break;
13530 }
13531
13532 SDValue Lo, Hi;
13533 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13534 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13535 VT = HalfVT;
13536
13537 // Stop if splitting is enough to make the reduction legal.
13538 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13539 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13540 Flags);
13541 }
13542 }
13543
13544 if (VT.isScalableVector())
13546 "Expanding reductions for scalable vectors is undefined.");
13547
13548 EVT EltVT = VT.getVectorElementType();
13549 unsigned NumElts = VT.getVectorNumElements();
13550
13552 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13553
13554 SDValue Res = Ops[0];
13555 for (unsigned i = 1; i < NumElts; i++)
13556 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13557
13558 // Result type may be wider than element type.
13559 if (EltVT != Node->getValueType(0))
13560 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13561 return Res;
13562}
13563
13565 SDLoc dl(Node);
13566 SDValue AccOp = Node->getOperand(0);
13567 SDValue VecOp = Node->getOperand(1);
13568 SDNodeFlags Flags = Node->getFlags();
13569
13570 EVT VT = VecOp.getValueType();
13571 EVT EltVT = VT.getVectorElementType();
13572
13573 if (VT.isScalableVector())
13575 "Expanding reductions for scalable vectors is undefined.");
13576
13577 unsigned NumElts = VT.getVectorNumElements();
13578
13580 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13581
13582 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13583
13584 SDValue Res = AccOp;
13585 for (unsigned i = 0; i < NumElts; i++)
13586 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13587
13588 return Res;
13589}
13590
13592 SelectionDAG &DAG) const {
13593 EVT VT = Node->getValueType(0);
13594 SDLoc dl(Node);
13595 bool isSigned = Node->getOpcode() == ISD::SREM;
13596 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13597 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13598 SDValue Dividend = Node->getOperand(0);
13599 SDValue Divisor = Node->getOperand(1);
13600 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13601 SDVTList VTs = DAG.getVTList(VT, VT);
13602 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13603 return true;
13604 }
13605 if (isOperationLegalOrCustom(DivOpc, VT)) {
13606 // X % Y -> X-X/Y*Y
13607 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13608 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13609 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13610 return true;
13611 }
13612 return false;
13613}
13614
13616 SelectionDAG &DAG) const {
13617 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13618 SDLoc dl(SDValue(Node, 0));
13619 SDValue Src = Node->getOperand(0);
13620
13621 // DstVT is the result type, while SatVT is the size to which we saturate
13622 EVT SrcVT = Src.getValueType();
13623 EVT DstVT = Node->getValueType(0);
13624
13625 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13626 unsigned SatWidth = SatVT.getScalarSizeInBits();
13627 unsigned DstWidth = DstVT.getScalarSizeInBits();
13628 assert(SatWidth <= DstWidth &&
13629 "Expected saturation width smaller than result width");
13630
13631 // Determine minimum and maximum integer values and their corresponding
13632 // floating-point values.
13633 APInt MinInt, MaxInt;
13634 if (IsSigned) {
13635 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13636 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13637 } else {
13638 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13639 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13640 }
13641
13642 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13643 // libcall emission cannot handle this. Large result types will fail.
13644 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13645 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13646 SrcVT = Src.getValueType();
13647 }
13648
13649 const fltSemantics &Sem = SrcVT.getFltSemantics();
13650 APFloat MinFloat(Sem);
13651 APFloat MaxFloat(Sem);
13652
13653 APFloat::opStatus MinStatus =
13654 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13655 APFloat::opStatus MaxStatus =
13656 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13657 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13658 !(MaxStatus & APFloat::opStatus::opInexact);
13659
13660 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13661 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13662
13663 // If the integer bounds are exactly representable as floats and min/max are
13664 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13665 // of comparisons and selects.
13666 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13667 bool MayPropagateNaN) {
13668 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13669 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13670 if (!MinMaxLegal)
13671 return SDValue();
13672
13673 SDValue Clamped = Src;
13674
13675 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13676 // then the result is MinFloat.
13677 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13678 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13679 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13680 // Convert clamped value to integer.
13681 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13682 dl, DstVT, Clamped);
13683
13684 // If !MayPropagateNan and the conversion is unsigned case we're done,
13685 // because we mapped NaN to MinFloat, which will cast to zero.
13686 if (!MayPropagateNaN && !IsSigned)
13687 return FpToInt;
13688
13689 // Otherwise, select 0 if Src is NaN.
13690 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13691 EVT SetCCVT =
13692 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13693 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13694 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13695 };
13696 if (AreExactFloatBounds) {
13697 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13698 /*MayPropagateNaN=*/false))
13699 return Res;
13700 // These may propagate NaN for sNaN operands.
13701 if (SDValue Res =
13702 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13703 return Res;
13704 // These always propagate NaN.
13705 if (SDValue Res =
13706 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13707 return Res;
13708 }
13709
13710 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13711 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13712
13713 // Result of direct conversion. The assumption here is that the operation is
13714 // non-trapping and it's fine to apply it to an out-of-range value if we
13715 // select it away later.
13716 SDValue FpToInt =
13717 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13718
13719 SDValue Select = FpToInt;
13720
13721 EVT SetCCVT =
13722 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13723
13724 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13725 // MinInt if Src is NaN.
13726 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13727 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13728 // If Src OGT MaxFloat, select MaxInt.
13729 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13730 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13731
13732 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13733 // is already zero.
13734 if (!IsSigned)
13735 return Select;
13736
13737 // Otherwise, select 0 if Src is NaN.
13738 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13739 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13740 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13741}
13742
13744 const SDLoc &dl,
13745 SelectionDAG &DAG) const {
13746 EVT OperandVT = Op.getValueType();
13747 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13748 return Op;
13749 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13750 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13751 // can induce double-rounding which may alter the results. We can
13752 // correct for this using a trick explained in: Boldo, Sylvie, and
13753 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13754 // World Congress. 2005.
13755 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13756 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13757
13758 // We can keep the narrow value as-is if narrowing was exact (no
13759 // rounding error), the wide value was NaN (the narrow value is also
13760 // NaN and should be preserved) or if we rounded to the odd value.
13761 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13762 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13763 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13764 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13765 EVT ResultIntVTCCVT = getSetCCResultType(
13766 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13767 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13768 // The result is already odd so we don't need to do anything.
13769 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13770
13771 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13772 Op.getValueType());
13773 // We keep results which are exact, odd or NaN.
13774 SDValue KeepNarrow =
13775 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13776 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13777 // We morally performed a round-down if AbsNarrow is smaller than
13778 // AbsWide.
13779 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13780 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13781 SDValue NarrowIsRd =
13782 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13783 // If the narrow value is odd or exact, pick it.
13784 // Otherwise, narrow is even and corresponds to either the rounded-up
13785 // or rounded-down value. If narrow is the rounded-down value, we want
13786 // the rounded-up value as it will be odd.
13787 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13788 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13789 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13790 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13791}
13792
13794 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13795 SDValue Op = Node->getOperand(0);
13796 EVT VT = Node->getValueType(0);
13797 SDLoc dl(Node);
13798 if (VT.getScalarType() == MVT::bf16) {
13799 if (Node->getConstantOperandVal(1) == 1) {
13800 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13801 }
13802 EVT OperandVT = Op.getValueType();
13803 SDValue IsNaN = DAG.getSetCC(
13804 dl,
13805 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
13806 Op, Op, ISD::SETUO);
13807
13808 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13809 // can induce double-rounding which may alter the results. We can
13810 // correct for this using a trick explained in: Boldo, Sylvie, and
13811 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13812 // World Congress. 2005.
13813 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
13814 EVT I32 = F32.changeTypeToInteger();
13815 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
13816 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
13817
13818 // Conversions should set NaN's quiet bit. This also prevents NaNs from
13819 // turning into infinities.
13820 SDValue NaN =
13821 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
13822
13823 // Factor in the contribution of the low 16 bits.
13824 SDValue One = DAG.getConstant(1, dl, I32);
13825 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
13826 DAG.getShiftAmountConstant(16, I32, dl));
13827 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
13828 SDValue RoundingBias =
13829 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
13830 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
13831
13832 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
13833 // 0x80000000.
13834 Op = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
13835
13836 // Now that we have rounded, shift the bits into position.
13837 Op = DAG.getNode(ISD::SRL, dl, I32, Op,
13838 DAG.getShiftAmountConstant(16, I32, dl));
13839 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
13840 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
13841 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13842 }
13843 return SDValue();
13844}
13845
13848 SelectionDAG &DAG) const {
13849 assert(Node->getOpcode() == ISD::VECTOR_INTERLEAVE && "Unexpected opcode");
13850 EVT VT = Node->getValueType(0);
13851 unsigned Factor = Node->getNumOperands();
13852 SDLoc DL(Node);
13853
13854 if (Factor > 2 && Factor % 2 == 0) {
13855 SmallVector<EVT> HalfVTs(Factor / 2, VT);
13856 SmallVector<SDValue, 8> LOps, ROps;
13857 // Interleave so we have 2 factors per result:
13858 // a0a1 b0b1 c0c1 d0d1 -> [a0c0 b0d0] [a1c1 b1d1]
13859 for (unsigned I = 0; I < Factor / 2; I++) {
13860 SDValue Interleave =
13861 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, {VT, VT},
13862 {Node->getOperand(I), Node->getOperand(I + Factor / 2)});
13863 LOps.push_back(Interleave.getValue(0));
13864 ROps.push_back(Interleave.getValue(1));
13865 }
13866 // Interleave at Factor/2:
13867 // [a0c0 b0d0] [a1c1 b1d1] -> a0b0 c0d0 a1b1 c1d1
13868 SDValue L = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, LOps);
13869 SDValue R = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, ROps);
13870 for (unsigned I = 0; I < Factor / 2; I++)
13871 Results.push_back(L.getValue(I));
13872 for (unsigned I = 0; I < Factor / 2; I++)
13873 Results.push_back(R.getValue(I));
13874 return;
13875 }
13876
13877 if (!VT.isFixedLengthVector())
13878 return;
13879
13880 unsigned NumElts = VT.getVectorNumElements();
13881 EVT EltVT = VT.getVectorElementType();
13882
13883 // A factor of two needs only same-width, two-input shuffles.
13884 if (Factor == 2) {
13885 SmallVector<int, 8> Mask = createInterleaveMask(NumElts, Factor);
13886 for (unsigned I = 0; I != Factor; ++I)
13887 Results.push_back(DAG.getVectorShuffle(
13888 VT, DL, Node->getOperand(0), Node->getOperand(1),
13889 ArrayRef<int>(Mask).slice(I * NumElts, NumElts)));
13890 return;
13891 }
13892
13893 SmallVector<SDValue> InterleavedElts;
13894 InterleavedElts.reserve(Factor * NumElts);
13895 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
13896 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
13897 InterleavedElts.push_back(DAG.getExtractVectorElt(
13898 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
13899
13900 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx)
13901 Results.push_back(DAG.getBuildVector(
13902 VT, DL, ArrayRef(InterleavedElts).slice(ResultIdx * NumElts, NumElts)));
13903}
13904
13907 SelectionDAG &DAG) const {
13908 assert(Node->getOpcode() == ISD::VECTOR_DEINTERLEAVE && "Unexpected opcode");
13909 EVT VT = Node->getValueType(0);
13910 unsigned Factor = Node->getNumOperands();
13911 SDLoc DL(Node);
13912
13913 if (Factor > 2 && Factor % 2 == 0) {
13915 SmallVector<EVT> HalfVTs(Factor / 2, VT);
13916 // Deinterleave at Factor/2 so each result contains two factors interleaved:
13917 // a0b0 c0d0 a1b1 c1d1 -> [a0c0 b0d0] [a1c1 b1d1]
13918 SDValue L = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
13919 ArrayRef(Ops).take_front(Factor / 2));
13920 SDValue R = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
13921 ArrayRef(Ops).take_back(Factor / 2));
13922 Results.resize(Factor);
13923 // Deinterleave the 2 factors out:
13924 // [a0c0 a1c1] [b0d0 b1d1] -> a0a1 b0b1 c0c1 d0d1
13925 for (unsigned I = 0; I < Factor / 2; ++I) {
13927 {L.getValue(I), R.getValue(I)});
13928 Results[I] = Deinterleave.getValue(0);
13929 Results[I + Factor / 2] = Deinterleave.getValue(1);
13930 }
13931 return;
13932 }
13933
13934 if (!VT.isFixedLengthVector())
13935 return;
13936
13937 unsigned NumElts = VT.getVectorNumElements();
13938 EVT EltVT = VT.getVectorElementType();
13939
13940 // A factor of two needs only same-width, two-input shuffles.
13941 if (Factor == 2) {
13942 for (unsigned I = 0; I != Factor; ++I)
13943 Results.push_back(
13944 DAG.getVectorShuffle(VT, DL, Node->getOperand(0), Node->getOperand(1),
13945 createStrideMask(I, Factor, NumElts)));
13946 return;
13947 }
13948
13949 SmallVector<SDValue> ConcatElts;
13950 ConcatElts.reserve(Factor * NumElts);
13951 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
13952 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
13953 ConcatElts.push_back(DAG.getExtractVectorElt(
13954 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
13955
13956 SmallVector<SDValue> DeinterleavedElts;
13957 DeinterleavedElts.reserve(Factor * NumElts);
13958 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx) {
13959 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
13960 DeinterleavedElts.push_back(ConcatElts[ResultIdx + EltIdx * Factor]);
13961 Results.push_back(DAG.getBuildVector(
13962 VT, DL,
13963 ArrayRef(DeinterleavedElts).slice(ResultIdx * NumElts, NumElts)));
13964 }
13965}
13966
13968 SelectionDAG &DAG) const {
13969 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
13970 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
13971 "Unexpected opcode!");
13972 assert((Node->getValueType(0).isScalableVector() ||
13973 !isa<ConstantSDNode>(Node->getOperand(2))) &&
13974 "Fixed length vector types with constant offsets expected to use "
13975 "SHUFFLE_VECTOR!");
13976
13977 EVT VT = Node->getValueType(0);
13978 SDValue V1 = Node->getOperand(0);
13979 SDValue V2 = Node->getOperand(1);
13980 SDValue Offset = Node->getOperand(2);
13981 SDLoc DL(Node);
13982
13983 // Expand through memory thusly:
13984 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
13985 // Store V1, Ptr
13986 // Store V2, Ptr + sizeof(V1)
13987 // if (VECTOR_SPLICE_LEFT)
13988 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
13989 // else
13990 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
13991 // Res = Load Ptr
13992
13993 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
13994
13996 VT.getVectorElementCount() * 2);
13997 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
13998 EVT PtrVT = StackPtr.getValueType();
13999 auto &MF = DAG.getMachineFunction();
14000 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14001 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
14002
14003 // Store the lo part of CONCAT_VECTORS(V1, V2)
14004 SDValue StoreV1 =
14005 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
14006 // Store the hi part of CONCAT_VECTORS(V1, V2)
14007 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
14008 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
14009 SDValue StoreV2 =
14010 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
14011
14012 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
14013 SDValue EltByteSize =
14014 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
14015 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
14016 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
14017
14018 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
14019
14020 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
14021 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
14022 else
14023 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
14024
14025 // Load the spliced result
14026 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
14028}
14029
14031 SelectionDAG &DAG) const {
14032 SDLoc DL(Node);
14033 SDValue Vec = Node->getOperand(0);
14034 SDValue Mask = Node->getOperand(1);
14035 SDValue Passthru = Node->getOperand(2);
14036
14037 EVT VecVT = Vec.getValueType();
14038 EVT ScalarVT = VecVT.getScalarType();
14039 EVT MaskVT = Mask.getValueType();
14040 EVT MaskScalarVT = MaskVT.getScalarType();
14041
14042 // Needs to be handled by targets that have scalable vector types.
14043 if (VecVT.isScalableVector())
14044 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
14045
14046 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
14047 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
14048 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14049 MachinePointerInfo PtrInfo =
14051
14052 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
14053 SDValue Chain = DAG.getEntryNode();
14054 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
14055
14056 bool HasPassthru = !Passthru.isUndef();
14057
14058 // If we have a passthru vector, store it on the stack, overwrite the matching
14059 // positions and then re-write the last element that was potentially
14060 // overwritten even though mask[i] = false.
14061 if (HasPassthru)
14062 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
14063
14064 SDValue LastWriteVal;
14065 APInt PassthruSplatVal;
14066 bool IsSplatPassthru =
14067 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal);
14068
14069 if (IsSplatPassthru) {
14070 // As we do not know which position we wrote to last, we cannot simply
14071 // access that index from the passthru vector. So we first check if passthru
14072 // is a splat vector, to use any element ...
14073 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
14074 } else if (HasPassthru) {
14075 // ... if it is not a splat vector, we need to get the passthru value at
14076 // position = popcount(mask) and re-load it from the stack before it is
14077 // overwritten in the loop below.
14078 EVT PopcountVT = ScalarVT.changeTypeToInteger();
14079 SDValue Popcount = DAG.getNode(
14081 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
14082 Popcount = DAG.getNode(
14084 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
14085 Popcount);
14086 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
14087 SDValue LastElmtPtr =
14088 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
14089 LastWriteVal = DAG.getLoad(
14090 ScalarVT, DL, Chain, LastElmtPtr,
14092 Chain = LastWriteVal.getValue(1);
14093 }
14094
14095 unsigned NumElms = VecVT.getVectorNumElements();
14096 for (unsigned I = 0; I < NumElms; I++) {
14097 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
14098 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14099 Chain = DAG.getStore(
14100 Chain, DL, ValI, OutPtr,
14102
14103 // Get the mask value and add it to the current output position. This
14104 // either increments by 1 if MaskI is true or adds 0 otherwise.
14105 // Freeze in case we have poison/undef mask entries.
14106 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
14107 MaskI = DAG.getFreeze(MaskI);
14108 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
14109 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
14110 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
14111
14112 if (HasPassthru && I == NumElms - 1) {
14113 SDValue EndOfVector =
14114 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
14115 SDValue AllLanesSelected =
14116 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
14117 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
14118 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14119
14120 // Re-write the last ValI if all lanes were selected. Otherwise,
14121 // overwrite the last write it with the passthru value.
14122 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
14123 LastWriteVal, SDNodeFlags::Unpredictable);
14124 Chain = DAG.getStore(
14125 Chain, DL, LastWriteVal, OutPtr,
14127 }
14128 }
14129
14130 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
14131}
14132
14134 SDLoc DL(Node);
14135 EVT VT = Node->getValueType(0);
14136 SDValue Op = Node->getOperand(0);
14137 ElementCount EC = Op.getValueType().getVectorElementCount();
14138
14139 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
14140 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
14141
14142 // No legal step vector: split mask in half and recombine results.
14143 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
14144 // (== LoNumElts when no active lane), allowing the SETNE comparison.
14145 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
14146 if (!StepVec) {
14147 EVT ResVT = Node->getValueType(0);
14148 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
14149 SDValue LoNumElts = DAG.getElementCount(
14150 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
14151 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
14152 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
14153 SDValue ResLoNotNumElts = DAG.getSetCC(
14154 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
14155 ResLo, LoNumElts, ISD::SETNE);
14156 // Per LangRef, ResVT must be wide enough to hold the total element count,
14157 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
14158 // the count is only required to fit unsigned.
14159 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
14161 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
14162 }
14163
14164 EVT StepVecVT = StepVec.getValueType();
14165 EVT StepVT = StepVecVT.getVectorElementType();
14166
14167 // Promote the scalar result type early to avoid redundant zexts.
14169 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
14170
14171 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
14172 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
14173 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
14174 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
14175 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
14177 StepVecVT.getVectorElementType(), Select);
14178 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
14179 DAG.getZExtOrTrunc(Max, DL, StepVT));
14180
14181 return DAG.getZExtOrTrunc(Sub, DL, VT);
14182}
14183
14185 SDLoc DL(N);
14186 SDValue Source = N->getOperand(0);
14187 SDValue Needle = N->getOperand(1);
14188 SDValue Mask = N->getOperand(2);
14189 EVT SourceVT = Source.getValueType();
14190 EVT NeedleVT = Needle.getValueType();
14191 EVT ResVT = N->getValueType(0);
14192 EVT CmpVT =
14193 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
14194
14195 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
14196
14197 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
14198 EVT NeedleEltVT = NeedleVT.getVectorElementType();
14199 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
14200 SDValue Splat;
14201 if (NeedleVT == SourceVT) {
14202 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
14203 Splat = DAG.getVectorShuffle(
14204 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
14206 } else {
14207 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
14208 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
14209 }
14210 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
14211 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
14212 }
14213
14214 EVT UseVT = ResVT;
14215 // If the result is immediately truncated, only extend to that type (to avoid
14216 // unnecessary sign/zero extends).
14217 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
14218 UseVT = N->user_begin()->getValueType(0);
14219
14220 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
14221 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
14222
14223 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
14224 if (UseVT != ResVT)
14225 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
14226 return Ret;
14227}
14228
14230 SelectionDAG &DAG) const {
14231 SDLoc DL(N);
14232 SDValue Acc = N->getOperand(0);
14233 SDValue MulLHS = N->getOperand(1);
14234 SDValue MulRHS = N->getOperand(2);
14235 EVT AccVT = Acc.getValueType();
14236 EVT MulOpVT = MulLHS.getValueType();
14237
14238 EVT ExtMulOpVT =
14240 MulOpVT.getVectorElementCount());
14241
14242 unsigned ExtOpcLHS, ExtOpcRHS;
14243 switch (N->getOpcode()) {
14244 default:
14245 llvm_unreachable("Unexpected opcode");
14247 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
14248 break;
14250 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
14251 break;
14253 ExtOpcLHS = ISD::SIGN_EXTEND;
14254 ExtOpcRHS = ISD::ZERO_EXTEND;
14255 break;
14257 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
14258 break;
14259 }
14260
14261 // A wide partial reduction is built from a ladder of narrower ones, a rung
14262 // at a time, each halving the element count and doubling the width.
14263 unsigned Opc = N->getOpcode();
14264 ElementCount MulEC = MulOpVT.getVectorElementCount();
14265 ElementCount AccEC = AccVT.getVectorElementCount();
14266 unsigned CountRatio =
14267 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
14268 unsigned WidthRatio =
14269 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
14270 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
14271 LLVMContext &Ctx = *DAG.getContext();
14272 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
14273
14274 // A pure reduction peels one rung and re-enters.
14275 if (llvm::isOneOrOneSplat(MulRHS)) {
14276 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
14277 return DAG.getNode(Opc, DL, AccVT, Acc,
14278 DAG.getNode(Opc, DL, RungVT,
14279 DAG.getConstant(0, DL, RungVT), MulLHS,
14280 MulRHS),
14281 DAG.getConstant(1, DL, RungVT));
14282 }
14283
14284 // A multiply widens the products by one rung, which legalizes back into a
14285 // widening multiply per half, and the ladder re-enters as a plain sum.
14286 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
14287 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
14288 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
14289 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
14290 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
14291
14292 // The halves meet at the narrowest rung, so the accumulator is added once.
14293 EVT MidVT = Lo.getValueType()
14294 .widenIntegerVectorElementType(Ctx)
14295 .getHalfNumVectorElementsVT(Ctx);
14297 return DAG.getNode(Opc, DL, AccVT,
14298 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
14299 SDValue Mid =
14300 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
14301 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
14302 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
14303 }
14304
14305 if (ExtMulOpVT != MulOpVT) {
14306 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
14307 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
14308 }
14309 SDValue Input = MulLHS;
14310 // Maintain the FP flags (if any).
14311 SDNodeFlags Flags = N->getFlags();
14312 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
14313 if (!llvm::isOneOrOneSplatFP(MulRHS))
14314 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS, Flags);
14315 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
14316 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14317 }
14318
14319 unsigned Stride = AccVT.getVectorMinNumElements();
14320 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
14321
14322 // Collect all of the subvectors
14323 std::deque<SDValue> Subvectors = {Acc};
14324 for (unsigned I = 0; I < ScaleFactor; I++)
14325 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
14326
14327 unsigned FlatNode =
14328 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
14329
14330 // Flatten the subvector tree
14331 while (Subvectors.size() > 1) {
14332 Subvectors.push_back(DAG.getNode(FlatNode, DL, AccVT,
14333 {Subvectors[0], Subvectors[1]}, Flags));
14334 Subvectors.pop_front();
14335 Subvectors.pop_front();
14336 }
14337
14338 assert(Subvectors.size() == 1 &&
14339 "There should only be one subvector after tree flattening");
14340
14341 return Subvectors[0];
14342}
14343
14344/// Given a store node \p StoreNode, return true if it is safe to fold that node
14345/// into \p FPNode, which expands to a library call with output pointers.
14347 SDNode *FPNode) {
14349 SmallVector<const SDNode *, 8> DeferredNodes;
14351
14352 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
14353 for (SDValue Op : StoreNode->ops())
14354 if (Op.getNode() != FPNode)
14355 Worklist.push_back(Op.getNode());
14356
14358 while (!Worklist.empty()) {
14359 const SDNode *Node = Worklist.pop_back_val();
14360 auto [_, Inserted] = Visited.insert(Node);
14361 if (!Inserted)
14362 continue;
14363
14364 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
14365 return false;
14366
14367 // Reached the FPNode (would result in a cycle).
14368 // OR Reached CALLSEQ_START (would result in nested call sequences).
14369 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
14370 return false;
14371
14372 if (Node->getOpcode() == ISD::CALLSEQ_END) {
14373 // Defer looking into call sequences (so we can check we're outside one).
14374 // We still need to look through these for the predecessor check.
14375 DeferredNodes.push_back(Node);
14376 continue;
14377 }
14378
14379 for (SDValue Op : Node->ops())
14380 Worklist.push_back(Op.getNode());
14381 }
14382
14383 // True if we're outside a call sequence and don't have the FPNode as a
14384 // predecessor. No cycles or nested call sequences possible.
14385 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
14386 MaxSteps);
14387}
14388
14390 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
14392 std::optional<unsigned> CallRetResNo) const {
14393 if (LC == RTLIB::UNKNOWN_LIBCALL)
14394 return false;
14395
14396 RTLIB::LibcallImpl LibcallImpl =
14398 if (LibcallImpl == RTLIB::Unsupported)
14399 return false;
14400
14401 LLVMContext &Ctx = *DAG.getContext();
14402 EVT VT = Node->getValueType(0);
14403 unsigned NumResults = Node->getNumValues();
14404
14405 // Find users of the node that store the results (and share input chains). The
14406 // destination pointers can be used instead of creating stack allocations.
14407 SDValue StoresInChain;
14408 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
14409 for (SDNode *User : Node->users()) {
14411 continue;
14412 auto *ST = cast<StoreSDNode>(User);
14413 SDValue StoreValue = ST->getValue();
14414 unsigned ResNo = StoreValue.getResNo();
14415 // Ensure the store corresponds to an output pointer.
14416 if (CallRetResNo == ResNo)
14417 continue;
14418 // Ensure the store to the default address space and not atomic or volatile.
14419 if (!ST->isSimple() || ST->getAddressSpace() != 0)
14420 continue;
14421 // Ensure all store chains are the same (so they don't alias).
14422 if (StoresInChain && ST->getChain() != StoresInChain)
14423 continue;
14424 // Ensure the store is properly aligned.
14425 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
14426 if (ST->getAlign() <
14427 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
14428 continue;
14429 // Avoid:
14430 // 1. Creating cyclic dependencies.
14431 // 2. Expanding the node to a call within a call sequence.
14433 continue;
14434 ResultStores[ResNo] = ST;
14435 StoresInChain = ST->getChain();
14436 }
14437
14438 ArgListTy Args;
14439
14440 // Pass the arguments.
14441 for (const SDValue &Op : Node->op_values()) {
14442 EVT ArgVT = Op.getValueType();
14443 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
14444 Args.emplace_back(Op, ArgTy);
14445 }
14446
14447 // Pass the output pointers.
14448 SmallVector<SDValue, 2> ResultPtrs(NumResults);
14450 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
14451 if (ResNo == CallRetResNo)
14452 continue;
14453 EVT ResVT = Node->getValueType(ResNo);
14454 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
14455 ResultPtrs[ResNo] = ResultPtr;
14456 Args.emplace_back(ResultPtr, PointerTy);
14457 }
14458
14459 SDLoc DL(Node);
14460
14462 // Pass the vector mask (if required).
14463 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
14464 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
14465 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14466 }
14467
14468 Type *RetType = CallRetResNo.has_value()
14469 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14470 : Type::getVoidTy(Ctx);
14471 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14472 SDValue Callee =
14473 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14475 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14476 getLibcallImplCallingConv(LibcallImpl), RetType, Callee, std::move(Args));
14477
14478 auto [Call, CallChain] = LowerCallTo(CLI);
14479
14480 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14481 if (ResNo == CallRetResNo) {
14482 Results.push_back(Call);
14483 continue;
14484 }
14485 MachinePointerInfo PtrInfo;
14486 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14487 ResultPtr, PtrInfo);
14488 SDValue OutChain = LoadResult.getValue(1);
14489
14490 if (StoreSDNode *ST = ResultStores[ResNo]) {
14491 // Replace store with the library call.
14492 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14493 PtrInfo = ST->getPointerInfo();
14494 } else {
14496 DAG.getMachineFunction(),
14497 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14498 }
14499
14500 Results.push_back(LoadResult);
14501 }
14502
14503 return true;
14504}
14505
14507 SDValue &LHS, SDValue &RHS,
14508 SDValue &CC, bool &NeedInvert,
14509 const SDLoc &dl, SDValue &Chain,
14510 bool IsSignaling) const {
14511 MVT OpVT = LHS.getSimpleValueType();
14512 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14513 NeedInvert = false;
14514 switch (getCondCodeAction(CCCode, OpVT)) {
14515 default:
14516 llvm_unreachable("Unknown condition code action!");
14518 // Nothing to do.
14519 break;
14522 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14523 std::swap(LHS, RHS);
14524 CC = DAG.getCondCode(InvCC);
14525 return true;
14526 }
14527 // Swapping operands didn't work. Try inverting the condition.
14528 bool NeedSwap = false;
14529 InvCC = getSetCCInverse(CCCode, OpVT);
14530 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14531 // If inverting the condition is not enough, try swapping operands
14532 // on top of it.
14533 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14534 NeedSwap = true;
14535 }
14536 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14537 CC = DAG.getCondCode(InvCC);
14538 NeedInvert = true;
14539 if (NeedSwap)
14540 std::swap(LHS, RHS);
14541 return true;
14542 }
14543
14544 // Special case: expand i1 comparisons using logical operations.
14545 if (OpVT == MVT::i1) {
14546 SDValue Ret;
14547 switch (CCCode) {
14548 default:
14549 llvm_unreachable("Unknown integer setcc!");
14550 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14551 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14552 MVT::i1);
14553 break;
14554 case ISD::SETNE: // X != Y --> (X ^ Y)
14555 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14556 break;
14557 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14558 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14559 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14560 DAG.getNOT(dl, LHS, MVT::i1));
14561 break;
14562 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14563 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14564 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14565 DAG.getNOT(dl, RHS, MVT::i1));
14566 break;
14567 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14568 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14569 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14570 DAG.getNOT(dl, LHS, MVT::i1));
14571 break;
14572 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14573 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14574 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14575 DAG.getNOT(dl, RHS, MVT::i1));
14576 break;
14577 }
14578
14579 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14580 RHS = SDValue();
14581 CC = SDValue();
14582 return true;
14583 }
14584
14586 unsigned Opc = 0;
14587 switch (CCCode) {
14588 default:
14589 llvm_unreachable("Don't know how to expand this condition!");
14590 case ISD::SETUO:
14591 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14592 CC1 = ISD::SETUNE;
14593 CC2 = ISD::SETUNE;
14594 Opc = ISD::OR;
14595 break;
14596 }
14598 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14599 NeedInvert = true;
14600 [[fallthrough]];
14601 case ISD::SETO:
14603 "If SETO is expanded, SETOEQ must be legal!");
14604 CC1 = ISD::SETOEQ;
14605 CC2 = ISD::SETOEQ;
14606 Opc = ISD::AND;
14607 break;
14608 case ISD::SETONE:
14609 case ISD::SETUEQ:
14610 // If the SETUO or SETO CC isn't legal, we might be able to use
14611 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14612 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14613 // the operands.
14614 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14615 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14616 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14617 CC1 = ISD::SETOGT;
14618 CC2 = ISD::SETOLT;
14619 Opc = ISD::OR;
14620 NeedInvert = ((unsigned)CCCode & 0x8U);
14621 break;
14622 }
14623 [[fallthrough]];
14624 case ISD::SETOEQ:
14625 case ISD::SETOGT:
14626 case ISD::SETOGE:
14627 case ISD::SETOLT:
14628 case ISD::SETOLE:
14629 case ISD::SETUNE:
14630 case ISD::SETUGT:
14631 case ISD::SETUGE:
14632 case ISD::SETULT:
14633 case ISD::SETULE:
14634 // If we are floating point, assign and break, otherwise fall through.
14635 if (!OpVT.isInteger()) {
14636 // We can use the 4th bit to tell if we are the unordered
14637 // or ordered version of the opcode.
14638 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14639 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14640 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14641 break;
14642 }
14643 // Fallthrough if we are unsigned integer.
14644 [[fallthrough]];
14645 case ISD::SETLE:
14646 case ISD::SETGT:
14647 case ISD::SETGE:
14648 case ISD::SETLT:
14649 case ISD::SETNE:
14650 case ISD::SETEQ:
14651 // If all combinations of inverting the condition and swapping operands
14652 // didn't work then we have no means to expand the condition.
14653 llvm_unreachable("Don't know how to expand this condition!");
14654 }
14655
14656 SDValue SetCC1, SetCC2;
14657 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14658 // If we aren't the ordered or unorder operation,
14659 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14660 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14661 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14662 } else {
14663 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14664 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14665 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14666 }
14667 if (Chain)
14668 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14669 SetCC2.getValue(1));
14670 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14671 RHS = SDValue();
14672 CC = SDValue();
14673 return true;
14674 }
14675 }
14676 return false;
14677}
14678
14680 SelectionDAG &DAG) const {
14681 EVT VT = Node->getValueType(0);
14682 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14683 // split into two equal parts.
14684 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14685 return SDValue();
14686
14687 // Restrict expansion to cases where both parts can be concatenated.
14688 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14689 if (LoVT != HiVT || !isTypeLegal(LoVT))
14690 return SDValue();
14691
14692 SDLoc DL(Node);
14693 unsigned Opcode = Node->getOpcode();
14694
14695 // Don't expand if the result is likely to be unrolled anyway.
14696 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14697 return SDValue();
14698
14699 SmallVector<SDValue, 4> LoOps, HiOps;
14700 for (const SDValue &V : Node->op_values()) {
14701 if (!V.getValueType().isVector()) {
14702 // Scalar operands pass through to both halves unchanged.
14703 LoOps.push_back(V);
14704 HiOps.push_back(V);
14705 continue;
14706 }
14707 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14708 LoOps.push_back(Lo);
14709 HiOps.push_back(Hi);
14710 }
14711
14712 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVT, LoOps, Node->getFlags());
14713 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVT, HiOps, Node->getFlags());
14714 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14715}
14716
14718 const SDLoc &DL,
14719 EVT InVecVT, SDValue EltNo,
14720 LoadSDNode *OriginalLoad,
14721 SelectionDAG &DAG) const {
14722 assert(OriginalLoad->isSimple());
14723
14724 EVT VecEltVT = InVecVT.getVectorElementType();
14725
14726 // If the vector element type is not a multiple of a byte then we are unable
14727 // to correctly compute an address to load only the extracted element as a
14728 // scalar.
14729 if (!VecEltVT.isByteSized())
14730 return SDValue();
14731
14732 ISD::LoadExtType ExtTy =
14733 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14734 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14735 return SDValue();
14736
14737 std::optional<unsigned> ByteOffset;
14738 Align Alignment = OriginalLoad->getAlign();
14740 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14741 int Elt = ConstEltNo->getZExtValue();
14742 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14743 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14744 Alignment = commonAlignment(Alignment, *ByteOffset);
14745 } else {
14746 // Discard the pointer info except the address space because the memory
14747 // operand can't represent this new access since the offset is variable.
14748 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14749 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14750 }
14751
14752 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14753 return SDValue();
14754
14755 unsigned IsFast = 0;
14756 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14757 OriginalLoad->getAddressSpace(), Alignment,
14758 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14759 !IsFast)
14760 return SDValue();
14761
14762 // The original DAG loaded the entire vector from memory, so arithmetic
14763 // within it must be inbounds.
14765 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
14766
14767 // We are replacing a vector load with a scalar load. The new load must have
14768 // identical memory op ordering to the original.
14769 SDValue Load;
14770 if (ResultVT.bitsGT(VecEltVT)) {
14771 // If the result type of vextract is wider than the load, then issue an
14772 // extending load instead.
14773 ISD::LoadExtType ExtType =
14774 isLoadLegal(ResultVT, VecEltVT, Alignment,
14775 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
14777 : ISD::EXTLOAD;
14778 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
14779 NewPtr, MPI, VecEltVT, Alignment,
14780 OriginalLoad->getMemOperand()->getFlags(),
14781 OriginalLoad->getMMOMetadataForSubAccess());
14782 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14783 } else {
14784 // The result type is narrower or the same width as the vector element
14785 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
14786 Alignment, OriginalLoad->getMemOperand()->getFlags(),
14787 OriginalLoad->getMMOMetadataForSubAccess());
14788 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14789 if (ResultVT.bitsLT(VecEltVT))
14790 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
14791 else
14792 Load = DAG.getBitcast(ResultVT, Load);
14793 }
14794
14795 return Load;
14796}
14797
14798// Set type id for call site info and metadata 'call_target'.
14799// We are filtering for:
14800// a) The call-graph-section use case that wants to know about indirect
14801// calls, or
14802// b) We want to annotate indirect calls.
14804 const CallBase *CB, MachineFunction &MF,
14805 MachineFunction::CallSiteInfo &CSInfo) const {
14806 if (CB && CB->isIndirectCall() &&
14809 CSInfo = MachineFunction::CallSiteInfo(*CB);
14810}
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:857
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
const SmallVectorImpl< MachineOperand > & Cond
Contains matchers for matching SelectionDAG nodes and values.
This file contains some templates that are useful if you are working with the STL at all.
static cl::opt< unsigned > MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192), cl::desc("DAG combiner limit number of steps when searching DAG " "for predecessor nodes"))
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static std::pair< SDValue, SDValue > getLegalMaskAndStepVector(SDValue Mask, bool ZeroIsPoison, SDLoc DL, SelectionDAG &DAG)
Returns a type-legalized version of Mask as the first item in the pair.
static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static bool lowerImmediateIfPossible(TargetLowering::ConstraintPair &P, SDValue Op, SelectionDAG *DAG, const TargetLowering &TLI)
If we have an immediate, see if we can lower it.
#define FP_CMP_LIBCALL(BASE)
static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, const APInt &UndefOp0, const APInt &UndefOp1)
Given a vector binary operation and known undefined elements for each input operand,...
static SDValue BuildExactUDIV(const TargetLowering &TLI, SDNode *N, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created)
Given an exact UDIV by a constant, create a multiplication with the multiplicative inverse of the con...
static void setArgListEntryAttributes(TargetLoweringBase::ArgListEntry &Entry, const SourceT &Src, unsigned ArgIdx)
Set CallLoweringInfo attribute flags based on a call instruction and called function attributes.
static std::pair< RTLIB::Libcall, ISD::CondCode > selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC, RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC, ISD::CondCode TriStateCC)
Select the libcall and the condition code to test its result against 0 for an ordered floating-point ...
static SDValue isSpecificZeroAfterMaybeRounding(SelectionDAG &DAG, const TargetLowering &TLI, const SDLoc &DL, SDValue Val, FPClassTest FPClass)
static bool canNarrowCLMULToLegal(const TargetLowering &TLI, LLVMContext &Ctx, EVT VT, unsigned HalveDepth=0, unsigned TotalDepth=0)
Check if CLMUL on VT can eventually reach a type with legal CLMUL through a chain of halving decompos...
static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, EVT VecVT, const SDLoc &dl, ElementCount SubEC)
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 void turnVectorIntoSplatVector(MutableArrayRef< SDValue > Values, std::function< bool(SDValue)> Predicate, SDValue AlternativeReplacement=SDValue())
If all values in Values that don't match the predicate are same 'splat' value, then replace all value...
static MaybeAlign getParamAlign(const CallBase &Call, unsigned ArgIdx)
static MaybeAlign getParamStackAlign(const CallBase &Call, unsigned ArgIdx)
static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT)
static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created)
Given an exact SDIV by a constant, create a multiplication with the multiplicative inverse of the con...
static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, SDValue N0, const APInt &C1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static SDValue combineShiftToAVG(SDValue Op, TargetLowering::TargetLoweringOpt &TLO, const TargetLowering &TLI, const APInt &DemandedBits, const APInt &DemandedElts, unsigned Depth)
static bool paramHasAttr(const CallBase &Call, unsigned ArgIdx, Attribute::AttrKind Kind)
This file describes how to lower LLVM code to machine code.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT, SelectionDAG &DAG)
Scalarize a vector store, bitcasting to TargetVT to determine the scalar type.
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static LLVM_ABI const llvm::fltSemantics & EnumToSemantics(Semantics S)
Definition APFloat.cpp:136
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:343
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:364
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:399
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:339
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:335
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:376
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1451
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1262
APInt bitcastToAPInt() const
Definition APFloat.h:1475
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
void changeSign()
Definition APFloat.h:1401
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1213
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
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
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1253
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
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
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 isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
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
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,...
LLVM_ABI MCRegister getLiveInPhysReg(Register VReg) const
getLiveInPhysReg - If VReg is a live-in virtual register, return the corresponding live-in physical r...
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.
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:348
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
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
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)
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:541
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
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
LLVM_ABI std::string getEVTString() const
This function returns value type as a string, e.g. "i32".
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