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
195 const AttributeList &FuncAttrs,
197 // TODO: This assumes each parameter maps to exactly one operand node, which
198 // does not hold when an argument requires type splitting.
199 assert(Ops.size() == FuncTy->getNumParams() &&
200 "argument count does not match the function type");
201 ArgListTy Args;
202 Args.reserve(Ops.size());
203 for (unsigned I = 0, E = FuncTy->getNumParams(); I != E; ++I) {
204 ArgListEntry Entry(Ops[I], FuncTy->getParamType(I));
205 Entry.setAttributes(FuncAttrs, I);
206 Args.push_back(Entry);
207 }
208 return Args;
209}
210
211/// Generate a libcall taking the given operands as arguments and returning a
212/// result of type RetVT.
213std::pair<SDValue, SDValue>
214TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl,
216 MakeLibCallOptions CallOptions, const SDLoc &dl,
217 SDValue InChain) const {
218 if (LibcallImpl == RTLIB::Unsupported)
219 reportFatalInternalError("unsupported library call operation");
220
221 if (!InChain)
222 InChain = DAG.getEntryNode();
223
225 Args.reserve(Ops.size());
226
227 ArrayRef<Type *> OpsTypeOverrides = CallOptions.OpsTypeOverrides;
228 for (unsigned i = 0; i < Ops.size(); ++i) {
229 SDValue NewOp = Ops[i];
230 Type *Ty = i < OpsTypeOverrides.size() && OpsTypeOverrides[i]
231 ? OpsTypeOverrides[i]
232 : NewOp.getValueType().getTypeForEVT(*DAG.getContext());
233 TargetLowering::ArgListEntry Entry(NewOp, Ty);
234 if (CallOptions.IsSoften)
235 Entry.OrigTy =
236 CallOptions.OpsVTBeforeSoften[i].getTypeForEVT(*DAG.getContext());
237
238 Entry.IsSExt =
239 shouldSignExtendTypeInLibCall(Entry.Ty, CallOptions.IsSigned);
240 Entry.IsZExt = !Entry.IsSExt;
241
242 if (CallOptions.IsSoften &&
244 Entry.IsSExt = Entry.IsZExt = false;
245 }
246 Args.push_back(Entry);
247 }
248
249 SDValue Callee =
250 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
251
252 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
253 Type *OrigRetTy = RetTy;
255 bool signExtend = shouldSignExtendTypeInLibCall(RetTy, CallOptions.IsSigned);
256 bool zeroExtend = !signExtend;
257
258 if (CallOptions.IsSoften) {
259 OrigRetTy = CallOptions.RetVTBeforeSoften.getTypeForEVT(*DAG.getContext());
261 signExtend = zeroExtend = false;
262 }
263
264 CLI.setDebugLoc(dl)
265 .setChain(InChain)
266 .setLibCallee(getLibcallImplCallingConv(LibcallImpl), RetTy, OrigRetTy,
267 Callee, std::move(Args))
268 .setNoReturn(CallOptions.DoesNotReturn)
271 .setSExtResult(signExtend)
272 .setZExtResult(zeroExtend);
273 return LowerCallTo(CLI);
274}
275
277 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
278 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
279 const AttributeList &FuncAttributes, EVT *LargestVT) const {
280 EVT VT = getOptimalMemOpType(Context, Op, FuncAttributes);
281
282 if (VT == MVT::Other) {
283 // Use the largest integer type whose alignment constraints are satisfied.
284 VT = MVT::LAST_INTEGER_VALUETYPE;
285 if (Op.isFixedDstAlign()) {
286 bool LoadsFromSrc = Op.isMemcpyOrMemmove() && !Op.isMemcpyStrSrc();
287 while (VT != MVT::i8) {
288 unsigned VTSize = VT.getSizeInBits() / 8;
289 bool DstOk =
290 Op.getDstAlign() >= VTSize ||
291 allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign());
292 bool SrcOk =
293 !LoadsFromSrc || Op.getSrcAlign() >= VTSize ||
294 allowsMisalignedMemoryAccesses(VT, SrcAS, Op.getSrcAlign());
295 if (DstOk && SrcOk)
296 break;
298 }
299 }
300 assert(VT.isInteger());
301
302 // Find the largest legal integer type.
303 MVT LVT = MVT::LAST_INTEGER_VALUETYPE;
304 while (!isTypeLegal(LVT))
305 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
306 assert(LVT.isInteger());
307
308 // If the type we've chosen is larger than the largest legal integer type
309 // then use the largest legal type.
310 if (VT.bitsGT(LVT))
311 VT = LVT;
312 }
313
314 unsigned NumMemOps = 0;
315 uint64_t Size = Op.size();
316 while (Size) {
317 unsigned VTSize = VT.getSizeInBits() / 8;
318 while (VTSize > Size) {
319 // For now, only use non-vector load / store's for the left-over pieces.
320 EVT NewVT = VT;
321 unsigned NewVTSize;
322
323 bool Found = false;
324 if (VT.isVector() || VT.isFloatingPoint()) {
325 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
328 Found = true;
329 else if (NewVT == MVT::i64 &&
331 isSafeMemOpType(MVT::f64)) {
332 // i64 is usually not legal on 32-bit targets, but f64 may be.
333 NewVT = MVT::f64;
334 Found = true;
335 }
336 }
337
338 if (!Found) {
339 do {
340 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
341 if (NewVT == MVT::i8)
342 break;
343 } while (!isSafeMemOpType(NewVT.getSimpleVT()));
344 }
345 NewVTSize = NewVT.getSizeInBits() / 8;
346
347 // If the new VT cannot cover all of the remaining bits, then consider
348 // issuing a (or a pair of) unaligned and overlapping load / store.
349 unsigned Fast;
350 if (NumMemOps && !Op.isVolatile() && NewVTSize < Size &&
352 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
354 Fast)
355 VTSize = Size;
356 else {
357 VT = NewVT;
358 VTSize = NewVTSize;
359 }
360 }
361
362 if (++NumMemOps > Limit)
363 return false;
364
365 MemOps.push_back(VT);
366 Size -= VTSize;
367 }
368
369 return true;
370}
371
372/// Soften the operands of a comparison. This code is shared among BR_CC,
373/// SELECT_CC, and SETCC handlers.
375 SDValue &NewLHS, SDValue &NewRHS,
376 ISD::CondCode &CCCode,
377 const SDLoc &dl, const SDValue OldLHS,
378 const SDValue OldRHS) const {
379 SDValue Chain;
380 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
381 OldRHS, Chain);
382}
383
384/// Select the libcall and the condition code to test its result against 0 for
385/// an ordered floating-point compare. \p BoolLC is the boolean helper (result
386/// is 0/1). \p TriStateLC is the per-predicate three-way helper and \p
387/// GenericLC the generic single-symbol three-way helper (both return -1/0/1,
388/// tested against 0 with \p TriStateCC). The boolean form is preferred, then
389/// the per-predicate three-way, then the generic three-way.
390static std::pair<RTLIB::Libcall, ISD::CondCode>
391selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC,
392 RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC,
393 ISD::CondCode TriStateCC) {
394 if (Libcalls.getLibcallImpl(BoolLC) != RTLIB::Unsupported)
395 return {BoolLC, ISD::SETNE};
396 if (Libcalls.getLibcallImpl(TriStateLC) != RTLIB::Unsupported)
397 return {TriStateLC, TriStateCC};
398 return {GenericLC, TriStateCC};
399}
400
402 SDValue &NewLHS, SDValue &NewRHS,
403 ISD::CondCode &CCCode,
404 const SDLoc &dl, const SDValue OldLHS,
405 const SDValue OldRHS,
406 SDValue &Chain,
407 bool IsSignaling) const {
408 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
409 // not supporting it. We can update this code when libgcc provides such
410 // functions.
411
412 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
413 && "Unsupported setcc type!");
414
415 // Expand into one or more soft-fp libcall(s).
416 ISD::CondCode OrigCCCode = CCCode;
417 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
419 bool ShouldInvertCC = false;
420
421 // Expand a compare libcall family name (e.g. OEQ, FCMP3_PRED_OEQ) to the
422 // RTLIB::Libcall for VT.
423#define FP_CMP_LIBCALL(BASE) \
424 RTLIB::getFPLibCall(VT, RTLIB::BASE##_F32, RTLIB::BASE##_F64, \
425 RTLIB::UNKNOWN_LIBCALL, RTLIB::BASE##_F128, \
426 RTLIB::BASE##_PPCF128)
427
428 switch (CCCode) {
429 case ISD::SETEQ:
430 case ISD::SETOEQ:
431 std::tie(LC1, CC1) = selectFPCmpLibcall(
432 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
433 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
434 break;
435 case ISD::SETNE:
436 case ISD::SETUNE:
437 std::tie(LC1, CC1) = selectFPCmpLibcall(
438 DAG.getLibcalls(), FP_CMP_LIBCALL(UNE), FP_CMP_LIBCALL(FCMP3_PRED_UNE),
439 FP_CMP_LIBCALL(FCMP3), ISD::SETNE);
440 // Some ABIs (e.g. AEABI) provide neither a not-equal nor a three-way
441 // compare; obtain not-equal (UNE = !OEQ) by inverting ordered-equal.
442 if (DAG.getLibcalls().getLibcallImpl(LC1) == RTLIB::Unsupported) {
443 std::tie(LC1, CC1) = selectFPCmpLibcall(
444 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ),
445 FP_CMP_LIBCALL(FCMP3_PRED_OEQ), FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
446 ShouldInvertCC = true;
447 }
448 break;
449 case ISD::SETGE:
450 case ISD::SETOGE:
451 std::tie(LC1, CC1) = selectFPCmpLibcall(
452 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE), FP_CMP_LIBCALL(FCMP3_PRED_OGE),
453 FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
454 break;
455 case ISD::SETLT:
456 case ISD::SETOLT:
457 std::tie(LC1, CC1) = selectFPCmpLibcall(
458 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT), FP_CMP_LIBCALL(FCMP3_PRED_OLT),
459 FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
460 break;
461 case ISD::SETLE:
462 case ISD::SETOLE:
463 std::tie(LC1, CC1) = selectFPCmpLibcall(
464 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE), FP_CMP_LIBCALL(FCMP3_PRED_OLE),
465 FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
466 break;
467 case ISD::SETGT:
468 case ISD::SETOGT:
469 std::tie(LC1, CC1) = selectFPCmpLibcall(
470 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT), FP_CMP_LIBCALL(FCMP3_PRED_OGT),
471 FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
472 break;
473 case ISD::SETO:
474 ShouldInvertCC = true;
475 [[fallthrough]];
476 case ISD::SETUO:
477 // Unordered is a boolean everywhere (__unordXf2 returns 0/1).
478 LC1 = FP_CMP_LIBCALL(UO);
479 CC1 = ISD::SETNE;
480 break;
481 case ISD::SETONE:
482 // SETONE = O && UNE
483 ShouldInvertCC = true;
484 [[fallthrough]];
485 case ISD::SETUEQ:
486 LC1 = FP_CMP_LIBCALL(UO);
487 CC1 = ISD::SETNE;
488 std::tie(LC2, CC2) = selectFPCmpLibcall(
489 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
490 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
491 break;
492 default:
493 // Invert CC for unordered comparisons, handled by the ordered inverse.
494 ShouldInvertCC = true;
495 switch (CCCode) {
496 case ISD::SETULT:
497 std::tie(LC1, CC1) = selectFPCmpLibcall(
498 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE),
499 FP_CMP_LIBCALL(FCMP3_PRED_OGE), FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
500 break;
501 case ISD::SETULE:
502 std::tie(LC1, CC1) = selectFPCmpLibcall(
503 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT),
504 FP_CMP_LIBCALL(FCMP3_PRED_OGT), FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
505 break;
506 case ISD::SETUGT:
507 std::tie(LC1, CC1) = selectFPCmpLibcall(
508 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE),
509 FP_CMP_LIBCALL(FCMP3_PRED_OLE), FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
510 break;
511 case ISD::SETUGE:
512 std::tie(LC1, CC1) = selectFPCmpLibcall(
513 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT),
514 FP_CMP_LIBCALL(FCMP3_PRED_OLT), FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
515 break;
516 default:
517 llvm_unreachable("Do not know how to soften this setcc!");
518 }
519 }
520
521#undef FP_CMP_LIBCALL
522
523 // Use the target specific return value for comparison lib calls.
525 SDValue Ops[2] = {NewLHS, NewRHS};
527 EVT OpsVT[2] = { OldLHS.getValueType(),
528 OldRHS.getValueType() };
529 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT);
530
531 auto ReportNoLibcall = [&]() {
532 DAG.getContext()->emitError(
533 Twine("no libcall available to soften floating-point ") +
534 ISD::getCondCodeName(OrigCCCode) + " compare with type " +
535 VT.getEVTString());
536 NewLHS = DAG.getPOISON(RetVT);
537 NewRHS = DAG.getConstant(0, dl, RetVT);
538 CCCode = ISD::SETNE;
539 };
540
541 // Check availability before makeLibCall, which fatally errors otherwise.
542 RTLIB::LibcallImpl LC1Impl = DAG.getLibcalls().getLibcallImpl(LC1);
543 if (LC1Impl == RTLIB::Unsupported) {
544 ReportNoLibcall();
545 return;
546 }
547
548 auto Call = makeLibCall(DAG, LC1Impl, RetVT, Ops, CallOptions, dl, Chain);
549 NewLHS = Call.first;
550 NewRHS = DAG.getConstant(0, dl, RetVT);
551
552 CCCode = CC1;
553 if (ShouldInvertCC) {
554 assert(RetVT.isInteger());
555 CCCode = getSetCCInverse(CCCode, RetVT);
556 }
557
558 if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
559 // Update Chain.
560 Chain = Call.second;
561 } else {
562 RTLIB::LibcallImpl LC2Impl = DAG.getLibcalls().getLibcallImpl(LC2);
563 if (LC2Impl == RTLIB::Unsupported) {
564 ReportNoLibcall();
565 return;
566 }
567
568 assert(CCCode == (ShouldInvertCC ? ISD::SETEQ : ISD::SETNE) &&
569 "unordered call should be simple boolean");
570
571 EVT SetCCVT =
572 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
574 NewLHS = DAG.getNode(ISD::AssertZext, dl, RetVT, Call.first,
575 DAG.getValueType(MVT::i1));
576 }
577
578 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
579 auto Call2 = makeLibCall(DAG, LC2Impl, RetVT, Ops, CallOptions, dl, Chain);
580 CCCode = CC2;
581 if (ShouldInvertCC)
582 CCCode = getSetCCInverse(CCCode, RetVT);
583 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
584 if (Chain)
585 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
586 Call2.second);
587 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
588 Tmp.getValueType(), Tmp, NewLHS);
589 NewRHS = SDValue();
590 }
591}
592
593/// Return the entry encoding for a jump table in the current function. The
594/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
596 // In non-pic modes, just use the address of a block.
599
600 // Otherwise, use a label difference.
602}
603
608
609/// This returns the relocation base for the given PIC jumptable, the same as
610/// getPICJumpTableRelocBase, but as an MCExpr.
611const MCExpr *
613 unsigned JTI,MCContext &Ctx) const{
614 // The normal PIC reloc base is the label at the start of the jump table.
615 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
616}
617
619 SDValue Addr, int JTI,
620 SelectionDAG &DAG) const {
621 SDValue Chain = Value;
622 // Jump table debug info is only needed if CodeView is enabled.
624 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl);
625 }
626 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr);
627}
628
629bool
631 const TargetMachine &TM = getTargetMachine();
632 const GlobalValue *GV = GA->getGlobal();
633
634 // If the address is not even local to this DSO we will have to load it from
635 // a got and then add the offset.
636 if (!TM.shouldAssumeDSOLocal(GV))
637 return false;
638
639 // If the code is position independent we will have to add a base register.
641 return false;
642
643 // Otherwise we can do it.
644 return true;
645}
646
647//===----------------------------------------------------------------------===//
648// Optimization Methods
649//===----------------------------------------------------------------------===//
650
651/// If the specified instruction has a constant integer operand and there are
652/// bits set in that constant that are not demanded, then clear those bits and
653/// return true.
655 const APInt &DemandedBits,
656 const APInt &DemandedElts,
657 TargetLoweringOpt &TLO) const {
658 SDLoc DL(Op);
659 unsigned Opcode = Op.getOpcode();
660
661 // Early-out if we've ended up calling an undemanded node, leave this to
662 // constant folding.
663 if (DemandedBits.isZero() || DemandedElts.isZero())
664 return false;
665
666 // Do target-specific constant optimization.
667 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
668 return TLO.New.getNode();
669
670 // FIXME: ISD::SELECT, ISD::SELECT_CC
671 switch (Opcode) {
672 default:
673 break;
674 case ISD::XOR:
675 case ISD::AND:
676 case ISD::OR: {
677 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
678 if (!Op1C || Op1C->isOpaque())
679 return false;
680
681 // If this is a 'not' op, don't touch it because that's a canonical form.
682 const APInt &C = Op1C->getAPIntValue();
683 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
684 return false;
685
686 if (!C.isSubsetOf(DemandedBits)) {
687 EVT VT = Op.getValueType();
688 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
689 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC,
690 Op->getFlags());
691 return TLO.CombineTo(Op, NewOp);
692 }
693
694 break;
695 }
696 }
697
698 return false;
699}
700
702 const APInt &DemandedBits,
703 TargetLoweringOpt &TLO) const {
704 EVT VT = Op.getValueType();
705 APInt DemandedElts = VT.isVector()
707 : APInt(1, 1);
708 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
709}
710
711/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
712/// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
713/// but it could be generalized for targets with other types of implicit
714/// widening casts.
716 const APInt &DemandedBits,
717 TargetLoweringOpt &TLO) const {
718 assert(Op.getNumOperands() == 2 &&
719 "ShrinkDemandedOp only supports binary operators!");
720 assert(Op.getNode()->getNumValues() == 1 &&
721 "ShrinkDemandedOp only supports nodes with one result!");
722
723 EVT VT = Op.getValueType();
724 SelectionDAG &DAG = TLO.DAG;
725 SDLoc dl(Op);
726
727 // Early return, as this function cannot handle vector types.
728 if (VT.isVector())
729 return false;
730
731 assert(Op.getOperand(0).getValueType().getScalarSizeInBits() == BitWidth &&
732 Op.getOperand(1).getValueType().getScalarSizeInBits() == BitWidth &&
733 "ShrinkDemandedOp only supports operands that have the same size!");
734
735 // Don't do this if the node has another user, which may require the
736 // full value.
737 if (!Op.getNode()->hasOneUse())
738 return false;
739
740 // Search for the smallest integer type with free casts to and from
741 // Op's type. For expedience, just check power-of-2 integer types.
742 unsigned DemandedSize = DemandedBits.getActiveBits();
743 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
744 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
745 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
746 if (isTruncateFree(Op, SmallVT) && isZExtFree(SmallVT, VT)) {
747 // We found a type with free casts.
748
749 // If the operation has the 'disjoint' flag, then the
750 // operands on the new node are also disjoint.
751 SDNodeFlags Flags(Op->getFlags().hasDisjoint() ? SDNodeFlags::Disjoint
753 unsigned Opcode = Op.getOpcode();
754 if (Opcode == ISD::PTRADD) {
755 // It isn't a ptradd anymore if it doesn't operate on the entire
756 // pointer.
757 Opcode = ISD::ADD;
758 }
759 SDValue X = DAG.getNode(
760 Opcode, dl, SmallVT,
761 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
762 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)), Flags);
763 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
764 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X);
765 return TLO.CombineTo(Op, Z);
766 }
767 }
768 return false;
769}
770
772 DAGCombinerInfo &DCI) const {
773 SelectionDAG &DAG = DCI.DAG;
774 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
775 !DCI.isBeforeLegalizeOps());
777
778 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
779 if (Simplified) {
780 DCI.AddToWorklist(Op.getNode());
782 }
783 return Simplified;
784}
785
787 const APInt &DemandedElts,
788 DAGCombinerInfo &DCI) const {
789 SelectionDAG &DAG = DCI.DAG;
790 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
791 !DCI.isBeforeLegalizeOps());
793
794 bool Simplified =
795 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
796 if (Simplified) {
797 DCI.AddToWorklist(Op.getNode());
799 }
800 return Simplified;
801}
802
806 unsigned Depth,
807 bool AssumeSingleUse) const {
808 EVT VT = Op.getValueType();
809
810 // Since the number of lanes in a scalable vector is unknown at compile time,
811 // we track one bit which is implicitly broadcast to all lanes. This means
812 // that all lanes in a scalable vector are considered demanded.
813 APInt DemandedElts = VT.isFixedLengthVector()
815 : APInt(1, 1);
816 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
817 AssumeSingleUse);
818}
819
820// TODO: Under what circumstances can we create nodes? Constant folding?
822 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
823 SelectionDAG &DAG, unsigned Depth) const {
824 EVT VT = Op.getValueType();
825
826 // Limit search depth.
828 return SDValue();
829
830 // Ignore UNDEFs.
831 if (Op.isUndef())
832 return SDValue();
833
834 // Not demanding any bits/elts from Op.
835 if (DemandedBits == 0 || DemandedElts == 0)
836 return DAG.getUNDEF(VT);
837
838 bool IsLE = DAG.getDataLayout().isLittleEndian();
839 unsigned NumElts = DemandedElts.getBitWidth();
840 unsigned BitWidth = DemandedBits.getBitWidth();
841 KnownBits LHSKnown, RHSKnown;
842 switch (Op.getOpcode()) {
843 case ISD::Constant: {
844 const APInt &Value = Op->getAsAPIntVal();
845 if (!Value.isZero() && (Value & DemandedBits).isZero())
846 return DAG.getConstant(0, SDLoc(Op), VT);
847 break;
848 }
849 case ISD::BITCAST: {
850 if (VT.isScalableVector())
851 return SDValue();
852
853 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
854 EVT SrcVT = Src.getValueType();
855 EVT DstVT = Op.getValueType();
856 if (SrcVT == DstVT)
857 return Src;
858
859 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
860 unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
861 if (NumSrcEltBits == NumDstEltBits)
863 Src, DemandedBits, DemandedElts, DAG, Depth + 1))
864 return DAG.getBitcast(DstVT, V);
865
866 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
867 unsigned Scale = NumDstEltBits / NumSrcEltBits;
868 unsigned NumSrcElts = SrcVT.getVectorNumElements();
869 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
870 for (unsigned i = 0; i != Scale; ++i) {
871 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
872 unsigned BitOffset = EltOffset * NumSrcEltBits;
873 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
874 }
875 // Recursive calls below may turn not demanded elements into poison, so we
876 // need to demand all smaller source elements that maps to a demanded
877 // destination element.
878 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
879
881 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
882 return DAG.getBitcast(DstVT, V);
883 }
884
885 // TODO - bigendian once we have test coverage.
886 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
887 unsigned Scale = NumSrcEltBits / NumDstEltBits;
888 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
889 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
890 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
891 for (unsigned i = 0; i != NumElts; ++i)
892 if (DemandedElts[i]) {
893 unsigned Offset = (i % Scale) * NumDstEltBits;
894 DemandedSrcBits.insertBits(DemandedBits, Offset);
895 DemandedSrcElts.setBit(i / Scale);
896 }
897
899 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
900 return DAG.getBitcast(DstVT, V);
901 }
902
903 break;
904 }
906 if (!VT.isScalableVector() && !DemandedElts[0])
907 return DAG.getPOISON(VT);
908 break;
909 }
910 case ISD::AND: {
911 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
912 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
913
914 // If all of the demanded bits are known 1 on one side, return the other.
915 // These bits cannot contribute to the result of the 'and' in this
916 // context.
917 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
918 return Op.getOperand(0);
919 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
920 return Op.getOperand(1);
921 break;
922 }
923 case ISD::OR: {
924 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
925 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
926
927 // If all of the demanded bits are known zero on one side, return the
928 // other. These bits cannot contribute to the result of the 'or' in this
929 // context.
930 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
931 return Op.getOperand(0);
932 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
933 return Op.getOperand(1);
934 break;
935 }
936 case ISD::XOR: {
937 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
938 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
939
940 // If all of the demanded bits are known zero on one side, return the
941 // other.
942 if (DemandedBits.isSubsetOf(RHSKnown.Zero))
943 return Op.getOperand(0);
944 if (DemandedBits.isSubsetOf(LHSKnown.Zero))
945 return Op.getOperand(1);
946 break;
947 }
948 case ISD::ADD:
949 case ISD::MUL:
950 case ISD::SMIN:
951 case ISD::SMAX:
952 case ISD::UMIN:
953 case ISD::UMAX: {
954 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(1),
955 DemandedElts, 1, Depth + 1))
956 return Op.getOperand(0);
957
958 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(0),
959 DemandedElts, 0, Depth + 1))
960 return Op.getOperand(1);
961 break;
962 }
963 case ISD::SHL: {
964 // If we are only demanding sign bits then we can use the shift source
965 // directly.
966 if (std::optional<unsigned> MaxSA =
967 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
968 SDValue Op0 = Op.getOperand(0);
969 unsigned ShAmt = *MaxSA;
970 unsigned NumSignBits =
971 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
972 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
973 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
974 return Op0;
975 }
976 break;
977 }
978 case ISD::SRL: {
979 // If we are only demanding sign bits then we can use the shift source
980 // directly.
981 if (std::optional<unsigned> MaxSA =
982 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
983 SDValue Op0 = Op.getOperand(0);
984 unsigned ShAmt = *MaxSA;
985 // Must already be signbits in DemandedBits bounds, and can't demand any
986 // shifted in zeroes.
987 if (DemandedBits.countl_zero() >= ShAmt) {
988 unsigned NumSignBits =
989 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
990 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
991 return Op0;
992 }
993 }
994 break;
995 }
996 case ISD::SETCC: {
997 SDValue Op0 = Op.getOperand(0);
998 SDValue Op1 = Op.getOperand(1);
999 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1000 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1001 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1002 // -1, we may be able to bypass the setcc.
1003 if (DemandedBits.isSignMask() &&
1007 // If we're testing X < 0, then this compare isn't needed - just use X!
1008 // FIXME: We're limiting to integer types here, but this should also work
1009 // if we don't care about FP signed-zero. The use of SETLT with FP means
1010 // that we don't care about NaNs.
1011 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1013 return Op0;
1014 }
1015 break;
1016 }
1018 // If none of the extended bits are demanded, eliminate the sextinreg.
1019 SDValue Op0 = Op.getOperand(0);
1020 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1021 unsigned ExBits = ExVT.getScalarSizeInBits();
1022 if (DemandedBits.getActiveBits() <= ExBits &&
1024 return Op0;
1025 // If the input is already sign extended, just drop the extension.
1026 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1027 if (NumSignBits >= (BitWidth - ExBits + 1))
1028 return Op0;
1029 break;
1030 }
1034 if (VT.isScalableVector())
1035 return SDValue();
1036
1037 // If we only want the lowest element and none of extended bits, then we can
1038 // return the bitcasted source vector.
1039 SDValue Src = Op.getOperand(0);
1040 EVT SrcVT = Src.getValueType();
1041 EVT DstVT = Op.getValueType();
1042 if (IsLE && DemandedElts == 1 &&
1043 DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
1044 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
1045 return DAG.getBitcast(DstVT, Src);
1046 }
1047 break;
1048 }
1050 if (VT.isScalableVector())
1051 return SDValue();
1052
1053 // If we don't demand the inserted element, return the base vector.
1054 SDValue Vec = Op.getOperand(0);
1055 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1056 EVT VecVT = Vec.getValueType();
1057 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
1058 !DemandedElts[CIdx->getZExtValue()])
1059 return Vec;
1060 break;
1061 }
1062 case ISD::INSERT_SUBVECTOR: {
1063 if (VT.isScalableVector())
1064 return SDValue();
1065
1066 SDValue Vec = Op.getOperand(0);
1067 SDValue Sub = Op.getOperand(1);
1068 uint64_t Idx = Op.getConstantOperandVal(2);
1069 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1070 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1071 // If we don't demand the inserted subvector, return the base vector.
1072 if (DemandedSubElts == 0)
1073 return Vec;
1074 break;
1075 }
1076 case ISD::VECTOR_SHUFFLE: {
1077 assert(!VT.isScalableVector());
1078 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1079
1080 // If all the demanded elts are from one operand and are inline,
1081 // then we can use the operand directly.
1082 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
1083 for (unsigned i = 0; i != NumElts; ++i) {
1084 int M = ShuffleMask[i];
1085 if (M < 0 || !DemandedElts[i])
1086 continue;
1087 AllUndef = false;
1088 IdentityLHS &= (M == (int)i);
1089 IdentityRHS &= ((M - NumElts) == i);
1090 }
1091
1092 if (AllUndef)
1093 return DAG.getUNDEF(Op.getValueType());
1094 if (IdentityLHS)
1095 return Op.getOperand(0);
1096 if (IdentityRHS)
1097 return Op.getOperand(1);
1098 break;
1099 }
1100 default:
1101 // TODO: Probably okay to remove after audit; here to reduce change size
1102 // in initial enablement patch for scalable vectors
1103 if (VT.isScalableVector())
1104 return SDValue();
1105
1106 if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
1108 Op, DemandedBits, DemandedElts, DAG, Depth))
1109 return V;
1110 break;
1111 }
1112 return SDValue();
1113}
1114
1117 unsigned Depth) const {
1118 EVT VT = Op.getValueType();
1119 // Since the number of lanes in a scalable vector is unknown at compile time,
1120 // we track one bit which is implicitly broadcast to all lanes. This means
1121 // that all lanes in a scalable vector are considered demanded.
1122 APInt DemandedElts = VT.isFixedLengthVector()
1124 : APInt(1, 1);
1125 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1126 Depth);
1127}
1128
1130 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
1131 unsigned Depth) const {
1132 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
1133 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1134 Depth);
1135}
1136
1137// Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
1138// or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
1141 const TargetLowering &TLI,
1142 const APInt &DemandedBits,
1143 const APInt &DemandedElts, unsigned Depth) {
1144 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1145 "SRL or SRA node is required here!");
1146 // Is the right shift using an immediate value of 1?
1147 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1148 if (!N1C || !N1C->isOne())
1149 return SDValue();
1150
1151 // We are looking for an avgfloor
1152 // add(ext, ext)
1153 // or one of these as a avgceil
1154 // add(add(ext, ext), 1)
1155 // add(add(ext, 1), ext)
1156 // add(ext, add(ext, 1))
1157 SDValue Add = Op.getOperand(0);
1158 if (Add.getOpcode() != ISD::ADD)
1159 return SDValue();
1160
1161 SDValue ExtOpA = Add.getOperand(0);
1162 SDValue ExtOpB = Add.getOperand(1);
1163 SDValue Add2;
1164 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) {
1165 ConstantSDNode *ConstOp;
1166 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
1167 ConstOp->isOne()) {
1168 ExtOpA = Op1;
1169 ExtOpB = Op3;
1170 Add2 = A;
1171 return true;
1172 }
1173 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
1174 ConstOp->isOne()) {
1175 ExtOpA = Op1;
1176 ExtOpB = Op2;
1177 Add2 = A;
1178 return true;
1179 }
1180 return false;
1181 };
1182 bool IsCeil =
1183 (ExtOpA.getOpcode() == ISD::ADD &&
1184 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) ||
1185 (ExtOpB.getOpcode() == ISD::ADD &&
1186 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB));
1187
1188 // If the shift is signed (sra):
1189 // - Needs >= 2 sign bit for both operands.
1190 // - Needs >= 2 zero bits.
1191 // If the shift is unsigned (srl):
1192 // - Needs >= 1 zero bit for both operands.
1193 // - Needs 1 demanded bit zero and >= 2 sign bits.
1194 SelectionDAG &DAG = TLO.DAG;
1195 unsigned ShiftOpc = Op.getOpcode();
1196 bool IsSigned = false;
1197 unsigned KnownBits;
1198 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
1199 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
1200 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
1201 unsigned NumZeroA =
1202 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
1203 unsigned NumZeroB =
1204 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
1205 unsigned NumZero = std::min(NumZeroA, NumZeroB);
1206
1207 switch (ShiftOpc) {
1208 default:
1209 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
1210 case ISD::SRA: {
1211 if (NumZero >= 2 && NumSigned < NumZero) {
1212 IsSigned = false;
1213 KnownBits = NumZero;
1214 break;
1215 }
1216 if (NumSigned >= 1) {
1217 IsSigned = true;
1218 KnownBits = NumSigned;
1219 break;
1220 }
1221 return SDValue();
1222 }
1223 case ISD::SRL: {
1224 if (NumZero >= 1 && NumSigned < NumZero) {
1225 IsSigned = false;
1226 KnownBits = NumZero;
1227 break;
1228 }
1229 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1230 IsSigned = true;
1231 KnownBits = NumSigned;
1232 break;
1233 }
1234 return SDValue();
1235 }
1236 }
1237
1238 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1239 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1240
1241 // Find the smallest power-2 type that is legal for this vector size and
1242 // operation, given the original type size and the number of known sign/zero
1243 // bits.
1244 EVT VT = Op.getValueType();
1245 unsigned MinWidth =
1246 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1247 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth));
1249 return SDValue();
1250 if (VT.isVector())
1251 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1252 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) {
1253 // If we could not transform, and (both) adds are nuw/nsw, we can use the
1254 // larger type size to do the transform.
1255 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT))
1256 return SDValue();
1257 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0),
1258 Add.getOperand(1)) &&
1259 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0),
1260 Add2.getOperand(1))))
1261 NVT = VT;
1262 else
1263 return SDValue();
1264 }
1265
1266 // Don't create a AVGFLOOR node with a scalar constant unless its legal as
1267 // this is likely to stop other folds (reassociation, value tracking etc.)
1268 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) &&
1269 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB)))
1270 return SDValue();
1271
1272 SDLoc DL(Op);
1273 SDValue ResultAVG =
1274 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT),
1275 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT));
1276 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT);
1277}
1278
1279/// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1280/// result of Op are ever used downstream. If we can use this information to
1281/// simplify Op, create a new simplified DAG node and return true, returning the
1282/// original and new nodes in Old and New. Otherwise, analyze the expression and
1283/// return a mask of Known bits for the expression (used to simplify the
1284/// caller). The Known bits may only be accurate for those bits in the
1285/// OriginalDemandedBits and OriginalDemandedElts.
1287 SDValue Op, const APInt &OriginalDemandedBits,
1288 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1289 unsigned Depth, bool AssumeSingleUse) const {
1290 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1291 assert(Op.getScalarValueSizeInBits() == BitWidth &&
1292 "Mask size mismatches value type size!");
1293
1294 // Don't know anything.
1296
1297 EVT VT = Op.getValueType();
1298 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1299 unsigned NumElts = OriginalDemandedElts.getBitWidth();
1300 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1301 "Unexpected vector size");
1302
1303 APInt DemandedBits = OriginalDemandedBits;
1304 APInt DemandedElts = OriginalDemandedElts;
1305 SDLoc dl(Op);
1306
1307 // Undef operand.
1308 if (Op.isUndef())
1309 return false;
1310
1311 // We can't simplify target constants.
1312 if (Op.getOpcode() == ISD::TargetConstant)
1313 return false;
1314
1315 if (Op.getOpcode() == ISD::Constant) {
1316 // We know all of the bits for a constant!
1317 Known = KnownBits::makeConstant(Op->getAsAPIntVal());
1318 return false;
1319 }
1320
1321 if (Op.getOpcode() == ISD::ConstantFP) {
1322 // We know all of the bits for a floating point constant!
1324 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1325 return false;
1326 }
1327
1328 // Other users may use these bits.
1329 bool HasMultiUse = false;
1330 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1332 // Limit search depth.
1333 return false;
1334 }
1335 // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1337 DemandedElts = APInt::getAllOnes(NumElts);
1338 HasMultiUse = true;
1339 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1340 // Not demanding any bits/elts from Op.
1341 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1342 } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1343 // Limit search depth.
1344 return false;
1345 }
1346
1347 KnownBits Known2;
1348 switch (Op.getOpcode()) {
1349 case ISD::SCALAR_TO_VECTOR: {
1350 if (VT.isScalableVector())
1351 return false;
1352 if (!DemandedElts[0])
1353 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
1354
1355 KnownBits SrcKnown;
1356 SDValue Src = Op.getOperand(0);
1357 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1358 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1359 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1360 return true;
1361
1362 // Upper elements are poison, so only get the knownbits if we just demand
1363 // the bottom element.
1364 if (DemandedElts == 1)
1365 Known = SrcKnown.anyextOrTrunc(BitWidth);
1366 break;
1367 }
1368 case ISD::BUILD_VECTOR:
1369 // Collect the known bits that are shared by every demanded element.
1370 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1371 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1372 return false; // Don't fall through, will infinitely loop.
1373 case ISD::SPLAT_VECTOR: {
1374 SDValue Scl = Op.getOperand(0);
1375 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1376 KnownBits KnownScl;
1377 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1378 return true;
1379
1380 // Implicitly truncate the bits to match the official semantics of
1381 // SPLAT_VECTOR.
1382 Known = KnownScl.trunc(BitWidth);
1383 break;
1384 }
1385 case ISD::FREEZE: {
1386 SDValue N0 = Op.getOperand(0);
1388 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
1389 return TLO.CombineTo(Op, N0);
1390 break;
1391 }
1392 case ISD::LOAD: {
1393 auto *LD = cast<LoadSDNode>(Op);
1394 if (getTargetConstantFromLoad(LD)) {
1395 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1396 return false; // Don't fall through, will infinitely loop.
1397 }
1398 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1399 // If this is a ZEXTLoad and we are looking at the loaded value.
1400 EVT MemVT = LD->getMemoryVT();
1401 unsigned MemBits = MemVT.getScalarSizeInBits();
1402 Known.Zero.setBitsFrom(MemBits);
1403 return false; // Don't fall through, will infinitely loop.
1404 }
1405 break;
1406 }
1408 if (VT.isScalableVector())
1409 return false;
1410 SDValue Vec = Op.getOperand(0);
1411 SDValue Scl = Op.getOperand(1);
1412 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1413 EVT VecVT = Vec.getValueType();
1414
1415 // If index isn't constant, assume we need all vector elements AND the
1416 // inserted element.
1417 APInt DemandedVecElts(DemandedElts);
1418 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1419 unsigned Idx = CIdx->getZExtValue();
1420 DemandedVecElts.clearBit(Idx);
1421
1422 // Inserted element is not required.
1423 if (!DemandedElts[Idx])
1424 return TLO.CombineTo(Op, Vec);
1425 }
1426
1427 KnownBits KnownScl;
1428 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1429 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1430 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1431 return true;
1432
1433 Known = KnownScl.anyextOrTrunc(BitWidth);
1434
1435 KnownBits KnownVec;
1436 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1437 Depth + 1))
1438 return true;
1439
1440 if (!!DemandedVecElts)
1441 Known = Known.intersectWith(KnownVec);
1442
1443 return false;
1444 }
1445 case ISD::INSERT_SUBVECTOR: {
1446 if (VT.isScalableVector())
1447 return false;
1448 // Demand any elements from the subvector and the remainder from the src its
1449 // inserted into.
1450 SDValue Src = Op.getOperand(0);
1451 SDValue Sub = Op.getOperand(1);
1452 uint64_t Idx = Op.getConstantOperandVal(2);
1453 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1454 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1455 APInt DemandedSrcElts = DemandedElts;
1456 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
1457
1458 KnownBits KnownSub, KnownSrc;
1459 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1460 Depth + 1))
1461 return true;
1462 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1463 Depth + 1))
1464 return true;
1465
1466 Known.setAllConflict();
1467 if (!!DemandedSubElts)
1468 Known = Known.intersectWith(KnownSub);
1469 if (!!DemandedSrcElts)
1470 Known = Known.intersectWith(KnownSrc);
1471
1472 // Attempt to avoid multi-use src if we don't need anything from it.
1473 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1474 !DemandedSrcElts.isAllOnes()) {
1476 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1478 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1479 if (NewSub || NewSrc) {
1480 NewSub = NewSub ? NewSub : Sub;
1481 NewSrc = NewSrc ? NewSrc : Src;
1482 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1483 Op.getOperand(2));
1484 return TLO.CombineTo(Op, NewOp);
1485 }
1486 }
1487 break;
1488 }
1490 if (VT.isScalableVector())
1491 return false;
1492 // Offset the demanded elts by the subvector index.
1493 SDValue Src = Op.getOperand(0);
1494 if (Src.getValueType().isScalableVector())
1495 break;
1496 uint64_t Idx = Op.getConstantOperandVal(1);
1497 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1498 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1499
1500 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1501 Depth + 1))
1502 return true;
1503
1504 // Attempt to avoid multi-use src if we don't need anything from it.
1505 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1507 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1508 if (DemandedSrc) {
1509 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1510 Op.getOperand(1));
1511 return TLO.CombineTo(Op, NewOp);
1512 }
1513 }
1514 break;
1515 }
1516 case ISD::CONCAT_VECTORS: {
1517 if (VT.isScalableVector())
1518 return false;
1519 Known.setAllConflict();
1520 EVT SubVT = Op.getOperand(0).getValueType();
1521 unsigned NumSubVecs = Op.getNumOperands();
1522 unsigned NumSubElts = SubVT.getVectorNumElements();
1523 for (unsigned i = 0; i != NumSubVecs; ++i) {
1524 APInt DemandedSubElts =
1525 DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1526 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1527 Known2, TLO, Depth + 1))
1528 return true;
1529 // Known bits are shared by every demanded subvector element.
1530 if (!!DemandedSubElts)
1531 Known = Known.intersectWith(Known2);
1532 }
1533 break;
1534 }
1535 case ISD::VECTOR_SHUFFLE: {
1536 assert(!VT.isScalableVector());
1537 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1538
1539 // Collect demanded elements from shuffle operands..
1540 APInt DemandedLHS, DemandedRHS;
1541 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1542 DemandedRHS))
1543 break;
1544
1545 if (!!DemandedLHS || !!DemandedRHS) {
1546 SDValue Op0 = Op.getOperand(0);
1547 SDValue Op1 = Op.getOperand(1);
1548
1549 Known.setAllConflict();
1550 if (!!DemandedLHS) {
1551 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1552 Depth + 1))
1553 return true;
1554 Known = Known.intersectWith(Known2);
1555 }
1556 if (!!DemandedRHS) {
1557 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1558 Depth + 1))
1559 return true;
1560 Known = Known.intersectWith(Known2);
1561 }
1562
1563 // Attempt to avoid multi-use ops if we don't need anything from them.
1565 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1567 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1568 if (DemandedOp0 || DemandedOp1) {
1569 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1570 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1571 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1572 return TLO.CombineTo(Op, NewOp);
1573 }
1574 }
1575 break;
1576 }
1577 case ISD::AND: {
1578 SDValue Op0 = Op.getOperand(0);
1579 SDValue Op1 = Op.getOperand(1);
1580
1581 // If the RHS is a constant, check to see if the LHS would be zero without
1582 // using the bits from the RHS. Below, we use knowledge about the RHS to
1583 // simplify the LHS, here we're using information from the LHS to simplify
1584 // the RHS.
1585 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) {
1586 // Do not increment Depth here; that can cause an infinite loop.
1587 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1588 // If the LHS already has zeros where RHSC does, this 'and' is dead.
1589 if ((LHSKnown.Zero & DemandedBits) ==
1590 (~RHSC->getAPIntValue() & DemandedBits))
1591 return TLO.CombineTo(Op, Op0);
1592
1593 // If any of the set bits in the RHS are known zero on the LHS, shrink
1594 // the constant.
1595 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1596 DemandedElts, TLO))
1597 return true;
1598
1599 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1600 // constant, but if this 'and' is only clearing bits that were just set by
1601 // the xor, then this 'and' can be eliminated by shrinking the mask of
1602 // the xor. For example, for a 32-bit X:
1603 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1604 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1605 LHSKnown.One == ~RHSC->getAPIntValue()) {
1606 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1607 return TLO.CombineTo(Op, Xor);
1608 }
1609 }
1610
1611 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2 (or zero).
1612 SDValue X, Y;
1613 if (sd_match(Op,
1614 m_And(m_Value(Y),
1616 m_Sub(m_Value(X), m_Deferred(Y)))))) &&
1617 TLO.DAG.isKnownToBeAPowerOfTwo(Y, DemandedElts, /*OrZero=*/true)) {
1618 return TLO.CombineTo(
1619 Op, TLO.DAG.getNode(ISD::AND, dl, VT, TLO.DAG.getNOT(dl, X, VT), Y));
1620 }
1621
1622 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1623 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1624 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1625 (Op0.getOperand(0).isUndef() ||
1627 Op0->hasOneUse()) {
1628 unsigned NumSubElts =
1630 unsigned SubIdx = Op0.getConstantOperandVal(2);
1631 APInt DemandedSub =
1632 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1633 KnownBits KnownSubMask =
1634 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1635 if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1636 SDValue NewAnd =
1637 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1638 SDValue NewInsert =
1639 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1640 Op0.getOperand(1), Op0.getOperand(2));
1641 return TLO.CombineTo(Op, NewInsert);
1642 }
1643 }
1644
1645 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1646 Depth + 1))
1647 return true;
1648 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1649 Known2, TLO, Depth + 1))
1650 return true;
1651
1652 // If all of the demanded bits are known one on one side, return the other.
1653 // These bits cannot contribute to the result of the 'and'.
1654 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1655 return TLO.CombineTo(Op, Op0);
1656 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1657 return TLO.CombineTo(Op, Op1);
1658 // If all of the demanded bits in the inputs are known zeros, return zero.
1659 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1660 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1661 // If the RHS is a constant, see if we can simplify it.
1662 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1663 TLO))
1664 return true;
1665 // If the operation can be done in a smaller type, do so.
1667 return true;
1668
1669 // Attempt to avoid multi-use ops if we don't need anything from them.
1670 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1672 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1674 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1675 if (DemandedOp0 || DemandedOp1) {
1676 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1677 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1678 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1679 return TLO.CombineTo(Op, NewOp);
1680 }
1681 }
1682
1683 Known &= Known2;
1684 break;
1685 }
1686 case ISD::OR: {
1687 SDValue Op0 = Op.getOperand(0);
1688 SDValue Op1 = Op.getOperand(1);
1689 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1690 Depth + 1)) {
1691 Op->dropFlags(SDNodeFlags::Disjoint);
1692 return true;
1693 }
1694
1695 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1696 Known2, TLO, Depth + 1)) {
1697 Op->dropFlags(SDNodeFlags::Disjoint);
1698 return true;
1699 }
1700
1701 // If all of the demanded bits are known zero on one side, return the other.
1702 // These bits cannot contribute to the result of the 'or'.
1703 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1704 return TLO.CombineTo(Op, Op0);
1705 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1706 return TLO.CombineTo(Op, Op1);
1707 // If the RHS is a constant, see if we can simplify it.
1708 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1709 return true;
1710 // If the operation can be done in a smaller type, do so.
1712 return true;
1713
1714 // Attempt to avoid multi-use ops if we don't need anything from them.
1715 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1717 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1719 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1720 if (DemandedOp0 || DemandedOp1) {
1721 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1722 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1723 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1724 return TLO.CombineTo(Op, NewOp);
1725 }
1726 }
1727
1728 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1729 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1730 SDValue X, Y, C1, C2;
1733 m_Value(C2)))))) {
1734 if (SDValue C12 =
1735 TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, {C1, C2})) {
1736 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1737 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1738 return TLO.CombineTo(Op,
1739 TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1740 }
1741 }
1742
1743 Known |= Known2;
1744 break;
1745 }
1746 case ISD::XOR: {
1747 SDValue Op0 = Op.getOperand(0);
1748 SDValue Op1 = Op.getOperand(1);
1749
1750 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1751 Depth + 1))
1752 return true;
1753 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1754 Depth + 1))
1755 return true;
1756
1757 // If all of the demanded bits are known zero on one side, return the other.
1758 // These bits cannot contribute to the result of the 'xor'.
1759 if (DemandedBits.isSubsetOf(Known.Zero))
1760 return TLO.CombineTo(Op, Op0);
1761 if (DemandedBits.isSubsetOf(Known2.Zero))
1762 return TLO.CombineTo(Op, Op1);
1763 // If the operation can be done in a smaller type, do so.
1765 return true;
1766
1767 // If all of the unknown bits are known to be zero on one side or the other
1768 // turn this into an *inclusive* or.
1769 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1770 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1771 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1772
1773 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1774 if (C) {
1775 // If one side is a constant, and all of the set bits in the constant are
1776 // also known set on the other side, turn this into an AND, as we know
1777 // the bits will be cleared.
1778 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1779 // NB: it is okay if more bits are known than are requested
1780 if (C->getAPIntValue() == Known2.One) {
1781 SDValue ANDC =
1782 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1783 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1784 }
1785
1786 // If the RHS is a constant, see if we can change it. Don't alter a -1
1787 // constant because that's a 'not' op, and that is better for combining
1788 // and codegen.
1789 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1790 // We're flipping all demanded bits. Flip the undemanded bits too.
1791 SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1792 return TLO.CombineTo(Op, New);
1793 }
1794
1795 unsigned Op0Opcode = Op0.getOpcode();
1796 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1797 if (ConstantSDNode *ShiftC =
1798 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1799 // Don't crash on an oversized shift. We can not guarantee that a
1800 // bogus shift has been simplified to undef.
1801 if (ShiftC->getAPIntValue().ult(BitWidth)) {
1802 uint64_t ShiftAmt = ShiftC->getZExtValue();
1804 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1805 : Ones.lshr(ShiftAmt);
1806 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1808 // If the xor constant is a demanded mask, do a 'not' before the
1809 // shift:
1810 // xor (X << ShiftC), XorC --> (not X) << ShiftC
1811 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1812 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1813 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1814 Op0.getOperand(1)));
1815 }
1816 }
1817 }
1818 }
1819 }
1820
1821 // If we can't turn this into a 'not', try to shrink the constant.
1822 if (!C || !C->isAllOnes())
1823 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1824 return true;
1825
1826 // Attempt to avoid multi-use ops if we don't need anything from them.
1827 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1829 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1831 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1832 if (DemandedOp0 || DemandedOp1) {
1833 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1834 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1835 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1836 return TLO.CombineTo(Op, NewOp);
1837 }
1838 }
1839
1840 Known ^= Known2;
1841 break;
1842 }
1843 case ISD::SELECT:
1844 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1845 Known, TLO, Depth + 1))
1846 return true;
1847 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1848 Known2, TLO, Depth + 1))
1849 return true;
1850
1851 // If the operands are constants, see if we can simplify them.
1852 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1853 return true;
1854
1855 // Only known if known in both the LHS and RHS.
1856 Known = Known.intersectWith(Known2);
1857 break;
1858 case ISD::VSELECT:
1859 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1860 Known, TLO, Depth + 1))
1861 return true;
1862 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1863 Known2, TLO, Depth + 1))
1864 return true;
1865
1866 // Only known if known in both the LHS and RHS.
1867 Known = Known.intersectWith(Known2);
1868 break;
1869 case ISD::SELECT_CC:
1870 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts,
1871 Known, TLO, Depth + 1))
1872 return true;
1873 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1874 Known2, TLO, Depth + 1))
1875 return true;
1876
1877 // If the operands are constants, see if we can simplify them.
1878 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1879 return true;
1880
1881 // Only known if known in both the LHS and RHS.
1882 Known = Known.intersectWith(Known2);
1883 break;
1884 case ISD::SETCC: {
1885 SDValue Op0 = Op.getOperand(0);
1886 SDValue Op1 = Op.getOperand(1);
1887 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1888 // If we're testing X < 0, X >= 0, X <= -1 or X > -1
1889 // (X is of integer type) then we only need the sign mask of the previous
1890 // result
1891 if (Op1.getValueType().isInteger() &&
1892 (((CC == ISD::SETLT || CC == ISD::SETGE) && isNullOrNullSplat(Op1)) ||
1893 ((CC == ISD::SETLE || CC == ISD::SETGT) &&
1894 isAllOnesOrAllOnesSplat(Op1)))) {
1895 KnownBits KnownOp0;
1898 DemandedElts, KnownOp0, TLO, Depth + 1))
1899 return true;
1900 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1901 // width as the setcc result, and (3) the result of a setcc conforms to 0
1902 // or -1, we may be able to bypass the setcc.
1903 if (DemandedBits.isSignMask() &&
1907 // If we remove a >= 0 or > -1 (for integers), we need to introduce a
1908 // NOT Operation
1909 if (CC == ISD::SETGE || CC == ISD::SETGT) {
1910 SDLoc DL(Op);
1911 EVT VT = Op0.getValueType();
1912 SDValue NotOp0 = TLO.DAG.getNOT(DL, Op0, VT);
1913 return TLO.CombineTo(Op, NotOp0);
1914 }
1915 return TLO.CombineTo(Op, Op0);
1916 }
1917 }
1918 if (getBooleanContents(Op0.getValueType()) ==
1920 BitWidth > 1)
1921 Known.Zero.setBitsFrom(1);
1922 break;
1923 }
1924 case ISD::SHL: {
1925 SDValue Op0 = Op.getOperand(0);
1926 SDValue Op1 = Op.getOperand(1);
1927 EVT ShiftVT = Op1.getValueType();
1928
1929 if (std::optional<unsigned> KnownSA =
1930 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
1931 unsigned ShAmt = *KnownSA;
1932 if (ShAmt == 0)
1933 return TLO.CombineTo(Op, Op0);
1934
1935 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1936 // single shift. We can do this if the bottom bits (which are shifted
1937 // out) are never demanded.
1938 // TODO - support non-uniform vector amounts.
1939 if (Op0.getOpcode() == ISD::SRL) {
1940 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1941 if (std::optional<unsigned> InnerSA =
1942 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
1943 unsigned C1 = *InnerSA;
1944 unsigned Opc = ISD::SHL;
1945 int Diff = ShAmt - C1;
1946 if (Diff < 0) {
1947 Diff = -Diff;
1948 Opc = ISD::SRL;
1949 }
1950 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1951 return TLO.CombineTo(
1952 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1953 }
1954 }
1955 }
1956
1957 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1958 // are not demanded. This will likely allow the anyext to be folded away.
1959 // TODO - support non-uniform vector amounts.
1960 if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1961 SDValue InnerOp = Op0.getOperand(0);
1962 EVT InnerVT = InnerOp.getValueType();
1963 unsigned InnerBits = InnerVT.getScalarSizeInBits();
1964 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1965 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1966 SDValue NarrowShl = TLO.DAG.getNode(
1967 ISD::SHL, dl, InnerVT, InnerOp,
1968 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
1969 return TLO.CombineTo(
1970 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1971 }
1972
1973 // Repeat the SHL optimization above in cases where an extension
1974 // intervenes: (shl (anyext (shr x, c1)), c2) to
1975 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
1976 // aren't demanded (as above) and that the shifted upper c1 bits of
1977 // x aren't demanded.
1978 // TODO - support non-uniform vector amounts.
1979 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
1980 InnerOp.hasOneUse()) {
1981 if (std::optional<unsigned> SA2 = TLO.DAG.getValidShiftAmount(
1982 InnerOp, DemandedElts, Depth + 2)) {
1983 unsigned InnerShAmt = *SA2;
1984 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1985 DemandedBits.getActiveBits() <=
1986 (InnerBits - InnerShAmt + ShAmt) &&
1987 DemandedBits.countr_zero() >= ShAmt) {
1988 SDValue NewSA =
1989 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1990 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1991 InnerOp.getOperand(0));
1992 return TLO.CombineTo(
1993 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1994 }
1995 }
1996 }
1997 }
1998
1999 APInt InDemandedMask = DemandedBits.lshr(ShAmt);
2000 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2001 Depth + 1)) {
2002 // Disable the nsw and nuw flags. We can no longer guarantee that we
2003 // won't wrap after simplification.
2004 Op->dropFlags(SDNodeFlags::NoWrap);
2005 return true;
2006 }
2007 Known <<= ShAmt;
2008 // low bits known zero.
2009 Known.Zero.setLowBits(ShAmt);
2010
2011 // Attempt to avoid multi-use ops if we don't need anything from them.
2012 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2014 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2015 if (DemandedOp0) {
2016 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
2017 return TLO.CombineTo(Op, NewOp);
2018 }
2019 }
2020
2021 // TODO: Can we merge this fold with the one below?
2022 // Try shrinking the operation as long as the shift amount will still be
2023 // in range.
2024 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() &&
2025 Op.getNode()->hasOneUse()) {
2026 // Search for the smallest integer type with free casts to and from
2027 // Op's type. For expedience, just check power-of-2 integer types.
2028 unsigned DemandedSize = DemandedBits.getActiveBits();
2029 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
2030 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
2031 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits);
2032 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) &&
2033 isTypeDesirableForOp(ISD::SHL, SmallVT) &&
2034 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) &&
2035 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) {
2036 assert(DemandedSize <= SmallVTBits &&
2037 "Narrowed below demanded bits?");
2038 // We found a type with free casts.
2039 SDValue NarrowShl = TLO.DAG.getNode(
2040 ISD::SHL, dl, SmallVT,
2041 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
2042 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl));
2043 return TLO.CombineTo(
2044 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2045 }
2046 }
2047 }
2048
2049 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2050 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
2051 // Only do this if we demand the upper half so the knownbits are correct.
2052 unsigned HalfWidth = BitWidth / 2;
2053 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
2054 DemandedBits.countLeadingOnes() >= HalfWidth) {
2055 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
2056 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2057 isTypeDesirableForOp(ISD::SHL, HalfVT) &&
2058 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2059 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
2060 // If we're demanding the upper bits at all, we must ensure
2061 // that the upper bits of the shift result are known to be zero,
2062 // which is equivalent to the narrow shift being NUW.
2063 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
2064 bool IsNSW = Known.countMinSignBits() > HalfWidth;
2065 SDNodeFlags Flags;
2066 Flags.setNoSignedWrap(IsNSW);
2067 Flags.setNoUnsignedWrap(IsNUW);
2068 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2069 SDValue NewShiftAmt =
2070 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2071 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
2072 NewShiftAmt, Flags);
2073 SDValue NewExt =
2074 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
2075 return TLO.CombineTo(Op, NewExt);
2076 }
2077 }
2078 }
2079 } else {
2080 // This is a variable shift, so we can't shift the demand mask by a known
2081 // amount. But if we are not demanding high bits, then we are not
2082 // demanding those bits from the pre-shifted operand either.
2083 if (unsigned CTLZ = DemandedBits.countl_zero()) {
2084 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
2085 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
2086 Depth + 1)) {
2087 // Disable the nsw and nuw flags. We can no longer guarantee that we
2088 // won't wrap after simplification.
2089 Op->dropFlags(SDNodeFlags::NoWrap);
2090 return true;
2091 }
2092 Known.resetAll();
2093 }
2094 }
2095
2096 // If we are only demanding sign bits then we can use the shift source
2097 // directly.
2098 if (std::optional<unsigned> MaxSA =
2099 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2100 unsigned ShAmt = *MaxSA;
2101 unsigned NumSignBits =
2102 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2103 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
2104 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
2105 return TLO.CombineTo(Op, Op0);
2106 }
2107 break;
2108 }
2109 case ISD::SRL: {
2110 SDValue Op0 = Op.getOperand(0);
2111 SDValue Op1 = Op.getOperand(1);
2112 EVT ShiftVT = Op1.getValueType();
2113
2114 if (std::optional<unsigned> KnownSA =
2115 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2116 unsigned ShAmt = *KnownSA;
2117 if (ShAmt == 0)
2118 return TLO.CombineTo(Op, Op0);
2119
2120 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
2121 // single shift. We can do this if the top bits (which are shifted out)
2122 // are never demanded.
2123 // TODO - support non-uniform vector amounts.
2124 if (Op0.getOpcode() == ISD::SHL) {
2125 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2126 if (std::optional<unsigned> InnerSA =
2127 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2128 unsigned C1 = *InnerSA;
2129 unsigned Opc = ISD::SRL;
2130 int Diff = ShAmt - C1;
2131 if (Diff < 0) {
2132 Diff = -Diff;
2133 Opc = ISD::SHL;
2134 }
2135 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2136 return TLO.CombineTo(
2137 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2138 }
2139 }
2140 }
2141
2142 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a
2143 // single sra. We can do this if the top bits are never demanded.
2144 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) {
2145 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2146 if (std::optional<unsigned> InnerSA =
2147 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2148 unsigned C1 = *InnerSA;
2149 // Clamp the combined shift amount if it exceeds the bit width.
2150 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1);
2151 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT);
2152 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT,
2153 Op0.getOperand(0), NewSA));
2154 }
2155 }
2156 }
2157
2158 APInt InDemandedMask = (DemandedBits << ShAmt);
2159
2160 // If the shift is exact, then it does demand the low bits (and knows that
2161 // they are zero).
2162 if (Op->getFlags().hasExact())
2163 InDemandedMask.setLowBits(ShAmt);
2164
2165 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2166 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
2167 if ((BitWidth % 2) == 0 && !VT.isVector()) {
2169 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
2170 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2171 isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2172 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2173 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
2174 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
2175 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
2176 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2177 SDValue NewShiftAmt =
2178 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2179 SDValue NewShift =
2180 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt);
2181 return TLO.CombineTo(
2182 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
2183 }
2184 }
2185
2186 // Compute the new bits that are at the top now.
2187 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2188 Depth + 1))
2189 return true;
2190 Known >>= ShAmt;
2191 // High bits known zero.
2192 Known.Zero.setHighBits(ShAmt);
2193
2194 // Attempt to avoid multi-use ops if we don't need anything from them.
2195 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2197 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2198 if (DemandedOp0) {
2199 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
2200 return TLO.CombineTo(Op, NewOp);
2201 }
2202 }
2203 } else {
2204 // Use generic knownbits computation as it has support for non-uniform
2205 // shift amounts.
2206 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2207 }
2208
2209 // If we are only demanding sign bits then we can use the shift source
2210 // directly.
2211 if (std::optional<unsigned> MaxSA =
2212 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2213 unsigned ShAmt = *MaxSA;
2214 // Must already be signbits in DemandedBits bounds, and can't demand any
2215 // shifted in zeroes.
2216 if (DemandedBits.countl_zero() >= ShAmt) {
2217 unsigned NumSignBits =
2218 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2219 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
2220 return TLO.CombineTo(Op, Op0);
2221 }
2222 }
2223
2224 // Try to match AVG patterns (after shift simplification).
2225 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2226 DemandedElts, Depth + 1))
2227 return TLO.CombineTo(Op, AVG);
2228
2229 break;
2230 }
2231 case ISD::SRA: {
2232 SDValue Op0 = Op.getOperand(0);
2233 SDValue Op1 = Op.getOperand(1);
2234 EVT ShiftVT = Op1.getValueType();
2235
2236 // If we only want bits that already match the signbit then we don't need
2237 // to shift.
2238 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
2239 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
2240 NumHiDemandedBits)
2241 return TLO.CombineTo(Op, Op0);
2242
2243 // If this is an arithmetic shift right and only the low-bit is set, we can
2244 // always convert this into a logical shr, even if the shift amount is
2245 // variable. The low bit of the shift cannot be an input sign bit unless
2246 // the shift amount is >= the size of the datatype, which is undefined.
2247 if (DemandedBits.isOne())
2248 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2249
2250 if (std::optional<unsigned> KnownSA =
2251 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2252 unsigned ShAmt = *KnownSA;
2253 if (ShAmt == 0)
2254 return TLO.CombineTo(Op, Op0);
2255
2256 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2257 // supports sext_inreg.
2258 if (Op0.getOpcode() == ISD::SHL) {
2259 if (std::optional<unsigned> InnerSA =
2260 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2261 unsigned LowBits = BitWidth - ShAmt;
2262 EVT ExtVT = VT.changeElementType(
2263 *TLO.DAG.getContext(),
2264 EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits));
2265
2266 if (*InnerSA == ShAmt) {
2267 if (!TLO.LegalOperations() ||
2269 return TLO.CombineTo(
2270 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2271 Op0.getOperand(0),
2272 TLO.DAG.getValueType(ExtVT)));
2273
2274 // Even if we can't convert to sext_inreg, we might be able to
2275 // remove this shift pair if the input is already sign extended.
2276 unsigned NumSignBits =
2277 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2278 if (NumSignBits > ShAmt)
2279 return TLO.CombineTo(Op, Op0.getOperand(0));
2280 }
2281 }
2282 }
2283
2284 APInt InDemandedMask = (DemandedBits << ShAmt);
2285
2286 // If the shift is exact, then it does demand the low bits (and knows that
2287 // they are zero).
2288 if (Op->getFlags().hasExact())
2289 InDemandedMask.setLowBits(ShAmt);
2290
2291 // If any of the demanded bits are produced by the sign extension, we also
2292 // demand the input sign bit.
2293 if (DemandedBits.countl_zero() < ShAmt)
2294 InDemandedMask.setSignBit();
2295
2296 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2297 Depth + 1))
2298 return true;
2299 Known >>= ShAmt;
2300
2301 // If the input sign bit is known to be zero, or if none of the top bits
2302 // are demanded, turn this into an unsigned shift right.
2303 if (Known.Zero[BitWidth - ShAmt - 1] ||
2304 DemandedBits.countl_zero() >= ShAmt) {
2305 SDNodeFlags Flags;
2306 Flags.setExact(Op->getFlags().hasExact());
2307 return TLO.CombineTo(
2308 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2309 }
2310
2311 int Log2 = DemandedBits.exactLogBase2();
2312 if (Log2 >= 0) {
2313 // The bit must come from the sign.
2314 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2315 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2316 }
2317
2318 if (Known.One[BitWidth - ShAmt - 1])
2319 // New bits are known one.
2320 Known.One.setHighBits(ShAmt);
2321
2322 // Attempt to avoid multi-use ops if we don't need anything from them.
2323 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2325 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2326 if (DemandedOp0) {
2327 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2328 return TLO.CombineTo(Op, NewOp);
2329 }
2330 }
2331 }
2332
2333 // Try to match AVG patterns (after shift simplification).
2334 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2335 DemandedElts, Depth + 1))
2336 return TLO.CombineTo(Op, AVG);
2337
2338 break;
2339 }
2340 case ISD::FSHL:
2341 case ISD::FSHR: {
2342 SDValue Op0 = Op.getOperand(0);
2343 SDValue Op1 = Op.getOperand(1);
2344 SDValue Op2 = Op.getOperand(2);
2345 bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2346
2347 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2348 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2349
2350 // For fshl, 0-shift returns the 1st arg.
2351 // For fshr, 0-shift returns the 2nd arg.
2352 if (Amt == 0) {
2353 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2354 Known, TLO, Depth + 1))
2355 return true;
2356 break;
2357 }
2358
2359 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2360 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2361 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2362 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2363 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2364 Depth + 1))
2365 return true;
2366 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2367 Depth + 1))
2368 return true;
2369
2370 Known2 <<= (IsFSHL ? Amt : (BitWidth - Amt));
2371 Known >>= (IsFSHL ? (BitWidth - Amt) : Amt);
2372 Known = Known.unionWith(Known2);
2373
2374 // Attempt to avoid multi-use ops if we don't need anything from them.
2375 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2376 !DemandedElts.isAllOnes()) {
2378 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2380 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2381 if (DemandedOp0 || DemandedOp1) {
2382 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2383 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2384 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2385 DemandedOp1, Op2);
2386 return TLO.CombineTo(Op, NewOp);
2387 }
2388 }
2389 }
2390
2391 if (isPowerOf2_32(BitWidth)) {
2392 // Fold FSHR(Op0,Op1,Op2) -> SRL(Op1,Op2)
2393 // iff we're guaranteed not to use Op0.
2394 // TODO: Add FSHL equivalent?
2395 if (!IsFSHL && !DemandedBits.isAllOnes() &&
2396 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT))) {
2397 KnownBits KnownAmt =
2398 TLO.DAG.computeKnownBits(Op2, DemandedElts, Depth + 1);
2399 unsigned MaxShiftAmt =
2400 KnownAmt.getMaxValue().getLimitedValue(BitWidth - 1);
2401 // Check we don't demand any shifted bits outside Op1.
2402 if (DemandedBits.countl_zero() >= MaxShiftAmt) {
2403 EVT AmtVT = Op2.getValueType();
2404 SDValue NewAmt =
2405 TLO.DAG.getNode(ISD::AND, dl, AmtVT, Op2,
2406 TLO.DAG.getConstant(BitWidth - 1, dl, AmtVT));
2407 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, Op1, NewAmt);
2408 return TLO.CombineTo(Op, NewOp);
2409 }
2410 }
2411
2412 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2413 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2414 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, Known2, TLO,
2415 Depth + 1))
2416 return true;
2417 }
2418 break;
2419 }
2420 case ISD::ROTL:
2421 case ISD::ROTR: {
2422 SDValue Op0 = Op.getOperand(0);
2423 SDValue Op1 = Op.getOperand(1);
2424 bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2425
2426 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2427 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2428 return TLO.CombineTo(Op, Op0);
2429
2430 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2431 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2432 unsigned RevAmt = BitWidth - Amt;
2433
2434 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2435 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2436 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2437 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2438 Depth + 1))
2439 return true;
2440
2441 // rot*(x, 0) --> x
2442 if (Amt == 0)
2443 return TLO.CombineTo(Op, Op0);
2444
2445 // See if we don't demand either half of the rotated bits.
2446 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2447 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2448 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2449 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2450 }
2451 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2452 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2453 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2454 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2455 }
2456 }
2457
2458 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2459 if (isPowerOf2_32(BitWidth)) {
2460 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2461 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2462 Depth + 1))
2463 return true;
2464 }
2465 break;
2466 }
2467 case ISD::SMIN:
2468 case ISD::SMAX:
2469 case ISD::UMIN:
2470 case ISD::UMAX: {
2471 unsigned Opc = Op.getOpcode();
2472 SDValue Op0 = Op.getOperand(0);
2473 SDValue Op1 = Op.getOperand(1);
2474
2475 // If we're only demanding signbits, then we can simplify to OR/AND node.
2476 unsigned BitOp =
2477 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2478 unsigned NumSignBits =
2479 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2480 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2481 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2482 if (NumSignBits >= NumDemandedUpperBits)
2483 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2484
2485 // Check if one arg is always less/greater than (or equal) to the other arg.
2486 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2487 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2488 switch (Opc) {
2489 case ISD::SMIN:
2490 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2491 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2492 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2493 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2494 Known = KnownBits::smin(Known0, Known1);
2495 break;
2496 case ISD::SMAX:
2497 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2498 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2499 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2500 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2501 Known = KnownBits::smax(Known0, Known1);
2502 break;
2503 case ISD::UMIN:
2504 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2505 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2506 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2507 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2508 Known = KnownBits::umin(Known0, Known1);
2509 break;
2510 case ISD::UMAX:
2511 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2512 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2513 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2514 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2515 Known = KnownBits::umax(Known0, Known1);
2516 break;
2517 }
2518 break;
2519 }
2520 case ISD::BITREVERSE: {
2521 SDValue Src = Op.getOperand(0);
2522 APInt DemandedSrcBits = DemandedBits.reverseBits();
2523 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2524 Depth + 1))
2525 return true;
2526 Known = Known2.reverseBits();
2527 break;
2528 }
2529 case ISD::BSWAP: {
2530 SDValue Src = Op.getOperand(0);
2531
2532 // If the only bits demanded come from one byte of the bswap result,
2533 // just shift the input byte into position to eliminate the bswap.
2534 unsigned NLZ = DemandedBits.countl_zero();
2535 unsigned NTZ = DemandedBits.countr_zero();
2536
2537 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
2538 // we need all the bits down to bit 8. Likewise, round NLZ. If we
2539 // have 14 leading zeros, round to 8.
2540 NLZ = alignDown(NLZ, 8);
2541 NTZ = alignDown(NTZ, 8);
2542 // If we need exactly one byte, we can do this transformation.
2543 if (BitWidth - NLZ - NTZ == 8) {
2544 // Replace this with either a left or right shift to get the byte into
2545 // the right place.
2546 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2547 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2548 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2549 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
2550 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2551 return TLO.CombineTo(Op, NewOp);
2552 }
2553 }
2554
2555 APInt DemandedSrcBits = DemandedBits.byteSwap();
2556 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2557 Depth + 1))
2558 return true;
2559 Known = Known2.byteSwap();
2560 break;
2561 }
2562 case ISD::CTPOP: {
2563 // If only 1 bit is demanded, replace with PARITY as long as we're before
2564 // op legalization.
2565 // FIXME: Limit to scalars for now.
2566 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2567 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2568 Op.getOperand(0)));
2569
2570 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2571 break;
2572 }
2573 case ISD::PDEP: {
2574 SDValue Op0 = Op.getOperand(0);
2575 SDValue Op1 = Op.getOperand(1);
2576
2577 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2578 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2579
2580 // If the demanded bits has leading zeroes, we don't demand those from the
2581 // mask.
2582 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
2583 return true;
2584
2585 // The number of possible 1s in the mask determines the number of LSBs of
2586 // operand 0 used. Undemanded bits from the mask don't matter so filter
2587 // them before counting.
2588 KnownBits Known2;
2589 uint64_t Count = (~Known.Zero & LoMask).popcount();
2590 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
2591 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
2592 return true;
2593
2594 // Zeroes are retained from the mask, but not ones.
2595 Known.One.clearAllBits();
2596 // The result will have at least as many trailing zeros as the non-mask
2597 // operand since bits can only map to the same or higher bit position.
2598 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
2599 break;
2600 }
2602 SDValue Op0 = Op.getOperand(0);
2603 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2604 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2605
2606 // If we only care about the highest bit, don't bother shifting right.
2607 if (DemandedBits.isSignMask()) {
2608 unsigned MinSignedBits =
2609 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2610 bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2611 // However if the input is already sign extended we expect the sign
2612 // extension to be dropped altogether later and do not simplify.
2613 if (!AlreadySignExtended) {
2614 // Compute the correct shift amount type, which must be getShiftAmountTy
2615 // for scalar types after legalization.
2616 SDValue ShiftAmt =
2617 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl);
2618 return TLO.CombineTo(Op,
2619 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2620 }
2621 }
2622
2623 // If none of the extended bits are demanded, eliminate the sextinreg.
2624 if (DemandedBits.getActiveBits() <= ExVTBits)
2625 return TLO.CombineTo(Op, Op0);
2626
2627 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2628
2629 // Since the sign extended bits are demanded, we know that the sign
2630 // bit is demanded.
2631 InputDemandedBits.setBit(ExVTBits - 1);
2632
2633 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2634 Depth + 1))
2635 return true;
2636
2637 // If the sign bit of the input is known set or clear, then we know the
2638 // top bits of the result.
2639
2640 // If the input sign bit is known zero, convert this into a zero extension.
2641 if (Known.Zero[ExVTBits - 1])
2642 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2643
2644 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2645 if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2646 Known.One.setBitsFrom(ExVTBits);
2647 Known.Zero &= Mask;
2648 } else { // Input sign bit unknown
2649 Known.Zero &= Mask;
2650 Known.One &= Mask;
2651 }
2652 break;
2653 }
2654 case ISD::BUILD_PAIR: {
2655 EVT HalfVT = Op.getOperand(0).getValueType();
2656 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2657
2658 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2659 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2660
2661 KnownBits KnownLo, KnownHi;
2662
2663 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2664 return true;
2665
2666 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2667 return true;
2668
2669 Known = KnownHi.concat(KnownLo);
2670 break;
2671 }
2673 if (VT.isScalableVector())
2674 return false;
2675 [[fallthrough]];
2676 case ISD::ZERO_EXTEND: {
2677 SDValue Src = Op.getOperand(0);
2678 EVT SrcVT = Src.getValueType();
2679 unsigned InBits = SrcVT.getScalarSizeInBits();
2680 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2681 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2682
2683 // If none of the top bits are demanded, convert this into an any_extend.
2684 if (DemandedBits.getActiveBits() <= InBits) {
2685 // If we only need the non-extended bits of the bottom element
2686 // then we can just bitcast to the result.
2687 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2688 VT.getSizeInBits() == SrcVT.getSizeInBits())
2689 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2690
2691 unsigned Opc =
2693 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2694 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2695 }
2696
2697 APInt InDemandedBits = DemandedBits.trunc(InBits);
2698 APInt InDemandedElts = DemandedElts.zext(InElts);
2699 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2700 Depth + 1)) {
2701 Op->dropFlags(SDNodeFlags::NonNeg);
2702 return true;
2703 }
2704 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2705 Known = Known.zext(BitWidth);
2706
2707 // Attempt to avoid multi-use ops if we don't need anything from them.
2709 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2710 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2711 break;
2712 }
2714 if (VT.isScalableVector())
2715 return false;
2716 [[fallthrough]];
2717 case ISD::SIGN_EXTEND: {
2718 SDValue Src = Op.getOperand(0);
2719 EVT SrcVT = Src.getValueType();
2720 unsigned InBits = SrcVT.getScalarSizeInBits();
2721 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2722 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2723
2724 APInt InDemandedElts = DemandedElts.zext(InElts);
2725 APInt InDemandedBits = DemandedBits.trunc(InBits);
2726
2727 // Since some of the sign extended bits are demanded, we know that the sign
2728 // bit is demanded.
2729 InDemandedBits.setBit(InBits - 1);
2730
2731 // If none of the top bits are demanded, convert this into an any_extend.
2732 if (DemandedBits.getActiveBits() <= InBits) {
2733 // If we only need the non-extended bits of the bottom element
2734 // then we can just bitcast to the result.
2735 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2736 VT.getSizeInBits() == SrcVT.getSizeInBits())
2737 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2738
2739 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans.
2741 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) !=
2742 InBits) {
2743 unsigned Opc =
2745 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2746 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2747 }
2748 }
2749
2750 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2751 Depth + 1))
2752 return true;
2753 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2754
2755 // If the sign bit is known one, the top bits match.
2756 Known = Known.sext(BitWidth);
2757
2758 // If the sign bit is known zero, convert this to a zero extend.
2759 if (Known.isNonNegative()) {
2760 unsigned Opc =
2762 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) {
2763 SDNodeFlags Flags;
2764 if (!IsVecInReg)
2765 Flags |= SDNodeFlags::NonNeg;
2766 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags));
2767 }
2768 }
2769
2770 // Attempt to avoid multi-use ops if we don't need anything from them.
2772 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2773 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2774 break;
2775 }
2777 if (VT.isScalableVector())
2778 return false;
2779 [[fallthrough]];
2780 case ISD::ANY_EXTEND: {
2781 SDValue Src = Op.getOperand(0);
2782 EVT SrcVT = Src.getValueType();
2783 unsigned InBits = SrcVT.getScalarSizeInBits();
2784 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2785 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2786
2787 // If we only need the bottom element then we can just bitcast.
2788 // TODO: Handle ANY_EXTEND?
2789 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2790 VT.getSizeInBits() == SrcVT.getSizeInBits())
2791 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2792
2793 APInt InDemandedBits = DemandedBits.trunc(InBits);
2794 APInt InDemandedElts = DemandedElts.zext(InElts);
2795 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2796 Depth + 1))
2797 return true;
2798 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2799 Known = Known.anyext(BitWidth);
2800
2801 // Attempt to avoid multi-use ops if we don't need anything from them.
2803 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2804 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2805 break;
2806 }
2807 case ISD::TRUNCATE: {
2808 SDValue Src = Op.getOperand(0);
2809
2810 // Simplify the input, using demanded bit information, and compute the known
2811 // zero/one bits live out.
2812 unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2813 APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2814 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2815 Depth + 1)) {
2816 // Disable the nsw and nuw flags. We can no longer guarantee that we
2817 // won't wrap after simplification.
2818 Op->dropFlags(SDNodeFlags::NoWrap);
2819 return true;
2820 }
2821 Known = Known.trunc(BitWidth);
2822
2823 // Attempt to avoid multi-use ops if we don't need anything from them.
2825 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2826 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2827
2828 // If the input is only used by this truncate, see if we can shrink it based
2829 // on the known demanded bits.
2830 switch (Src.getOpcode()) {
2831 default:
2832 break;
2833 case ISD::SRL:
2834 // Shrink SRL by a constant if none of the high bits shifted in are
2835 // demanded.
2836 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2837 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2838 // undesirable.
2839 break;
2840
2841 if (Src.getNode()->hasOneUse()) {
2842 if (isTruncateFree(Src, VT) &&
2843 !isTruncateFree(Src.getValueType(), VT)) {
2844 // If truncate is only free at trunc(srl), do not turn it into
2845 // srl(trunc). The check is done by first check the truncate is free
2846 // at Src's opcode(srl), then check the truncate is not done by
2847 // referencing sub-register. In test, if both trunc(srl) and
2848 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only
2849 // trunc(srl)'s trunc is free, trunc(srl) is better.
2850 break;
2851 }
2852
2853 std::optional<unsigned> ShAmtC =
2854 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2);
2855 if (!ShAmtC || *ShAmtC >= BitWidth)
2856 break;
2857 unsigned ShVal = *ShAmtC;
2858
2859 APInt HighBits =
2860 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2861 HighBits.lshrInPlace(ShVal);
2862 HighBits = HighBits.trunc(BitWidth);
2863 if (!(HighBits & DemandedBits)) {
2864 // None of the shifted in bits are needed. Add a truncate of the
2865 // shift input, then shift it.
2866 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2867 SDValue NewTrunc =
2868 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2869 return TLO.CombineTo(
2870 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2871 }
2872 }
2873 break;
2874 }
2875
2876 break;
2877 }
2878 case ISD::AssertZext: {
2879 // AssertZext demands all of the high bits, plus any of the low bits
2880 // demanded by its users.
2881 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2883 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2884 TLO, Depth + 1))
2885 return true;
2886
2887 Known.Zero |= ~InMask;
2888 Known.One &= (~Known.Zero);
2889 break;
2890 }
2892 SDValue Src = Op.getOperand(0);
2893 SDValue Idx = Op.getOperand(1);
2894 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2895 unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2896
2897 if (SrcEltCnt.isScalable())
2898 return false;
2899
2900 // Demand the bits from every vector element without a constant index.
2901 unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2902 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2903 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2904 if (CIdx->getAPIntValue().ult(NumSrcElts))
2905 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2906
2907 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2908 // anything about the extended bits.
2909 APInt DemandedSrcBits = DemandedBits;
2910 if (BitWidth > EltBitWidth)
2911 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2912
2913 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2914 Depth + 1))
2915 return true;
2916
2917 // Attempt to avoid multi-use ops if we don't need anything from them.
2918 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2919 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2920 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2921 SDValue NewOp =
2922 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2923 return TLO.CombineTo(Op, NewOp);
2924 }
2925 }
2926
2927 Known = Known2;
2928 if (BitWidth > EltBitWidth)
2929 Known = Known.anyext(BitWidth);
2930 break;
2931 }
2932 case ISD::BITCAST: {
2933 if (VT.isScalableVector())
2934 return false;
2935 SDValue Src = Op.getOperand(0);
2936 EVT SrcVT = Src.getValueType();
2937 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2938
2939 // If this is an FP->Int bitcast and if the sign bit is the only
2940 // thing demanded, turn this into a FGETSIGN.
2941 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2942 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2943 SrcVT.isFloatingPoint()) {
2945 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2946 // place. We expect the SHL to be eliminated by other optimizations.
2947 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, VT, Src);
2948 unsigned ShVal = Op.getValueSizeInBits() - 1;
2949 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2950 return TLO.CombineTo(Op,
2951 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2952 }
2953 }
2954
2955 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2956 // Demand the elt/bit if any of the original elts/bits are demanded.
2957 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2958 unsigned Scale = BitWidth / NumSrcEltBits;
2959 unsigned NumSrcElts = SrcVT.getVectorNumElements();
2960 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2961 for (unsigned i = 0; i != Scale; ++i) {
2962 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2963 unsigned BitOffset = EltOffset * NumSrcEltBits;
2964 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2965 }
2966 // Recursive calls below may turn not demanded elements into poison, so we
2967 // need to demand all smaller source elements that maps to a demanded
2968 // destination element.
2969 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2970
2971 APInt KnownSrcUndef, KnownSrcZero;
2972 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2973 KnownSrcZero, TLO, Depth + 1))
2974 return true;
2975
2976 KnownBits KnownSrcBits;
2977 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2978 KnownSrcBits, TLO, Depth + 1))
2979 return true;
2980 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2981 // TODO - bigendian once we have test coverage.
2982 unsigned Scale = NumSrcEltBits / BitWidth;
2983 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2984 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2985 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2986 for (unsigned i = 0; i != NumElts; ++i)
2987 if (DemandedElts[i]) {
2988 unsigned Offset = (i % Scale) * BitWidth;
2989 DemandedSrcBits.insertBits(DemandedBits, Offset);
2990 DemandedSrcElts.setBit(i / Scale);
2991 }
2992
2993 if (SrcVT.isVector()) {
2994 APInt KnownSrcUndef, KnownSrcZero;
2995 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2996 KnownSrcZero, TLO, Depth + 1))
2997 return true;
2998 }
2999
3000 KnownBits KnownSrcBits;
3001 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
3002 KnownSrcBits, TLO, Depth + 1))
3003 return true;
3004
3005 // Attempt to avoid multi-use ops if we don't need anything from them.
3006 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
3007 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
3008 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
3009 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
3010 return TLO.CombineTo(Op, NewOp);
3011 }
3012 }
3013 }
3014
3015 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
3016 // recursive call where Known may be useful to the caller.
3017 if (Depth > 0) {
3018 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3019 return false;
3020 }
3021 break;
3022 }
3023 case ISD::MUL:
3024 if (DemandedBits.isPowerOf2()) {
3025 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
3026 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
3027 // odd (has LSB set), then the left-shifted low bit of X is the answer.
3028 unsigned CTZ = DemandedBits.countr_zero();
3029 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
3030 if (C && C->getAPIntValue().countr_zero() == CTZ) {
3031 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl);
3032 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
3033 return TLO.CombineTo(Op, Shl);
3034 }
3035 }
3036 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
3037 // X * X is odd iff X is odd.
3038 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
3039 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
3040 SDValue One = TLO.DAG.getConstant(1, dl, VT);
3041 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
3042 return TLO.CombineTo(Op, And1);
3043 }
3044 [[fallthrough]];
3045 case ISD::PTRADD:
3046 if (Op.getOperand(0).getValueType() != Op.getOperand(1).getValueType())
3047 break;
3048 // PTRADD behaves like ADD if pointers are represented as integers.
3049 [[fallthrough]];
3050 case ISD::ADD:
3051 case ISD::SUB: {
3052 // Add, Sub, and Mul don't demand any bits in positions beyond that
3053 // of the highest bit demanded of them.
3054 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
3055 SDNodeFlags Flags = Op.getNode()->getFlags();
3056 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
3057 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
3058 KnownBits KnownOp0, KnownOp1;
3059 auto GetDemandedBitsLHSMask = [&](APInt Demanded,
3060 const KnownBits &KnownRHS) {
3061 if (Op.getOpcode() == ISD::MUL)
3062 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros());
3063 return Demanded;
3064 };
3065 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
3066 Depth + 1) ||
3067 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1),
3068 DemandedElts, KnownOp0, TLO, Depth + 1) ||
3069 // See if the operation should be performed at a smaller bit width.
3071 // Disable the nsw and nuw flags. We can no longer guarantee that we
3072 // won't wrap after simplification.
3073 Op->dropFlags(SDNodeFlags::NoWrap);
3074 return true;
3075 }
3076
3077 // neg x with only low bit demanded is simply x.
3078 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
3079 isNullConstant(Op0))
3080 return TLO.CombineTo(Op, Op1);
3081
3082 // Attempt to avoid multi-use ops if we don't need anything from them.
3083 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
3085 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3087 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3088 if (DemandedOp0 || DemandedOp1) {
3089 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
3090 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
3091 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
3092 Flags & ~SDNodeFlags::NoWrap);
3093 return TLO.CombineTo(Op, NewOp);
3094 }
3095 }
3096
3097 // If we have a constant operand, we may be able to turn it into -1 if we
3098 // do not demand the high bits. This can make the constant smaller to
3099 // encode, allow more general folding, or match specialized instruction
3100 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
3101 // is probably not useful (and could be detrimental).
3103 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
3104 if (C && !C->isAllOnes() && !C->isOne() &&
3105 (C->getAPIntValue() | HighMask).isAllOnes()) {
3106 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
3107 // Disable the nsw and nuw flags. We can no longer guarantee that we
3108 // won't wrap after simplification.
3109 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1,
3110 Flags & ~SDNodeFlags::NoWrap);
3111 return TLO.CombineTo(Op, NewOp);
3112 }
3113
3114 // Match a multiply with a disguised negated-power-of-2 and convert to a
3115 // an equivalent shift-left amount.
3116 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3117 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
3118 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
3119 return 0;
3120
3121 // Don't touch opaque constants. Also, ignore zero and power-of-2
3122 // multiplies. Those will get folded later.
3123 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
3124 if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
3125 !MulC->getAPIntValue().isPowerOf2()) {
3126 APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
3127 if (UnmaskedC.isNegatedPowerOf2())
3128 return (-UnmaskedC).logBase2();
3129 }
3130 return 0;
3131 };
3132
3133 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y,
3134 unsigned ShlAmt) {
3135 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl);
3136 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
3137 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
3138 return TLO.CombineTo(Op, Res);
3139 };
3140
3142 if (Op.getOpcode() == ISD::ADD) {
3143 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3144 if (unsigned ShAmt = getShiftLeftAmt(Op0))
3145 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
3146 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
3147 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3148 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
3149 }
3150 if (Op.getOpcode() == ISD::SUB) {
3151 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
3152 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3153 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
3154 }
3155 }
3156
3157 if (Op.getOpcode() == ISD::MUL) {
3158 Known = KnownBits::mul(KnownOp0, KnownOp1);
3159 } else { // Op.getOpcode() is either ISD::ADD, ISD::PTRADD, or ISD::SUB.
3161 Op.getOpcode() != ISD::SUB, Flags.hasNoSignedWrap(),
3162 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1);
3163 }
3164 break;
3165 }
3166 case ISD::FABS: {
3167 SDValue Op0 = Op.getOperand(0);
3168 APInt SignMask = APInt::getSignMask(BitWidth);
3169
3170 if (!DemandedBits.intersects(SignMask))
3171 return TLO.CombineTo(Op, Op0);
3172
3173 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3174 Depth + 1))
3175 return true;
3176
3177 if (Known.isNonNegative())
3178 return TLO.CombineTo(Op, Op0);
3179 if (Known.isNegative())
3180 return TLO.CombineTo(
3181 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT, Op0, Op->getFlags()));
3182
3183 Known.Zero |= SignMask;
3184 Known.One &= ~SignMask;
3185
3186 break;
3187 }
3188 case ISD::FCOPYSIGN: {
3189 SDValue Op0 = Op.getOperand(0);
3190 SDValue Op1 = Op.getOperand(1);
3191
3192 unsigned BitWidth0 = Op0.getScalarValueSizeInBits();
3193 unsigned BitWidth1 = Op1.getScalarValueSizeInBits();
3194 APInt SignMask0 = APInt::getSignMask(BitWidth0);
3195 APInt SignMask1 = APInt::getSignMask(BitWidth1);
3196
3197 if (!DemandedBits.intersects(SignMask0))
3198 return TLO.CombineTo(Op, Op0);
3199
3200 if (SimplifyDemandedBits(Op0, ~SignMask0 & DemandedBits, DemandedElts,
3201 Known, TLO, Depth + 1) ||
3202 SimplifyDemandedBits(Op1, SignMask1, DemandedElts, Known2, TLO,
3203 Depth + 1))
3204 return true;
3205
3206 if (Known2.isNonNegative())
3207 return TLO.CombineTo(
3208 Op, TLO.DAG.getNode(ISD::FABS, dl, VT, Op0, Op->getFlags()));
3209
3210 if (Known2.isNegative())
3211 return TLO.CombineTo(
3212 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT,
3213 TLO.DAG.getNode(ISD::FABS, SDLoc(Op0), VT, Op0)));
3214
3215 Known.Zero &= ~SignMask0;
3216 Known.One &= ~SignMask0;
3217 break;
3218 }
3219 case ISD::FNEG: {
3220 SDValue Op0 = Op.getOperand(0);
3221 APInt SignMask = APInt::getSignMask(BitWidth);
3222
3223 if (!DemandedBits.intersects(SignMask))
3224 return TLO.CombineTo(Op, Op0);
3225
3226 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3227 Depth + 1))
3228 return true;
3229
3230 if (!Known.isSignUnknown()) {
3231 Known.Zero ^= SignMask;
3232 Known.One ^= SignMask;
3233 }
3234
3235 break;
3236 }
3237 default:
3238 // We also ask the target about intrinsics (which could be specific to it).
3239 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3240 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
3241 // TODO: Probably okay to remove after audit; here to reduce change size
3242 // in initial enablement patch for scalable vectors
3243 if (Op.getValueType().isScalableVector())
3244 break;
3246 Known, TLO, Depth))
3247 return true;
3248 break;
3249 }
3250
3251 // Just use computeKnownBits to compute output bits.
3252 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3253 break;
3254 }
3255
3256 // If we know the value of all of the demanded bits, return this as a
3257 // constant.
3259 DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
3260 // Avoid folding to a constant if any OpaqueConstant is involved.
3261 if (llvm::any_of(Op->ops(), [](SDValue V) {
3262 auto *C = dyn_cast<ConstantSDNode>(V);
3263 return C && C->isOpaque();
3264 }))
3265 return false;
3266 if (VT.isInteger())
3267 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
3268 if (VT.isFloatingPoint())
3269 return TLO.CombineTo(
3271 dl, VT));
3272 }
3273
3274 // A multi use 'all demanded elts' simplify failed to find any knownbits.
3275 // Try again just for the original demanded elts.
3276 // Ensure we do this AFTER constant folding above.
3277 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
3278 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
3279
3280 return false;
3281}
3282
3284 const APInt &DemandedElts,
3285 DAGCombinerInfo &DCI) const {
3286 SelectionDAG &DAG = DCI.DAG;
3287 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3288 !DCI.isBeforeLegalizeOps());
3289
3290 APInt KnownUndef, KnownZero;
3291 bool Simplified =
3292 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
3293 if (Simplified) {
3294 DCI.AddToWorklist(Op.getNode());
3295 DCI.CommitTargetLoweringOpt(TLO);
3296 }
3297
3298 return Simplified;
3299}
3300
3301/// Given a vector binary operation and known undefined elements for each input
3302/// operand, compute whether each element of the output is undefined.
3304 const APInt &UndefOp0,
3305 const APInt &UndefOp1) {
3306 EVT VT = BO.getValueType();
3308 "Vector binop only");
3309
3310 EVT EltVT = VT.getVectorElementType();
3311 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
3312 assert(UndefOp0.getBitWidth() == NumElts &&
3313 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
3314
3315 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
3316 const APInt &UndefVals) {
3317 if (UndefVals[Index])
3318 return DAG.getUNDEF(EltVT);
3319
3320 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
3321 // Try hard to make sure that the getNode() call is not creating temporary
3322 // nodes. Ignore opaque integers because they do not constant fold.
3323 SDValue Elt = BV->getOperand(Index);
3324 auto *C = dyn_cast<ConstantSDNode>(Elt);
3325 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
3326 return Elt;
3327 }
3328
3329 return SDValue();
3330 };
3331
3332 APInt KnownUndef = APInt::getZero(NumElts);
3333 for (unsigned i = 0; i != NumElts; ++i) {
3334 // If both inputs for this element are either constant or undef and match
3335 // the element type, compute the constant/undef result for this element of
3336 // the vector.
3337 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
3338 // not handle FP constants. The code within getNode() should be refactored
3339 // to avoid the danger of creating a bogus temporary node here.
3340 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
3341 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
3342 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
3343 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
3344 KnownUndef.setBit(i);
3345 }
3346 return KnownUndef;
3347}
3348
3350 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3351 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3352 bool AssumeSingleUse) const {
3353 EVT VT = Op.getValueType();
3354 unsigned Opcode = Op.getOpcode();
3355 APInt DemandedElts = OriginalDemandedElts;
3356 unsigned NumElts = DemandedElts.getBitWidth();
3357 assert(VT.isVector() && "Expected vector op");
3358
3359 KnownUndef = KnownZero = APInt::getZero(NumElts);
3360
3362 return false;
3363
3364 // TODO: For now we assume we know nothing about scalable vectors.
3365 if (VT.isScalableVector())
3366 return false;
3367
3368 assert(VT.getVectorNumElements() == NumElts &&
3369 "Mask size mismatches value type element count!");
3370
3371 // Undef operand.
3372 if (Op.isUndef()) {
3373 KnownUndef.setAllBits();
3374 return false;
3375 }
3376
3377 // If Op has other users, assume that all elements are needed.
3378 if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3379 DemandedElts.setAllBits();
3380
3381 // Not demanding any elements from Op.
3382 if (DemandedElts == 0) {
3383 KnownUndef.setAllBits();
3384 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3385 }
3386
3387 // Limit search depth.
3389 return false;
3390
3391 SDLoc DL(Op);
3392 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3393 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3394
3395 auto TryShrinkBinOp = [&](SDValue Op0, SDValue Op1) {
3396 unsigned ShrunkSize = getPreferredShrunkVectorSizeInBits(Op, DemandedElts);
3397 if (!ShrunkSize)
3398 return false;
3399
3400 assert(ShrunkSize % EltSizeInBits == 0 &&
3401 "Shrunk size not a multiple of element size");
3402 assert(ShrunkSize < VT.getSizeInBits() &&
3403 "Shrunk size must be < original vector size");
3404 assert(ShrunkSize >= EltSizeInBits * DemandedElts.getActiveBits() &&
3405 "Shrunk size must be >= demanded size");
3406
3407 EVT ShrunkVT = VT.changeVectorElementCount(
3408 *TLO.DAG.getContext(),
3409 ElementCount::getFixed(ShrunkSize / EltSizeInBits));
3410 Op0 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op0, 0);
3411 Op1 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op1, 0);
3412 SDValue NewOp =
3413 TLO.DAG.getNode(Opcode, DL, ShrunkVT, Op0, Op1, Op->getFlags());
3414 return TLO.CombineTo(
3415 Op, TLO.DAG.getInsertSubvector(DL, TLO.DAG.getUNDEF(VT), NewOp, 0));
3416 };
3417
3418 // Helper for demanding the specified elements and all the bits of both binary
3419 // operands.
3420 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3421 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3422 TLO.DAG, Depth + 1);
3423 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3424 TLO.DAG, Depth + 1);
3425 if (NewOp0 || NewOp1) {
3426 SDValue NewOp =
3427 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3428 NewOp1 ? NewOp1 : Op1, Op->getFlags());
3429 return TLO.CombineTo(Op, NewOp);
3430 }
3431
3432 if (TryShrinkBinOp(Op0, Op1))
3433 return true;
3434
3435 return false;
3436 };
3437
3438 switch (Opcode) {
3439 case ISD::SCALAR_TO_VECTOR: {
3440 if (!DemandedElts[0])
3441 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
3442 // Upper elements are poison, not undef - don't mark them as KnownUndef.
3443 break;
3444 }
3445 case ISD::BITCAST: {
3446 SDValue Src = Op.getOperand(0);
3447 EVT SrcVT = Src.getValueType();
3448
3449 if (!SrcVT.isVector()) {
3450 // TODO - bigendian once we have test coverage.
3451 if (IsLE) {
3452 APInt DemandedSrcBits = APInt::getZero(SrcVT.getSizeInBits());
3453 unsigned EltSize = VT.getScalarSizeInBits();
3454 for (unsigned I = 0; I != NumElts; ++I) {
3455 if (DemandedElts[I]) {
3456 unsigned Offset = I * EltSize;
3457 DemandedSrcBits.setBits(Offset, Offset + EltSize);
3458 }
3459 }
3461 if (SimplifyDemandedBits(Src, DemandedSrcBits, Known, TLO, Depth + 1))
3462 return true;
3463 }
3464 break;
3465 }
3466
3467 // Fast handling of 'identity' bitcasts.
3468 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3469 if (NumSrcElts == NumElts)
3470 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3471 KnownZero, TLO, Depth + 1);
3472
3473 APInt SrcDemandedElts, SrcZero, SrcUndef;
3474
3475 // Bitcast from 'large element' src vector to 'small element' vector, we
3476 // must demand a source element if any DemandedElt maps to it.
3477 if ((NumElts % NumSrcElts) == 0) {
3478 unsigned Scale = NumElts / NumSrcElts;
3479 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3480 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3481 TLO, Depth + 1))
3482 return true;
3483
3484 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3485 // of the large element.
3486 // TODO - bigendian once we have test coverage.
3487 if (IsLE) {
3488 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3489 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3490 for (unsigned i = 0; i != NumElts; ++i)
3491 if (DemandedElts[i]) {
3492 unsigned Ofs = (i % Scale) * EltSizeInBits;
3493 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3494 }
3495
3497 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3498 TLO, Depth + 1))
3499 return true;
3500
3501 // The bitcast has split each wide element into a number of
3502 // narrow subelements. We have just computed the Known bits
3503 // for wide elements. See if element splitting results in
3504 // some subelements being zero. Only for demanded elements!
3505 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3506 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3507 .isAllOnes())
3508 continue;
3509 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3510 unsigned Elt = Scale * SrcElt + SubElt;
3511 // A wholly-undef source lane is reported as undef below; don't also
3512 // flag it as zero, keeping the undef and zero sets disjoint.
3513 if (DemandedElts[Elt] && !SrcUndef[SrcElt])
3514 KnownZero.setBit(Elt);
3515 }
3516 }
3517 }
3518
3519 // If the src element is zero/undef then all the output elements will be -
3520 // only demanded elements are guaranteed to be correct.
3521 for (unsigned i = 0; i != NumSrcElts; ++i) {
3522 if (SrcDemandedElts[i]) {
3523 if (SrcZero[i])
3524 KnownZero.setBits(i * Scale, (i + 1) * Scale);
3525 if (SrcUndef[i])
3526 KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3527 }
3528 }
3529 }
3530
3531 // Bitcast from 'small element' src vector to 'large element' vector, we
3532 // demand all smaller source elements covered by the larger demanded element
3533 // of this vector.
3534 if ((NumSrcElts % NumElts) == 0) {
3535 unsigned Scale = NumSrcElts / NumElts;
3536 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3537 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3538 TLO, Depth + 1))
3539 return true;
3540
3541 // If all the src elements covering an output element are zero/undef, then
3542 // the output element will be as well, assuming it was demanded.
3543 for (unsigned i = 0; i != NumElts; ++i) {
3544 if (DemandedElts[i]) {
3545 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3546 KnownZero.setBit(i);
3547 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3548 KnownUndef.setBit(i);
3549 }
3550 }
3551 }
3552 break;
3553 }
3554 case ISD::FREEZE: {
3555 SDValue N0 = Op.getOperand(0);
3557 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
3558 return TLO.CombineTo(Op, N0);
3559
3560 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE
3561 // freeze(op(x, ...)) -> op(freeze(x), ...).
3562 // Don't sink the freeze below SCALAR_TO_VECTOR when the scalar is a load
3563 // of a promoted (wider than the element) type: freeze(load) can never be
3564 // folded away (the loaded value may be poison in memory), and the extra
3565 // freeze node then blocks ISel patterns matching scalar_to_vector of a
3566 // load, e.g. the AArch64 scalar_to_vector(extload) -> ldr b/h forms.
3567 // freeze(scalar_to_vector(load)) is equivalent for the demanded element
3568 // zero, and ISel selects the freeze as a plain copy.
3569 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) {
3570 SDValue Scalar = N0.getOperand(0);
3571 bool IsPromotedLoad = Scalar.getOpcode() == ISD::LOAD &&
3572 Scalar.getValueType() != VT.getVectorElementType();
3573 if (!IsPromotedLoad)
3574 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
3575 TLO.DAG.getFreeze(Scalar)));
3576 }
3577 break;
3578 }
3579 case ISD::BUILD_VECTOR: {
3580 // Check all elements and simplify any unused elements with UNDEF.
3581 if (!DemandedElts.isAllOnes()) {
3582 // Don't simplify BROADCASTS.
3583 if (llvm::any_of(Op->op_values(),
3584 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3586 bool Updated = false;
3587 for (unsigned i = 0; i != NumElts; ++i) {
3588 if (!DemandedElts[i] && !Ops[i].isUndef()) {
3589 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3590 KnownUndef.setBit(i);
3591 Updated = true;
3592 }
3593 }
3594 if (Updated)
3595 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3596 }
3597 }
3598 for (unsigned i = 0; i != NumElts; ++i) {
3599 SDValue SrcOp = Op.getOperand(i);
3600 if (SrcOp.isUndef()) {
3601 KnownUndef.setBit(i);
3602 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3604 KnownZero.setBit(i);
3605 }
3606 }
3607 break;
3608 }
3609 case ISD::CONCAT_VECTORS: {
3610 EVT SubVT = Op.getOperand(0).getValueType();
3611 unsigned NumSubVecs = Op.getNumOperands();
3612 unsigned NumSubElts = SubVT.getVectorNumElements();
3613 for (unsigned i = 0; i != NumSubVecs; ++i) {
3614 SDValue SubOp = Op.getOperand(i);
3615 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3616 APInt SubUndef, SubZero;
3617 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3618 Depth + 1))
3619 return true;
3620 KnownUndef.insertBits(SubUndef, i * NumSubElts);
3621 KnownZero.insertBits(SubZero, i * NumSubElts);
3622 }
3623
3624 // Attempt to avoid multi-use ops if we don't need anything from them.
3625 if (!DemandedElts.isAllOnes()) {
3626 bool FoundNewSub = false;
3627 SmallVector<SDValue, 2> DemandedSubOps;
3628 for (unsigned i = 0; i != NumSubVecs; ++i) {
3629 SDValue SubOp = Op.getOperand(i);
3630 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3632 SubOp, SubElts, TLO.DAG, Depth + 1);
3633 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3634 FoundNewSub = NewSubOp ? true : FoundNewSub;
3635 }
3636 if (FoundNewSub) {
3637 SDValue NewOp =
3638 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3639 return TLO.CombineTo(Op, NewOp);
3640 }
3641 }
3642 break;
3643 }
3644 case ISD::INSERT_SUBVECTOR: {
3645 // Demand any elements from the subvector and the remainder from the src it
3646 // is inserted into.
3647 SDValue Src = Op.getOperand(0);
3648 SDValue Sub = Op.getOperand(1);
3649 uint64_t Idx = Op.getConstantOperandVal(2);
3650 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3651 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3652 APInt DemandedSrcElts = DemandedElts;
3653 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3654
3655 // If none of the sub operand elements are demanded, bypass the insert.
3656 if (!DemandedSubElts)
3657 return TLO.CombineTo(Op, Src);
3658
3659 APInt SubUndef, SubZero;
3660 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3661 Depth + 1))
3662 return true;
3663
3664 // If none of the src operand elements are demanded, replace it with undef.
3665 if (!DemandedSrcElts && !Src.isUndef())
3666 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3667 TLO.DAG.getUNDEF(VT), Sub,
3668 Op.getOperand(2)));
3669
3670 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3671 TLO, Depth + 1))
3672 return true;
3673 KnownUndef.insertBits(SubUndef, Idx);
3674 KnownZero.insertBits(SubZero, Idx);
3675
3676 // Attempt to avoid multi-use ops if we don't need anything from them.
3677 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3679 Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3681 Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3682 if (NewSrc || NewSub) {
3683 NewSrc = NewSrc ? NewSrc : Src;
3684 NewSub = NewSub ? NewSub : Sub;
3685 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3686 NewSub, Op.getOperand(2));
3687 return TLO.CombineTo(Op, NewOp);
3688 }
3689 }
3690 break;
3691 }
3693 // Offset the demanded elts by the subvector index.
3694 SDValue Src = Op.getOperand(0);
3695 if (Src.getValueType().isScalableVector())
3696 break;
3697 uint64_t Idx = Op.getConstantOperandVal(1);
3698 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3699 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3700
3701 APInt SrcUndef, SrcZero;
3702 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3703 Depth + 1))
3704 return true;
3705 KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3706 KnownZero = SrcZero.extractBits(NumElts, Idx);
3707
3708 // Attempt to avoid multi-use ops if we don't need anything from them.
3709 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(Src, DemandedSrcElts,
3710 TLO.DAG, Depth + 1);
3711 if (NewSrc) {
3712 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3713 Op.getOperand(1));
3714 return TLO.CombineTo(Op, NewOp);
3715 }
3716 break;
3717 }
3719 SDValue Vec = Op.getOperand(0);
3720 SDValue Scl = Op.getOperand(1);
3721 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3722
3723 // For a legal, constant insertion index, if we don't need this insertion
3724 // then strip it, else remove it from the demanded elts.
3725 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3726 unsigned Idx = CIdx->getZExtValue();
3727 if (!DemandedElts[Idx])
3728 return TLO.CombineTo(Op, Vec);
3729
3730 APInt DemandedVecElts(DemandedElts);
3731 DemandedVecElts.clearBit(Idx);
3732 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3733 KnownZero, TLO, Depth + 1))
3734 return true;
3735
3736 KnownUndef.setBitVal(Idx, Scl.isUndef());
3737
3738 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3739 break;
3740 }
3741
3742 APInt VecUndef, VecZero;
3743 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3744 Depth + 1))
3745 return true;
3746 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3747 break;
3748 }
3749 case ISD::VSELECT: {
3750 SDValue Sel = Op.getOperand(0);
3751 SDValue LHS = Op.getOperand(1);
3752 SDValue RHS = Op.getOperand(2);
3753
3754 // Try to transform the select condition based on the current demanded
3755 // elements.
3756 APInt UndefSel, ZeroSel;
3757 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3758 Depth + 1))
3759 return true;
3760
3761 // See if we can simplify either vselect operand.
3762 APInt DemandedLHS(DemandedElts);
3763 APInt DemandedRHS(DemandedElts);
3764 APInt UndefLHS, ZeroLHS;
3765 APInt UndefRHS, ZeroRHS;
3766 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3767 Depth + 1))
3768 return true;
3769 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3770 Depth + 1))
3771 return true;
3772
3773 KnownUndef = UndefLHS & UndefRHS;
3774 KnownZero = ZeroLHS & ZeroRHS;
3775
3776 // If we know that the selected element is always zero, we don't need the
3777 // select value element.
3778 APInt DemandedSel = DemandedElts & ~KnownZero;
3779 if (DemandedSel != DemandedElts)
3780 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3781 Depth + 1))
3782 return true;
3783
3784 break;
3785 }
3786 case ISD::VECTOR_SHUFFLE: {
3787 SDValue LHS = Op.getOperand(0);
3788 SDValue RHS = Op.getOperand(1);
3789 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3790
3791 // Collect demanded elements from shuffle operands..
3792 APInt DemandedLHS(NumElts, 0);
3793 APInt DemandedRHS(NumElts, 0);
3794 for (unsigned i = 0; i != NumElts; ++i) {
3795 int M = ShuffleMask[i];
3796 if (M < 0 || !DemandedElts[i])
3797 continue;
3798 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3799 if (M < (int)NumElts)
3800 DemandedLHS.setBit(M);
3801 else
3802 DemandedRHS.setBit(M - NumElts);
3803 }
3804
3805 // If either side isn't demanded, replace it by UNDEF. We handle this
3806 // explicitly here to also simplify in case of multiple uses (on the
3807 // contrary to the SimplifyDemandedVectorElts calls below).
3808 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
3809 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
3810 if (FoldLHS || FoldRHS) {
3811 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
3812 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
3813 SDValue NewOp =
3814 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
3815 return TLO.CombineTo(Op, NewOp);
3816 }
3817
3818 // See if we can simplify either shuffle operand.
3819 APInt UndefLHS, ZeroLHS;
3820 APInt UndefRHS, ZeroRHS;
3821 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3822 Depth + 1))
3823 return true;
3824 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3825 Depth + 1))
3826 return true;
3827
3828 // Simplify mask using undef elements from LHS/RHS.
3829 bool Updated = false;
3830 bool IdentityLHS = true, IdentityRHS = true;
3831 SmallVector<int, 32> NewMask(ShuffleMask);
3832 for (unsigned i = 0; i != NumElts; ++i) {
3833 int &M = NewMask[i];
3834 if (M < 0)
3835 continue;
3836 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3837 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3838 Updated = true;
3839 M = -1;
3840 }
3841 IdentityLHS &= (M < 0) || (M == (int)i);
3842 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3843 }
3844
3845 // Update legal shuffle masks based on demanded elements if it won't reduce
3846 // to Identity which can cause premature removal of the shuffle mask.
3847 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3848 SDValue LegalShuffle =
3849 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
3850 if (LegalShuffle)
3851 return TLO.CombineTo(Op, LegalShuffle);
3852 }
3853
3854 // Propagate undef/zero elements from LHS/RHS.
3855 for (unsigned i = 0; i != NumElts; ++i) {
3856 int M = ShuffleMask[i];
3857 if (M < 0) {
3858 KnownUndef.setBit(i);
3859 } else if (M < (int)NumElts) {
3860 if (UndefLHS[M])
3861 KnownUndef.setBit(i);
3862 if (ZeroLHS[M])
3863 KnownZero.setBit(i);
3864 } else {
3865 if (UndefRHS[M - NumElts])
3866 KnownUndef.setBit(i);
3867 if (ZeroRHS[M - NumElts])
3868 KnownZero.setBit(i);
3869 }
3870 }
3871 break;
3872 }
3876 APInt SrcUndef, SrcZero;
3877 SDValue Src = Op.getOperand(0);
3878 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3879 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3880 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3881 Depth + 1))
3882 return true;
3883 KnownZero = SrcZero.zextOrTrunc(NumElts);
3884 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3885
3886 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3887 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3888 DemandedSrcElts == 1) {
3889 // aext - if we just need the bottom element then we can bitcast.
3890 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3891 }
3892
3893 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3894 // zext(undef) upper bits are guaranteed to be zero.
3895 if (DemandedElts.isSubsetOf(KnownUndef))
3896 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3897 KnownUndef.clearAllBits();
3898
3899 // zext - if we just need the bottom element then we can mask:
3900 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3901 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3902 Op->isOnlyUserOf(Src.getNode()) &&
3903 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3904 SDLoc DL(Op);
3905 EVT SrcVT = Src.getValueType();
3906 EVT SrcSVT = SrcVT.getScalarType();
3907
3908 // If we're after type legalization and SrcSVT is not legal, use the
3909 // promoted type for creating constants to avoid creating nodes with
3910 // illegal types.
3911 if (TLO.LegalTypes())
3912 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
3913
3914 SmallVector<SDValue> MaskElts;
3915 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3916 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3917 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3918 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3919 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3920 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3921 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3922 }
3923 }
3924 }
3925 break;
3926 }
3927
3928 // TODO: There are more binop opcodes that could be handled here - MIN,
3929 // MAX, saturated math, etc.
3930 case ISD::ADD: {
3931 SDValue Op0 = Op.getOperand(0);
3932 SDValue Op1 = Op.getOperand(1);
3933 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3934 APInt UndefLHS, ZeroLHS;
3935 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3936 Depth + 1, /*AssumeSingleUse*/ true))
3937 return true;
3938 }
3939 [[fallthrough]];
3940 }
3941 case ISD::AVGCEILS:
3942 case ISD::AVGCEILU:
3943 case ISD::AVGFLOORS:
3944 case ISD::AVGFLOORU:
3945 case ISD::OR:
3946 case ISD::XOR:
3947 case ISD::SUB:
3948 case ISD::FADD:
3949 case ISD::FSUB:
3950 case ISD::FMUL:
3951 case ISD::FDIV:
3952 case ISD::FREM:
3953 case ISD::PSEUDO_FMIN:
3954 case ISD::PSEUDO_FMAX: {
3955 SDValue Op0 = Op.getOperand(0);
3956 SDValue Op1 = Op.getOperand(1);
3957
3958 APInt UndefRHS, ZeroRHS;
3959 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3960 Depth + 1))
3961 return true;
3962 APInt UndefLHS, ZeroLHS;
3963 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3964 Depth + 1))
3965 return true;
3966
3967 KnownZero = ZeroLHS & ZeroRHS;
3968 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3969
3970 // Attempt to avoid multi-use ops if we don't need anything from them.
3971 // TODO - use KnownUndef to relax the demandedelts?
3972 if (!DemandedElts.isAllOnes())
3973 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3974 return true;
3975 break;
3976 }
3977 case ISD::SHL:
3978 case ISD::SRL:
3979 case ISD::SRA:
3980 case ISD::ROTL:
3981 case ISD::ROTR: {
3982 SDValue Op0 = Op.getOperand(0);
3983 SDValue Op1 = Op.getOperand(1);
3984
3985 APInt UndefRHS, ZeroRHS;
3986 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3987 Depth + 1))
3988 return true;
3989 APInt UndefLHS, ZeroLHS;
3990 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3991 Depth + 1))
3992 return true;
3993
3994 KnownZero = ZeroLHS;
3995 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3996
3997 // Attempt to avoid multi-use ops if we don't need anything from them.
3998 // TODO - use KnownUndef to relax the demandedelts?
3999 if (!DemandedElts.isAllOnes())
4000 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4001 return true;
4002 break;
4003 }
4004 case ISD::MUL:
4005 case ISD::MULHU:
4006 case ISD::MULHS:
4007 case ISD::AND: {
4008 SDValue Op0 = Op.getOperand(0);
4009 SDValue Op1 = Op.getOperand(1);
4010
4011 APInt SrcUndef, SrcZero;
4012 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
4013 Depth + 1))
4014 return true;
4015 // FIXME: If we know that a demanded element was zero in Op1 we don't need
4016 // to demand it in Op0 - its guaranteed to be zero. There is however a
4017 // restriction, as we must not make any of the originally demanded elements
4018 // more poisonous. We could reduce amount of elements demanded, but then we
4019 // also need a to inform SimplifyDemandedVectorElts that some elements must
4020 // not be made more poisonous.
4021 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
4022 TLO, Depth + 1))
4023 return true;
4024
4025 KnownUndef &= DemandedElts;
4026 KnownZero &= DemandedElts;
4027
4028 // If every element pair has a zero/undef/poison then just fold to zero.
4029 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
4030 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
4031 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
4032 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4033
4034 // If either side has a zero element, then the result element is zero, even
4035 // if the other is an UNDEF.
4036 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
4037 // and then handle 'and' nodes with the rest of the binop opcodes.
4038 KnownZero |= SrcZero;
4039 KnownUndef &= SrcUndef;
4040 KnownUndef &= ~KnownZero;
4041
4042 // Attempt to avoid multi-use ops if we don't need anything from them.
4043 if (!DemandedElts.isAllOnes())
4044 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4045 return true;
4046 break;
4047 }
4048 case ISD::TRUNCATE:
4049 case ISD::SIGN_EXTEND:
4050 case ISD::ZERO_EXTEND:
4051 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4052 KnownZero, TLO, Depth + 1))
4053 return true;
4054
4055 if (!DemandedElts.isAllOnes())
4057 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
4058 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
4059
4060 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
4061 // zext(undef) upper bits are guaranteed to be zero.
4062 if (DemandedElts.isSubsetOf(KnownUndef))
4063 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4064 KnownUndef.clearAllBits();
4065 }
4066 break;
4067 case ISD::SINT_TO_FP:
4068 case ISD::UINT_TO_FP:
4069 case ISD::FP_TO_SINT:
4070 case ISD::FP_TO_UINT:
4071 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4072 KnownZero, TLO, Depth + 1))
4073 return true;
4074 // Don't fall through to generic undef -> undef handling.
4075 return false;
4076 default: {
4077 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
4078 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
4079 KnownZero, TLO, Depth))
4080 return true;
4081 } else {
4083 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
4084 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
4085 TLO, Depth, AssumeSingleUse))
4086 return true;
4087 }
4088 break;
4089 }
4090 }
4091
4092 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
4093
4094 // Constant fold all undef cases.
4095 // TODO: Handle zero cases as well.
4096 if (DemandedElts.isSubsetOf(KnownUndef))
4097 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
4098
4099 return false;
4100}
4101
4102/// Determine which of the bits specified in Mask are known to be either zero or
4103/// one and return them in the Known.
4106 const APInt &DemandedElts,
4107 const SelectionDAG &DAG,
4108 unsigned Depth) const {
4109 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4110 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4111 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4112 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4113 "Should use MaskedValueIsZero if you don't know whether Op"
4114 " is a target node!");
4115 Known.resetAll();
4116}
4117
4120 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4121 unsigned Depth) const {
4122 Known.resetAll();
4123}
4124
4127 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4128 unsigned Depth) const {
4129 Known.resetAll();
4130}
4131
4133 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4134 // The low bits are known zero if the pointer is aligned.
4135 Known.Zero.setLowBits(Log2(Alignment));
4136}
4137
4139 SelectionDAG &DAG,
4140 const SDLoc &DL,
4141 Align Alignment) const {
4142 // Materialize leading-zero stack object pointer facts as AssertZext.
4143 // Alignment-derived low zero bits are not represented on the returned DAG
4144 // value here.
4145 EVT PtrVT = Ptr.getValueType();
4146
4147 unsigned RegSize = PtrVT.getScalarSizeInBits();
4150 Alignment);
4151
4152 unsigned NumZeroBits = Known.countMinLeadingZeros();
4153 if (!NumZeroBits)
4154 return Ptr;
4155
4156 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4157 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4158}
4159
4165
4166/// This method can be implemented by targets that want to expose additional
4167/// information about sign bits to the DAG Combiner.
4169 const APInt &,
4170 const SelectionDAG &,
4171 unsigned Depth) const {
4172 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4173 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4174 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4175 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4176 "Should use ComputeNumSignBits if you don't know whether Op"
4177 " is a target node!");
4178 return 1;
4179}
4180
4182 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4183 const MachineRegisterInfo &MRI, unsigned Depth) const {
4184 return 1;
4185}
4186
4188 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4189 TargetLoweringOpt &TLO, unsigned Depth) const {
4190 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4191 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4192 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4193 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4194 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4195 " is a target node!");
4196 return false;
4197}
4198
4200 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4201 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4202 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4203 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4204 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4205 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4206 "Should use SimplifyDemandedBits if you don't know whether Op"
4207 " is a target node!");
4208 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4209 return false;
4210}
4211
4213 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4214 SelectionDAG &DAG, unsigned Depth) const {
4215 assert(
4216 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4217 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4218 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4219 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4220 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4221 " is a target node!");
4222 return SDValue();
4223}
4224
4225SDValue
4228 SelectionDAG &DAG) const {
4229 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4230 if (!LegalMask) {
4231 std::swap(N0, N1);
4233 LegalMask = isShuffleMaskLegal(Mask, VT);
4234 }
4235
4236 if (!LegalMask)
4237 return SDValue();
4238
4239 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4240}
4241
4243 return nullptr;
4244}
4245
4247 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4248 UndefPoisonKind Kind, unsigned Depth) const {
4249 assert(
4250 (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 isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4255 " is a target node!");
4256
4257 // If Op can't create undef/poison and none of its operands are undef/poison
4258 // then Op is never undef/poison.
4259 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4260 /*ConsiderFlags*/ true, Depth) &&
4261 all_of(Op->ops(), [&](SDValue V) {
4262 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4263 });
4264}
4265
4267 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4268 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4269 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4270 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4271 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4272 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4273 "Should use canCreateUndefOrPoison if you don't know whether Op"
4274 " is a target node!");
4275 // Be conservative and return true.
4276 return true;
4277}
4278
4281 const APInt &DemandedElts,
4282 const SelectionDAG &DAG,
4283 unsigned Depth) const {
4284 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4285 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4286 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4287 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4288 "Should use computeKnownFPClass if you don't know whether Op"
4289 " is a target node!");
4290}
4291
4293 const APInt &DemandedElts,
4294 const SelectionDAG &DAG,
4295 bool SNaN,
4296 unsigned Depth) const {
4297 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4298 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4299 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4300 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4301 "Should use isKnownNeverNaN if you don't know whether Op"
4302 " is a target node!");
4303 return false;
4304}
4305
4307 const APInt &DemandedElts,
4308 APInt &UndefElts,
4309 const SelectionDAG &DAG,
4310 unsigned Depth) const {
4311 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4312 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4313 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4314 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4315 "Should use isSplatValue if you don't know whether Op"
4316 " is a target node!");
4317 return false;
4318}
4319
4320// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4321// work with truncating build vectors and vectors with elements of less than
4322// 8 bits.
4324 if (!N)
4325 return false;
4326
4327 unsigned EltWidth;
4328 APInt CVal;
4329 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4330 /*AllowTruncation=*/true)) {
4331 CVal = CN->getAPIntValue();
4332 EltWidth = N.getValueType().getScalarSizeInBits();
4333 } else
4334 return false;
4335
4336 // If this is a truncating splat, truncate the splat value.
4337 // Otherwise, we may fail to match the expected values below.
4338 if (EltWidth < CVal.getBitWidth())
4339 CVal = CVal.trunc(EltWidth);
4340
4341 switch (getBooleanContents(N.getValueType())) {
4343 return CVal[0];
4345 return CVal.isOne();
4347 return CVal.isAllOnes();
4348 }
4349
4350 llvm_unreachable("Invalid boolean contents");
4351}
4352
4354 if (!N)
4355 return false;
4356
4358 if (!CN) {
4360 if (!BV)
4361 return false;
4362
4363 // Only interested in constant splats, we don't care about undef
4364 // elements in identifying boolean constants and getConstantSplatNode
4365 // returns NULL if all ops are undef;
4366 CN = BV->getConstantSplatNode();
4367 if (!CN)
4368 return false;
4369 }
4370
4371 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4372 return !CN->getAPIntValue()[0];
4373
4374 return CN->isZero();
4375}
4376
4378 bool SExt) const {
4379 if (VT == MVT::i1)
4380 return N->isOne();
4381
4383 switch (Cnt) {
4385 // An extended value of 1 is always true, unless its original type is i1,
4386 // in which case it will be sign extended to -1.
4387 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4390 return N->isAllOnes() && SExt;
4391 }
4392 llvm_unreachable("Unexpected enumeration.");
4393}
4394
4395/// This helper function of SimplifySetCC tries to optimize the comparison when
4396/// either operand of the SetCC node is a bitwise-and instruction.
4397SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4398 ISD::CondCode Cond, const SDLoc &DL,
4399 DAGCombinerInfo &DCI) const {
4400 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4401 std::swap(N0, N1);
4402
4403 SelectionDAG &DAG = DCI.DAG;
4404 EVT OpVT = N0.getValueType();
4405 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4406 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4407 return SDValue();
4408
4409 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4410 // iff everything but LSB is known zero:
4411 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4414 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4415 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4416 if (DAG.MaskedValueIsZero(N0, UpperBits))
4417 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4418 }
4419
4420 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4421 // test in a narrow type that we can truncate to with no cost. Examples:
4422 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4423 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4424 // TODO: This conservatively checks for type legality on the source and
4425 // destination types. That may inhibit optimizations, but it also
4426 // allows setcc->shift transforms that may be more beneficial.
4427 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4428 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4429 isTypeLegal(OpVT) && N0.hasOneUse()) {
4430 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4431 AndC->getAPIntValue().getActiveBits());
4432 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4433 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4434 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4435 return DAG.getSetCC(DL, VT, Trunc, Zero,
4437 }
4438 }
4439
4440 // Match these patterns in any of their permutations:
4441 // (X & Y) == Y
4442 // (X & Y) != Y
4443 SDValue X, Y;
4444 if (N0.getOperand(0) == N1) {
4445 X = N0.getOperand(1);
4446 Y = N0.getOperand(0);
4447 } else if (N0.getOperand(1) == N1) {
4448 X = N0.getOperand(0);
4449 Y = N0.getOperand(1);
4450 } else {
4451 return SDValue();
4452 }
4453
4454 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4455 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4456 // its liable to create and infinite loop.
4457 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4458 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4460 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4461 // Note that where Y is variable and is known to have at most one bit set
4462 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4463 // equivalent when Y == 0.
4464 assert(OpVT.isInteger());
4466 if (DCI.isBeforeLegalizeOps() ||
4468 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4469 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4470 // If the target supports an 'and-not' or 'and-complement' logic operation,
4471 // try to use that to make a comparison operation more efficient.
4472 // But don't do this transform if the mask is a single bit because there are
4473 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4474 // 'rlwinm' on PPC).
4475
4476 // Bail out if the compare operand that we want to turn into a zero is
4477 // already a zero (otherwise, infinite loop).
4478 if (isNullConstant(Y))
4479 return SDValue();
4480
4481 // Transform this into: ~X & Y == 0.
4482 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4483 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4484 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4485 }
4486
4487 return SDValue();
4488}
4489
4490/// This helper function of SimplifySetCC tries to optimize the comparison when
4491/// either operand of the SetCC node is a bitwise-or instruction.
4492/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4493SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4494 ISD::CondCode Cond, const SDLoc &DL,
4495 DAGCombinerInfo &DCI) const {
4496 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4497 std::swap(N0, N1);
4498
4499 SelectionDAG &DAG = DCI.DAG;
4500 EVT OpVT = N0.getValueType();
4501 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4502 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4503 return SDValue();
4504
4505 // (X | Y) == Y
4506 // (X | Y) != Y
4507 SDValue X;
4508 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4509 // If the target supports an 'and-not' or 'and-complement' logic operation,
4510 // try to use that to make a comparison operation more efficient.
4511
4512 // Bail out if the compare operand that we want to turn into a zero is
4513 // already a zero (otherwise, infinite loop).
4514 if (isNullConstant(N1))
4515 return SDValue();
4516
4517 // Transform this into: X & ~Y ==/!= 0.
4518 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4519 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4520 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4521 }
4522
4523 return SDValue();
4524}
4525
4526/// There are multiple IR patterns that could be checking whether certain
4527/// truncation of a signed number would be lossy or not. The pattern which is
4528/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4529/// We are looking for the following pattern: (KeptBits is a constant)
4530/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4531/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4532/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4533/// We will unfold it into the natural trunc+sext pattern:
4534/// ((%x << C) a>> C) dstcond %x
4535/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4536SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4537 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4538 const SDLoc &DL) const {
4539 // We must be comparing with a constant.
4540 ConstantSDNode *C1;
4541 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4542 return SDValue();
4543
4544 // N0 should be: add %x, (1 << (KeptBits-1))
4545 if (N0->getOpcode() != ISD::ADD)
4546 return SDValue();
4547
4548 // And we must be 'add'ing a constant.
4549 ConstantSDNode *C01;
4550 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4551 return SDValue();
4552
4553 SDValue X = N0->getOperand(0);
4554 EVT XVT = X.getValueType();
4555
4556 // Validate constants ...
4557
4558 APInt I1 = C1->getAPIntValue();
4559
4560 ISD::CondCode NewCond;
4561 if (Cond == ISD::CondCode::SETULT) {
4562 NewCond = ISD::CondCode::SETEQ;
4563 } else if (Cond == ISD::CondCode::SETULE) {
4564 NewCond = ISD::CondCode::SETEQ;
4565 // But need to 'canonicalize' the constant.
4566 I1 += 1;
4567 } else if (Cond == ISD::CondCode::SETUGT) {
4568 NewCond = ISD::CondCode::SETNE;
4569 // But need to 'canonicalize' the constant.
4570 I1 += 1;
4571 } else if (Cond == ISD::CondCode::SETUGE) {
4572 NewCond = ISD::CondCode::SETNE;
4573 } else
4574 return SDValue();
4575
4576 APInt I01 = C01->getAPIntValue();
4577
4578 auto checkConstants = [&I1, &I01]() -> bool {
4579 // Both of them must be power-of-two, and the constant from setcc is bigger.
4580 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4581 };
4582
4583 if (checkConstants()) {
4584 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4585 } else {
4586 // What if we invert constants? (and the target predicate)
4587 I1.negate();
4588 I01.negate();
4589 assert(XVT.isInteger());
4590 NewCond = getSetCCInverse(NewCond, XVT);
4591 if (!checkConstants())
4592 return SDValue();
4593 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4594 }
4595
4596 // They are power-of-two, so which bit is set?
4597 const unsigned KeptBits = I1.logBase2();
4598 const unsigned KeptBitsMinusOne = I01.logBase2();
4599
4600 // Magic!
4601 if (KeptBits != (KeptBitsMinusOne + 1))
4602 return SDValue();
4603 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4604
4605 // We don't want to do this in every single case.
4606 SelectionDAG &DAG = DCI.DAG;
4607 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4608 return SDValue();
4609
4610 // Unfold into: sext_inreg(%x) cond %x
4611 // Where 'cond' will be either 'eq' or 'ne'.
4612 SDValue SExtInReg = DAG.getNode(
4614 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4615 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4616}
4617
4618// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4619SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4620 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4621 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4623 "Should be a comparison with 0.");
4624 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4625 "Valid only for [in]equality comparisons.");
4626
4627 unsigned NewShiftOpcode;
4628 SDValue X, C, Y;
4629
4630 SelectionDAG &DAG = DCI.DAG;
4631
4632 // Look for '(C l>>/<< Y)'.
4633 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4634 // The shift should be one-use.
4635 if (!V.hasOneUse())
4636 return false;
4637 unsigned OldShiftOpcode = V.getOpcode();
4638 switch (OldShiftOpcode) {
4639 case ISD::SHL:
4640 NewShiftOpcode = ISD::SRL;
4641 break;
4642 case ISD::SRL:
4643 NewShiftOpcode = ISD::SHL;
4644 break;
4645 default:
4646 return false; // must be a logical shift.
4647 }
4648 // We should be shifting a constant.
4649 // FIXME: best to use isConstantOrConstantVector().
4650 C = V.getOperand(0);
4651 ConstantSDNode *CC =
4652 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4653 if (!CC)
4654 return false;
4655 Y = V.getOperand(1);
4656
4657 ConstantSDNode *XC =
4658 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4660 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4661 };
4662
4663 // LHS of comparison should be an one-use 'and'.
4664 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4665 return SDValue();
4666
4667 X = N0.getOperand(0);
4668 SDValue Mask = N0.getOperand(1);
4669
4670 // 'and' is commutative!
4671 if (!Match(Mask)) {
4672 std::swap(X, Mask);
4673 if (!Match(Mask))
4674 return SDValue();
4675 }
4676
4677 EVT VT = X.getValueType();
4678
4679 // Produce:
4680 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4681 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4682 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4683 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4684 return T2;
4685}
4686
4687/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4688/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4689/// handle the commuted versions of these patterns.
4690SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4691 ISD::CondCode Cond, const SDLoc &DL,
4692 DAGCombinerInfo &DCI) const {
4693 unsigned BOpcode = N0.getOpcode();
4694 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4695 "Unexpected binop");
4696 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4697
4698 // (X + Y) == X --> Y == 0
4699 // (X - Y) == X --> Y == 0
4700 // (X ^ Y) == X --> Y == 0
4701 SelectionDAG &DAG = DCI.DAG;
4702 EVT OpVT = N0.getValueType();
4703 SDValue X = N0.getOperand(0);
4704 SDValue Y = N0.getOperand(1);
4705 if (X == N1)
4706 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4707
4708 if (Y != N1)
4709 return SDValue();
4710
4711 // (X + Y) == Y --> X == 0
4712 // (X ^ Y) == Y --> X == 0
4713 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4714 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4715
4716 // The shift would not be valid if the operands are boolean (i1).
4717 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4718 return SDValue();
4719
4720 // (X - Y) == Y --> X == Y << 1
4721 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4722 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4723 if (!DCI.isCalledByLegalizer())
4724 DCI.AddToWorklist(YShl1.getNode());
4725 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4726}
4727
4729 SDValue N0, const APInt &C1,
4730 ISD::CondCode Cond, const SDLoc &dl,
4731 SelectionDAG &DAG) {
4732 // Look through truncs that don't change the value of a ctpop.
4733 // FIXME: Add vector support? Need to be careful with setcc result type below.
4734 SDValue CTPOP = N0;
4735 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4737 CTPOP = N0.getOperand(0);
4738
4739 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4740 return SDValue();
4741
4742 EVT CTVT = CTPOP.getValueType();
4743 SDValue CTOp = CTPOP.getOperand(0);
4744
4745 // Expand a power-of-2-or-zero comparison based on ctpop:
4746 // (ctpop x) u< 2 -> (x & x-1) == 0
4747 // (ctpop x) u> 1 -> (x & x-1) != 0
4748 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4749 // Keep the CTPOP if it is a cheap vector op.
4750 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4751 return SDValue();
4752
4753 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4754 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4755 return SDValue();
4756 if (C1 == 0 && (Cond == ISD::SETULT))
4757 return SDValue(); // This is handled elsewhere.
4758
4759 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4760
4761 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4762 SDValue Result = CTOp;
4763 for (unsigned i = 0; i < Passes; i++) {
4764 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4765 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4766 }
4768 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4769 }
4770
4771 // Expand a power-of-2 comparison based on ctpop
4772 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4773 // Keep the CTPOP if it is cheap.
4774 if (TLI.isCtpopFast(CTVT))
4775 return SDValue();
4776
4777 SDValue Zero = DAG.getConstant(0, dl, CTVT);
4778 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4779 assert(CTVT.isInteger());
4780 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4781
4782 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4783 // check before emitting a potentially unnecessary op.
4784 if (DAG.isKnownNeverZero(CTOp)) {
4785 // (ctpop x) == 1 --> (x & x-1) == 0
4786 // (ctpop x) != 1 --> (x & x-1) != 0
4787 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4788 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4789 return RHS;
4790 }
4791
4792 // (ctpop x) == 1 --> (x ^ x-1) > x-1
4793 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4794 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4796 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4797 }
4798
4799 return SDValue();
4800}
4801
4803 ISD::CondCode Cond, const SDLoc &dl,
4804 SelectionDAG &DAG) {
4805 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4806 return SDValue();
4807
4808 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4809 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
4810 return SDValue();
4811
4812 auto getRotateSource = [](SDValue X) {
4813 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
4814 return X.getOperand(0);
4815 return SDValue();
4816 };
4817
4818 // Peek through a rotated value compared against 0 or -1:
4819 // (rot X, Y) == 0/-1 --> X == 0/-1
4820 // (rot X, Y) != 0/-1 --> X != 0/-1
4821 if (SDValue R = getRotateSource(N0))
4822 return DAG.getSetCC(dl, VT, R, N1, Cond);
4823
4824 // Peek through an 'or' of a rotated value compared against 0:
4825 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
4826 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
4827 //
4828 // TODO: Add the 'and' with -1 sibling.
4829 // TODO: Recurse through a series of 'or' ops to find the rotate.
4830 EVT OpVT = N0.getValueType();
4831 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
4832 if (SDValue R = getRotateSource(N0.getOperand(0))) {
4833 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
4834 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4835 }
4836 if (SDValue R = getRotateSource(N0.getOperand(1))) {
4837 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
4838 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4839 }
4840 }
4841
4842 return SDValue();
4843}
4844
4846 ISD::CondCode Cond, const SDLoc &dl,
4847 SelectionDAG &DAG) {
4848 // If we are testing for all-bits-clear, we might be able to do that with
4849 // less shifting since bit-order does not matter.
4850 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4851 return SDValue();
4852
4853 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4854 if (!C1 || !C1->isZero())
4855 return SDValue();
4856
4857 if (!N0.hasOneUse() ||
4858 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
4859 return SDValue();
4860
4861 unsigned BitWidth = N0.getScalarValueSizeInBits();
4862 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
4863 if (!ShAmtC)
4864 return SDValue();
4865
4866 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
4867 if (ShAmt == 0)
4868 return SDValue();
4869
4870 // Canonicalize fshr as fshl to reduce pattern-matching.
4871 if (N0.getOpcode() == ISD::FSHR)
4872 ShAmt = BitWidth - ShAmt;
4873
4874 // Match an 'or' with a specific operand 'Other' in either commuted variant.
4875 SDValue X, Y;
4876 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
4877 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
4878 return false;
4879 if (Or.getOperand(0) == Other) {
4880 X = Or.getOperand(0);
4881 Y = Or.getOperand(1);
4882 return true;
4883 }
4884 if (Or.getOperand(1) == Other) {
4885 X = Or.getOperand(1);
4886 Y = Or.getOperand(0);
4887 return true;
4888 }
4889 return false;
4890 };
4891
4892 EVT OpVT = N0.getValueType();
4893 EVT ShAmtVT = N0.getOperand(2).getValueType();
4894 SDValue F0 = N0.getOperand(0);
4895 SDValue F1 = N0.getOperand(1);
4896 if (matchOr(F0, F1)) {
4897 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4898 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4899 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4900 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4901 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4902 }
4903 if (matchOr(F1, F0)) {
4904 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4905 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4906 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4907 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4908 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4909 }
4910
4911 return SDValue();
4912}
4913
4914/// Try to simplify a setcc built with the specified operands and cc. If it is
4915/// unable to simplify it, return a null SDValue.
4917 ISD::CondCode Cond, bool foldBooleans,
4918 DAGCombinerInfo &DCI,
4919 const SDLoc &dl) const {
4920 SelectionDAG &DAG = DCI.DAG;
4921 const DataLayout &Layout = DAG.getDataLayout();
4922 EVT OpVT = N0.getValueType();
4924
4925 // Constant fold or commute setcc.
4926 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
4927 return Fold;
4928
4929 bool N0ConstOrSplat =
4930 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4931 bool N1ConstOrSplat =
4932 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4933
4934 // Canonicalize toward having the constant on the RHS.
4935 // TODO: Handle non-splat vector constants. All undef causes trouble.
4936 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
4937 // infinite loop here when we encounter one.
4939 if (N0ConstOrSplat && !N1ConstOrSplat &&
4940 (DCI.isBeforeLegalizeOps() ||
4941 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
4942 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4943
4944 // If we have a subtract with the same 2 non-constant operands as this setcc
4945 // -- but in reverse order -- then try to commute the operands of this setcc
4946 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
4947 // instruction on some targets.
4948 if (!N0ConstOrSplat && !N1ConstOrSplat &&
4949 (DCI.isBeforeLegalizeOps() ||
4950 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
4951 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
4952 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
4953 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4954
4955 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
4956 return V;
4957
4958 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
4959 return V;
4960
4961 if (auto *N1C = isConstOrConstSplat(N1)) {
4962 const APInt &C1 = N1C->getAPIntValue();
4963
4964 // Optimize some CTPOP cases.
4965 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
4966 return V;
4967
4968 // For equality to 0 of a no-wrap multiply, decompose and test each op:
4969 // X * Y == 0 --> (X == 0) || (Y == 0)
4970 // X * Y != 0 --> (X != 0) && (Y != 0)
4971 // TODO: This bails out if minsize is set, but if the target doesn't have a
4972 // single instruction multiply for this type, it would likely be
4973 // smaller to decompose.
4974 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4975 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
4976 (N0->getFlags().hasNoUnsignedWrap() ||
4977 N0->getFlags().hasNoSignedWrap()) &&
4978 !Attr.hasFnAttr(Attribute::MinSize)) {
4979 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4980 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
4981 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
4982 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
4983 }
4984
4985 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
4986 // equality comparison, then we're just comparing whether X itself is
4987 // zero.
4988 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
4989 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
4991 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
4992 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4993 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
4994 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
4995 // (srl (ctlz x), 5) == 0 -> X != 0
4996 // (srl (ctlz x), 5) != 1 -> X != 0
4997 Cond = ISD::SETNE;
4998 } else {
4999 // (srl (ctlz x), 5) != 0 -> X == 0
5000 // (srl (ctlz x), 5) == 1 -> X == 0
5001 Cond = ISD::SETEQ;
5002 }
5003 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
5004 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
5005 Cond);
5006 }
5007 }
5008 }
5009 }
5010
5011 // setcc X, 0, setlt --> X (when X is all sign bits)
5012 // setcc X, 0, setne --> X (when X is all sign bits)
5013 //
5014 // When we know that X has 0 or -1 in each element (or scalar), this
5015 // comparison will produce X. This is only true when boolean contents are
5016 // represented via 0s and -1s.
5017 if (VT == OpVT &&
5018 // Check that the result of setcc is 0 and -1.
5020 // Match only for checks X < 0 and X != 0
5021 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
5022 // The identity holds iff we know all sign bits for all lanes.
5024 return N0;
5025
5026 // FIXME: Support vectors.
5027 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5028 const APInt &C1 = N1C->getAPIntValue();
5029
5030 // (zext x) == C --> x == (trunc C)
5031 // (sext x) == C --> x == (trunc C)
5032 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5033 DCI.isBeforeLegalize() && N0->hasOneUse()) {
5034 unsigned MinBits = N0.getValueSizeInBits();
5035 SDValue PreExt;
5036 bool Signed = false;
5037 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
5038 // ZExt
5039 MinBits = N0->getOperand(0).getValueSizeInBits();
5040 PreExt = N0->getOperand(0);
5041 } else if (N0->getOpcode() == ISD::AND) {
5042 // DAGCombine turns costly ZExts into ANDs
5043 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
5044 if ((C->getAPIntValue()+1).isPowerOf2()) {
5045 MinBits = C->getAPIntValue().countr_one();
5046 PreExt = N0->getOperand(0);
5047 }
5048 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
5049 // SExt
5050 MinBits = N0->getOperand(0).getValueSizeInBits();
5051 PreExt = N0->getOperand(0);
5052 Signed = true;
5053 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
5054 // ZEXTLOAD / SEXTLOAD
5055 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
5056 MinBits = LN0->getMemoryVT().getSizeInBits();
5057 PreExt = N0;
5058 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
5059 Signed = true;
5060 MinBits = LN0->getMemoryVT().getSizeInBits();
5061 PreExt = N0;
5062 }
5063 }
5064
5065 // Figure out how many bits we need to preserve this constant.
5066 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
5067
5068 // Make sure we're not losing bits from the constant.
5069 if (MinBits > 0 &&
5070 MinBits < C1.getBitWidth() &&
5071 MinBits >= ReqdBits) {
5072 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
5073 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
5074 // Will get folded away.
5075 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
5076 if (MinBits == 1 && C1 == 1)
5077 // Invert the condition.
5078 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
5080 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
5081 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
5082 }
5083
5084 // If truncating the setcc operands is not desirable, we can still
5085 // simplify the expression in some cases:
5086 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
5087 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
5088 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
5089 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
5090 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
5091 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
5092 SDValue TopSetCC = N0->getOperand(0);
5093 unsigned N0Opc = N0->getOpcode();
5094 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
5095 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
5096 TopSetCC.getOpcode() == ISD::SETCC &&
5097 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
5098 (isConstFalseVal(N1) ||
5099 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
5100
5101 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
5102 (!N1C->isZero() && Cond == ISD::SETNE);
5103
5104 if (!Inverse)
5105 return TopSetCC;
5106
5108 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
5109 TopSetCC.getOperand(0).getValueType());
5110 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
5111 TopSetCC.getOperand(1),
5112 InvCond);
5113 }
5114 }
5115 }
5116
5117 // If the LHS is '(and load, const)', the RHS is 0, the test is for
5118 // equality or unsigned, and all 1 bits of the const are in the same
5119 // partial word, see if we can shorten the load.
5120 if (DCI.isBeforeLegalize() &&
5122 N0.getOpcode() == ISD::AND && C1 == 0 &&
5123 N0.getNode()->hasOneUse() &&
5124 isa<LoadSDNode>(N0.getOperand(0)) &&
5125 N0.getOperand(0).getNode()->hasOneUse() &&
5127 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5128 APInt bestMask;
5129 unsigned bestWidth = 0, bestOffset = 0;
5130 if (Lod->isSimple() && Lod->isUnindexed() &&
5131 (Lod->getMemoryVT().isByteSized() ||
5132 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5133 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5134 unsigned origWidth = N0.getValueSizeInBits();
5135 unsigned maskWidth = origWidth;
5136 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5137 // 8 bits, but have to be careful...
5138 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5139 origWidth = Lod->getMemoryVT().getSizeInBits();
5140 const APInt &Mask = N0.getConstantOperandAPInt(1);
5141 // Only consider power-of-2 widths (and at least one byte) as candiates
5142 // for the narrowed load.
5143 for (unsigned width = 8; width < origWidth; width *= 2) {
5144 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5145 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5146 // Avoid accessing any padding here for now (we could use memWidth
5147 // instead of origWidth here otherwise).
5148 unsigned maxOffset = origWidth - width;
5149 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5150 if (Mask.isSubsetOf(newMask)) {
5151 unsigned ptrOffset =
5152 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5153 unsigned IsFast = 0;
5154 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5155 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5157 ptrOffset / 8) &&
5159 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5160 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5161 IsFast) {
5162 bestOffset = ptrOffset / 8;
5163 bestMask = Mask.lshr(offset);
5164 bestWidth = width;
5165 break;
5166 }
5167 }
5168 newMask <<= 8;
5169 }
5170 if (bestWidth)
5171 break;
5172 }
5173 }
5174 if (bestWidth) {
5175 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5176 SDValue Ptr = Lod->getBasePtr();
5177 if (bestOffset != 0)
5178 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5179 SDValue NewLoad =
5180 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5181 Lod->getPointerInfo().getWithOffset(bestOffset),
5182 Lod->getBaseAlign());
5183 SDValue And =
5184 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5185 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5186 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5187 }
5188 }
5189
5190 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5191 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5192 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5193
5194 // If the comparison constant has bits in the upper part, the
5195 // zero-extended value could never match.
5197 C1.getBitWidth() - InSize))) {
5198 switch (Cond) {
5199 case ISD::SETUGT:
5200 case ISD::SETUGE:
5201 case ISD::SETEQ:
5202 return DAG.getConstant(0, dl, VT);
5203 case ISD::SETULT:
5204 case ISD::SETULE:
5205 case ISD::SETNE:
5206 return DAG.getConstant(1, dl, VT);
5207 case ISD::SETGT:
5208 case ISD::SETGE:
5209 // True if the sign bit of C1 is set.
5210 return DAG.getConstant(C1.isNegative(), dl, VT);
5211 case ISD::SETLT:
5212 case ISD::SETLE:
5213 // True if the sign bit of C1 isn't set.
5214 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5215 default:
5216 break;
5217 }
5218 }
5219
5220 // Otherwise, we can perform the comparison with the low bits.
5221 switch (Cond) {
5222 case ISD::SETEQ:
5223 case ISD::SETNE:
5224 case ISD::SETUGT:
5225 case ISD::SETUGE:
5226 case ISD::SETULT:
5227 case ISD::SETULE: {
5228 EVT newVT = N0.getOperand(0).getValueType();
5229 // FIXME: Should use isNarrowingProfitable.
5230 if (DCI.isBeforeLegalizeOps() ||
5231 (isOperationLegal(ISD::SETCC, newVT) &&
5232 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5234 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5235 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5236
5237 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5238 NewConst, Cond);
5239 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5240 }
5241 break;
5242 }
5243 default:
5244 break; // todo, be more careful with signed comparisons
5245 }
5246 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5247 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5249 OpVT)) {
5250 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5251 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5252 EVT ExtDstTy = N0.getValueType();
5253 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5254
5255 // If the constant doesn't fit into the number of bits for the source of
5256 // the sign extension, it is impossible for both sides to be equal.
5257 if (C1.getSignificantBits() > ExtSrcTyBits)
5258 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5259
5260 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5261 ExtDstTy != ExtSrcTy && "Unexpected types!");
5262 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5263 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5264 DAG.getConstant(Imm, dl, ExtDstTy));
5265 if (!DCI.isCalledByLegalizer())
5266 DCI.AddToWorklist(ZextOp.getNode());
5267 // Otherwise, make this a use of a zext.
5268 return DAG.getSetCC(dl, VT, ZextOp,
5269 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5270 } else if ((N1C->isZero() || N1C->isOne()) &&
5271 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5272 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5273 // excluded as they are handled below whilst checking for foldBooleans.
5274 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5275 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5276 (N0.getValueType() == MVT::i1 ||
5280 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5281 if (TrueWhenTrue)
5282 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5283 // Invert the condition.
5284 if (N0.getOpcode() == ISD::SETCC) {
5287 if (DCI.isBeforeLegalizeOps() ||
5289 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5290 }
5291 }
5292
5293 if ((N0.getOpcode() == ISD::XOR ||
5294 (N0.getOpcode() == ISD::AND &&
5295 N0.getOperand(0).getOpcode() == ISD::XOR &&
5296 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5297 isOneConstant(N0.getOperand(1))) {
5298 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5299 // can only do this if the top bits are known zero.
5300 unsigned BitWidth = N0.getValueSizeInBits();
5301 if (DAG.MaskedValueIsZero(N0,
5303 BitWidth-1))) {
5304 // Okay, get the un-inverted input value.
5305 SDValue Val;
5306 if (N0.getOpcode() == ISD::XOR) {
5307 Val = N0.getOperand(0);
5308 } else {
5309 assert(N0.getOpcode() == ISD::AND &&
5310 N0.getOperand(0).getOpcode() == ISD::XOR);
5311 // ((X^1)&1)^1 -> X & 1
5312 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5313 N0.getOperand(0).getOperand(0),
5314 N0.getOperand(1));
5315 }
5316
5317 return DAG.getSetCC(dl, VT, Val, N1,
5319 }
5320 } else if (N1C->isOne()) {
5321 SDValue Op0 = N0;
5322 if (Op0.getOpcode() == ISD::TRUNCATE)
5323 Op0 = Op0.getOperand(0);
5324
5325 if ((Op0.getOpcode() == ISD::XOR) &&
5326 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5327 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5328 SDValue XorLHS = Op0.getOperand(0);
5329 SDValue XorRHS = Op0.getOperand(1);
5330 // Ensure that the input setccs return an i1 type or 0/1 value.
5331 if (Op0.getValueType() == MVT::i1 ||
5336 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5338 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5339 }
5340 }
5341 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5342 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5343 if (Op0.getValueType().bitsGT(VT))
5344 Op0 = DAG.getNode(ISD::AND, dl, VT,
5345 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5346 DAG.getConstant(1, dl, VT));
5347 else if (Op0.getValueType().bitsLT(VT))
5348 Op0 = DAG.getNode(ISD::AND, dl, VT,
5349 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5350 DAG.getConstant(1, dl, VT));
5351
5352 return DAG.getSetCC(dl, VT, Op0,
5353 DAG.getConstant(0, dl, Op0.getValueType()),
5355 }
5356 if (Op0.getOpcode() == ISD::AssertZext &&
5357 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5358 return DAG.getSetCC(dl, VT, Op0,
5359 DAG.getConstant(0, dl, Op0.getValueType()),
5361 }
5362 }
5363
5364 // Given:
5365 // icmp eq/ne (urem %x, %y), 0
5366 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5367 // icmp eq/ne %x, 0
5368 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5369 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5370 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5371 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5372 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5373 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5374 }
5375
5376 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5377 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5378 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5380 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5381 N1C->isAllOnes()) {
5382 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5383 DAG.getConstant(0, dl, OpVT),
5385 }
5386
5387 // fold (setcc (trunc x) c) -> (setcc x c)
5388 if (N0.getOpcode() == ISD::TRUNCATE &&
5390 (N0->getFlags().hasNoSignedWrap() &&
5393 EVT NewVT = N0.getOperand(0).getValueType();
5394 SDValue NewConst = DAG.getConstant(
5396 ? C1.sext(NewVT.getSizeInBits())
5397 : C1.zext(NewVT.getSizeInBits()),
5398 dl, NewVT);
5399 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5400 }
5401
5402 if (SDValue V =
5403 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5404 return V;
5405 }
5406
5407 // These simplifications apply to splat vectors as well.
5408 // TODO: Handle more splat vector cases.
5409 if (auto *N1C = isConstOrConstSplat(N1)) {
5410 const APInt &C1 = N1C->getAPIntValue();
5411
5412 APInt MinVal, MaxVal;
5413 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5415 MinVal = APInt::getSignedMinValue(OperandBitSize);
5416 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5417 } else {
5418 MinVal = APInt::getMinValue(OperandBitSize);
5419 MaxVal = APInt::getMaxValue(OperandBitSize);
5420 }
5421
5422 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5423 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5424 // X >= MIN --> true
5425 if (C1 == MinVal)
5426 return DAG.getBoolConstant(true, dl, VT, OpVT);
5427
5428 if (!VT.isVector()) { // TODO: Support this for vectors.
5429 // X >= C0 --> X > (C0 - 1)
5430 APInt C = C1 - 1;
5432 if ((DCI.isBeforeLegalizeOps() ||
5433 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5434 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5435 isLegalICmpImmediate(C.getSExtValue())))) {
5436 return DAG.getSetCC(dl, VT, N0,
5437 DAG.getConstant(C, dl, N1.getValueType()),
5438 NewCC);
5439 }
5440 }
5441 }
5442
5443 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5444 // X <= MAX --> true
5445 if (C1 == MaxVal)
5446 return DAG.getBoolConstant(true, dl, VT, OpVT);
5447
5448 // X <= C0 --> X < (C0 + 1)
5449 if (!VT.isVector()) { // TODO: Support this for vectors.
5450 APInt C = C1 + 1;
5452 if ((DCI.isBeforeLegalizeOps() ||
5453 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5454 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5455 isLegalICmpImmediate(C.getSExtValue())))) {
5456 return DAG.getSetCC(dl, VT, N0,
5457 DAG.getConstant(C, dl, N1.getValueType()),
5458 NewCC);
5459 }
5460 }
5461 }
5462
5463 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5464 if (C1 == MinVal)
5465 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5466
5467 // TODO: Support this for vectors after legalize ops.
5468 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5469 // Canonicalize setlt X, Max --> setne X, Max
5470 if (C1 == MaxVal)
5471 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5472
5473 // If we have setult X, 1, turn it into seteq X, 0
5474 if (C1 == MinVal+1)
5475 return DAG.getSetCC(dl, VT, N0,
5476 DAG.getConstant(MinVal, dl, N0.getValueType()),
5477 ISD::SETEQ);
5478 }
5479 }
5480
5481 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5482 if (C1 == MaxVal)
5483 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5484
5485 // TODO: Support this for vectors after legalize ops.
5486 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5487 // Canonicalize setgt X, Min --> setne X, Min
5488 if (C1 == MinVal)
5489 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5490
5491 // If we have setugt X, Max-1, turn it into seteq X, Max
5492 if (C1 == MaxVal-1)
5493 return DAG.getSetCC(dl, VT, N0,
5494 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5495 ISD::SETEQ);
5496 }
5497 }
5498
5499 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5500 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5501 if (C1.isZero())
5502 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5503 VT, N0, N1, Cond, DCI, dl))
5504 return CC;
5505
5506 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5507 // For example, when high 32-bits of i64 X are known clear:
5508 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5509 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5510 bool CmpZero = N1C->isZero();
5511 bool CmpNegOne = N1C->isAllOnes();
5512 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5513 // Match or(lo,shl(hi,bw/2)) pattern.
5514 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5515 unsigned EltBits = V.getScalarValueSizeInBits();
5516 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5517 return false;
5518 SDValue LHS = V.getOperand(0);
5519 SDValue RHS = V.getOperand(1);
5520 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5521 // Unshifted element must have zero upperbits.
5522 if (RHS.getOpcode() == ISD::SHL &&
5523 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5524 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5525 DAG.MaskedValueIsZero(LHS, HiBits)) {
5526 Lo = LHS;
5527 Hi = RHS.getOperand(0);
5528 return true;
5529 }
5530 if (LHS.getOpcode() == ISD::SHL &&
5531 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5532 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5533 DAG.MaskedValueIsZero(RHS, HiBits)) {
5534 Lo = RHS;
5535 Hi = LHS.getOperand(0);
5536 return true;
5537 }
5538 return false;
5539 };
5540
5541 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5542 unsigned EltBits = N0.getScalarValueSizeInBits();
5543 unsigned HalfBits = EltBits / 2;
5544 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5545 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5546 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5547 SDValue NewN0 =
5548 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5549 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5550 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5551 };
5552
5553 SDValue Lo, Hi;
5554 if (IsConcat(N0, Lo, Hi))
5555 return MergeConcat(Lo, Hi);
5556
5557 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5558 SDValue Lo0, Lo1, Hi0, Hi1;
5559 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5560 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5561 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5562 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5563 }
5564 }
5565 }
5566 }
5567
5568 // If we have "setcc X, C0", check to see if we can shrink the immediate
5569 // by changing cc.
5570 // TODO: Support this for vectors after legalize ops.
5571 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5572 // SETUGT X, SINTMAX -> SETLT X, 0
5573 // SETUGE X, SINTMIN -> SETLT X, 0
5574 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5575 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5576 return DAG.getSetCC(dl, VT, N0,
5577 DAG.getConstant(0, dl, N1.getValueType()),
5578 ISD::SETLT);
5579
5580 // SETULT X, SINTMIN -> SETGT X, -1
5581 // SETULE X, SINTMAX -> SETGT X, -1
5582 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5583 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5584 return DAG.getSetCC(dl, VT, N0,
5585 DAG.getAllOnesConstant(dl, N1.getValueType()),
5586 ISD::SETGT);
5587 }
5588 }
5589
5590 // Back to non-vector simplifications.
5591 // TODO: Can we do these for vector splats?
5592 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5593 const APInt &C1 = N1C->getAPIntValue();
5594 EVT ShValTy = N0.getValueType();
5595
5596 // Fold bit comparisons when we can. This will result in an
5597 // incorrect value when boolean false is negative one, unless
5598 // the bitsize is 1 in which case the false value is the same
5599 // in practice regardless of the representation.
5600 if ((VT.getSizeInBits() == 1 ||
5602 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5603 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5604 N0.getOpcode() == ISD::AND) {
5605 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5606 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5607 // Perform the xform if the AND RHS is a single bit.
5608 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5609 if (AndRHS->getAPIntValue().isPowerOf2() &&
5610 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5611 return DAG.getNode(
5612 ISD::TRUNCATE, dl, VT,
5613 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5614 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5615 }
5616 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5617 // (X & 8) == 8 --> (X & 8) >> 3
5618 // Perform the xform if C1 is a single bit.
5619 unsigned ShCt = C1.logBase2();
5620 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5621 return DAG.getNode(
5622 ISD::TRUNCATE, dl, VT,
5623 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5624 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5625 }
5626 }
5627 }
5628 }
5629
5630 if (C1.getSignificantBits() <= 64 &&
5632 // (X & -256) == 256 -> (X >> 8) == 1
5633 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5634 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5635 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5636 const APInt &AndRHSC = AndRHS->getAPIntValue();
5637 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5638 unsigned ShiftBits = AndRHSC.countr_zero();
5639 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5640 // If using an unsigned shift doesn't yield a legal compare
5641 // immediate, try using sra instead.
5642 APInt NewC = C1.lshr(ShiftBits);
5643 if (NewC.getSignificantBits() <= 64 &&
5645 APInt SignedC = C1.ashr(ShiftBits);
5646 if (SignedC.getSignificantBits() <= 64 &&
5648 SDValue Shift = DAG.getNode(
5649 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5650 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5651 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5652 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5653 }
5654 }
5655 SDValue Shift = DAG.getNode(
5656 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5657 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5658 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5659 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5660 }
5661 }
5662 }
5663 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5664 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5665 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5666 // X < 0x100000000 -> (X >> 32) < 1
5667 // X >= 0x100000000 -> (X >> 32) >= 1
5668 // X <= 0x0ffffffff -> (X >> 32) < 1
5669 // X > 0x0ffffffff -> (X >> 32) >= 1
5670 unsigned ShiftBits;
5671 APInt NewC = C1;
5672 ISD::CondCode NewCond = Cond;
5673 if (AdjOne) {
5674 ShiftBits = C1.countr_one();
5675 NewC = NewC + 1;
5676 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5677 } else {
5678 ShiftBits = C1.countr_zero();
5679 }
5680 APInt RangeWidth = NewC;
5681 NewC.lshrInPlace(ShiftBits);
5682 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5684 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5685 // If this is an offset range check, try to move the offset after the
5686 // shift to avoid preserving the pre-shift add with a mask.
5687 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse()) {
5688 if (auto *AddC = isConstOrConstSplat(N0.getOperand(1))) {
5689 const APInt &AddVal = AddC->getAPIntValue();
5690 if (AddVal.countr_zero() >= ShiftBits) {
5691 APInt RangeLower = -AddVal;
5692 bool Overflow;
5693 (void)RangeLower.uadd_ov(RangeWidth, Overflow);
5694 if (!RangeWidth.isZero() && !Overflow) {
5695 SDValue Shift = DAG.getNode(
5696 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5697 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5698 APInt Offset = -RangeLower.lshr(ShiftBits);
5699 SDValue ShiftedAdd =
5700 DAG.getNode(ISD::ADD, dl, ShValTy, Shift,
5701 DAG.getConstant(Offset, dl, ShValTy));
5702 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5703 return DAG.getSetCC(dl, VT, ShiftedAdd, CmpRHS, NewCond);
5704 }
5705 }
5706 }
5707 }
5708 SDValue Shift =
5709 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5710 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5711 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5712 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5713 }
5714 }
5715 }
5716 }
5717
5719 auto *CFP = cast<ConstantFPSDNode>(N1);
5720 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5721
5722 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5723 // constant if knowing that the operand is non-nan is enough. We prefer to
5724 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5725 // materialize 0.0.
5726 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5727 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5728
5729 // setcc (fneg x), C -> setcc swap(pred) x, -C
5730 if (N0.getOpcode() == ISD::FNEG) {
5732 if (DCI.isBeforeLegalizeOps() ||
5733 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5734 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5735 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5736 }
5737 }
5738
5739 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5741 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5742 bool IsFabs = N0.getOpcode() == ISD::FABS;
5743 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5744 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5745 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5746 : (IsFabs ? fcInf : fcPosInf);
5747 if (Cond == ISD::SETUEQ)
5748 Flag |= fcNan;
5749 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5750 DAG.getTargetConstant(Flag, dl, MVT::i32));
5751 }
5752 }
5753
5754 // If the condition is not legal, see if we can find an equivalent one
5755 // which is legal.
5757 // If the comparison was an awkward floating-point == or != and one of
5758 // the comparison operands is infinity or negative infinity, convert the
5759 // condition to a less-awkward <= or >=.
5760 if (CFP->getValueAPF().isInfinity()) {
5761 bool IsNegInf = CFP->getValueAPF().isNegative();
5763 switch (Cond) {
5764 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5765 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5766 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5767 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5768 default: break;
5769 }
5770 if (NewCond != ISD::SETCC_INVALID &&
5771 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5772 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5773 }
5774 }
5775 }
5776
5777 if (N0 == N1) {
5778 // The sext(setcc()) => setcc() optimization relies on the appropriate
5779 // constant being emitted.
5780 assert(!N0.getValueType().isInteger() &&
5781 "Integer types should be handled by FoldSetCC");
5782
5783 bool EqTrue = ISD::isTrueWhenEqual(Cond);
5784 unsigned UOF = ISD::getUnorderedFlavor(Cond);
5785 if (UOF == 2) // FP operators that are undefined on NaNs.
5786 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5787 if (UOF == unsigned(EqTrue))
5788 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5789 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
5790 // if it is not already.
5791 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5792 if (NewCond != Cond &&
5793 (DCI.isBeforeLegalizeOps() ||
5794 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5795 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5796 }
5797
5798 // ~X > ~Y --> Y > X
5799 // ~X < ~Y --> Y < X
5800 // ~X < C --> X > ~C
5801 // ~X > C --> X < ~C
5802 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5803 N0.getValueType().isInteger()) {
5804 if (isBitwiseNot(N0)) {
5805 if (isBitwiseNot(N1))
5806 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
5807
5810 SDValue Not = DAG.getNOT(dl, N1, OpVT);
5811 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
5812 }
5813 }
5814 }
5815
5816 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5817 N0.getValueType().isInteger()) {
5818 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
5819 N0.getOpcode() == ISD::XOR) {
5820 // Simplify (X+Y) == (X+Z) --> Y == Z
5821 if (N0.getOpcode() == N1.getOpcode()) {
5822 if (N0.getOperand(0) == N1.getOperand(0))
5823 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
5824 if (N0.getOperand(1) == N1.getOperand(1))
5825 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5826 if (isCommutativeBinOp(N0.getOpcode())) {
5827 // If X op Y == Y op X, try other combinations.
5828 if (N0.getOperand(0) == N1.getOperand(1))
5829 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
5830 Cond);
5831 if (N0.getOperand(1) == N1.getOperand(0))
5832 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
5833 Cond);
5834 }
5835 }
5836
5837 // If RHS is a legal immediate value for a compare instruction, we need
5838 // to be careful about increasing register pressure needlessly.
5839 bool LegalRHSImm = false;
5840
5841 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
5842 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5843 // Turn (X+C1) == C2 --> X == C2-C1
5844 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
5845 return DAG.getSetCC(
5846 dl, VT, N0.getOperand(0),
5847 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
5848 dl, N0.getValueType()),
5849 Cond);
5850
5851 // Turn (X^C1) == C2 --> X == C1^C2
5852 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
5853 return DAG.getSetCC(
5854 dl, VT, N0.getOperand(0),
5855 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
5856 dl, N0.getValueType()),
5857 Cond);
5858 }
5859
5860 // Turn (C1-X) == C2 --> X == C1-C2
5861 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
5862 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
5863 return DAG.getSetCC(
5864 dl, VT, N0.getOperand(1),
5865 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
5866 dl, N0.getValueType()),
5867 Cond);
5868
5869 // Could RHSC fold directly into a compare?
5870 if (RHSC->getValueType(0).getSizeInBits() <= 64)
5871 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
5872 }
5873
5874 // (X+Y) == X --> Y == 0 and similar folds.
5875 // Don't do this if X is an immediate that can fold into a cmp
5876 // instruction and X+Y has other uses. It could be an induction variable
5877 // chain, and the transform would increase register pressure.
5878 if (!LegalRHSImm || N0.hasOneUse())
5879 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
5880 return V;
5881 }
5882
5883 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
5884 N1.getOpcode() == ISD::XOR)
5885 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
5886 return V;
5887
5888 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
5889 return V;
5890
5891 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
5892 return V;
5893 }
5894
5895 // Fold remainder of division by a constant.
5896 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
5897 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5898 // When division is cheap or optimizing for minimum size,
5899 // fall through to DIVREM creation by skipping this fold.
5900 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
5901 if (N0.getOpcode() == ISD::UREM) {
5902 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
5903 return Folded;
5904 } else if (N0.getOpcode() == ISD::SREM) {
5905 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
5906 return Folded;
5907 }
5908 }
5909 }
5910
5911 // Fold away ALL boolean setcc's.
5912 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
5913 SDValue Temp;
5914 switch (Cond) {
5915 default: llvm_unreachable("Unknown integer setcc!");
5916 case ISD::SETEQ: // X == Y -> ~(X^Y)
5917 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5918 N0 = DAG.getNOT(dl, Temp, OpVT);
5919 if (!DCI.isCalledByLegalizer())
5920 DCI.AddToWorklist(Temp.getNode());
5921 break;
5922 case ISD::SETNE: // X != Y --> (X^Y)
5923 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5924 break;
5925 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
5926 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
5927 Temp = DAG.getNOT(dl, N0, OpVT);
5928 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
5929 if (!DCI.isCalledByLegalizer())
5930 DCI.AddToWorklist(Temp.getNode());
5931 break;
5932 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
5933 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
5934 Temp = DAG.getNOT(dl, N1, OpVT);
5935 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
5936 if (!DCI.isCalledByLegalizer())
5937 DCI.AddToWorklist(Temp.getNode());
5938 break;
5939 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
5940 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
5941 Temp = DAG.getNOT(dl, N0, OpVT);
5942 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
5943 if (!DCI.isCalledByLegalizer())
5944 DCI.AddToWorklist(Temp.getNode());
5945 break;
5946 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
5947 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
5948 Temp = DAG.getNOT(dl, N1, OpVT);
5949 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
5950 break;
5951 }
5952 if (VT.getScalarType() != MVT::i1) {
5953 if (!DCI.isCalledByLegalizer())
5954 DCI.AddToWorklist(N0.getNode());
5955 // FIXME: If running after legalize, we probably can't do this.
5957 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
5958 }
5959 return N0;
5960 }
5961
5962 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
5963 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
5964 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
5966 N1->getFlags().hasNoUnsignedWrap()) ||
5968 N1->getFlags().hasNoSignedWrap())) &&
5970 if (VT.getScalarType() == MVT::i1)
5971 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5972 // For (legal) non vXi1 cases - ensure we adjust the cmp and result types.
5973 EVT OldCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5974 N0.getValueType());
5975 if (VT == OldCCVT) {
5976 EVT NewCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5977 N0.getOperand(0).getValueType());
5978 return DAG.getBoolExtOrTrunc(
5979 DAG.getSetCC(dl, NewCCVT, N0.getOperand(0), N1.getOperand(0), Cond),
5980 dl, VT, N0.getOperand(0).getValueType());
5981 }
5982 }
5983
5984 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
5985 // TODO: Remove that .isVector() check
5986 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
5988 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
5989 }
5990
5991 // Could not fold it.
5992 return SDValue();
5993}
5994
5995/// Returns true (and the GlobalValue and the offset) if the node is a
5996/// GlobalAddress + offset.
5998 int64_t &Offset) const {
5999
6000 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
6001
6002 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
6003 GA = GASD->getGlobal();
6004 Offset += GASD->getOffset();
6005 return true;
6006 }
6007
6008 if (N->isAnyAdd()) {
6009 SDValue N1 = N->getOperand(0);
6010 SDValue N2 = N->getOperand(1);
6011 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
6012 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
6013 Offset += V->getSExtValue();
6014 return true;
6015 }
6016 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
6017 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
6018 Offset += V->getSExtValue();
6019 return true;
6020 }
6021 }
6022 }
6023
6024 return false;
6025}
6026
6028 DAGCombinerInfo &DCI) const {
6029 // Default implementation: no optimization.
6030 return SDValue();
6031}
6032
6033//===----------------------------------------------------------------------===//
6034// Inline Assembler Implementation Methods
6035//===----------------------------------------------------------------------===//
6036
6039 unsigned S = Constraint.size();
6040
6041 if (S == 1) {
6042 switch (Constraint[0]) {
6043 default: break;
6044 case 'r':
6045 return C_RegisterClass;
6046 case 'm': // memory
6047 case 'o': // offsetable
6048 case 'V': // not offsetable
6049 return C_Memory;
6050 case 'p': // Address.
6051 return C_Address;
6052 case 'n': // Simple Integer
6053 case 'E': // Floating Point Constant
6054 case 'F': // Floating Point Constant
6055 return C_Immediate;
6056 case 'i': // Simple Integer or Relocatable Constant
6057 case 's': // Relocatable Constant
6058 case 'X': // Allow ANY value.
6059 case 'I': // Target registers.
6060 case 'J':
6061 case 'K':
6062 case 'L':
6063 case 'M':
6064 case 'N':
6065 case 'O':
6066 case 'P':
6067 case '<':
6068 case '>':
6069 return C_Other;
6070 }
6071 }
6072
6073 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
6074 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
6075 return C_Memory;
6076 return C_Register;
6077 }
6078 return C_Unknown;
6079}
6080
6081/// Try to replace an X constraint, which matches anything, with another that
6082/// has more specific requirements based on the type of the corresponding
6083/// operand.
6084const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6085 if (ConstraintVT.isInteger())
6086 return "r";
6087 if (ConstraintVT.isFloatingPoint())
6088 return "f"; // works for many targets
6089 return nullptr;
6090}
6091
6093 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
6094 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
6095 return SDValue();
6096}
6097
6098/// Lower the specified operand into the Ops vector.
6099/// If it is invalid, don't add anything to Ops.
6101 StringRef Constraint,
6102 std::vector<SDValue> &Ops,
6103 SelectionDAG &DAG) const {
6104
6105 if (Constraint.size() > 1)
6106 return;
6107
6108 char ConstraintLetter = Constraint[0];
6109 switch (ConstraintLetter) {
6110 default: break;
6111 case 'X': // Allows any operand
6112 case 'i': // Simple Integer or Relocatable Constant
6113 case 'n': // Simple Integer
6114 case 's': { // Relocatable Constant
6115
6117 uint64_t Offset = 0;
6118
6119 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
6120 // etc., since getelementpointer is variadic. We can't use
6121 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
6122 // while in this case the GA may be furthest from the root node which is
6123 // likely an ISD::ADD.
6124 while (true) {
6125 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
6126 // gcc prints these as sign extended. Sign extend value to 64 bits
6127 // now; without this it would get ZExt'd later in
6128 // ScheduleDAGSDNodes::EmitNode, which is very generic.
6129 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
6130 BooleanContent BCont = getBooleanContents(MVT::i64);
6131 ISD::NodeType ExtOpc =
6132 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
6133 int64_t ExtVal =
6134 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
6135 Ops.push_back(
6136 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
6137 return;
6138 }
6139 if (ConstraintLetter != 'n') {
6140 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6141 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6142 GA->getValueType(0),
6143 Offset + GA->getOffset()));
6144 return;
6145 }
6146 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
6147 Ops.push_back(DAG.getTargetBlockAddress(
6148 BA->getBlockAddress(), BA->getValueType(0),
6149 Offset + BA->getOffset(), BA->getTargetFlags()));
6150 return;
6151 }
6153 Ops.push_back(Op);
6154 return;
6155 }
6156 }
6157 const unsigned OpCode = Op.getOpcode();
6158 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6159 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6160 Op = Op.getOperand(1);
6161 // Subtraction is not commutative.
6162 else if (OpCode == ISD::ADD &&
6163 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6164 Op = Op.getOperand(0);
6165 else
6166 return;
6167 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6168 continue;
6169 }
6170 return;
6171 }
6172 break;
6173 }
6174 }
6175}
6176
6180
6181std::pair<unsigned, const TargetRegisterClass *>
6183 StringRef Constraint,
6184 MVT VT) const {
6185 if (!Constraint.starts_with("{"))
6186 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6187 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6188
6189 // Remove the braces from around the name.
6190 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6191
6192 std::pair<unsigned, const TargetRegisterClass *> R =
6193 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6194
6195 // Figure out which register class contains this reg.
6196 for (const TargetRegisterClass &RC : RI->regclasses()) {
6197 // If none of the value types for this register class are valid, we
6198 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6199 if (!isLegalRC(*RI, RC))
6200 continue;
6201
6202 for (const MCPhysReg &PR : RC) {
6203 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6204 std::pair<unsigned, const TargetRegisterClass *> S =
6205 std::make_pair(PR, &RC);
6206
6207 // If this register class has the requested value type, return it,
6208 // otherwise keep searching and return the first class found
6209 // if no other is found which explicitly has the requested type.
6210 if (RI->isTypeLegalForClass(RC, VT))
6211 return S;
6212 if (!R.second)
6213 R = S;
6214 }
6215 }
6216 }
6217
6218 return R;
6219}
6220
6221//===----------------------------------------------------------------------===//
6222// Constraint Selection.
6223
6224/// Return true of this is an input operand that is a matching constraint like
6225/// "4".
6227 assert(!ConstraintCode.empty() && "No known constraint!");
6228 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6229}
6230
6231/// If this is an input matching constraint, this method returns the output
6232/// operand it matches.
6234 assert(!ConstraintCode.empty() && "No known constraint!");
6235 return atoi(ConstraintCode.c_str());
6236}
6237
6238/// Split up the constraint string from the inline assembly value into the
6239/// specific constraints and their prefixes, and also tie in the associated
6240/// operand values.
6241/// If this returns an empty vector, and if the constraint string itself
6242/// isn't empty, there was an error parsing.
6245 const TargetRegisterInfo *TRI,
6246 const CallBase &Call) const {
6247 /// Information about all of the constraints.
6248 AsmOperandInfoVector ConstraintOperands;
6249 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6250 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6251
6252 // Do a prepass over the constraints, canonicalizing them, and building up the
6253 // ConstraintOperands list.
6254 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6255 unsigned ResNo = 0; // ResNo - The result number of the next output.
6256 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6257
6258 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6259 ConstraintOperands.emplace_back(std::move(CI));
6260 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6261
6262 // Update multiple alternative constraint count.
6263 if (OpInfo.multipleAlternatives.size() > maCount)
6264 maCount = OpInfo.multipleAlternatives.size();
6265
6266 OpInfo.ConstraintVT = MVT::Other;
6267
6268 // Compute the value type for each operand.
6269 switch (OpInfo.Type) {
6270 case InlineAsm::isOutput: {
6271 // Indirect outputs just consume an argument.
6272 if (OpInfo.isIndirect) {
6273 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6274 break;
6275 }
6276
6277 // The return value of the call is this value. As such, there is no
6278 // corresponding argument.
6279 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6280 EVT VT;
6281 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6282 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6283 } else {
6284 assert(ResNo == 0 && "Asm only has one result!");
6285 VT = getAsmOperandValueType(DL, Call.getType());
6286 }
6287 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6288 ++ResNo;
6289 break;
6290 }
6291 case InlineAsm::isInput:
6292 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6293 break;
6294 case InlineAsm::isLabel:
6295 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6296 ++LabelNo;
6297 continue;
6299 // Nothing to do.
6300 break;
6301 }
6302
6303 if (OpInfo.CallOperandVal) {
6304 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6305 if (OpInfo.isIndirect) {
6306 OpTy = Call.getParamElementType(ArgNo);
6307 assert(OpTy && "Indirect operand must have elementtype attribute");
6308 }
6309
6310 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6312 if (STy->getNumElements() == 1)
6313 OpTy = STy->getElementType(0);
6314
6315 // If OpTy is not a single value, it may be a struct/union that we
6316 // can tile with integers.
6317 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6318 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6319 switch (BitSize) {
6320 default: break;
6321 case 1:
6322 case 8:
6323 case 16:
6324 case 32:
6325 case 64:
6326 case 128:
6327 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6328 break;
6329 }
6330 }
6331
6332 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6333 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6334 ArgNo++;
6335 }
6336 }
6337
6338 // If we have multiple alternative constraints, select the best alternative.
6339 if (!ConstraintOperands.empty()) {
6340 if (maCount) {
6341 unsigned bestMAIndex = 0;
6342 int bestWeight = -1;
6343 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6344 int weight = -1;
6345 unsigned maIndex;
6346 // Compute the sums of the weights for each alternative, keeping track
6347 // of the best (highest weight) one so far.
6348 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6349 int weightSum = 0;
6350 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6351 cIndex != eIndex; ++cIndex) {
6352 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6353 if (OpInfo.Type == InlineAsm::isClobber)
6354 continue;
6355
6356 // If this is an output operand with a matching input operand,
6357 // look up the matching input. If their types mismatch, e.g. one
6358 // is an integer, the other is floating point, or their sizes are
6359 // different, flag it as an maCantMatch.
6360 if (OpInfo.hasMatchingInput()) {
6361 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6362 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6363 if ((OpInfo.ConstraintVT.isInteger() !=
6364 Input.ConstraintVT.isInteger()) ||
6365 (OpInfo.ConstraintVT.getSizeInBits() !=
6366 Input.ConstraintVT.getSizeInBits())) {
6367 weightSum = -1; // Can't match.
6368 break;
6369 }
6370 }
6371 }
6372 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6373 if (weight == -1) {
6374 weightSum = -1;
6375 break;
6376 }
6377 weightSum += weight;
6378 }
6379 // Update best.
6380 if (weightSum > bestWeight) {
6381 bestWeight = weightSum;
6382 bestMAIndex = maIndex;
6383 }
6384 }
6385
6386 // Now select chosen alternative in each constraint.
6387 for (AsmOperandInfo &cInfo : ConstraintOperands)
6388 if (cInfo.Type != InlineAsm::isClobber)
6389 cInfo.selectAlternative(bestMAIndex);
6390 }
6391 }
6392
6393 // Check and hook up tied operands, choose constraint code to use.
6394 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6395 cIndex != eIndex; ++cIndex) {
6396 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6397
6398 // If this is an output operand with a matching input operand, look up the
6399 // matching input. If their types mismatch, e.g. one is an integer, the
6400 // other is floating point, or their sizes are different, flag it as an
6401 // error.
6402 if (OpInfo.hasMatchingInput()) {
6403 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6404
6405 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6406 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6407 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6408 OpInfo.ConstraintVT);
6409 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6410 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6411 Input.ConstraintVT);
6412 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6413 OpInfo.ConstraintVT.isFloatingPoint();
6414 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6415 Input.ConstraintVT.isFloatingPoint();
6416 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6417 (MatchRC.second != InputRC.second)) {
6418 report_fatal_error("Unsupported asm: input constraint"
6419 " with a matching output constraint of"
6420 " incompatible type!");
6421 }
6422 }
6423 }
6424 }
6425
6426 return ConstraintOperands;
6427}
6428
6429/// Return a number indicating our preference for chosing a type of constraint
6430/// over another, for the purpose of sorting them. Immediates are almost always
6431/// preferrable (when they can be emitted). A higher return value means a
6432/// stronger preference for one constraint type relative to another.
6433/// FIXME: We should prefer registers over memory but doing so may lead to
6434/// unrecoverable register exhaustion later.
6435/// https://github.com/llvm/llvm-project/issues/20571
6437 switch (CT) {
6440 return 4;
6443 return 3;
6445 return 2;
6447 return 1;
6449 return 0;
6450 }
6451 llvm_unreachable("Invalid constraint type");
6452}
6453
6454/// Examine constraint type and operand type and determine a weight value.
6455/// This object must already have been set up with the operand type
6456/// and the current alternative constraint selected.
6459 AsmOperandInfo &info, int maIndex) const {
6461 if (maIndex >= (int)info.multipleAlternatives.size())
6462 rCodes = &info.Codes;
6463 else
6464 rCodes = &info.multipleAlternatives[maIndex].Codes;
6465 ConstraintWeight BestWeight = CW_Invalid;
6466
6467 // Loop over the options, keeping track of the most general one.
6468 for (const std::string &rCode : *rCodes) {
6469 ConstraintWeight weight =
6470 getSingleConstraintMatchWeight(info, rCode.c_str());
6471 if (weight > BestWeight)
6472 BestWeight = weight;
6473 }
6474
6475 return BestWeight;
6476}
6477
6478/// Examine constraint type and operand type and determine a weight value.
6479/// This object must already have been set up with the operand type
6480/// and the current alternative constraint selected.
6483 AsmOperandInfo &info, const char *constraint) const {
6485 Value *CallOperandVal = info.CallOperandVal;
6486 // If we don't have a value, we can't do a match,
6487 // but allow it at the lowest weight.
6488 if (!CallOperandVal)
6489 return CW_Default;
6490 // Look at the constraint type.
6491 switch (*constraint) {
6492 case 'i': // immediate integer.
6493 case 'n': // immediate integer with a known value.
6494 if (isa<ConstantInt>(CallOperandVal))
6495 weight = CW_Constant;
6496 break;
6497 case 's': // non-explicit intregal immediate.
6498 if (isa<GlobalValue>(CallOperandVal))
6499 weight = CW_Constant;
6500 break;
6501 case 'E': // immediate float if host format.
6502 case 'F': // immediate float.
6503 if (isa<ConstantFP>(CallOperandVal))
6504 weight = CW_Constant;
6505 break;
6506 case '<': // memory operand with autodecrement.
6507 case '>': // memory operand with autoincrement.
6508 case 'm': // memory operand.
6509 case 'o': // offsettable memory operand
6510 case 'V': // non-offsettable memory operand
6511 weight = CW_Memory;
6512 break;
6513 case 'r': // general register.
6514 case 'g': // general register, memory operand or immediate integer.
6515 // note: Clang converts "g" to "imr".
6516 if (CallOperandVal->getType()->isIntegerTy())
6517 weight = CW_Register;
6518 break;
6519 case 'X': // any operand.
6520 default:
6521 weight = CW_Default;
6522 break;
6523 }
6524 return weight;
6525}
6526
6527/// If there are multiple different constraints that we could pick for this
6528/// operand (e.g. "imr") try to pick the 'best' one.
6529/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6530/// into seven classes:
6531/// Register -> one specific register
6532/// RegisterClass -> a group of regs
6533/// Memory -> memory
6534/// Address -> a symbolic memory reference
6535/// Immediate -> immediate values
6536/// Other -> magic values (such as "Flag Output Operands")
6537/// Unknown -> something we don't recognize yet and can't handle
6538/// Ideally, we would pick the most specific constraint possible: if we have
6539/// something that fits into a register, we would pick it. The problem here
6540/// is that if we have something that could either be in a register or in
6541/// memory that use of the register could cause selection of *other*
6542/// operands to fail: they might only succeed if we pick memory. Because of
6543/// this the heuristic we use is:
6544///
6545/// 1) If there is an 'other' constraint, and if the operand is valid for
6546/// that constraint, use it. This makes us take advantage of 'i'
6547/// constraints when available.
6548/// 2) Otherwise, pick the most general constraint present. This prefers
6549/// 'm' over 'r', for example.
6550///
6552 TargetLowering::AsmOperandInfo &OpInfo) const {
6553 ConstraintGroup Ret;
6554
6555 Ret.reserve(OpInfo.Codes.size());
6556 for (StringRef Code : OpInfo.Codes) {
6558
6559 // Indirect 'other' or 'immediate' constraints are not allowed.
6560 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6561 CType == TargetLowering::C_Register ||
6563 continue;
6564
6565 // Things with matching constraints can only be registers, per gcc
6566 // documentation. This mainly affects "g" constraints.
6567 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6568 continue;
6569
6570 Ret.emplace_back(Code, CType);
6571 }
6572
6574 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6575 });
6576
6577 return Ret;
6578}
6579
6580/// If we have an immediate, see if we can lower it. Return true if we can,
6581/// false otherwise.
6583 SDValue Op, SelectionDAG *DAG,
6584 const TargetLowering &TLI) {
6585
6586 assert((P.second == TargetLowering::C_Other ||
6587 P.second == TargetLowering::C_Immediate) &&
6588 "need immediate or other");
6589
6590 if (!Op.getNode())
6591 return false;
6592
6593 std::vector<SDValue> ResultOps;
6594 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6595 return !ResultOps.empty();
6596}
6597
6598/// Determines the constraint code and constraint type to use for the specific
6599/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6601 SDValue Op,
6602 SelectionDAG *DAG) const {
6603 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6604
6605 // Single-letter constraints ('r') are very common.
6606 if (OpInfo.Codes.size() == 1) {
6607 OpInfo.ConstraintCode = OpInfo.Codes[0];
6608 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6609 } else {
6611 if (G.empty())
6612 return;
6613
6614 unsigned BestIdx = 0;
6615 for (const unsigned E = G.size();
6616 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6617 G[BestIdx].second == TargetLowering::C_Immediate);
6618 ++BestIdx) {
6619 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6620 break;
6621 // If we're out of constraints, just pick the first one.
6622 if (BestIdx + 1 == E) {
6623 BestIdx = 0;
6624 break;
6625 }
6626 }
6627
6628 OpInfo.ConstraintCode = G[BestIdx].first;
6629 OpInfo.ConstraintType = G[BestIdx].second;
6630 }
6631
6632 // 'X' matches anything.
6633 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6634 // Constants are handled elsewhere. For Functions, the type here is the
6635 // type of the result, which is not what we want to look at; leave them
6636 // alone.
6637 Value *v = OpInfo.CallOperandVal;
6638 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6639 return;
6640 }
6641
6642 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6643 OpInfo.ConstraintCode = "i";
6644 return;
6645 }
6646
6647 // Otherwise, try to resolve it to something we know about by looking at
6648 // the actual operand type.
6649 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6650 OpInfo.ConstraintCode = Repl;
6651 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6652 }
6653 }
6654}
6655
6656/// Given an exact SDIV by a constant, create a multiplication
6657/// with the multiplicative inverse of the constant.
6658/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6660 const SDLoc &dl, SelectionDAG &DAG,
6661 SmallVectorImpl<SDNode *> &Created) {
6662 SDValue Op0 = N->getOperand(0);
6663 SDValue Op1 = N->getOperand(1);
6664 EVT VT = N->getValueType(0);
6665 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6666 EVT ShSVT = ShVT.getScalarType();
6667
6668 bool UseSRA = false;
6669 SmallVector<SDValue, 16> Shifts, Factors;
6670
6671 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6672 if (C->isZero())
6673 return false;
6674
6675 EVT CT = C->getValueType(0);
6676 APInt Divisor = C->getAPIntValue();
6677 unsigned Shift = Divisor.countr_zero();
6678 if (Shift) {
6679 Divisor.ashrInPlace(Shift);
6680 UseSRA = true;
6681 }
6682 APInt Factor = Divisor.multiplicativeInverse();
6683 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6684 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6685 return true;
6686 };
6687
6688 // Collect all magic values from the build vector.
6689 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6690 return SDValue();
6691
6692 SDValue Shift, Factor;
6693 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6694 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6695 Factor = DAG.getBuildVector(VT, dl, Factors);
6696 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6697 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6698 "Expected matchUnaryPredicate to return one element for scalable "
6699 "vectors");
6700 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6701 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6702 } else {
6703 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6704 Shift = Shifts[0];
6705 Factor = Factors[0];
6706 }
6707
6708 SDValue Res = Op0;
6709 if (UseSRA) {
6710 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6711 Created.push_back(Res.getNode());
6712 }
6713
6714 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6715}
6716
6717/// Given an exact UDIV by a constant, create a multiplication
6718/// with the multiplicative inverse of the constant.
6719/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6721 const SDLoc &dl, SelectionDAG &DAG,
6722 SmallVectorImpl<SDNode *> &Created) {
6723 EVT VT = N->getValueType(0);
6724 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6725 EVT ShSVT = ShVT.getScalarType();
6726
6727 bool UseSRL = false;
6728 SmallVector<SDValue, 16> Shifts, Factors;
6729
6730 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6731 if (C->isZero())
6732 return false;
6733
6734 EVT CT = C->getValueType(0);
6735 APInt Divisor = C->getAPIntValue();
6736 unsigned Shift = Divisor.countr_zero();
6737 if (Shift) {
6738 Divisor.lshrInPlace(Shift);
6739 UseSRL = true;
6740 }
6741 // Calculate the multiplicative inverse modulo BW.
6742 APInt Factor = Divisor.multiplicativeInverse();
6743 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6744 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6745 return true;
6746 };
6747
6748 SDValue Op1 = N->getOperand(1);
6749
6750 // Collect all magic values from the build vector.
6751 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6752 return SDValue();
6753
6754 SDValue Shift, Factor;
6755 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6756 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6757 Factor = DAG.getBuildVector(VT, dl, Factors);
6758 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6759 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6760 "Expected matchUnaryPredicate to return one element for scalable "
6761 "vectors");
6762 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6763 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6764 } else {
6765 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6766 Shift = Shifts[0];
6767 Factor = Factors[0];
6768 }
6769
6770 SDValue Res = N->getOperand(0);
6771 if (UseSRL) {
6772 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
6773 Created.push_back(Res.getNode());
6774 }
6775
6776 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6777}
6778
6780 SelectionDAG &DAG,
6781 SmallVectorImpl<SDNode *> &Created) const {
6783 if (isIntDivCheap(N->getValueType(0), Attr))
6784 return SDValue(N, 0); // Lower SDIV as SDIV
6785 return SDValue();
6786}
6787
6788SDValue
6790 SelectionDAG &DAG,
6791 SmallVectorImpl<SDNode *> &Created) const {
6793 if (isIntDivCheap(N->getValueType(0), Attr))
6794 return SDValue(N, 0); // Lower SREM as SREM
6795 return SDValue();
6796}
6797
6798/// Build sdiv by power-of-2 with conditional move instructions
6799/// Ref: "Hacker's Delight" by Henry Warren 10-1
6800/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6801/// bgez x, label
6802/// add x, x, 2**k-1
6803/// label:
6804/// sra res, x, k
6805/// neg res, res (when the divisor is negative)
6807 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
6808 SmallVectorImpl<SDNode *> &Created) const {
6809 unsigned Lg2 = Divisor.countr_zero();
6810 EVT VT = N->getValueType(0);
6811
6812 SDLoc DL(N);
6813 SDValue N0 = N->getOperand(0);
6814 SDValue Zero = DAG.getConstant(0, DL, VT);
6815 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
6816 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
6817
6818 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
6819 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6820 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
6821 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6822 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
6823
6824 Created.push_back(Cmp.getNode());
6825 Created.push_back(Add.getNode());
6826 Created.push_back(CMov.getNode());
6827
6828 // Divide by pow2.
6829 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
6830 DAG.getShiftAmountConstant(Lg2, VT, DL));
6831
6832 // If we're dividing by a positive value, we're done. Otherwise, we must
6833 // negate the result.
6834 if (Divisor.isNonNegative())
6835 return SRA;
6836
6837 Created.push_back(SRA.getNode());
6838 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
6839}
6840
6841/// Given an ISD::SDIV node expressing a divide by constant,
6842/// return a DAG expression to select that will generate the same value by
6843/// multiplying by a magic number.
6844/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6846 bool IsAfterLegalization,
6847 bool IsAfterLegalTypes,
6848 SmallVectorImpl<SDNode *> &Created) const {
6849 SDLoc dl(N);
6850
6851 // If the sdiv has an 'exact' bit we can use a simpler lowering.
6852 if (N->getFlags().hasExact())
6853 return BuildExactSDIV(*this, N, dl, DAG, Created);
6854
6855 EVT VT = N->getValueType(0);
6856 EVT SVT = VT.getScalarType();
6857 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6858 EVT ShSVT = ShVT.getScalarType();
6859 unsigned EltBits = VT.getScalarSizeInBits();
6860 EVT MulVT;
6861
6862 // Check to see if we can do this.
6863 // FIXME: We should be more aggressive here.
6864 EVT QueryVT = VT;
6865 if (VT.isVector()) {
6866 // If the vector type will be legalized to a vector type with the same
6867 // element type, allow the transform before type legalization if MULHS or
6868 // SMUL_LOHI are supported.
6869 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
6870 if (!QueryVT.isVector() ||
6872 return SDValue();
6873 } else if (!isTypeLegal(VT)) {
6874 // Limit this to simple scalars for now.
6875 if (!VT.isSimple())
6876 return SDValue();
6877
6878 // If this type will be promoted to a large enough type with a legal
6879 // multiply operation, we can go ahead and do this transform.
6881 return SDValue();
6882
6883 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6884 if (MulVT.getSizeInBits() < (2 * EltBits) ||
6885 !isOperationLegal(ISD::MUL, MulVT))
6886 return SDValue();
6887 }
6888
6889 bool HasMULHS =
6890 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
6891 bool HasSMUL_LOHI =
6892 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
6893
6894 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
6895 // If type twice as wide legal, widen and use a mul plus a shift.
6896 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
6897 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
6898 // custom lowered. This is very expensive so avoid it at all costs for
6899 // constant divisors.
6900 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
6903 MulVT = WideVT;
6904 }
6905
6906 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
6907 return SDValue();
6908
6909 // If we're after type legalization and SVT is not legal, use the
6910 // promoted type for creating constants to avoid creating nodes with
6911 // illegal types.
6912 if (IsAfterLegalTypes && VT.isVector()) {
6913 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
6914 if (SVT.bitsLT(VT.getScalarType()))
6915 return SDValue();
6916 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
6917 if (ShSVT.bitsLT(ShVT.getScalarType()))
6918 return SDValue();
6919 }
6920 const unsigned SVTBits = SVT.getSizeInBits();
6921
6922 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
6923
6924 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6925 if (C->isZero())
6926 return false;
6927 // Truncate the divisor to the target scalar type in case it was promoted
6928 // during type legalization.
6929 APInt Divisor = C->getAPIntValue().trunc(EltBits);
6931 int NumeratorFactor = 0;
6932 int ShiftMask = -1;
6933
6934 if (Divisor.isOne() || Divisor.isAllOnes()) {
6935 // If d is +1/-1, we just multiply the numerator by +1/-1.
6936 NumeratorFactor = Divisor.getSExtValue();
6937 magics.Magic = 0;
6938 magics.ShiftAmount = 0;
6939 ShiftMask = 0;
6940 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
6941 // If d > 0 and m < 0, add the numerator.
6942 NumeratorFactor = 1;
6943 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
6944 // If d < 0 and m > 0, subtract the numerator.
6945 NumeratorFactor = -1;
6946 }
6947
6948 MagicFactors.push_back(
6949 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
6950 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
6951 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
6952 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
6953 return true;
6954 };
6955
6956 SDValue N0 = N->getOperand(0);
6957 SDValue N1 = N->getOperand(1);
6958
6959 // Collect the shifts / magic values from each element.
6960 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
6961 /*AllowTruncation=*/true))
6962 return SDValue();
6963
6964 SDValue MagicFactor, Factor, Shift, ShiftMask;
6965 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
6966 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
6967 Factor = DAG.getBuildVector(VT, dl, Factors);
6968 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6969 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
6970 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
6971 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
6972 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
6973 "Expected matchUnaryPredicate to return one element for scalable "
6974 "vectors");
6975 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
6976 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6977 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6978 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
6979 } else {
6980 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
6981 MagicFactor = MagicFactors[0];
6982 Factor = Factors[0];
6983 Shift = Shifts[0];
6984 ShiftMask = ShiftMasks[0];
6985 }
6986
6987 // Multiply the numerator (operand 0) by the magic value.
6988 auto GetMULHS = [&](SDValue X, SDValue Y) {
6989 if (HasMULHS)
6990 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
6991 if (HasSMUL_LOHI) {
6992 SDValue LoHi =
6993 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
6994 return LoHi.getValue(1);
6995 }
6996
6997 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
6998 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
6999 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7000 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7001 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7002 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7003 };
7004
7005 SDValue Q = GetMULHS(N0, MagicFactor);
7006 if (!Q)
7007 return SDValue();
7008
7009 Created.push_back(Q.getNode());
7010
7011 // (Optionally) Add/subtract the numerator using Factor.
7012 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
7013 Created.push_back(Factor.getNode());
7014 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
7015 Created.push_back(Q.getNode());
7016
7017 // Shift right algebraic by shift value.
7018 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
7019 Created.push_back(Q.getNode());
7020
7021 // Extract the sign bit, mask it and add it to the quotient.
7022 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
7023 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
7024 Created.push_back(T.getNode());
7025 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
7026 Created.push_back(T.getNode());
7027 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
7028}
7029
7030/// Given an ISD::UDIV node expressing a divide by constant,
7031/// return a DAG expression to select that will generate the same value by
7032/// multiplying by a magic number.
7033/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7035 bool IsAfterLegalization,
7036 bool IsAfterLegalTypes,
7037 SmallVectorImpl<SDNode *> &Created) const {
7038 SDLoc dl(N);
7039
7040 // If the udiv has an 'exact' bit we can use a simpler lowering.
7041 if (N->getFlags().hasExact())
7042 return BuildExactUDIV(*this, N, dl, DAG, Created);
7043
7044 EVT VT = N->getValueType(0);
7045 EVT SVT = VT.getScalarType();
7046 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7047 EVT ShSVT = ShVT.getScalarType();
7048 unsigned EltBits = VT.getScalarSizeInBits();
7049 EVT MulVT;
7050
7051 // Check to see if we can do this.
7052 // FIXME: We should be more aggressive here.
7053 EVT QueryVT = VT;
7054 if (VT.isVector()) {
7055 // If the vector type will be legalized to a vector type with the same
7056 // element type, allow the transform before type legalization if MULHU or
7057 // UMUL_LOHI are supported.
7058 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7059 if (!QueryVT.isVector() ||
7061 return SDValue();
7062 } else if (!isTypeLegal(VT)) {
7063 // Limit this to simple scalars for now.
7064 if (!VT.isSimple())
7065 return SDValue();
7066
7067 // If this type will be promoted to a large enough type with a legal
7068 // multiply operation, we can go ahead and do this transform.
7070 return SDValue();
7071
7072 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7073 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7074 !isOperationLegal(ISD::MUL, MulVT))
7075 return SDValue();
7076 }
7077
7078 bool HasMULHU =
7079 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
7080 bool HasUMUL_LOHI =
7081 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
7082
7083 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
7084 // If type twice as wide legal, widen and use a mul plus a shift.
7085 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7086 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
7087 // custom lowered. This is very expensive so avoid it at all costs for
7088 // constant divisors.
7089 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
7092 MulVT = WideVT;
7093 }
7094
7095 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
7096 return SDValue();
7097
7098 SDValue N0 = N->getOperand(0);
7099 SDValue N1 = N->getOperand(1);
7100
7101 // Try to use leading zeros of the dividend to reduce the multiplier and
7102 // avoid expensive fixups.
7103 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
7104
7105 // If we're after type legalization and SVT is not legal, use the
7106 // promoted type for creating constants to avoid creating nodes with
7107 // illegal types.
7108 if (IsAfterLegalTypes && VT.isVector()) {
7109 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7110 if (SVT.bitsLT(VT.getScalarType()))
7111 return SDValue();
7112 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7113 if (ShSVT.bitsLT(ShVT.getScalarType()))
7114 return SDValue();
7115 }
7116 const unsigned SVTBits = SVT.getSizeInBits();
7117
7118 // Allow i32 to be widened to i64 for uncooperative divisors if i64 MULHU or
7119 // UMUL_LOHI is supported.
7120 const EVT WideSVT = MVT::i64;
7121 const bool HasWideMULHU =
7122 VT == MVT::i32 &&
7123 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
7124 const bool HasWideUMUL_LOHI =
7125 VT == MVT::i32 &&
7126 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
7127 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
7128
7129 // For even divisors with a 33-bit magic number, the widened high-multiply
7130 // path is only worthwhile over the even-divisor rewrite on targets that
7131 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
7132 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
7133 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
7134
7135 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
7136 bool UseWiden = false;
7137 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
7138
7139 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
7140 if (C->isZero())
7141 return false;
7142 // Truncate the divisor to the target scalar type in case it was promoted
7143 // during type legalization.
7144 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7145
7146 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
7147
7148 // Magic algorithm doesn't work for division by 1. We need to emit a select
7149 // at the end.
7150 if (Divisor.isOne()) {
7151 PreShift = PostShift = DAG.getUNDEF(ShSVT);
7152 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
7153 } else {
7156 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7157 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7158 /*AllowWidenOptimization=*/AllowWiden);
7159
7160 if (magics.Widen) {
7161 UseWiden = true;
7162 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7163 } else {
7164 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7165 }
7166
7167 assert(magics.PreShift < Divisor.getBitWidth() &&
7168 "We shouldn't generate an undefined shift!");
7169 assert(magics.PostShift < Divisor.getBitWidth() &&
7170 "We shouldn't generate an undefined shift!");
7171 assert((!magics.IsAdd || magics.PreShift == 0) &&
7172 "Unexpected pre-shift");
7173 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7174 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7175 NPQFactor = DAG.getConstant(
7176 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7177 : APInt::getZero(SVTBits),
7178 dl, SVT);
7179 UseNPQ |= magics.IsAdd;
7180 UsePreShift |= magics.PreShift != 0;
7181 UsePostShift |= magics.PostShift != 0;
7182 }
7183
7184 PreShifts.push_back(PreShift);
7185 MagicFactors.push_back(MagicFactor);
7186 NPQFactors.push_back(NPQFactor);
7187 PostShifts.push_back(PostShift);
7188 return true;
7189 };
7190
7191 // Collect the shifts/magic values from each element.
7192 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7193 /*AllowTruncation=*/true))
7194 return SDValue();
7195
7196 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7197 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7198 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7199 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7200 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7201 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7202 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7203 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7204 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7205 "Expected matchUnaryPredicate to return one for scalable vectors");
7206 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7207 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7208 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7209 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7210 } else {
7211 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7212 PreShift = PreShifts[0];
7213 MagicFactor = MagicFactors[0];
7214 PostShift = PostShifts[0];
7215 }
7216
7217 if (UseWiden) {
7218 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7219 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7220
7221 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7222 // WideSVT bits
7223 SDValue High;
7224 if (HasWideMULHU) {
7225 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7226 } else {
7227 assert(HasWideUMUL_LOHI);
7228 SDValue LoHi =
7229 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7230 WideN0, MagicFactor);
7231 High = LoHi.getValue(1);
7232 }
7233
7234 Created.push_back(High.getNode());
7235 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7236 }
7237
7238 SDValue Q = N0;
7239 if (UsePreShift) {
7240 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7241 Created.push_back(Q.getNode());
7242 }
7243
7244 auto GetMULHU = [&](SDValue X, SDValue Y) {
7245 if (HasMULHU)
7246 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7247 if (HasUMUL_LOHI) {
7248 SDValue LoHi =
7249 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7250 return LoHi.getValue(1);
7251 }
7252
7253 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7254 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7255 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7256 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7257 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7258 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7259 };
7260
7261 // Multiply the numerator (operand 0) by the magic value.
7262 Q = GetMULHU(Q, MagicFactor);
7263 if (!Q)
7264 return SDValue();
7265
7266 Created.push_back(Q.getNode());
7267
7268 if (UseNPQ) {
7269 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7270 Created.push_back(NPQ.getNode());
7271
7272 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7273 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7274 if (VT.isVector())
7275 NPQ = GetMULHU(NPQ, NPQFactor);
7276 else
7277 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7278
7279 Created.push_back(NPQ.getNode());
7280
7281 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7282 Created.push_back(Q.getNode());
7283 }
7284
7285 if (UsePostShift) {
7286 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7287 Created.push_back(Q.getNode());
7288 }
7289
7290 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7291
7292 SDValue One = DAG.getConstant(1, dl, VT);
7293 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7294 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7295}
7296
7297/// If all values in Values that *don't* match the predicate are same 'splat'
7298/// value, then replace all values with that splat value.
7299/// Else, if AlternativeReplacement was provided, then replace all values that
7300/// do match predicate with AlternativeReplacement value.
7301static void
7303 std::function<bool(SDValue)> Predicate,
7304 SDValue AlternativeReplacement = SDValue()) {
7305 SDValue Replacement;
7306 // Is there a value for which the Predicate does *NOT* match? What is it?
7307 auto SplatValue = llvm::find_if_not(Values, Predicate);
7308 if (SplatValue != Values.end()) {
7309 // Does Values consist only of SplatValue's and values matching Predicate?
7310 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7311 return Value == *SplatValue || Predicate(Value);
7312 })) // Then we shall replace values matching predicate with SplatValue.
7313 Replacement = *SplatValue;
7314 }
7315 if (!Replacement) {
7316 // Oops, we did not find the "baseline" splat value.
7317 if (!AlternativeReplacement)
7318 return; // Nothing to do.
7319 // Let's replace with provided value then.
7320 Replacement = AlternativeReplacement;
7321 }
7322 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7323}
7324
7325/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7326/// where the divisor and comparison target are constants,
7327/// return a DAG expression that will generate the same comparison result
7328/// using only multiplications, additions and shifts/rotations.
7329/// Ref: "Hacker's Delight" 10-17.
7330SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7331 SDValue CompTargetNode,
7333 DAGCombinerInfo &DCI,
7334 const SDLoc &DL) const {
7336 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7337 DCI, DL, Built)) {
7338 for (SDNode *N : Built)
7339 DCI.AddToWorklist(N);
7340 return Folded;
7341 }
7342
7343 return SDValue();
7344}
7345
7346SDValue
7347TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7348 SDValue CompTargetNode, ISD::CondCode Cond,
7349 DAGCombinerInfo &DCI, const SDLoc &DL,
7350 SmallVectorImpl<SDNode *> &Created) const {
7351 // fold (seteq/ne (urem N, D), C) ->
7352 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7353 // - D must be constant, with D = D0 * 2^K where D0 is odd
7354 // - P is the multiplicative inverse of D0 modulo 2^W
7355 // - Q = floor(((2^W) - 1) / D)
7356 // where W is the width of the common type of N and D.
7357 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7358 "Only applicable for (in)equality comparisons.");
7359
7360 SelectionDAG &DAG = DCI.DAG;
7361
7362 EVT VT = REMNode.getValueType();
7363 EVT SVT = VT.getScalarType();
7364 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7365 EVT ShSVT = ShVT.getScalarType();
7366
7367 // If MUL is unavailable, we cannot proceed in any case.
7368 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7369 return SDValue();
7370
7371 bool ComparingWithAllZeros = true;
7372 bool AllComparisonsWithNonZerosAreTautological = true;
7373 bool HadTautologicalLanes = false;
7374 bool AllLanesAreTautological = true;
7375 bool HadEvenDivisor = false;
7376 bool AllDivisorsArePowerOfTwo = true;
7377 bool HadTautologicalInvertedLanes = false;
7378 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7379
7380 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7381 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7382 if (CDiv->isZero())
7383 return false;
7384
7385 const APInt &D = CDiv->getAPIntValue();
7386 const APInt &Cmp = CCmp->getAPIntValue();
7387
7388 ComparingWithAllZeros &= Cmp.isZero();
7389
7390 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7391 // if C2 is not less than C1, the comparison is always false.
7392 // But we will only be able to produce the comparison that will give the
7393 // opposive tautological answer. So this lane would need to be fixed up.
7394 bool TautologicalInvertedLane = D.ule(Cmp);
7395 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7396
7397 // If all lanes are tautological (either all divisors are ones, or divisor
7398 // is not greater than the constant we are comparing with),
7399 // we will prefer to avoid the fold.
7400 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7401 HadTautologicalLanes |= TautologicalLane;
7402 AllLanesAreTautological &= TautologicalLane;
7403
7404 // If we are comparing with non-zero, we need'll need to subtract said
7405 // comparison value from the LHS. But there is no point in doing that if
7406 // every lane where we are comparing with non-zero is tautological..
7407 if (!Cmp.isZero())
7408 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7409
7410 // Decompose D into D0 * 2^K
7411 unsigned K = D.countr_zero();
7412 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7413 APInt D0 = D.lshr(K);
7414
7415 // D is even if it has trailing zeros.
7416 HadEvenDivisor |= (K != 0);
7417 // D is a power-of-two if D0 is one.
7418 // If all divisors are power-of-two, we will prefer to avoid the fold.
7419 AllDivisorsArePowerOfTwo &= D0.isOne();
7420
7421 // P = inv(D0, 2^W)
7422 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7423 unsigned W = D.getBitWidth();
7424 APInt P = D0.multiplicativeInverse();
7425 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7426
7427 // Q = floor((2^W - 1) u/ D)
7428 // R = ((2^W - 1) u% D)
7429 APInt Q, R;
7431
7432 // If we are comparing with zero, then that comparison constant is okay,
7433 // else it may need to be one less than that.
7434 if (Cmp.ugt(R))
7435 Q -= 1;
7436
7438 "We are expecting that K is always less than all-ones for ShSVT");
7439
7440 // If the lane is tautological the result can be constant-folded.
7441 if (TautologicalLane) {
7442 // Set P and K amount to a bogus values so we can try to splat them.
7443 P = 0;
7444 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7445 // And ensure that comparison constant is tautological,
7446 // it will always compare true/false.
7447 Q.setAllBits();
7448 } else {
7449 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7450 }
7451
7452 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7453 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7454 return true;
7455 };
7456
7457 SDValue N = REMNode.getOperand(0);
7458 SDValue D = REMNode.getOperand(1);
7459
7460 // Collect the values from each element.
7461 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7462 return SDValue();
7463
7464 // If all lanes are tautological, the result can be constant-folded.
7465 if (AllLanesAreTautological)
7466 return SDValue();
7467
7468 // If this is a urem by a powers-of-two, avoid the fold since it can be
7469 // best implemented as a bit test.
7470 if (AllDivisorsArePowerOfTwo)
7471 return SDValue();
7472
7473 SDValue PVal, KVal, QVal;
7474 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7475 if (HadTautologicalLanes) {
7476 // Try to turn PAmts into a splat, since we don't care about the values
7477 // that are currently '0'. If we can't, just keep '0'`s.
7479 // Try to turn KAmts into a splat, since we don't care about the values
7480 // that are currently '-1'. If we can't, change them to '0'`s.
7482 DAG.getConstant(0, DL, ShSVT));
7483 }
7484
7485 PVal = DAG.getBuildVector(VT, DL, PAmts);
7486 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7487 QVal = DAG.getBuildVector(VT, DL, QAmts);
7488 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7489 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7490 "Expected matchBinaryPredicate to return one element for "
7491 "SPLAT_VECTORs");
7492 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7493 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7494 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7495 } else {
7496 PVal = PAmts[0];
7497 KVal = KAmts[0];
7498 QVal = QAmts[0];
7499 }
7500
7501 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7502 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7503 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7504 assert(CompTargetNode.getValueType() == N.getValueType() &&
7505 "Expecting that the types on LHS and RHS of comparisons match.");
7506 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7507 }
7508
7509 // (mul N, P)
7510 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7511 Created.push_back(Op0.getNode());
7512
7513 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7514 // divisors as a performance improvement, since rotating by 0 is a no-op.
7515 if (HadEvenDivisor) {
7516 // We need ROTR to do this.
7517 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7518 return SDValue();
7519 // UREM: (rotr (mul N, P), K)
7520 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7521 Created.push_back(Op0.getNode());
7522 }
7523
7524 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7525 SDValue NewCC =
7526 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7528 if (!HadTautologicalInvertedLanes)
7529 return NewCC;
7530
7531 // If any lanes previously compared always-false, the NewCC will give
7532 // always-true result for them, so we need to fixup those lanes.
7533 // Or the other way around for inequality predicate.
7534 assert(VT.isVector() && "Can/should only get here for vectors.");
7535 Created.push_back(NewCC.getNode());
7536
7537 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7538 // if C2 is not less than C1, the comparison is always false.
7539 // But we have produced the comparison that will give the
7540 // opposive tautological answer. So these lanes would need to be fixed up.
7541 SDValue TautologicalInvertedChannels =
7542 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7543 Created.push_back(TautologicalInvertedChannels.getNode());
7544
7545 // NOTE: we avoid letting illegal types through even if we're before legalize
7546 // ops – legalization has a hard time producing good code for this.
7547 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7548 // If we have a vector select, let's replace the comparison results in the
7549 // affected lanes with the correct tautological result.
7550 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7551 DL, SETCCVT, SETCCVT);
7552 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7553 Replacement, NewCC);
7554 }
7555
7556 // Else, we can just invert the comparison result in the appropriate lanes.
7557 //
7558 // NOTE: see the note above VSELECT above.
7559 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7560 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7561 TautologicalInvertedChannels);
7562
7563 return SDValue(); // Don't know how to lower.
7564}
7565
7566/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7567/// where the divisor is constant and the comparison target is zero,
7568/// return a DAG expression that will generate the same comparison result
7569/// using only multiplications, additions and shifts/rotations.
7570/// Ref: "Hacker's Delight" 10-17.
7571SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7572 SDValue CompTargetNode,
7574 DAGCombinerInfo &DCI,
7575 const SDLoc &DL) const {
7577 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7578 DCI, DL, Built)) {
7579 assert(Built.size() <= 7 && "Max size prediction failed.");
7580 for (SDNode *N : Built)
7581 DCI.AddToWorklist(N);
7582 return Folded;
7583 }
7584
7585 return SDValue();
7586}
7587
7588SDValue
7589TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7590 SDValue CompTargetNode, ISD::CondCode Cond,
7591 DAGCombinerInfo &DCI, const SDLoc &DL,
7592 SmallVectorImpl<SDNode *> &Created) const {
7593 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7594 // Fold:
7595 // (seteq/ne (srem N, D), 0)
7596 // To:
7597 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7598 //
7599 // - D must be constant, with D = D0 * 2^K where D0 is odd
7600 // - P is the multiplicative inverse of D0 modulo 2^W
7601 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7602 // - Q = floor((2 * A) / (2^K))
7603 // where W is the width of the common type of N and D.
7604 //
7605 // When D is a power of two (and thus D0 is 1), the normal
7606 // formula for A and Q don't apply, because the derivation
7607 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7608 // does not apply. This specifically fails when N = INT_MIN.
7609 //
7610 // Instead, for power-of-two D, we use:
7611 // - A = 0
7612 // | -> No offset needed. We're effectively treating it the same as urem.
7613 // - Q = 2^(W-K) - 1
7614 // |-> Test that the top K bits are zero after rotation
7615 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7616 "Only applicable for (in)equality comparisons.");
7617
7618 SelectionDAG &DAG = DCI.DAG;
7619
7620 EVT VT = REMNode.getValueType();
7621 EVT SVT = VT.getScalarType();
7622 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7623 EVT ShSVT = ShVT.getScalarType();
7624
7625 // If we are after ops legalization, and MUL is unavailable, we can not
7626 // proceed.
7627 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7628 return SDValue();
7629
7630 // TODO: Could support comparing with non-zero too.
7631 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7632 if (!CompTarget || !CompTarget->isZero())
7633 return SDValue();
7634
7635 bool HadOneDivisor = false;
7636 bool AllDivisorsAreOnes = true;
7637 bool HadEvenDivisor = false;
7638 bool AllDivisorsArePowerOfTwo = true;
7639 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7640
7641 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7642 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7643 if (C->isZero())
7644 return false;
7645
7646 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7647
7648 // WARNING: this fold is only valid for positive divisors!
7649 // `rem %X, -C` is equivalent to `rem %X, C`
7650 APInt D = C->getAPIntValue().abs();
7651
7652 // If all divisors are ones, we will prefer to avoid the fold.
7653 HadOneDivisor |= D.isOne();
7654 AllDivisorsAreOnes &= D.isOne();
7655
7656 // Decompose D into D0 * 2^K
7657 unsigned K = D.countr_zero();
7658 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7659 APInt D0 = D.lshr(K);
7660
7661 // D is even if it has trailing zeros.
7662 HadEvenDivisor |= (K != 0);
7663
7664 // D is a power-of-two if D0 is one. This includes INT_MIN.
7665 // If all divisors are power-of-two, we will prefer to avoid the fold.
7666 AllDivisorsArePowerOfTwo &= D0.isOne();
7667
7668 // P = inv(D0, 2^W)
7669 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7670 unsigned W = D.getBitWidth();
7671 APInt P = D0.multiplicativeInverse();
7672 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7673
7674 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7675 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7676 A.clearLowBits(K);
7677
7678 // Q = floor((2 * A) / (2^K))
7679 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7680
7682 "We are expecting that A is always less than all-ones for SVT");
7684 "We are expecting that K is always less than all-ones for ShSVT");
7685
7686 // If D was a power of two, apply the alternate constant derivation.
7687 if (D0.isOne()) {
7688 // A = 0
7689 A = APInt(W, 0);
7690 // - Q = 2^(W-K) - 1
7691 Q = APInt::getLowBitsSet(W, W - K);
7692 }
7693
7694 // If the divisor is 1 the result can be constant-folded.
7695 if (D.isOne()) {
7696 // Set P, A and K to a bogus values so we can try to splat them.
7697 P = 0;
7698 A.setAllBits();
7699 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7700
7701 // x ?% 1 == 0 <--> true <--> x u<= -1
7702 Q.setAllBits();
7703 } else {
7704 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7705 }
7706
7707 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7708 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7709 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7710 return true;
7711 };
7712
7713 SDValue N = REMNode.getOperand(0);
7714 SDValue D = REMNode.getOperand(1);
7715
7716 // Collect the values from each element.
7717 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7718 return SDValue();
7719
7720 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7721 if (AllDivisorsAreOnes)
7722 return SDValue();
7723
7724 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7725 // since it can be best implemented as a bit test.
7726 if (AllDivisorsArePowerOfTwo)
7727 return SDValue();
7728
7729 SDValue PVal, AVal, KVal, QVal;
7730 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7731 if (HadOneDivisor) {
7732 // Try to turn PAmts into a splat, since we don't care about the values
7733 // that are currently '0'. If we can't, just keep '0'`s.
7735 // Try to turn AAmts into a splat, since we don't care about the
7736 // values that are currently '-1'. If we can't, change them to '0'`s.
7738 DAG.getConstant(0, DL, SVT));
7739 // Try to turn KAmts into a splat, since we don't care about the values
7740 // that are currently '-1'. If we can't, change them to '0'`s.
7742 DAG.getConstant(0, DL, ShSVT));
7743 }
7744
7745 PVal = DAG.getBuildVector(VT, DL, PAmts);
7746 AVal = DAG.getBuildVector(VT, DL, AAmts);
7747 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7748 QVal = DAG.getBuildVector(VT, DL, QAmts);
7749 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7750 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7751 QAmts.size() == 1 &&
7752 "Expected matchUnaryPredicate to return one element for scalable "
7753 "vectors");
7754 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7755 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7756 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7757 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7758 } else {
7759 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7760 PVal = PAmts[0];
7761 AVal = AAmts[0];
7762 KVal = KAmts[0];
7763 QVal = QAmts[0];
7764 }
7765
7766 // (mul N, P)
7767 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7768 Created.push_back(Op0.getNode());
7769
7770 // We need ADD to do this.
7771 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
7772 return SDValue();
7773
7774 // (add (mul N, P), A)
7775 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
7776 Created.push_back(Op0.getNode());
7777
7778 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7779 // divisors as a performance improvement, since rotating by 0 is a no-op.
7780 if (HadEvenDivisor) {
7781 // We need ROTR to do this.
7782 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7783 return SDValue();
7784 // SREM: (rotr (add (mul N, P), A), K)
7785 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7786 Created.push_back(Op0.getNode());
7787 }
7788
7789 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
7790 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7792}
7793
7795 const DenormalMode &Mode,
7796 SDNodeFlags Flags) const {
7797 SDLoc DL(Op);
7798 EVT VT = Op.getValueType();
7799 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7800 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7801
7802 // This is specifically a check for the handling of denormal inputs, not the
7803 // result.
7804 if (Mode.Input == DenormalMode::PreserveSign ||
7805 Mode.Input == DenormalMode::PositiveZero) {
7806 // Test = X == 0.0
7807 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
7808 /*Signaling=*/false, Flags);
7809 }
7810
7811 // Testing it with denormal inputs to avoid wrong estimate.
7812 //
7813 // Test = fabs(X) < SmallestNormal
7814 const fltSemantics &FltSem = VT.getFltSemantics();
7815 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
7816 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
7817 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
7818 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
7819 /*Signaling=*/false, Flags);
7820}
7821
7823 bool LegalOps, bool OptForSize,
7825 unsigned Depth) const {
7826 // fneg is removable even if it has multiple uses.
7827 if (Op.getOpcode() == ISD::FNEG) {
7829 return Op.getOperand(0);
7830 }
7831
7832 // Don't recurse exponentially.
7834 return SDValue();
7835
7836 // Pre-increment recursion depth for use in recursive calls.
7837 ++Depth;
7838 const SDNodeFlags Flags = Op->getFlags();
7839 EVT VT = Op.getValueType();
7840 unsigned Opcode = Op.getOpcode();
7841
7842 // Don't allow anything with multiple uses unless we know it is free.
7843 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
7844 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
7845 isFPExtFree(VT, Op.getOperand(0).getValueType());
7846 if (!IsFreeExtend)
7847 return SDValue();
7848 }
7849
7850 auto RemoveDeadNode = [&](SDValue N) {
7851 if (N && N.getNode()->use_empty())
7852 DAG.RemoveDeadNode(N.getNode());
7853 };
7854
7855 SDLoc DL(Op);
7856
7857 // Because getNegatedExpression can delete nodes we need a handle to keep
7858 // temporary nodes alive in case the recursion manages to create an identical
7859 // node.
7860 std::list<HandleSDNode> Handles;
7861
7862 switch (Opcode) {
7863 case ISD::ConstantFP: {
7864 // Don't invert constant FP values after legalization unless the target says
7865 // the negated constant is legal.
7866 bool IsOpLegal =
7868 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
7869 OptForSize);
7870
7871 if (LegalOps && !IsOpLegal)
7872 break;
7873
7874 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
7875 V.changeSign();
7876 SDValue CFP = DAG.getConstantFP(V, DL, VT);
7877
7878 // If we already have the use of the negated floating constant, it is free
7879 // to negate it even it has multiple uses.
7880 if (!Op.hasOneUse() && CFP.use_empty())
7881 break;
7883 return CFP;
7884 }
7885 case ISD::SPLAT_VECTOR: {
7886 // fold splat_vector(fneg(X)) -> splat_vector(-X)
7887 SDValue X = Op.getOperand(0);
7889 break;
7890
7891 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
7892 if (!NegX)
7893 break;
7895 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
7896 }
7897 case ISD::BUILD_VECTOR: {
7898 // Only permit BUILD_VECTOR of constants.
7899 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
7900 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
7901 }))
7902 break;
7903
7904 bool IsOpLegal =
7907 llvm::all_of(Op->op_values(), [&](SDValue N) {
7908 return N.isUndef() ||
7909 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
7910 OptForSize);
7911 });
7912
7913 if (LegalOps && !IsOpLegal)
7914 break;
7915
7917 for (SDValue C : Op->op_values()) {
7918 if (C.isUndef()) {
7919 Ops.push_back(C);
7920 continue;
7921 }
7922 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
7923 V.changeSign();
7924 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
7925 }
7927 return DAG.getBuildVector(VT, DL, Ops);
7928 }
7929 case ISD::FADD: {
7930 if (!Flags.hasNoSignedZeros())
7931 break;
7932
7933 // After operation legalization, it might not be legal to create new FSUBs.
7934 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
7935 break;
7936 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7937
7938 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
7940 SDValue NegX =
7941 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7942 // Prevent this node from being deleted by the next call.
7943 if (NegX)
7944 Handles.emplace_back(NegX);
7945
7946 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
7948 SDValue NegY =
7949 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7950
7951 // We're done with the handles.
7952 Handles.clear();
7953
7954 // Negate the X if its cost is less or equal than Y.
7955 if (NegX && (CostX <= CostY)) {
7956 Cost = CostX;
7957 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
7958 if (NegY != N)
7959 RemoveDeadNode(NegY);
7960 return N;
7961 }
7962
7963 // Negate the Y if it is not expensive.
7964 if (NegY) {
7965 Cost = CostY;
7966 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
7967 if (NegX != N)
7968 RemoveDeadNode(NegX);
7969 return N;
7970 }
7971 break;
7972 }
7973 case ISD::FSUB: {
7974 // We can't turn -(A-B) into B-A when we honor signed zeros.
7975 if (!Flags.hasNoSignedZeros())
7976 break;
7977
7978 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7979 // fold (fneg (fsub 0, Y)) -> Y
7980 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
7981 if (C->isZero()) {
7983 return Y;
7984 }
7985
7986 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
7988 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
7989 }
7990 case ISD::FMUL:
7991 case ISD::FDIV: {
7992 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7993
7994 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
7996 SDValue NegX =
7997 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7998 // Prevent this node from being deleted by the next call.
7999 if (NegX)
8000 Handles.emplace_back(NegX);
8001
8002 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
8004 SDValue NegY =
8005 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8006
8007 // We're done with the handles.
8008 Handles.clear();
8009
8010 // Negate the X if its cost is less or equal than Y.
8011 if (NegX && (CostX <= CostY)) {
8012 Cost = CostX;
8013 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
8014 if (NegY != N)
8015 RemoveDeadNode(NegY);
8016 return N;
8017 }
8018
8019 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
8020 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
8021 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
8022 break;
8023
8024 // Negate the Y if it is not expensive.
8025 if (NegY) {
8026 Cost = CostY;
8027 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
8028 if (NegX != N)
8029 RemoveDeadNode(NegX);
8030 return N;
8031 }
8032 break;
8033 }
8034 case ISD::FMA:
8035 case ISD::FMULADD:
8036 case ISD::FMAD: {
8037 if (!Flags.hasNoSignedZeros())
8038 break;
8039
8040 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
8042 SDValue NegZ =
8043 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
8044 // Give up if fail to negate the Z.
8045 if (!NegZ)
8046 break;
8047
8048 // Prevent this node from being deleted by the next two calls.
8049 Handles.emplace_back(NegZ);
8050
8051 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
8053 SDValue NegX =
8054 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8055 // Prevent this node from being deleted by the next call.
8056 if (NegX)
8057 Handles.emplace_back(NegX);
8058
8059 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
8061 SDValue NegY =
8062 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8063
8064 // We're done with the handles.
8065 Handles.clear();
8066
8067 // Negate the X if its cost is less or equal than Y.
8068 if (NegX && (CostX <= CostY)) {
8069 Cost = std::min(CostX, CostZ);
8070 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
8071 if (NegY != N)
8072 RemoveDeadNode(NegY);
8073 return N;
8074 }
8075
8076 // Negate the Y if it is not expensive.
8077 if (NegY) {
8078 Cost = std::min(CostY, CostZ);
8079 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
8080 if (NegX != N)
8081 RemoveDeadNode(NegX);
8082 return N;
8083 }
8084 break;
8085 }
8086
8087 case ISD::FP_EXTEND:
8088 case ISD::FSIN:
8089 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8090 OptForSize, Cost, Depth))
8091 return DAG.getNode(Opcode, DL, VT, NegV);
8092 break;
8093 case ISD::FP_ROUND:
8094 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8095 OptForSize, Cost, Depth))
8096 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
8097 break;
8098 case ISD::SELECT:
8099 case ISD::VSELECT: {
8100 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
8101 // iff at least one cost is cheaper and the other is neutral/cheaper
8102 SDValue LHS = Op.getOperand(1);
8104 SDValue NegLHS =
8105 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
8106 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
8107 RemoveDeadNode(NegLHS);
8108 break;
8109 }
8110
8111 // Prevent this node from being deleted by the next call.
8112 Handles.emplace_back(NegLHS);
8113
8114 SDValue RHS = Op.getOperand(2);
8116 SDValue NegRHS =
8117 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
8118
8119 // We're done with the handles.
8120 Handles.clear();
8121
8122 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
8123 (CostLHS != NegatibleCost::Cheaper &&
8124 CostRHS != NegatibleCost::Cheaper)) {
8125 RemoveDeadNode(NegLHS);
8126 RemoveDeadNode(NegRHS);
8127 break;
8128 }
8129
8130 Cost = std::min(CostLHS, CostRHS);
8131 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
8132 }
8133 }
8134
8135 return SDValue();
8136}
8137
8138//===----------------------------------------------------------------------===//
8139// Legalization Utilities
8140//===----------------------------------------------------------------------===//
8141
8142bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
8143 SDValue LHS, SDValue RHS,
8145 EVT HiLoVT, SelectionDAG &DAG,
8146 MulExpansionKind Kind, SDValue LL,
8147 SDValue LH, SDValue RL, SDValue RH) const {
8148 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
8149 Opcode == ISD::SMUL_LOHI);
8150
8151 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
8153 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8155 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8157 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8159
8160 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8161 return false;
8162
8163 unsigned OuterBitSize = VT.getScalarSizeInBits();
8164 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8165
8166 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8167 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8168 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8169
8170 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8171 bool Signed) -> bool {
8172 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8173 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8174 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8175 Hi = Lo.getValue(1);
8176 return true;
8177 }
8178 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8179 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8180 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8181 return true;
8182 }
8183 return false;
8184 };
8185
8186 SDValue Lo, Hi;
8187
8188 if (!LL.getNode() && !RL.getNode() &&
8190 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8191 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8192 }
8193
8194 if (!LL.getNode())
8195 return false;
8196
8197 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8198 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8199 DAG.MaskedValueIsZero(RHS, HighMask)) {
8200 // The inputs are both zero-extended.
8201 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8202 Result.push_back(Lo);
8203 Result.push_back(Hi);
8204 if (Opcode != ISD::MUL) {
8205 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8206 Result.push_back(Zero);
8207 Result.push_back(Zero);
8208 }
8209 return true;
8210 }
8211 }
8212
8213 if (!VT.isVector() && Opcode == ISD::MUL &&
8214 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8215 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8216 // The input values are both sign-extended.
8217 // TODO non-MUL case?
8218 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8219 Result.push_back(Lo);
8220 Result.push_back(Hi);
8221 return true;
8222 }
8223 }
8224
8225 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8226 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8227
8228 if (!LH.getNode() && !RH.getNode() &&
8231 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8232 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8233 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8234 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8235 }
8236
8237 if (!LH.getNode())
8238 return false;
8239
8240 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8241 return false;
8242
8243 Result.push_back(Lo);
8244
8245 if (Opcode == ISD::MUL) {
8246 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8247 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8248 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8249 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8250 Result.push_back(Hi);
8251 return true;
8252 }
8253
8254 // Compute the full width result.
8255 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8256 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8257 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8258 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8259 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8260 };
8261
8262 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8263 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8264 return false;
8265
8266 // This is effectively the add part of a multiply-add of half-sized operands,
8267 // so it cannot overflow.
8268 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8269
8270 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8271 return false;
8272
8273 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8274 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8275
8276 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8278 if (UseGlue)
8279 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8280 Merge(Lo, Hi));
8281 else
8282 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8283 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8284
8285 SDValue Carry = Next.getValue(1);
8286 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8287 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8288
8289 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8290 return false;
8291
8292 if (UseGlue)
8293 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8294 Carry);
8295 else
8296 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8297 Zero, Carry);
8298
8299 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8300
8301 if (Opcode == ISD::SMUL_LOHI) {
8302 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8303 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8304 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8305
8306 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8307 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8308 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8309 }
8310
8311 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8312 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8313 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8314 return true;
8315}
8316
8318 SelectionDAG &DAG, MulExpansionKind Kind,
8319 SDValue LL, SDValue LH, SDValue RL,
8320 SDValue RH) const {
8322 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8323 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8324 DAG, Kind, LL, LH, RL, RH);
8325 if (Ok) {
8326 assert(Result.size() == 2);
8327 Lo = Result[0];
8328 Hi = Result[1];
8329 }
8330 return Ok;
8331}
8332
8333// Optimize unsigned division or remainder by constants for types twice as large
8334// as a legal VT.
8335//
8336// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8337// can be computed
8338// as:
8339// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8340// Remainder = Sum % Constant;
8341//
8342// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8343// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8344// High:Low into 3 chunks of W bits and compute remainder as
8345// Sum = Chunk0 + Chunk1 + Chunk2;
8346// Remainder = Sum % Constant;
8347//
8348// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8349//
8350// For division, we can compute the remainder using the algorithm described
8351// above, subtract it from the dividend to get an exact multiple of Constant.
8352// Then multiply that exact multiply by the multiplicative inverse modulo
8353// (1 << (BitWidth / 2)) to get the quotient.
8354
8355// If Constant is even, we can shift right the dividend and the divisor by the
8356// number of trailing zeros in Constant before applying the remainder algorithm.
8357// If we're after the quotient, we can subtract this value from the shifted
8358// dividend and multiply by the multiplicative inverse of the shifted divisor.
8359// If we want the remainder, we shift the value left by the number of trailing
8360// zeros and add the bits that were shifted out of the dividend.
8361bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8362 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8363 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8364 unsigned Opcode = N->getOpcode();
8365 EVT VT = N->getValueType(0);
8366
8367 unsigned BitWidth = Divisor.getBitWidth();
8368 unsigned HBitWidth = BitWidth / 2;
8370 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8371
8372 // If the divisor is even, shift it until it becomes odd.
8373 unsigned TrailingZeros = 0;
8374 if (!Divisor[0]) {
8375 TrailingZeros = Divisor.countr_zero();
8376 Divisor.lshrInPlace(TrailingZeros);
8377 }
8378
8379 // After removing trailing zeros, the divisor needs to be less than
8380 // (1 << HBitWidth).
8381 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8382 if (Divisor.uge(HalfMaxPlus1))
8383 return false;
8384
8385 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8386 // (1 << W) % Divisor == -1.
8387 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8388 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8389 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8390 if (I == HBitWidth - 1)
8391 continue;
8392
8393 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8394
8395 if (Mod.isOne()) {
8396 BestChunkWidth = I;
8397 break;
8398 }
8399
8400 // We have an alternate strategy for Remainder == Divisor - 1.
8401 // FIXME: Support HBitWidth.
8402 if (I != HBitWidth && Mod == Divisor - 1)
8403 AltChunkWidth = I;
8404 }
8405
8406 bool Alternate = false;
8407 if (!BestChunkWidth) {
8408 if (!AltChunkWidth)
8409 return false;
8410 Alternate = true;
8411 BestChunkWidth = AltChunkWidth;
8412 }
8413
8414 SDLoc dl(N);
8415
8416 assert(!LL == !LH && "Expected both input halves or no input halves!");
8417 if (!LL)
8418 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8419
8420 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8421
8422 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8423 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8424 if (HasFSHR)
8425 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8426 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8427 return DAG.getNode(
8428 ISD::OR, dl, HiLoVT,
8429 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8430 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8431 DAG.getNode(
8432 ISD::SHL, dl, HiLoVT, Hi,
8433 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8434 };
8435
8436 // Helper to perform a right shift on a 128-bit value split into two halves.
8437 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8438 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8439 if (ShiftAmt == 0)
8440 return;
8441 if (ShiftAmt < HBitWidth) {
8442 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8443 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8444 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8445 } else if (ShiftAmt == HBitWidth) {
8446 Lo = Hi;
8447 Hi = DAG.getConstant(0, dl, HiLoVT);
8448 } else {
8449 Lo = DAG.getNode(
8450 ISD::SRL, dl, HiLoVT, Hi,
8451 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8452 Hi = DAG.getConstant(0, dl, HiLoVT);
8453 }
8454 };
8455
8456 // Shift the input by the number of TrailingZeros in the divisor. The
8457 // shifted out bits will be added to the remainder later.
8458 SDValue PartialRemL, PartialRemH;
8459 if (TrailingZeros && Opcode != ISD::UDIV) {
8460 // Save the shifted off bits if we need the remainder.
8461 if (TrailingZeros < HBitWidth) {
8462 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8463 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8464 DAG.getConstant(Mask, dl, HiLoVT));
8465 } else if (TrailingZeros == HBitWidth) {
8466 // All of LL is part of the remainder.
8467 PartialRemL = LL;
8468 } else {
8469 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8470 PartialRemL = LL;
8471 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8472 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8473 DAG.getConstant(Mask, dl, HiLoVT));
8474 }
8475 }
8476
8477 SDValue Sum;
8478 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8479 // out, add that to the final sum.
8480 if (BestChunkWidth == HBitWidth) {
8481 assert(!Alternate);
8482 // Shift LH:LL right if there were trailing zeros in the divisor.
8483 ShiftRight(LL, LH, TrailingZeros);
8484
8485 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8486 EVT SetCCType =
8487 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8489 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8490 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8491 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8492 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8493 } else {
8494 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8495 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8496 // If the boolean for the target is 0 or 1, we can add the setcc result
8497 // directly.
8498 if (getBooleanContents(HiLoVT) ==
8500 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8501 else
8502 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8503 DAG.getConstant(0, dl, HiLoVT));
8504 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8505 }
8506 } else {
8507 // Otherwise split into multple chunks and add them together. We chose
8508 // BestChunkWidth so that the sum will not overflow.
8509 SDValue Mask = DAG.getConstant(
8510 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8511
8512 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8513 // If there were trailing zeros in the divisor, increase the shift amount.
8514 unsigned Shift = I + TrailingZeros;
8515 SDValue Chunk;
8516 if (Shift == 0)
8517 Chunk = LL;
8518 else if (Shift >= HBitWidth)
8519 Chunk = DAG.getNode(
8520 ISD::SRL, dl, HiLoVT, LH,
8521 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8522 else
8523 Chunk = GetFSHR(LL, LH, Shift);
8524 // If we're on the last chunk, we don't need an AND.
8525 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8526 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8527 if (!Sum) {
8528 Sum = Chunk;
8529 } else {
8530 // For Alternate, we need to subtract odd chunks.
8531 unsigned ChunkNum = I / BestChunkWidth;
8532 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8533 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8534 }
8535 }
8536
8537 // For Alternate, the sum may be negative, but we need a positive sum. We
8538 // can increase it by a multiple of the divisor to make it positive. For 3
8539 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8540 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8541 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8542 // positive.
8543 if (Alternate) {
8544 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8545 assert(NumChunks <= 4);
8546
8547 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8548 Adjust.setBit(0);
8549 // If there are 4 chunks, we need to adjust twice.
8550 if (NumChunks == 4)
8551 Adjust <<= 1;
8552 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8553 DAG.getConstant(Adjust, dl, HiLoVT));
8554 }
8555 }
8556
8557 // Perform a HiLoVT urem on the Sum using truncated divisor.
8558 SDValue RemL =
8559 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8560 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8561 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8562
8563 if (Opcode != ISD::UREM) {
8564 // If we didn't shift LH/LR earlier, do it now.
8565 if (BestChunkWidth != HBitWidth)
8566 ShiftRight(LL, LH, TrailingZeros);
8567
8568 // Subtract the remainder from the shifted dividend.
8569 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8570 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8571
8572 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8573
8574 // Multiply by the multiplicative inverse of the divisor modulo
8575 // (1 << BitWidth).
8576 APInt MulFactor = Divisor.multiplicativeInverse();
8577
8578 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8579 DAG.getConstant(MulFactor, dl, VT));
8580
8581 // Split the quotient into low and high parts.
8582 SDValue QuotL, QuotH;
8583 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8584 Result.push_back(QuotL);
8585 Result.push_back(QuotH);
8586 }
8587
8588 if (Opcode != ISD::UDIV) {
8589 // If we shifted the input, shift the remainder left and add the bits we
8590 // shifted off the input.
8591 if (TrailingZeros) {
8592 if (TrailingZeros < HBitWidth) {
8593 // Shift RemH:RemL left by TrailingZeros.
8594 // RemH gets the high bits shifted out of RemL.
8595 RemH = DAG.getNode(
8596 ISD::SRL, dl, HiLoVT, RemL,
8597 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8598 RemL =
8599 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8600 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8601 // OR in the partial remainder.
8602 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8604 } else if (TrailingZeros == HBitWidth) {
8605 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8606 // PartialRemL.
8607 RemH = RemL;
8608 RemL = PartialRemL;
8609 } else {
8610 // Shift left by more than HBitWidth.
8611 RemH = DAG.getNode(
8612 ISD::SHL, dl, HiLoVT, RemL,
8613 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8614 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8616 RemL = PartialRemL;
8617 }
8618 }
8619 Result.push_back(RemL);
8620 Result.push_back(RemH);
8621 }
8622
8623 return true;
8624}
8625
8626bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8627 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8628 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8629
8630 SDValue N0 = N->getOperand(0);
8631 EVT VT = N0->getValueType(0);
8632 SDLoc DL{N};
8633
8634 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8635
8636 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8637 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8638 const APInt &Const,
8639 SmallVectorImpl<SDValue> &Result) {
8640 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8641 SDValue RHS = DAG.getConstant(Const, DL, VT);
8642 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8643 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8645 LL, LH, RL, RH);
8646 };
8647
8648 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8649 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8650 SDValue RH) {
8651 SDValue AddSubNode =
8653 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8654 SDValue OutL = AddSubNode.getValue(0);
8655 SDValue Overflow = AddSubNode.getValue(1);
8656 SDValue AddSubWithOverflow =
8658 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8659 SDValue OutH = AddSubWithOverflow.getValue(0);
8660 return std::make_pair(OutL, OutH);
8661 };
8662
8663 // This helper creates a SRL of the pair (LL, LH) by Shift.
8664 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8665 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8666 if (Shift < HBitWidth) {
8667 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8668 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8669 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8670 return std::make_pair(ResL, ResH);
8671 }
8672 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8673 if (Shift == HBitWidth)
8674 return std::make_pair(LH, Zero);
8675 assert(Shift - HBitWidth < HBitWidth &&
8676 "We shouldn't generate an undefined shift");
8677 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8678 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8679 };
8680
8681 // Knowledge of leading zeros may help to reduce the multiplier.
8682 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8683
8684 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8685 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8686
8687 assert(!LL == !LH && "Expected both input halves or no input halves!");
8688 if (!LL)
8689 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8690 SDValue QL = LL;
8691 SDValue QH = LH;
8692 if (Magics.PreShift != 0)
8693 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8694
8695 SmallVector<SDValue, 4> UMulResult;
8696 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8697 return false;
8698
8699 QL = UMulResult[2];
8700 QH = UMulResult[3];
8701
8702 if (Magics.IsAdd) {
8703 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8704 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8705 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8706 }
8707
8708 if (Magics.PostShift != 0)
8709 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8710
8711 unsigned Opcode = N->getOpcode();
8712 if (Opcode != ISD::UREM) {
8713 Result.push_back(QL);
8714 Result.push_back(QH);
8715 }
8716
8717 if (Opcode != ISD::UDIV) {
8718 SmallVector<SDValue, 2> MulResult;
8719 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8720 return false;
8721
8722 assert(MulResult.size() == 2);
8723
8724 auto [RemL, RemH] =
8725 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8726
8727 Result.push_back(RemL);
8728 Result.push_back(RemH);
8729 }
8730
8731 return true;
8732}
8733
8736 EVT HiLoVT, SelectionDAG &DAG,
8737 SDValue LL, SDValue LH) const {
8738 unsigned Opcode = N->getOpcode();
8739
8740 // TODO: Support signed division/remainder.
8741 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8742 return false;
8743 assert(
8744 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8745 "Unexpected opcode");
8746
8747 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8748 if (!CN)
8749 return false;
8750
8751 APInt Divisor = CN->getAPIntValue();
8752
8753 // The generated half-width UREM is normally optimized using high multiply.
8754 // If the wide UREM libcall is unavailable, a legal or custom half-width
8755 // UDIVREM can lower it instead.
8756 bool CanDecomposeUREMWithoutMulHi =
8757 Opcode == ISD::UREM &&
8758 getLibcallImpl(RTLIB::getUREM(N->getValueType(0))) ==
8759 RTLIB::Unsupported &&
8761 if (!CanDecomposeUREMWithoutMulHi &&
8764 return false;
8765
8766 // Prefer the smaller libcall when one is available.
8767 if (DAG.shouldOptForSize() && !CanDecomposeUREMWithoutMulHi)
8768 return false;
8769
8770 // Early out for 0 or 1 divisors.
8771 if (Divisor.ule(1))
8772 return false;
8773
8774 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
8775 DAG, LL, LH))
8776 return true;
8777
8778 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
8779 LH))
8780 return true;
8781
8782 return false;
8783}
8784
8785// Check that (every element of) Z is undef or not an exact multiple of BW.
8786static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
8788 Z,
8789 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
8790 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
8791}
8792
8794 SelectionDAG &DAG) const {
8795 EVT VT = Node->getValueType(0);
8796
8797 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
8801 return SDValue();
8802
8803 SDValue X = Node->getOperand(0);
8804 SDValue Y = Node->getOperand(1);
8805 SDValue Z = Node->getOperand(2);
8806
8807 unsigned BW = VT.getScalarSizeInBits();
8808 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
8809 SDLoc DL(SDValue(Node, 0));
8810
8811 EVT ShVT = Z.getValueType();
8812
8813 // If a funnel shift in the other direction is more supported, use it.
8814 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
8815 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8816 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
8817 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8818 // fshl X, Y, Z -> fshr X, Y, -Z
8819 // fshr X, Y, Z -> fshl X, Y, -Z
8820 Z = DAG.getNegative(Z, DL, ShVT);
8821 } else {
8822 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
8823 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
8824 SDValue One = DAG.getConstant(1, DL, ShVT);
8825 if (IsFSHL) {
8826 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8827 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
8828 } else {
8829 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8830 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
8831 }
8832 Z = DAG.getNOT(DL, Z, ShVT);
8833 }
8834 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
8835 }
8836
8837 SDValue ShX, ShY;
8838 SDValue ShAmt, InvShAmt;
8839 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8840 // fshl: X << C | Y >> (BW - C)
8841 // fshr: X << (BW - C) | Y >> C
8842 // where C = Z % BW is not zero
8843 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8844 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8845 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
8846 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
8847 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
8848 } else {
8849 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
8850 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
8851 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
8852 if (isPowerOf2_32(BW)) {
8853 // Z % BW -> Z & (BW - 1)
8854 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
8855 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
8856 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
8857 } else {
8858 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8859 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8860 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
8861 }
8862
8863 SDValue One = DAG.getConstant(1, DL, ShVT);
8864 if (IsFSHL) {
8865 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
8866 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
8867 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
8868 } else {
8869 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
8870 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
8871 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
8872 }
8873 }
8874 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
8875}
8876
8877// TODO: Merge with expandFunnelShift.
8879 SelectionDAG &DAG) const {
8880 EVT VT = Node->getValueType(0);
8881 unsigned EltSizeInBits = VT.getScalarSizeInBits();
8882 bool IsLeft = Node->getOpcode() == ISD::ROTL;
8883 SDValue Op0 = Node->getOperand(0);
8884 SDValue Op1 = Node->getOperand(1);
8885 SDLoc DL(SDValue(Node, 0));
8886
8887 EVT ShVT = Op1.getValueType();
8888 SDValue Zero = DAG.getConstant(0, DL, ShVT);
8889
8890 // If a rotate in the other direction is more supported, use it.
8891 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
8892 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8893 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
8894 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8895 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
8896 }
8897
8898 if (!AllowVectorOps && VT.isVector() &&
8904 return SDValue();
8905
8906 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
8907 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
8908 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
8909 SDValue ShVal;
8910 SDValue HsVal;
8911 if (isPowerOf2_32(EltSizeInBits)) {
8912 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
8913 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
8914 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8915 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
8916 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8917 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
8918 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
8919 } else {
8920 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
8921 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
8922 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
8923 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
8924 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8925 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
8926 SDValue One = DAG.getConstant(1, DL, ShVT);
8927 HsVal =
8928 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
8929 }
8930 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
8931}
8932
8933/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
8934/// a chain of halving decompositions (halving element width) and/or vector
8935/// widening (doubling element count). This guides expansion strategy selection:
8936/// if true, the halving/widening path produces better code than bit-by-bit.
8937///
8938/// HalveDepth tracks halving steps only (each creates ~4x more operations).
8939/// Widening steps are cheap (O(1) pad/extract) and don't count.
8940/// Limiting halvings to 2 prevents exponential blowup:
8941/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
8942/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
8943/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
8945 EVT VT, unsigned HalveDepth = 0,
8946 unsigned TotalDepth = 0) {
8947 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
8948 return false;
8950 return true;
8951 if (!TLI.isTypeLegal(VT))
8952 return false;
8953
8954 unsigned BW = VT.getScalarSizeInBits();
8955
8956 // Halve: halve element width, same element count.
8957 // This is the expensive step -- each halving creates ~4x more operations.
8958 if (BW % 2 == 0) {
8959 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
8960 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
8961 if (TLI.isTypeLegal(HalfVT) &&
8962 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
8963 return true;
8964 }
8965
8966 // Widen: double element count (fixed-width vectors only).
8967 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
8968 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
8969 if (TLI.isTypeLegal(WideVT) &&
8970 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
8971 return true;
8972
8973 return false;
8974}
8975
8977 SDLoc DL(Node);
8978 EVT VT = Node->getValueType(0);
8979 SDValue X = Node->getOperand(0);
8980 SDValue Y = Node->getOperand(1);
8981 unsigned BW = VT.getScalarSizeInBits();
8982 unsigned Opcode = Node->getOpcode();
8983 LLVMContext &Ctx = *DAG.getContext();
8984
8985 switch (Opcode) {
8986 case ISD::CLMUL: {
8987 // For vector types, try decomposition strategies that leverage legal
8988 // CLMUL on narrower or wider element types, avoiding the expensive
8989 // bit-by-bit expansion.
8990 if (VT.isVector()) {
8991 // Strategy 1: Halving decomposition to half-element-width CLMUL.
8992 // Applies ExpandIntRes_CLMUL's identity element-wise:
8993 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
8994 // where:
8995 // Lo = CLMUL(XLo, YLo)
8996 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
8997 unsigned HalfBW = BW / 2;
8998 if (BW % 2 == 0) {
8999 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
9000 EVT HalfVT =
9001 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
9002 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
9003 /*HalveDepth=*/1)) {
9004 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
9005
9006 // Extract low and high halves of each element.
9007 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
9008 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9009 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
9010 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
9011 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9012 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
9013
9014 // Lo = CLMUL(XLo, YLo)
9015 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
9016
9017 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9018 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
9019 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
9020 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
9021 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
9022 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
9023
9024 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
9025 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
9026 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
9027 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
9028 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
9029 }
9030 }
9031
9032 // Strategy 2: Promote to double-element-width CLMUL.
9033 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
9034 {
9035 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9036 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
9037 // If CLMUL on ExtVT is Custom (not Legal), the target may
9038 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
9039 // fallback costs O(BW) vectorized iterations. Only widen when
9040 // element count is small enough that scalarization is cheaper.
9041 unsigned NumElts = VT.getVectorMinNumElements();
9042 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
9043 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
9044 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
9045 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9046 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
9047 }
9048 }
9049 }
9050
9051 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
9052 // vector, extract lower result). CLMUL is element-wise, so upper
9053 // (undef) lanes don't affect the lower results.
9054 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
9055 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
9056 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
9057 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
9058 SDValue Undef = DAG.getUNDEF(WideVT);
9059 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9060 X, DAG.getVectorIdxConstant(0, DL));
9061 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9062 Y, DAG.getVectorIdxConstant(0, DL));
9063 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
9064 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
9065 DAG.getVectorIdxConstant(0, DL));
9066 }
9067 }
9068 }
9069
9070 // Special case: clmul(X, Y) where Y is a known constant (splat) that forms
9071 // a contiguous block of trailing ones whose length N is a power of two
9072 // (e.g. i8 0xFF, i8 0x0F, ...) or equal to the operand width. In this
9073 // special case, clmul(X, Y) is equivalent to a "parallel prefix XOR" or
9074 // "bitwise parity" operation on X.
9075 //
9076 // Note: This special currently dose NOT apply when the mask is neither a
9077 // power of two nor equal to the operand width because the loop inside
9078 // behaves as if the mask was bit-ceiled, and "undoing" the XOR with parts
9079 // of that CLMUL is a recursive problem (e.g. CLMUL with a 20-bit mask
9080 // requires correction XOR with CLMUL with 12-bit mask).
9081 if (auto *C = isConstOrConstSplat(Y, /*AllowUndefs=*/true)) {
9082 const APInt &YVal = C->getAPIntValue();
9083 unsigned N = YVal.countr_one();
9084 if (YVal.isAllOnes() || (YVal.isMask() && isPowerOf2_32(N))) {
9085 SDValue R = X;
9086 for (unsigned I = 1; I < N; I <<= 1) {
9087 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
9088 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
9089 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
9090 }
9091 return R;
9092 }
9093 }
9094
9095 // NOTE: If you change this expansion, please update the cost model
9096 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
9097 // Intrinsic::clmul.
9098
9099 // Strategy 4: multiplication with holes.
9100 //
9101 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
9102 // do occur, they wind up in a "hole" and are subsequently masked out of the
9103 // result.
9104 //
9105 // https://www.bearssl.org/constanttime.html#ghash-for-gcm describes this
9106 // approach.
9107
9108 // Stride S handles operands up to S·2^S bits using S² multiplies.
9109 //
9110 // * BW <= 8 uses S = 2 (holes of 1 bit)
9111 // * BW <= 24 uses S = 3 (holes of 2 bits)
9112 // * BW <= 64 uses S = 4 (holes of 3 bits)
9113 // * BW <= 160 uses S = 5 (holes of 4 bits)
9114 // * BW <= 384 uses S = 6 (holes of 5 bits)
9115 //
9116 // We distribute the BW bits over S phases:
9117 //
9118 // phase 0 keeps bits: 0, S, 2S, ...
9119 // phase 1 keeps bits: 1, S + 1, 2S + 1, ...
9120 // ...
9121 //
9122 // Each phase has up to n = ceil(BW / S) bits set, and the holes are S-1
9123 // bits wide.
9124 //
9125 // Take BW = 4, S = 2, n = 2. The worst case is a fully populated phase (all
9126 // non-hole bits are set to 1) multiplied by itself, 0b0101 * 0b0101. Each
9127 // set bit of one operand shifts a copy of the other, and we add the copies:
9128 //
9129 // col: 4 3 2 1 0
9130 // 0b0101 << 0: 0 0 1 0 1
9131 // 0b0101 << 2: 1 0 1 0 0
9132 // ----------------- +
9133 // count: 1 0 2 0 1
9134 //
9135 // Counting the number of one-bits in each column gives a triangle: the
9136 // counts climb 1, 2, ..., n and back down (here 1, 2, 1 across the data
9137 // columns). So a column holds at most n one-bits, and that maximum n is
9138 // reached in only one column: the peak. Every other column holds at most n
9139 // - 1 one-bits.
9140 //
9141 // A stack of one-bits in a column turns into carries: column 2 above really
9142 // stores the value 1 + 1 = 2 = n. A column spans S bits, its kept bit
9143 // plus S-1 hole bits, and the count is written from the kept bit upward,
9144 // so any count <= 2^S - 1 stays within the column and never interferes with
9145 // the next data bit S positions up. Every non-peak column holds at most n -
9146 // 1, so they all fit as soon as n - 1 <= 2^S - 1.
9147 //
9148 // That leaves only the peak column. Because both operands set all data
9149 // bits, the triangle peaks at the top of the word at the highest data bit
9150 // still inside BW. Here the count reaches exactly n = 2^S and overflows.
9151 // But its carry lands at bit n*S >= BW, off the top, where it (and the
9152 // whole descending half of the triangle) is truncated.
9153 //
9154 // Hence the holes suffice exactly when n = ceil(BW / S) <= 2^S, i.e. BW <=
9155 // S*2^S.
9156 //
9157 // Here we find the smallest S that satisfies this inequality.
9158 unsigned S = 1;
9159 while (S < 32 && divideCeil(BW, S) > (1u << S))
9160 ++S;
9161
9162 // The "multiplication with holes" expansion emits S*S MULs, 3*S ANDs,
9163 // S*(S-1) XORs and S-1 ORs.
9164 unsigned HolesCost = S * S + 3 * S + S * (S - 1) + (S - 1);
9165
9166 // Estimate the cost of the naive algorithm.
9167 KnownBits KnownY = DAG.computeKnownBits(Y);
9168 unsigned NaiveCost = 0;
9169 for (unsigned I = 0; I < BW; ++I) {
9170 // The iteration folds away entirely and is free.
9171 if (KnownY.Zero[I])
9172 continue;
9173
9174 // On targets with a fast bit test instruction more instructions are used
9175 // to not need a (potentially expensive) multiplication. See also below.
9176 if (hasBitTest(Y, DAG.getShiftAmountConstant(I, VT, DL))) {
9177 // AND + SETCC + SHL + SELECT + XOR.
9178 NaiveCost += 5;
9179 } else {
9180 // AND + MUL + XOR.
9181 NaiveCost += 3;
9182 }
9183 }
9184
9185 // Only use multiplication with holes when it is cheaper, else use the naive
9186 // fallback below.
9187 if (HolesCost < NaiveCost &&
9189
9190 // Set a bit every S positions, e.g. for S = 4 this is equivalent to
9191 // 0b...00010001...0001.
9192 APInt MaskVal = APInt::getSplat(BW, APInt(S, 1));
9193
9194 // Create versions of X and Y that keep only the I-th bit of each S-bit
9195 // slice.
9196 SmallVector<SDValue, 4> M(S), Xp(S), Yp(S);
9197 for (unsigned I = 0; I < S; ++I) {
9198 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9199 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9200 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9201 }
9202
9203 // Codegens these expressions (S*S multiplications), e.g. for S=4:
9204 //
9205 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9206 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9207 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9208 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9209 SDValue Res = DAG.getConstant(0, DL, VT);
9210 for (unsigned I = 0; I < S; ++I) {
9211 SDValue Zi = DAG.getConstant(0, DL, VT);
9212 for (unsigned J = 0; J < S; ++J) {
9213 unsigned K = (I + S - J) % S;
9214 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9215 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9216 }
9217
9218 // Keep only the bits belonging to this iteration, and bitwise or it all
9219 // together.
9220 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9221 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9222 }
9223 return Res;
9224 }
9225
9226 // Strategy 5: the naive fallback.
9227 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9228
9229 SDValue Res = DAG.getConstant(0, DL, VT);
9230 for (unsigned I = 0; I < BW; ++I) {
9231 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9232 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9233 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9234
9235 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9236 // multiply, use a shift-based expansion to avoid expensive MUL
9237 // instructions.
9238 SDValue Part;
9239 if (!hasBitTest(Y, ShiftAmt) &&
9242 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9243 } else {
9244 // Canonical bit test: (Y & (1 << I)) != 0
9245 SDValue Zero = DAG.getConstant(0, DL, VT);
9246 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9247 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9248 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9249 }
9250 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9251 }
9252 return Res;
9253 }
9254 case ISD::CLMULR:
9255 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9258 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9259 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9260 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9261 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9262 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9263 DAG.getShiftAmountConstant(1, VT, DL));
9264 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9265 }
9266 [[fallthrough]];
9267 case ISD::CLMULH: {
9268 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9269 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9270 // when any of these hold:
9271 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9272 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9273 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9274 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9275 // path creates CLMUL(VT) which will be expanded efficiently. The
9276 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9277 // causing a cycle.
9278 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9279 // => trunc path is preferred over the bitreverse path, as it avoids the
9280 // cost of 3 bitreverse operations.
9285 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9286 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9287 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9288 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9289 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9290 if (Opcode == ISD::CLMULH)
9291 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9292 DAG.getShiftAmountConstant(1, VT, DL));
9293 return Res;
9294 }
9295 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9296 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9297 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9298 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9299 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9300 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9301 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9302 }
9303 }
9304 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9305}
9306
9308 SDLoc DL(Node);
9309 EVT VT = Node->getValueType(0);
9310 SDValue Val = Node->getOperand(0);
9311 SDValue Msk = Node->getOperand(1);
9312 unsigned BW = VT.getScalarSizeInBits();
9313
9314 // Just scalarize if scalar PEXT is legal
9316 return DAG.UnrollVectorOp(Node);
9317
9318 // Hacker's Delight §7-4: Compress, or Generalized Extract
9319 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9320 SDValue M = Msk;
9321 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9322 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9323
9324 // Repeatedly compute which bits would shift to the right by an odd amount,
9325 // shift all such bits in parallel using a mask, and double the shift amount.
9326 for (unsigned I = 1; I < BW; I *= 2) {
9327 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9328 SDValue Mp =
9329 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9330 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9331 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9332 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9333 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9335 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9336 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9337 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9339 if (I * 2 < BW)
9340 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9341 }
9342
9343 return X;
9344}
9345
9347 SDLoc DL(Node);
9348 EVT VT = Node->getValueType(0);
9349 SDValue Val = Node->getOperand(0);
9350 SDValue Msk = Node->getOperand(1);
9351 unsigned BW = VT.getScalarSizeInBits();
9352
9353 // Just scalarize if scalar PDEP is legal
9355 return DAG.UnrollVectorOp(Node);
9356
9357 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9358 unsigned LogBW = Log2_32_Ceil(BW);
9359 SmallVector<SDValue, 8> MvArray(LogBW);
9360 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9361 SDValue Mc = Msk;
9362 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9363
9364 // First pass: compute move masks for each power of two that a bit moves by.
9365 for (unsigned S = 0; S < LogBW; ++S) {
9366 unsigned ShiftS = 1u << S;
9367 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9368 SDValue Mp =
9369 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9370 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9371 MvArray[S] = Mv;
9372 if (S + 1 < LogBW) {
9373 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9374 SDValue MvShifted = DAG.getNode(
9375 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9376 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9378 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9379 }
9380 }
9381
9382 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9383 // Each pass handles half the shift amount of the previous pass.
9384 SDValue X = Val;
9385 for (int S = (int)LogBW - 1; S >= 0; --S) {
9386 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9387 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9388 SDValue UnshiftedBits =
9389 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9390 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9391 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9393 }
9394
9395 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9396}
9397
9399 SelectionDAG &DAG) const {
9400 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9401 EVT VT = Node->getValueType(0);
9402 unsigned VTBits = VT.getScalarSizeInBits();
9403 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9404
9405 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9406 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9407 SDValue ShOpLo = Node->getOperand(0);
9408 SDValue ShOpHi = Node->getOperand(1);
9409 SDValue ShAmt = Node->getOperand(2);
9410 EVT ShAmtVT = ShAmt.getValueType();
9411 EVT ShAmtCCVT =
9412 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9413 SDLoc dl(Node);
9414
9415 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9416 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9417 // away during isel.
9418 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9419 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9420 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9421 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9422 : DAG.getConstant(0, dl, VT);
9423
9424 SDValue Tmp2, Tmp3;
9425 if (IsSHL) {
9426 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9427 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9428 } else {
9429 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9430 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9431 }
9432
9433 // If the shift amount is larger or equal than the width of a part we don't
9434 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9435 // values for large shift amounts.
9436 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9437 DAG.getConstant(VTBits, dl, ShAmtVT));
9438 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9439 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9440
9441 if (IsSHL) {
9442 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9443 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9444 } else {
9445 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9446 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9447 }
9448}
9449
9451 SelectionDAG &DAG) const {
9452 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9453 // suggested in
9454 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9455 // It uses strict_fp operations even outside a strict_fp context in order
9456 // to guarantee that the canonicalization is not optimized away by later
9457 // passes. The result chain introduced by that is intentionally ignored
9458 // since no ordering requirement is intended here.
9459 EVT VT = Node->getValueType(0);
9460 SDLoc DL(Node);
9461 SDNodeFlags Flags = Node->getFlags();
9462 Flags.setNoFPExcept(true);
9463 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9464 SDValue Mul =
9465 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9466 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9467 return Mul;
9468}
9469
9471 SelectionDAG &DAG) const {
9472 // Expand conversion from a native IEEE float type to an arbitrary FP format
9473 // returning the result as an integer using bit manipulation.
9474 EVT ResVT = Node->getValueType(0);
9475 SDLoc dl(Node);
9476
9477 SDValue FloatVal = Node->getOperand(0);
9478 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9479 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9480 const auto RoundMode =
9481 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9482 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9483
9484 // Supported destination formats.
9485 switch (Sem) {
9492 break;
9493 default:
9494 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9495 "destination format (semantics enum " +
9496 Twine(SemEnum) + ")");
9497 return SDValue();
9498 }
9499
9500 // Supported rounding modes.
9501 switch (RoundMode) {
9507 break;
9508 default:
9509 DAG.getContext()->emitError(
9510 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9511 Twine(static_cast<int>(RoundMode)) + ")");
9512 return SDValue();
9513 }
9514
9515 // Destination format parameters.
9516 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9517 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9518 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9519 const unsigned DstMant = DstPrecision - 1;
9520 // Unsigned formats spend no bit on the sign.
9521 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9522 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9523 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9524 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9525 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9526 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9527 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9528
9529 // Compute the maximum normal exponent for the destination format.
9530 const unsigned DstExpMaxNormal =
9531 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9532 : DstExpMax;
9533
9534 // For NanOnly formats the max exponent field for finite values
9535 // is DstExpMax, but the encoding with exp = DstExpMax and
9536 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9537 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9538 // avoid the NaN encoding.
9539 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9540 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9541 DstNanEnc == fltNanEncoding::AllOnes)
9542 DstMaxMantAtMaxExp = DstMantMask - 1;
9543
9544 // Source format parameters.
9545 EVT SrcVT = FloatVal.getValueType();
9546 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9547 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9548 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9549 const unsigned SrcMant = SrcPrecision - 1;
9550 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9551
9552 // Work in the source integer type. Match the destination shape so the
9553 // expansion stays vector when ResVT is a vector.
9554 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9555 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9556 EVT SetCCVT =
9557 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9558 EVT FPSetCCVT =
9559 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9560
9561 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9562 SDValue One = DAG.getConstant(1, dl, IntVT);
9563
9564 // Bitcast source float to integer to extract the sign bit.
9565 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9566 SDValue SignBit =
9567 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9568 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9569
9570 // Classify the input.
9571 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9572 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9573 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9574 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9575 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9576 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9577
9578 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9579 // source denormals automatically. The result is unspecified for Inf/NaN, but
9580 // those inputs are detected above and override the final result.
9581 EVT FrexpExpScalarVT =
9583 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9584 SDValue Frexp =
9585 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9586 SDValue FrexpFrac = Frexp.getValue(0);
9587 SDValue FrexpExp = Frexp.getValue(1);
9588
9589 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9590 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9591 DAG.getConstant(SrcMantMask, dl, IntVT));
9592
9593 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9594 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9595 DAG.getConstant(DstBias - 1, dl, IntVT));
9596
9597 // Compute rounding increment given the round bit, sticky bits, and LSB
9598 // of the truncated mantissa.
9599 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9600 SDValue LSB) -> SDValue {
9601 switch (RoundMode) {
9603 // Round up if round_bit && (sticky || lsb)
9604 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9605 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9606 }
9608 return Zero;
9610 // Round up if positive and any truncated bits are set.
9611 SDValue AnyTruncBits =
9612 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9613 SDValue HasTruncBits =
9614 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9615 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9616 SDValue DoRound =
9617 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9618 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9619 }
9621 // Round up if negative and any truncated bits are set (to -Inf).
9622 SDValue AnyTruncBits =
9623 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9624 SDValue HasTruncBits =
9625 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9626 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9627 SDValue DoRound =
9628 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9629 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9630 }
9632 return RoundBit;
9633 default:
9634 llvm_unreachable("unsupported rounding mode");
9635 }
9636 };
9637
9638 // Round mantissa from SrcMant bits to DstMant bits.
9639 SDValue TruncMant;
9640 SDValue RoundUp;
9641 if (SrcMant > DstMant) {
9642 const unsigned Shift = SrcMant - DstMant;
9643 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9644 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9645
9646 // Check bit at position Shift - 1 aka the round bit.
9647 SDValue RoundBit;
9648 if (Shift >= 1) {
9649 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9650 SDValue ShiftedMant =
9651 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9652 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9653 } else {
9654 RoundBit = Zero;
9655 }
9656
9657 // OR of all bits below the round bit to get sticky bits.
9658 SDValue StickyBits;
9659 if (Shift >= 2) {
9660 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9661 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9662 DAG.getConstant(StickyMask, dl, IntVT));
9663 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9664 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9665 } else {
9666 StickyBits = Zero;
9667 }
9668
9669 // LSB of truncated mantissa.
9670 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9671
9672 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9673 } else {
9674 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9675 SDValue MantShift =
9676 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9677 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9678 RoundUp = Zero;
9679 }
9680
9681 // Apply rounding.
9682 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9683
9684 // Handle mantissa overflow from rounding.
9685 // If rounded_mant > DstMantMask, carry into exponent.
9686 SDValue MantOverflow =
9687 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9688 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9689 // On overflow: mant = 0, exp += 1.
9690 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9691 SDValue AdjExp =
9692 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9693 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9694
9695 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9696 // sign bit to merge in.
9697 SDValue SignShifted =
9698 DstHasSign
9699 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9700 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9701 : Zero;
9702
9703 // Destination denormal conversion (when new_exp <= 0).
9704 // Shift the mantissa right by 1 - new_exp additional bits and set the
9705 // exponent field to 0.
9706 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9707 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9708
9709 SDValue DenormResult;
9710 {
9711 // denorm_shift = 1 - NewExp.
9712 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9713
9714 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9715 SDValue ImplicitOne =
9716 DAG.getNode(ISD::SHL, dl, IntVT, One,
9717 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9718 SDValue FullSrcMant =
9719 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9720
9721 // Total right shift = DenormShift + (SrcMant - DstMant).
9722 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9723 SDValue TotalShift =
9724 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9725 DAG.getSignedConstant(MantDelta, dl, IntVT));
9726
9727 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9728 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9729 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9730 SDValue ClampedShift =
9731 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9732 SDValue DenormTruncMant =
9733 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9734 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9735
9736 // Rounding for denorm path.
9737 SDValue DenormRoundUp;
9738 {
9739 // Round bit is at position TotalShift - 1 of FullSrcMant.
9740 // Clamp to at least 1 so the subtraction doesn't underflow and create
9741 // shift nodes with invalid shift amounts.
9742 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
9743 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
9744 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
9745 SDValue DenormRoundBit = DAG.getNode(
9746 ISD::AND, dl, IntVT,
9747 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
9748
9749 // Sticky: all bits below round bit.
9750 // sticky_mask = (1 << RoundBitPos) - 1
9751 SDValue StickyMask = DAG.getNode(
9752 ISD::SUB, dl, IntVT,
9753 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
9754 SDValue DenormStickyBits =
9755 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
9756 SDValue HasSticky = DAG.getNode(
9757 ISD::ZERO_EXTEND, dl, IntVT,
9758 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
9759
9760 SDValue DenormLSB =
9761 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
9762
9763 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
9764
9765 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
9766 SDValue ShiftGEOne =
9767 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
9768 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
9769 }
9770
9771 SDValue DenormRoundedMant =
9772 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
9773
9774 // If rounding caused overflow into the normal range, then we get the
9775 // smallest normal number.
9776 SDValue DenormMantOF =
9777 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
9778 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9779 SDValue DenormFinalMant =
9780 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
9781 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
9782
9783 // Assemble: sign | (exp << DstMant) | mant
9784 SDValue DenormExpShifted =
9785 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
9786 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9787 DenormResult = DAG.getNode(
9788 ISD::OR, dl, IntVT,
9789 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
9790 DenormFinalMant);
9791 }
9792
9793 // Exponent overflow detection.
9794 SDValue ExpOF =
9795 DAG.getSetCC(dl, SetCCVT, AdjExp,
9796 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
9797
9798 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
9799 // a value that exceeds the max allowed mantissa at that exponent.
9800 SDValue ExpAtMax =
9801 DAG.getSetCC(dl, SetCCVT, AdjExp,
9802 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
9803 SDValue MantExceedsMax =
9804 DAG.getSetCC(dl, SetCCVT, AdjMant,
9805 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
9806 SDValue ExpMantOF =
9807 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
9808 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
9809
9810 // Build overflow result.
9812
9813 if (Saturate) {
9814 // Clamp to max finite value:
9815 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
9816 uint64_t MaxFinite =
9817 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9818 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9819 DAG.getConstant(MaxFinite, dl, IntVT));
9820 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9821 // Produce infinity.
9822 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9823 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9824 DAG.getConstant(InfBits, dl, IntVT));
9825 } else {
9826 // Emit poison if no Inf in format and not saturating.
9827 OverflowResult = DAG.getPOISON(IntVT);
9828 }
9829
9830 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
9831 SDValue NormExpShifted =
9832 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
9833 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9834 SDValue NormResult = DAG.getNode(
9835 ISD::OR, dl, IntVT,
9836 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
9837
9838 // Build special-value results.
9839 SDValue NaNResult;
9840 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9841 // Produce canonical NaN.
9842 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
9843 NaNResult =
9844 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
9845 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9846 DstNanEnc == fltNanEncoding::AllOnes) {
9847 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
9848 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
9849 dl, IntVT);
9850 } else {
9851 // NaN -> poison for finite only values.
9852 NaNResult = DAG.getPOISON(IntVT);
9853 }
9854
9855 // Inf handling.
9856 SDValue InfResult;
9857 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9858 // Produce signed infinity.
9859 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9860 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9861 DAG.getConstant(InfBits, dl, IntVT));
9862 } else if (Saturate) {
9863 // Inf saturates to max finite.
9864 uint64_t MaxFinite =
9865 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9866 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9867 DAG.getConstant(MaxFinite, dl, IntVT));
9868 } else {
9869 // No Inf and not saturating -> poison.
9870 InfResult = DAG.getPOISON(IntVT);
9871 }
9872
9873 SDValue ZeroResult = SignShifted;
9874
9875 // Final selection in an order: NaN takes priority, then Inf, then Zero.
9876 SDValue FiniteResult =
9877 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
9878 FiniteResult =
9879 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
9880
9881 SDValue Result = FiniteResult;
9882 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
9883 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
9884
9885 // Negative values are unrepresentable in an unsigned format: clamp to zero
9886 // when saturating, poison otherwise so no select is needed. -0.0 is handled
9887 // by IsZero above. Run before the NaN case so a negative NaN still yields
9888 // NaN.
9889 if (!DstHasSign && Saturate) {
9890 SDValue IsNegative =
9891 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
9892 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
9893 }
9894
9895 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
9896
9897 // Truncate to destination integer type.
9898 return DAG.getZExtOrTrunc(Result, dl, ResVT);
9899}
9900
9901SDValue
9903 SelectionDAG &DAG) const {
9904 SDLoc dl(Node);
9905 EVT DstVT = Node->getValueType(0);
9906 EVT DstScalarVT = DstVT.getScalarType();
9907
9908 SDValue IntVal = Node->getOperand(0);
9909 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9910 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9911
9912 // Supported source formats.
9913 switch (Sem) {
9920 break;
9921 default:
9922 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
9923 "source format (semantics enum " +
9924 Twine(SemEnum) + ")");
9925 return SDValue();
9926 }
9927
9928 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
9929 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9930 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9931 const unsigned SrcMant = SrcPrecision - 1;
9932 // Unsigned formats spend no bit on the sign.
9933 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
9934 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
9935 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
9936 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
9937
9938 // Destination format parameters.
9939 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
9940 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9941 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
9942 const unsigned DstExpBits = DstBits - DstMant - 1;
9943 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
9944 const int DstBias = 1 - DstMinExp;
9945 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
9946
9947 // Work in an integer type matching the destination float width.
9948 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
9949 EVT IntVT = IntScalarVT;
9950 if (DstVT.isVector()) {
9951 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
9952 DstVT.getVectorElementCount());
9953 } else if (!isTypeLegal(IntScalarVT)) {
9954 // Avoid generating illegal type as there is no other places that'll
9955 // legalize it. Vector types don't have this problem because they
9956 // are subject to LegalizeVectorOps and another type legalization phase
9957 // will follow.
9958 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
9959 // We only know how to handle situations where the legal type is wider.
9960 DAG.getContext()->emitError(
9961 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
9962 "legalization is not supported");
9963 return SDValue();
9964 }
9965 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
9966 }
9967
9968 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
9969
9970 EVT SetCCVT =
9971 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9972
9973 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9974 SDValue One = DAG.getConstant(1, dl, IntVT);
9975
9976 // Extract bit fields.
9977 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
9978 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
9979
9980 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
9981 DAG.getConstant(MantMask, dl, IntVT));
9982
9983 SDValue ExpField =
9984 DAG.getNode(ISD::AND, dl, IntVT,
9985 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9986 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
9987 DAG.getConstant(ExpMask, dl, IntVT));
9988
9989 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
9990 // exponent.
9991 SDValue SignShifted =
9992 SrcHasSign
9993 ? DAG.getNode(
9994 ISD::SHL, dl, IntVT,
9995 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9996 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
9997 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9998 : Zero;
9999
10000 // Classify the input.
10001 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
10002 SDValue IsExpAllOnes =
10003 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
10004 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
10005 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
10006 SDValue IsMantNonZero =
10007 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
10008
10009 SDValue IsNaN;
10010 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
10011 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10012 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
10013 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
10014 } else {
10016 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
10017 SDValue IsMantAllOnes =
10018 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
10019 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
10020 }
10021
10022 SDValue IsInf;
10023 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
10024 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
10025 else
10026 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10027
10028 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
10029 SDValue IsDenorm =
10030 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
10031
10032 // Normal value conversion.
10033 const int BiasAdjust = DstBias - SrcBias;
10034 SDValue NormDstExp = DAG.getNode(
10035 ISD::ADD, dl, IntVT, ExpField,
10036 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
10037 IntVT));
10038
10039 SDValue NormDstMant;
10040 if (DstMant > SrcMant) {
10041 SDValue NormDstMantShift =
10042 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
10043 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
10044 } else {
10045 NormDstMant = MantField;
10046 }
10047
10048 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
10049 SDValue NormExpShifted =
10050 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
10051 SDValue NormResult =
10052 DAG.getNode(ISD::OR, dl, IntVT,
10053 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
10054 NormDstMant);
10055
10056 // With identical exponent biases, denormal values remain denormal and the
10057 // normal conversion's mantissa shift is sufficient.
10058 SDValue DenormResult = NormResult;
10059 if (BiasAdjust != 0) {
10060 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
10061 SDValue LeadingZeros =
10062 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
10063
10064 const int DenormExpConst =
10065 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
10066 SDValue DenormDstExp = DAG.getNode(
10067 ISD::SUB, dl, IntVT,
10068 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
10069 LeadingZeros);
10070
10071 SDValue MantMSB =
10072 DAG.getNode(ISD::SUB, dl, IntVT,
10073 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
10074
10075 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
10076 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
10077
10078 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
10079 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
10080 DAG.getConstant(ShiftSub, dl, IntVT));
10081
10082 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
10083
10084 SDValue DenormExpShifted =
10085 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
10086 DenormResult = DAG.getNode(
10087 ISD::OR, dl, IntVT,
10088 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10089 DenormDstMant);
10090 }
10091
10092 SDValue FiniteResult =
10093 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
10094
10095 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10096 SDValue NaNResult =
10097 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
10098
10099 SDValue InfResult =
10100 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10101 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
10102
10103 // A source format may have a larger finite exponent range despite having
10104 // fewer bits, as with Float8E5M3FNU converted to half. Its overflowing finite
10105 // values become infinity. The NaN selection below still takes precedence.
10106 if (APFloat::semanticsMaxExponent(SrcSem) >
10108 SDValue IsOverflow =
10109 DAG.getSetCC(dl, SetCCVT, NormDstExp,
10110 DAG.getConstant(DstExpAllOnes, dl, IntVT), ISD::SETUGE);
10111 FiniteResult =
10112 DAG.getSelect(dl, IntVT, IsOverflow, InfResult, FiniteResult);
10113 }
10114
10115 SDValue ZeroResult = SignShifted;
10116
10117 SDValue Result = FiniteResult;
10118 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10119 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10120 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10121
10122 if (!DstVT.bitsEq(IntVT)) {
10123 // Store to stack before loading it back.
10124 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
10125 // IntScalarVT is the original type that has the same width as DstVT.
10126 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
10127 SDValue StackPtr =
10128 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
10129 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10131 MachinePointerInfo PtrInfo =
10132 MachinePointerInfo::getFixedStack(MF, FrameIndex);
10133 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
10134 PtrInfo, IntScalarVT, Alignment);
10135
10136 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
10137 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
10138 }
10139
10140 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
10141}
10142
10144 SelectionDAG &DAG) const {
10145 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10146 SDValue Src = Node->getOperand(OpNo);
10147 EVT SrcVT = Src.getValueType();
10148 EVT DstVT = Node->getValueType(0);
10149 SDLoc dl(SDValue(Node, 0));
10150
10151 // FIXME: Only f32 to i64 conversions are supported.
10152 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
10153 return false;
10154
10155 if (Node->isStrictFPOpcode())
10156 // When a NaN is converted to an integer a trap is allowed. We can't
10157 // use this expansion here because it would eliminate that trap. Other
10158 // traps are also allowed and cannot be eliminated. See
10159 // IEEE 754-2008 sec 5.8.
10160 return false;
10161
10162 // Expand f32 -> i64 conversion
10163 // This algorithm comes from compiler-rt's implementation of fixsfdi:
10164 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
10165 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
10166 EVT IntVT = SrcVT.changeTypeToInteger();
10167 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
10168
10169 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
10170 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
10171 SDValue Bias = DAG.getConstant(127, dl, IntVT);
10172 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
10173 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
10174 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
10175
10176 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
10177
10178 SDValue ExponentBits = DAG.getNode(
10179 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
10180 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
10181 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
10182
10183 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
10184 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
10185 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
10186 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10187
10188 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10189 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10190 DAG.getConstant(0x00800000, dl, IntVT));
10191
10192 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10193
10194 R = DAG.getSelectCC(
10195 dl, Exponent, ExponentLoBit,
10196 DAG.getNode(ISD::SHL, dl, DstVT, R,
10197 DAG.getZExtOrTrunc(
10198 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10199 dl, IntShVT)),
10200 DAG.getNode(ISD::SRL, dl, DstVT, R,
10201 DAG.getZExtOrTrunc(
10202 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10203 dl, IntShVT)),
10204 ISD::SETGT);
10205
10206 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10207 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10208
10209 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10210 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10211 return true;
10212}
10213
10215 SDValue &Chain,
10216 SelectionDAG &DAG) const {
10217 SDLoc dl(SDValue(Node, 0));
10218 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10219 SDValue Src = Node->getOperand(OpNo);
10220
10221 EVT SrcVT = Src.getValueType();
10222 EVT DstVT = Node->getValueType(0);
10223 EVT SetCCVT =
10224 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10225 EVT DstSetCCVT =
10226 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10227
10228 // Only expand vector types if we have the appropriate vector bit operations.
10229 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10231 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10233 return false;
10234
10235 // If the maximum float value is smaller then the signed integer range,
10236 // the destination signmask can't be represented by the float, so we can
10237 // just use FP_TO_SINT directly.
10238 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10239 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10240 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10242 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10243 if (Node->isStrictFPOpcode()) {
10244 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10245 { Node->getOperand(0), Src });
10246 Chain = Result.getValue(1);
10247 } else
10248 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10249 return true;
10250 }
10251
10252 // Don't expand it if there isn't cheap fsub instruction.
10254 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10255 return false;
10256
10257 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10258 SDValue Sel;
10259
10260 if (Node->isStrictFPOpcode()) {
10261 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10262 Node->getOperand(0), /*IsSignaling*/ true);
10263 Chain = Sel.getValue(1);
10264 } else {
10265 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10266 }
10267
10268 bool Strict = Node->isStrictFPOpcode() ||
10269 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10270
10271 if (Strict) {
10272 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10273 // signmask then offset (the result of which should be fully representable).
10274 // Sel = Src < 0x8000000000000000
10275 // FltOfs = select Sel, 0, 0x8000000000000000
10276 // IntOfs = select Sel, 0, 0x8000000000000000
10277 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10278
10279 // TODO: Should any fast-math-flags be set for the FSUB?
10280 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10281 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10282 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10283 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10284 DAG.getConstant(0, dl, DstVT),
10285 DAG.getConstant(SignMask, dl, DstVT));
10286 SDValue SInt;
10287 if (Node->isStrictFPOpcode()) {
10288 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10289 { Chain, Src, FltOfs });
10290 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10291 { Val.getValue(1), Val });
10292 Chain = SInt.getValue(1);
10293 } else {
10294 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10295 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10296 }
10297 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10298 } else {
10299 // Expand based on maximum range of FP_TO_SINT:
10300 // True = fp_to_sint(Src)
10301 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10302 // Result = select (Src < 0x8000000000000000), True, False
10303
10304 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10305 // TODO: Should any fast-math-flags be set for the FSUB?
10306 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10307 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10308 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10309 DAG.getConstant(SignMask, dl, DstVT));
10310 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10311 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10312 }
10313 return true;
10314}
10315
10317 SDValue &Chain, SelectionDAG &DAG) const {
10318 // This transform is not correct for converting 0 when rounding mode is set
10319 // to round toward negative infinity which will produce -0.0. So disable
10320 // under strictfp.
10321 if (Node->isStrictFPOpcode())
10322 return false;
10323
10324 SDValue Src = Node->getOperand(0);
10325 EVT SrcVT = Src.getValueType();
10326 EVT DstVT = Node->getValueType(0);
10327
10328 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10329 // it.
10330 if (Node->getFlags().hasNonNeg() &&
10332 Result =
10333 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10334 return true;
10335 }
10336
10337 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10338 return false;
10339
10340 // Only expand vector types if we have the appropriate vector bit
10341 // operations.
10342 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10347 return false;
10348
10349 SDLoc dl(SDValue(Node, 0));
10350
10351 // Implementation of unsigned i64 to f64 following the algorithm in
10352 // __floatundidf in compiler_rt. This implementation performs rounding
10353 // correctly in all rounding modes with the exception of converting 0
10354 // when rounding toward negative infinity. In that case the fsub will
10355 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10356 // incorrect.
10357 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10358 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10359 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10360 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10361 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10362 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10363
10364 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10365 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10366 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10367 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10368 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10369 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10370 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10371 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10372 return true;
10373}
10374
10375SDValue
10377 SelectionDAG &DAG) const {
10378 unsigned Opcode = Node->getOpcode();
10379 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10380 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10381 "Wrong opcode");
10382
10383 if (Node->getFlags().hasNoNaNs()) {
10384 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10385 EVT VT = Node->getValueType(0);
10386 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10388 VT.isVector())
10389 return SDValue();
10390 SDValue Op1 = Node->getOperand(0);
10391 SDValue Op2 = Node->getOperand(1);
10392 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10393 Node->getFlags());
10394 }
10395
10396 return SDValue();
10397}
10398
10400 SelectionDAG &DAG) const {
10401 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10402 return Expanded;
10403
10404 EVT VT = Node->getValueType(0);
10405 if (VT.isScalableVector())
10407 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10408
10409 SDLoc dl(Node);
10410 unsigned NewOp =
10412
10413 if (isOperationLegalOrCustom(NewOp, VT)) {
10414 SDValue Quiet0 = Node->getOperand(0);
10415 SDValue Quiet1 = Node->getOperand(1);
10416
10417 if (!Node->getFlags().hasNoNaNs()) {
10418 // Insert canonicalizes if it's possible we need to quiet to get correct
10419 // sNaN behavior.
10420 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10421 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10422 Node->getFlags());
10423 }
10424 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10425 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10426 Node->getFlags());
10427 }
10428 }
10429
10430 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10431 }
10432
10433 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10434 // instead if there are no NaNs.
10435 if (Node->getFlags().hasNoNaNs() ||
10436 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10437 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10438 unsigned IEEE2018Op =
10439 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10440 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10441 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10442 Node->getOperand(1), Node->getFlags());
10443 }
10444
10446 return SelCC;
10447
10448 return SDValue();
10449}
10450
10452 const TargetLowering &TLI,
10453 const SDLoc &DL, SDValue Val,
10454 FPClassTest FPClass) {
10455 EVT VT = Val.getValueType();
10456 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10457 EVT IntVT = VT.changeTypeToInteger();
10458 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10459 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10460 if (!TLI.isTypeLegal(IntVT) &&
10462 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10463 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10464 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10465}
10466
10468 SelectionDAG &DAG) const {
10469 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10470 return Expanded;
10471
10472 SDLoc DL(N);
10473 SDValue LHS = N->getOperand(0);
10474 SDValue RHS = N->getOperand(1);
10475 unsigned Opc = N->getOpcode();
10476 EVT VT = N->getValueType(0);
10477 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10478 bool IsMax = Opc == ISD::FMAXIMUM;
10479 SDNodeFlags Flags = N->getFlags();
10480
10481 // First, implement comparison not propagating NaN. If no native fmin or fmax
10482 // available, use plain select with setcc instead.
10484 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10485 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10486
10487 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10488 // signed zero behavior.
10489 bool MinMaxMustRespectOrderedZero = false;
10490
10491 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10492 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10493 MinMaxMustRespectOrderedZero = true;
10494 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10495 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10496 } else {
10498 return DAG.UnrollVectorOp(N);
10499
10500 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10501 SDValue Compare =
10502 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10503 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10504 }
10505
10506 // Propagate any NaN of both operands
10507 if (!N->getFlags().hasNoNaNs() &&
10508 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10509 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10511 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10512 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10513 }
10514
10515 // fminimum/fmaximum requires -0.0 less than +0.0
10516 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10517 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10518 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10520 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10521 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10522 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10523 }
10524
10525 return MinMax;
10526}
10527
10529 SelectionDAG &DAG) const {
10530 SDLoc DL(Node);
10531 SDValue LHS = Node->getOperand(0);
10532 SDValue RHS = Node->getOperand(1);
10533 unsigned Opc = Node->getOpcode();
10534 EVT VT = Node->getValueType(0);
10535 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10536 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10537 SDNodeFlags Flags = Node->getFlags();
10538
10539 unsigned NewOp =
10541
10542 if (isOperationLegalOrCustom(NewOp, VT)) {
10543 if (!Flags.hasNoNaNs()) {
10544 // Insert canonicalizes if it's possible we need to quiet to get correct
10545 // sNaN behavior.
10546 if (!DAG.isKnownNeverSNaN(LHS)) {
10547 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10548 }
10549 if (!DAG.isKnownNeverSNaN(RHS)) {
10550 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10551 }
10552 }
10553
10554 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10555 }
10556
10557 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10558 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10559 if (Flags.hasNoNaNs() ||
10560 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10561 unsigned IEEE2019Op =
10563 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10564 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10565 }
10566
10567 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10568 // either one for +0.0 vs -0.0.
10569 if ((Flags.hasNoNaNs() ||
10570 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10571 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10572 DAG.isKnownNeverLogicalZero(RHS))) {
10573 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10574 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10575 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10576 }
10577
10578 if (VT.isVector() &&
10581 return DAG.UnrollVectorOp(Node);
10582
10583 // If only one operand is NaN, override it with another operand.
10584 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10585 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10586 }
10587 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10588 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10589 }
10590
10591 // Always prefer RHS if equal.
10592 SDValue MinMax =
10593 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10594
10595 // TODO: We need quiet sNaN if strictfp.
10596
10597 // Fixup signed zero behavior.
10598 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10599 DAG.isKnownNeverLogicalZero(RHS)) {
10600 return MinMax;
10601 }
10602 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10603 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10605 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10606 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10607 // we preferred RHS when generate MinMax, if the operands are equal.
10608 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10609 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10610}
10611
10612/// Returns a true value if if this FPClassTest can be performed with an ordered
10613/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10614/// std::nullopt if it cannot be performed as a compare with 0.
10615static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10616 const fltSemantics &Semantics,
10617 const MachineFunction &MF) {
10618 FPClassTest OrderedMask = Test & ~fcNan;
10619 FPClassTest NanTest = Test & fcNan;
10620 bool IsOrdered = NanTest == fcNone;
10621 bool IsUnordered = NanTest == fcNan;
10622
10623 // Skip cases that are testing for only a qnan or snan.
10624 if (!IsOrdered && !IsUnordered)
10625 return std::nullopt;
10626
10627 if (OrderedMask == fcZero &&
10628 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10629 return IsOrdered;
10630 if (OrderedMask == (fcZero | fcSubnormal) &&
10631 MF.getDenormalMode(Semantics).inputsAreZero())
10632 return IsOrdered;
10633 return std::nullopt;
10634}
10635
10637 const FPClassTest OrigTestMask,
10638 SDNodeFlags Flags, const SDLoc &DL,
10639 SelectionDAG &DAG) const {
10640 EVT OperandVT = Op.getValueType();
10641 assert(OperandVT.isFloatingPoint());
10642 FPClassTest Test = OrigTestMask;
10643
10644 // Degenerated cases.
10645 if (Test == fcNone)
10646 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10647 if (Test == fcAllFlags)
10648 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10649
10650 // PPC double double is a pair of doubles, of which the higher part determines
10651 // the value class.
10652 if (OperandVT == MVT::ppcf128) {
10653 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10654 DAG.getConstant(1, DL, MVT::i32));
10655 OperandVT = MVT::f64;
10656 }
10657
10658 // Floating-point type properties.
10659 EVT ScalarFloatVT = OperandVT.getScalarType();
10660 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10661 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10662 bool IsF80 = (ScalarFloatVT == MVT::f80);
10663
10664 // Some checks can be implemented using float comparisons, if floating point
10665 // exceptions are ignored.
10666 if (Flags.hasNoFPExcept() &&
10668 FPClassTest FPTestMask = Test;
10669 bool IsInvertedFP = false;
10670
10671 if (FPClassTest InvertedFPCheck =
10672 invertFPClassTestIfSimpler(FPTestMask, true)) {
10673 FPTestMask = InvertedFPCheck;
10674 IsInvertedFP = true;
10675 }
10676
10677 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10678 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10679
10680 // See if we can fold an | fcNan into an unordered compare.
10681 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10682
10683 // Can't fold the ordered check if we're only testing for snan or qnan
10684 // individually.
10685 if ((FPTestMask & fcNan) != fcNan)
10686 OrderedFPTestMask = FPTestMask;
10687
10688 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10689
10690 if (std::optional<bool> IsCmp0 =
10691 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10692 IsCmp0 && (isCondCodeLegalOrCustom(
10693 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10694 OperandVT.getScalarType().getSimpleVT()))) {
10695
10696 // If denormals could be implicitly treated as 0, this is not equivalent
10697 // to a compare with 0 since it will also be true for denormals.
10698 return DAG.getSetCC(DL, ResultVT, Op,
10699 DAG.getConstantFP(0.0, DL, OperandVT),
10700 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10701 }
10702
10703 if (FPTestMask == fcNan &&
10705 OperandVT.getScalarType().getSimpleVT()))
10706 return DAG.getSetCC(DL, ResultVT, Op, Op,
10707 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10708
10709 bool IsOrderedInf = FPTestMask == fcInf;
10710 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10711 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10712 : UnorderedCmpOpcode,
10713 OperandVT.getScalarType().getSimpleVT()) &&
10716 (OperandVT.isVector() &&
10718 // isinf(x) --> fabs(x) == inf
10719 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10720 SDValue Inf =
10721 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10722 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10723 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10724 }
10725
10726 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10727 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10728 : UnorderedCmpOpcode,
10729 OperandVT.getSimpleVT())) {
10730 // isposinf(x) --> x == inf
10731 // isneginf(x) --> x == -inf
10732 // isposinf(x) || nan --> x u== inf
10733 // isneginf(x) || nan --> x u== -inf
10734
10735 SDValue Inf = DAG.getConstantFP(
10736 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
10737 OperandVT);
10738 return DAG.getSetCC(DL, ResultVT, Op, Inf,
10739 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
10740 }
10741
10742 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
10743 // TODO: Could handle ordered case, but it produces worse code for
10744 // x86. Maybe handle ordered if fabs is free?
10745
10746 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10747 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
10748
10749 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
10750 OperandVT.getScalarType().getSimpleVT())) {
10751 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
10752
10753 // TODO: Maybe only makes sense if fabs is free. Integer test of
10754 // exponent bits seems better for x86.
10755 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10756 SDValue SmallestNormal = DAG.getConstantFP(
10757 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10758 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
10759 IsOrdered ? OrderedOp : UnorderedOp);
10760 }
10761 }
10762
10763 if (FPTestMask == fcNormal) {
10764 // TODO: Handle unordered
10765 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10766 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
10767
10768 if (isCondCodeLegalOrCustom(IsFiniteOp,
10769 OperandVT.getScalarType().getSimpleVT()) &&
10770 isCondCodeLegalOrCustom(IsNormalOp,
10771 OperandVT.getScalarType().getSimpleVT()) &&
10772 isFAbsFree(OperandVT)) {
10773 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
10774 SDValue Inf =
10775 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10776 SDValue SmallestNormal = DAG.getConstantFP(
10777 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10778
10779 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10780 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
10781 SDValue IsNormal =
10782 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
10783 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
10784 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
10785 }
10786 }
10787 }
10788
10789 // Some checks may be represented as inversion of simpler check, for example
10790 // "inf|normal|subnormal|zero" => !"nan".
10791 bool IsInverted = false;
10792
10793 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
10794 Test = InvertedCheck;
10795 IsInverted = true;
10796 }
10797
10798 // In the general case use integer operations.
10799 unsigned BitSize = OperandVT.getScalarSizeInBits();
10800 EVT IntVT = OperandVT.changeElementType(
10801 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
10802 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
10803
10804 // Various masks.
10805 APInt SignBit = APInt::getSignMask(BitSize);
10806 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
10807 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
10808 const unsigned ExplicitIntBitInF80 = 63;
10809 APInt ExpMask = Inf;
10810 if (IsF80)
10811 ExpMask.clearBit(ExplicitIntBitInF80);
10812 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
10813 APInt QNaNBitMask =
10814 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
10815 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
10816
10817 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
10818 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
10819 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
10820 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
10821 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
10822 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
10823
10824 SDValue Res;
10825 const auto appendResult = [&](SDValue PartialRes) {
10826 if (PartialRes) {
10827 if (Res)
10828 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
10829 else
10830 Res = PartialRes;
10831 }
10832 };
10833
10834 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
10835 const auto getIntBitIsSet = [&]() -> SDValue {
10836 if (!IntBitIsSetV) {
10837 APInt IntBitMask(BitSize, 0);
10838 IntBitMask.setBit(ExplicitIntBitInF80);
10839 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
10840 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
10841 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
10842 }
10843 return IntBitIsSetV;
10844 };
10845
10846 // Split the value into sign bit and absolute value.
10847 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
10848 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
10849 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
10850
10851 // Tests that involve more than one class should be processed first.
10852 SDValue PartialRes;
10853
10854 if (IsF80)
10855 ; // Detect finite numbers of f80 by checking individual classes because
10856 // they have different settings of the explicit integer bit.
10857 else if ((Test & fcFinite) == fcFinite) {
10858 // finite(V) ==> (a << 1) < (inf << 1)
10859 //
10860 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
10861 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
10862
10864 "finite check requires IEEE-like FP");
10865
10866 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
10867 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
10868 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
10869
10870 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
10871 Test &= ~fcFinite;
10872 } else if ((Test & fcFinite) == fcPosFinite) {
10873 // finite(V) && V > 0 ==> V < exp_mask
10874 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
10875 Test &= ~fcPosFinite;
10876 } else if ((Test & fcFinite) == fcNegFinite) {
10877 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
10878 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
10879 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10880 Test &= ~fcNegFinite;
10881 }
10882 appendResult(PartialRes);
10883
10884 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
10885 // fcZero | fcSubnormal => test all exponent bits are 0
10886 // TODO: Handle sign bit specific cases
10887 if (PartialCheck == (fcZero | fcSubnormal)) {
10888 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
10889 SDValue ExpIsZero =
10890 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10891 appendResult(ExpIsZero);
10892 Test &= ~PartialCheck & fcAllFlags;
10893 }
10894 }
10895
10896 // Check for individual classes.
10897
10898 if (unsigned PartialCheck = Test & fcZero) {
10899 if (PartialCheck == fcPosZero)
10900 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
10901 else if (PartialCheck == fcZero)
10902 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
10903 else // ISD::fcNegZero
10904 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
10905 appendResult(PartialRes);
10906 }
10907
10908 if (unsigned PartialCheck = Test & fcSubnormal) {
10909 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
10910 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
10911 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
10912 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
10913 SDValue VMinusOneV =
10914 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
10915 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
10916 if (PartialCheck == fcNegSubnormal)
10917 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10918 appendResult(PartialRes);
10919 }
10920
10921 if (unsigned PartialCheck = Test & fcInf) {
10922 if (PartialCheck == fcPosInf)
10923 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
10924 else if (PartialCheck == fcInf)
10925 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
10926 else { // ISD::fcNegInf
10927 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
10928 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
10929 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
10930 }
10931 appendResult(PartialRes);
10932 }
10933
10934 if (unsigned PartialCheck = Test & fcNan) {
10935 APInt InfWithQnanBit = Inf | QNaNBitMask;
10936 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
10937 if (PartialCheck == fcNan) {
10938 // isnan(V) ==> abs(V) > int(inf)
10939 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
10940 if (IsF80) {
10941 // Recognize unsupported values as NaNs for compatibility with glibc.
10942 // In them (exp(V)==0) == int_bit.
10943 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
10944 SDValue ExpIsZero =
10945 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10946 SDValue IsPseudo =
10947 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
10948 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
10949 }
10950 } else if (PartialCheck == fcQNan) {
10951 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
10952 PartialRes =
10953 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
10954 } else { // ISD::fcSNan
10955 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
10956 // abs(V) < (unsigned(Inf) | quiet_bit)
10957 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
10958 SDValue IsNotQnan =
10959 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
10960 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
10961 }
10962 appendResult(PartialRes);
10963 }
10964
10965 if (unsigned PartialCheck = Test & fcNormal) {
10966 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
10967 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
10968 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
10969 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
10970 APInt ExpLimit = ExpMask - ExpLSB;
10971 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
10972 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
10973 if (PartialCheck == fcNegNormal)
10974 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10975 else if (PartialCheck == fcPosNormal) {
10976 SDValue PosSignV =
10977 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
10978 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
10979 }
10980 if (IsF80)
10981 PartialRes =
10982 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
10983 appendResult(PartialRes);
10984 }
10985
10986 if (!Res)
10987 return DAG.getConstant(IsInverted, DL, ResultVT);
10988 if (IsInverted)
10989 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
10990 return Res;
10991}
10992
10993// Only expand vector types if we have the appropriate vector bit operations.
10994static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
10995 assert(VT.isVector() && "Expected vector type");
10996 unsigned Len = VT.getScalarSizeInBits();
10997 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
11000 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
11002}
11003
11005 SDLoc dl(Node);
11006 EVT VT = Node->getValueType(0);
11007 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11008 SDValue Op = Node->getOperand(0);
11009 unsigned Len = VT.getScalarSizeInBits();
11010
11011 // Compute effective bit width from known bits, allowing us to shift the
11012 // active bits down if necessary to fit into smaller specialized expansions.
11014 unsigned LZ = Known.countMinLeadingZeros();
11015 unsigned TZ = Known.countMinTrailingZeros();
11016 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
11017
11018 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
11019 unsigned EffectiveLen = Len;
11020 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
11021 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
11022
11023 assert(VT.isInteger() && "CTPOP not implemented for this type.");
11024
11025 // TODO: Add support for irregular type lengths.
11026 if (!(Len <= 128 && Len % 8 == 0))
11027 return SDValue();
11028
11029 // Only expand vector types if we have the appropriate vector bit operations.
11030 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
11031 return SDValue();
11032
11033 // If the active bits are not at the low end, shift them down
11034 if (EffectiveLen < Len && TZ > 0) {
11035 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
11036 DAG.getShiftAmountConstant(TZ, VT, dl));
11037 }
11038
11039 // This is the "best" algorithm from
11040 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
11041 SDValue Mask55 =
11042 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
11043 SDValue Mask33 =
11044 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
11045 SDValue Mask0F =
11046 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
11047
11048 // v = v - ((v >> 1) & 0x55555555...)
11049 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
11050 DAG.getNode(ISD::AND, dl, VT,
11051 DAG.getNode(ISD::SRL, dl, VT, Op,
11052 DAG.getConstant(1, dl, ShVT)),
11053 Mask55));
11054 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
11055 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
11056 DAG.getNode(ISD::AND, dl, VT,
11057 DAG.getNode(ISD::SRL, dl, VT, Op,
11058 DAG.getConstant(2, dl, ShVT)),
11059 Mask33));
11060 // v = (v + (v >> 4)) & 0x0F0F0F0F...
11061 Op = DAG.getNode(ISD::AND, dl, VT,
11062 DAG.getNode(ISD::ADD, dl, VT, Op,
11063 DAG.getNode(ISD::SRL, dl, VT, Op,
11064 DAG.getConstant(4, dl, ShVT))),
11065 Mask0F);
11066
11067 if (EffectiveLen <= 8)
11068 return Op;
11069
11070 // Avoid the multiply if we only have 2 bytes to add.
11071 // TODO: Only doing this for scalars because vectors weren't as obviously
11072 // improved.
11073 if (EffectiveLen == 16 && !VT.isVector()) {
11074 // v = (v + (v >> 8)) & 0x00FF;
11075 return DAG.getNode(ISD::AND, dl, VT,
11076 DAG.getNode(ISD::ADD, dl, VT, Op,
11077 DAG.getNode(ISD::SRL, dl, VT, Op,
11078 DAG.getConstant(8, dl, ShVT))),
11079 DAG.getConstant(0xFF, dl, VT));
11080 }
11081
11082 // v = (v * 0x01010101...) >> (Len - 8)
11083 SDValue V;
11086 SDValue Mask01 =
11087 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
11088 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
11089 } else {
11090 V = Op;
11091 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
11092 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
11093 V = DAG.getNode(ISD::ADD, dl, VT, V,
11094 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
11095 }
11096 }
11097 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
11098}
11099
11101 SDLoc dl(Node);
11102 EVT VT = Node->getValueType(0);
11103 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11104 SDValue Op = Node->getOperand(0);
11105 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11106
11107 // If the non-ZERO_POISON version is supported we can use that instead.
11108 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
11110 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
11111
11112 // If the ZERO_POISON version is supported use that and handle the zero case.
11114 EVT SetCCVT =
11115 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11116 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
11117 SDValue Zero = DAG.getConstant(0, dl, VT);
11118 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11119 return DAG.getSelect(dl, VT, SrcIsZero,
11120 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
11121 }
11122
11123 // Only expand vector types if we have the appropriate vector bit operations.
11124 // This includes the operations needed to expand CTPOP if it isn't supported.
11125 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11127 !canExpandVectorCTPOP(*this, VT)) ||
11130 return SDValue();
11131
11132 // for now, we do this:
11133 // x = x | (x >> 1);
11134 // x = x | (x >> 2);
11135 // ...
11136 // x = x | (x >>16);
11137 // x = x | (x >>32); // for 64-bit input
11138 // return popcount(~x);
11139 //
11140 // Ref: "Hacker's Delight" by Henry Warren
11141 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
11142 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
11143 Op = DAG.getNode(ISD::OR, dl, VT, Op,
11144 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
11145 }
11146 Op = DAG.getNOT(dl, Op, VT);
11147 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
11148}
11149
11151 SDLoc dl(Node);
11152 EVT VT = Node->getValueType(0);
11153 SDValue Op = DAG.getFreeze(Node->getOperand(0));
11154 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11155
11156 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
11157 // This transforms the sign bits into leading zeros that can be counted.
11158 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
11159 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
11160 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
11161 SDValue Shl =
11162 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11163 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
11164 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
11165}
11166
11168 const SDLoc &DL, EVT VT, SDValue Op,
11169 unsigned BitWidth) const {
11170 if (BitWidth != 32 && BitWidth != 64)
11171 return SDValue();
11172
11173 const DataLayout &TD = DAG.getDataLayout();
11175 return SDValue();
11176
11177 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
11178 : APInt(64, 0x0218A392CD3D5DBFULL);
11179 MachinePointerInfo PtrInfo =
11181 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
11182 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11183 SDValue Lookup = DAG.getNode(
11184 ISD::SRL, DL, VT,
11185 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
11186 DAG.getConstant(DeBruijn, DL, VT)),
11187 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11189
11191 for (unsigned i = 0; i < BitWidth; i++) {
11192 APInt Shl = DeBruijn.shl(i);
11193 APInt Lshr = Shl.lshr(ShiftAmt);
11194 Table[Lshr.getZExtValue()] = i;
11195 }
11196
11197 // Create a ConstantArray in Constant Pool
11198 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11199 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11200 TD.getPrefTypeAlign(CA->getType()));
11201 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11202 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11203 PtrInfo, MVT::i8);
11204 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11205 return ExtLoad;
11206
11207 EVT SetCCVT =
11208 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11209 SDValue Zero = DAG.getConstant(0, DL, VT);
11210 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11211 return DAG.getSelect(DL, VT, SrcIsZero,
11212 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11213}
11214
11216 SDLoc dl(Node);
11217 EVT VT = Node->getValueType(0);
11218 SDValue Op = Node->getOperand(0);
11219 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11220
11221 // If the non-ZERO_POISON version is supported we can use that instead.
11222 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11224 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11225
11226 // If the ZERO_POISON version is supported use that and handle the zero case.
11228 EVT SetCCVT =
11229 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11230 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11231 SDValue Zero = DAG.getConstant(0, dl, VT);
11232 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11233 return DAG.getSelect(dl, VT, SrcIsZero,
11234 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11235 }
11236
11237 // Only expand vector types if we have the appropriate vector bit operations.
11238 // This includes the operations needed to expand CTPOP if it isn't supported.
11239 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11242 !canExpandVectorCTPOP(*this, VT)) ||
11246 return SDValue();
11247
11248 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11249 // to be expanded or converted to a libcall.
11252 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11253 return V;
11254
11255 bool UseCTLZ =
11257
11258 // When only ctlz is available and the operand is nonzero we can use:
11259 // { return nlz(x & -x) ^ 31; }
11260 // which is more efficient than:
11261 // { return 32 - nlz(~x & (x - 1)); }.
11262 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11263 SDValue LowestBit =
11264 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11265 return DAG.getNode(ISD::XOR, dl, VT,
11266 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11267 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11268 }
11269
11270 // If ctpop is available, we use:
11271 // { return popcount(~x & (x-1)); }
11272 // If the target has ctlz but not ctpop, we use:
11273 // { return 32 - nlz(~x & (x-1)); }
11274 // Ref: "Hacker's Delight" by Henry Warren
11275 SDValue Tmp = DAG.getNode(
11276 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11277 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11278
11279 if (UseCTLZ)
11280 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11281 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11282
11283 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11284}
11285
11287 SelectionDAG &DAG) const {
11288 // %cond = to_bool_vec %source
11289 // %splat = splat /*val=*/VL
11290 // %tz = step_vector
11291 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11292 // %r = vp.reduce.umin %v
11293 SDLoc DL(N);
11294 SDValue Source = N->getOperand(0);
11295 SDValue Mask = N->getOperand(1);
11296 SDValue EVL = N->getOperand(2);
11297 EVT SrcVT = Source.getValueType();
11298 EVT ResVT = N->getValueType(0);
11299 EVT ResVecVT =
11300 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11301
11302 // Convert to boolean vector.
11303 if (SrcVT.getScalarType() != MVT::i1) {
11304 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11305 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11306 SrcVT.getVectorElementCount());
11307 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11308 }
11309
11310 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11311 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11312 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11313 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11314 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11315}
11316
11317/// Returns a type-legalized version of \p Mask as the first item in the
11318/// pair. The second item contains a type-legalized step vector that's
11319/// guaranteed to fit the number of elements in \p Mask.
11320/// If the stepvector would require splitting, returns an empty SDValue
11321/// as the second item to signal that the operation should be split instead.
11322static std::pair<SDValue, SDValue>
11324 SelectionDAG &DAG) {
11325 EVT MaskVT = Mask.getValueType();
11326 EVT BoolVT = MaskVT.getScalarType();
11327
11328 // Find a suitable type for a stepvector.
11329 // If zero is poison, we can assume the upper limit of the result is VF-1.
11330 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11331 if (MaskVT.isScalableVector())
11332 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11333 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11334 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11335 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11336 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11337 // If the step vector element type is smaller than the mask element type,
11338 // use the mask type directly to avoid widening issues.
11339 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11340 EVT StepVT = MVT::getIntegerVT(EltWidth);
11341 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11342
11343 // If promotion or widening is required to make the type legal, do it here.
11344 // Promotion of integers within LegalizeVectorOps is looking for types of
11345 // the same size but with a smaller number of larger elements, not the usual
11346 // larger size with the same number of larger elements.
11348 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11349 SDValue StepVec;
11350 if (TypeAction == TargetLowering::TypePromoteInteger) {
11351 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11352 StepVec = DAG.getStepVector(DL, StepVecVT);
11353 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11354 // For widening, the element count changes. Create a step vector with only
11355 // the original elements valid and zeros for padding. Also widen the mask.
11356 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11357 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11358
11359 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11360 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11361 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11362 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11363
11364 // Widen mask: pad with zeros.
11365 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11366 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11367 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11368 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11369 // The stepvector type would require splitting. Signal to the caller
11370 // that the operation should be split instead of expanded.
11371 return {Mask, SDValue()};
11372 } else {
11373 StepVec = DAG.getStepVector(DL, StepVecVT);
11374 }
11375
11376 return {Mask, StepVec};
11377}
11378
11380 SelectionDAG &DAG) const {
11381 SDLoc DL(N);
11382 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11383 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11384
11385 // If StepVec is empty, the stepvector would require splitting.
11386 // Split the operation instead and let it be recursively legalized.
11387 if (!StepVec) {
11388 EVT MaskVT = N->getOperand(0).getValueType();
11389 EVT ResVT = N->getValueType(0);
11390
11391 // Split the mask
11392 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11393 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11394
11395 // Create split VECTOR_FIND_LAST_ACTIVE operations
11396 SDValue LoResult =
11397 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11398 SDValue HiResult =
11399 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11400
11401 // Check if any lane is active in the high mask.
11402 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11404 AnyHiActive, DL,
11405 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11406 MVT::i1);
11407
11408 // Adjust HiResult by adding the number of elements in Lo
11409 SDValue LoNumElts =
11410 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11411 SDValue AdjustedHiResult =
11412 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11413
11414 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11415 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11416 LoResult);
11417 }
11418
11419 EVT StepVecVT = StepVec.getValueType();
11420 EVT StepVT = StepVec.getValueType().getVectorElementType();
11421
11422 // Zero out lanes with inactive elements, then find the highest remaining
11423 // value from the stepvector.
11424 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11425 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11426 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11427 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11428}
11429
11431 SelectionDAG &DAG) const {
11432 SDLoc DL(N);
11433 EVT VT = N->getValueType(0);
11434 SDValue SourceValue = N->getOperand(0);
11435 SDValue SinkValue = N->getOperand(1);
11436 SDValue EltSizeInBytes = N->getOperand(2);
11437
11438 // Note: The lane offset is scalable if the mask is scalable.
11439 ElementCount LaneOffsetEC =
11440 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11441
11442 EVT AddrVT = SourceValue->getValueType(0);
11443 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11444
11445 EVT CmpVT =
11446 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11447
11448 // Unsigned compare: Source >= Sink.
11449 SDValue SourceAheadOfOrEqualToSink =
11450 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11451
11452 // Take the difference between the pointers and divided by the element size,
11453 // to see how many lanes separate them.
11454 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11455
11456 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11457 if (IsReadAfterWrite)
11458 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11459 DAG.getNegative(Diff, DL, AddrVT), Diff);
11460
11461 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11462
11463 // The pointers do not alias if:
11464 // - Source >= Sink (WAR_MASK)
11465 // - Source == Sink (RAW_MASK)
11466 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11467 if (IsReadAfterWrite)
11468 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11469
11470 // The pointers do not alias if:
11471 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11472 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11473 SDValue MaskN = DAG.getSelect(
11474 DL, AddrVT, NoAlias,
11476 AddrVT),
11477 Diff);
11478
11479 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11480}
11481
11483 bool IsNegative) const {
11484 SDLoc dl(N);
11485 EVT VT = N->getValueType(0);
11486 SDValue Op = N->getOperand(0);
11487
11488 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11489 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11491 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11492 if (IsNegative)
11493 return DAG.getNegative(AbsVal, dl, VT);
11494 return AbsVal;
11495 }
11496
11497 // abs(x) -> smax(x,sub(0,x))
11498 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11500 SDValue Zero = DAG.getConstant(0, dl, VT);
11501 Op = DAG.getFreeze(Op);
11502 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11503 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11504 }
11505
11506 // abs(x) -> umin(x,sub(0,x))
11507 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11509 SDValue Zero = DAG.getConstant(0, dl, VT);
11510 Op = DAG.getFreeze(Op);
11511 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11512 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11513 }
11514
11515 // 0 - abs(x) -> smin(x, sub(0,x))
11516 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11518 SDValue Zero = DAG.getConstant(0, dl, VT);
11519 Op = DAG.getFreeze(Op);
11520 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11521 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11522 }
11523
11524 // Only expand vector types if we have the appropriate vector operations.
11525 if (VT.isVector() &&
11527 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11528 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11530 return SDValue();
11531
11532 Op = DAG.getFreeze(Op);
11533 SDValue Shift = DAG.getNode(
11534 ISD::SRA, dl, VT, Op,
11535 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11536 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11537
11538 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11539 if (!IsNegative)
11540 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11541
11542 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11543 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11544}
11545
11547 SDLoc dl(N);
11548 EVT VT = N->getValueType(0);
11549 SDValue LHS = N->getOperand(0);
11550 SDValue RHS = N->getOperand(1);
11551 bool IsSigned = N->getOpcode() == ISD::ABDS;
11552
11553 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11554 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11555 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11556 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11557 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11558 LHS = DAG.getFreeze(LHS);
11559 RHS = DAG.getFreeze(RHS);
11560 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11561 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11562 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11563 }
11564
11565 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11566 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11567 LHS = DAG.getFreeze(LHS);
11568 RHS = DAG.getFreeze(RHS);
11569 return DAG.getNode(ISD::OR, dl, VT,
11570 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11571 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11572 }
11573
11574 // If the subtract doesn't overflow then just use abs(sub())
11575 bool IsNonNegative = DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS);
11576
11577 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, LHS, RHS))
11578 return DAG.getNode(ISD::ABS, dl, VT,
11579 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11580
11581 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, RHS, LHS))
11582 return DAG.getNode(ISD::ABS, dl, VT,
11583 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11584
11585 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11587 LHS = DAG.getFreeze(LHS);
11588 RHS = DAG.getFreeze(RHS);
11589 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11590
11591 // Branchless expansion iff cmp result is allbits:
11592 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11593 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11594 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11595 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11596 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11597 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11598 }
11599
11600 // Similar to the branchless expansion, if we don't prefer selects, use the
11601 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11602 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11603 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11604 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11606 SDValue USubO =
11607 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11608 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11609 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11610 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11611 }
11612
11613 // FIXME: Should really try to split the vector in case it's legal on a
11614 // subvector.
11616 return DAG.UnrollVectorOp(N);
11617
11618 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11619 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11620 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11621 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11622}
11623
11625 SDLoc dl(N);
11626 EVT VT = N->getValueType(0);
11627 SDValue LHS = N->getOperand(0);
11628 SDValue RHS = N->getOperand(1);
11629
11630 unsigned Opc = N->getOpcode();
11631 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11632 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11633 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11634 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11635 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11636 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11638 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11639 "Unknown AVG node");
11640
11641 // If the operands are already extended, we can add+shift.
11642 bool IsExt =
11643 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11644 DAG.ComputeNumSignBits(RHS) >= 2) ||
11645 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11646 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11647 if (IsExt) {
11648 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11649 if (!IsFloor)
11650 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11651 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11652 DAG.getShiftAmountConstant(1, VT, dl));
11653 }
11654
11655 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11656 if (VT.isScalarInteger()) {
11657 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11658 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11659 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11660 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11661 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11662 if (!IsFloor)
11663 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11664 DAG.getConstant(1, dl, ExtVT));
11665 // Just use SRL as we will be truncating away the extended sign bits.
11666 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11667 DAG.getShiftAmountConstant(1, ExtVT, dl));
11668 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11669 }
11670 }
11671
11672 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11673 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11676 SDValue UAddWithOverflow =
11677 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11678
11679 SDValue Sum = UAddWithOverflow.getValue(0);
11680 SDValue Overflow = UAddWithOverflow.getValue(1);
11681
11682 // Right shift the sum by 1
11683 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
11684 DAG.getShiftAmountConstant(1, VT, dl));
11685
11686 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
11687 SDValue OverflowShl = DAG.getNode(
11688 ISD::SHL, dl, VT, ZeroExtOverflow,
11689 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11690
11691 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
11692 }
11693
11694 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
11695 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
11696 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
11697 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
11698 LHS = DAG.getFreeze(LHS);
11699 RHS = DAG.getFreeze(RHS);
11700 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
11701 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
11702 SDValue Shift =
11703 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11704 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
11705}
11706
11708 SDLoc dl(N);
11709 EVT VT = N->getValueType(0);
11710 SDValue Op = N->getOperand(0);
11711
11712 if (!VT.isSimple())
11713 return SDValue();
11714
11715 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11716 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11717 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11718 default:
11719 return SDValue();
11720 case MVT::i16:
11721 // Use a rotate by 8. This can be further expanded if necessary.
11722 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11723 case MVT::i32:
11724 // This is meant for ARM specifically, which has ROTR but no ROTL.
11725 // t = x ^ rotr(x, 16)
11726 // t = bic(t, 0x00ff0000)
11727 // t = lshr(t, 8)
11728 // x = t ^ rotr(x, 8)
11730 SDValue Rotr16 =
11731 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
11732 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
11733 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
11734 DAG.getConstant(0xFF00FFFF, dl, VT));
11735 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
11736 SDValue Rotr8 =
11737 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11738 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
11739 }
11740 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11741 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
11742 DAG.getConstant(0xFF00, dl, VT));
11743 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
11744 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11745 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
11746 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11747 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11748 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11749 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11750 case MVT::i64:
11751 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11752 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
11753 DAG.getConstant(255ULL<<8, dl, VT));
11754 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
11755 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
11756 DAG.getConstant(255ULL<<16, dl, VT));
11757 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
11758 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
11759 DAG.getConstant(255ULL<<24, dl, VT));
11760 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
11761 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11762 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
11763 DAG.getConstant(255ULL<<24, dl, VT));
11764 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11765 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
11766 DAG.getConstant(255ULL<<16, dl, VT));
11767 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
11768 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
11769 DAG.getConstant(255ULL<<8, dl, VT));
11770 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11771 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
11772 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
11773 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11774 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11775 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
11776 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11777 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
11778 }
11779}
11780
11782 SDLoc dl(N);
11783 EVT VT = N->getValueType(0);
11784 SDValue Op = N->getOperand(0);
11785 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11786 unsigned Sz = VT.getScalarSizeInBits();
11787
11788 SDValue Tmp, Tmp2, Tmp3;
11789
11790 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
11791 // and finally the i1 pairs.
11792 // TODO: We can easily support i4/i2 legal types if any target ever does.
11793 if (Sz >= 8 && isPowerOf2_32(Sz)) {
11794 // Create the masks - repeating the pattern every byte.
11795 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
11796 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
11797 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
11798
11799 // BSWAP if the type is wider than a single byte.
11800 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
11801
11802 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
11803 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
11804 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
11805 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
11806 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
11807 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11808
11809 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
11810 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
11811 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
11812 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
11813 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
11814 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11815
11816 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
11817 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
11818 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
11819 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
11820 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
11821 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11822 return Tmp;
11823 }
11824
11825 Tmp = DAG.getConstant(0, dl, VT);
11826 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
11827 if (I < J)
11828 Tmp2 =
11829 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
11830 else
11831 Tmp2 =
11832 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
11833
11834 APInt Shift = APInt::getOneBitSet(Sz, J);
11835 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
11836 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
11837 }
11838
11839 return Tmp;
11840}
11841
11842std::pair<SDValue, SDValue>
11844 SelectionDAG &DAG) const {
11845 SDLoc SL(LD);
11846 SDValue Chain = LD->getChain();
11847 SDValue BasePTR = LD->getBasePtr();
11848 EVT SrcVT = LD->getMemoryVT();
11849 EVT DstVT = LD->getValueType(0);
11850 ISD::LoadExtType ExtType = LD->getExtensionType();
11851
11852 if (SrcVT.isScalableVector())
11853 report_fatal_error("Cannot scalarize scalable vector loads");
11854
11855 unsigned NumElem = SrcVT.getVectorNumElements();
11856
11857 EVT SrcEltVT = SrcVT.getScalarType();
11858 EVT DstEltVT = DstVT.getScalarType();
11859
11860 // A vector must always be stored in memory as-is, i.e. without any padding
11861 // between the elements, since various code depend on it, e.g. in the
11862 // handling of a bitcast of a vector type to int, which may be done with a
11863 // vector store followed by an integer load. A vector that does not have
11864 // elements that are byte-sized must therefore be stored as an integer
11865 // built out of the extracted vector elements.
11866 if (!SrcEltVT.isByteSized()) {
11867 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
11868 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
11869
11870 unsigned NumSrcBits = SrcVT.getSizeInBits();
11871 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
11872
11873 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
11874 SDValue SrcEltBitMask = DAG.getConstant(
11875 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
11876
11877 // Load the whole vector and avoid masking off the top bits as it makes
11878 // the codegen worse.
11879 SDValue Load = DAG.getExtLoad(
11880 ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, LD->getPointerInfo(),
11881 SrcIntVT, LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
11882 LD->getMMOMetadataForSubAccess());
11883
11885 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11886 unsigned ShiftIntoIdx =
11887 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
11888 SDValue ShiftAmount = DAG.getShiftAmountConstant(
11889 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
11890 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
11891 SDValue Elt =
11892 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
11893 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
11894
11895 if (ExtType != ISD::NON_EXTLOAD) {
11896 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
11897 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
11898 }
11899
11900 Vals.push_back(Scalar);
11901 }
11902
11903 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
11904 return std::make_pair(Value, Load.getValue(1));
11905 }
11906
11907 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
11908 assert(SrcEltVT.isByteSized());
11909
11911 SmallVector<SDValue, 8> LoadChains;
11912
11913 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11914 SDValue ScalarLoad = DAG.getExtLoad(
11915 ExtType, SL, DstEltVT, Chain, BasePTR,
11916 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
11917 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
11918 LD->getMMOMetadataForSubAccess());
11919
11920 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
11921
11922 Vals.push_back(ScalarLoad.getValue(0));
11923 LoadChains.push_back(ScalarLoad.getValue(1));
11924 }
11925
11926 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
11927 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
11928
11929 return std::make_pair(Value, NewChain);
11930}
11931
11933 SelectionDAG &DAG) const {
11934 SDLoc SL(ST);
11935
11936 SDValue Chain = ST->getChain();
11937 SDValue BasePtr = ST->getBasePtr();
11938 SDValue Value = ST->getValue();
11939 EVT StVT = ST->getMemoryVT();
11940
11941 if (StVT.isScalableVector())
11942 report_fatal_error("Cannot scalarize scalable vector stores");
11943
11944 // The type of the data we want to save
11945 EVT RegVT = Value.getValueType();
11946 EVT RegSclVT = RegVT.getScalarType();
11947
11948 // The type of data as saved in memory.
11949 EVT MemSclVT = StVT.getScalarType();
11950
11951 unsigned NumElem = StVT.getVectorNumElements();
11952
11953 // A vector must always be stored in memory as-is, i.e. without any padding
11954 // between the elements, since various code depend on it, e.g. in the
11955 // handling of a bitcast of a vector type to int, which may be done with a
11956 // vector store followed by an integer load. A vector that does not have
11957 // elements that are byte-sized must therefore be stored as an integer
11958 // built out of the extracted vector elements.
11959 if (!MemSclVT.isByteSized()) {
11960 unsigned NumBits = StVT.getSizeInBits();
11961 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
11962
11963 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
11964
11965 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11966 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
11967 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
11968 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
11969 unsigned ShiftIntoIdx =
11970 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
11971 SDValue ShiftAmount =
11972 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
11973 SDValue ShiftedElt =
11974 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
11975 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
11976 }
11977
11978 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
11979 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
11980 ST->getMMOMetadataForSubAccess());
11981 }
11982
11983 // Store Stride in bytes
11984 unsigned Stride = MemSclVT.getSizeInBits() / 8;
11985 assert(Stride && "Zero stride!");
11986 // Extract each of the elements from the original vector and save them into
11987 // memory individually.
11989 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11990 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
11991
11992 SDValue Ptr =
11993 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
11994
11995 // This scalar TruncStore may be illegal, but we legalize it later.
11997 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
11998 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
11999 ST->getMMOMetadataForSubAccess());
12000
12001 Stores.push_back(Store);
12002 }
12003
12004 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
12005}
12006
12007std::pair<SDValue, SDValue>
12009 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
12010 "unaligned indexed loads not implemented!");
12011 SDValue Chain = LD->getChain();
12012 SDValue Ptr = LD->getBasePtr();
12013 EVT VT = LD->getValueType(0);
12014 EVT LoadedVT = LD->getMemoryVT();
12015 SDLoc dl(LD);
12016 auto &MF = DAG.getMachineFunction();
12017
12018 if (VT.isFloatingPoint() || VT.isVector()) {
12019 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
12020 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
12021 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
12022 LoadedVT.isVector()) {
12023 // Scalarize the load and let the individual components be handled.
12024 return scalarizeVectorLoad(LD, DAG);
12025 }
12026
12027 // Expand to a (misaligned) integer load of the same size,
12028 // then bitconvert to floating point or vector.
12029 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
12030 LD->getMemOperand());
12031 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
12032 if (LoadedVT != VT)
12033 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
12034 ISD::ANY_EXTEND, dl, VT, Result);
12035
12036 return std::make_pair(Result, newLoad.getValue(1));
12037 }
12038
12039 // Copy the value to a (aligned) stack slot using (unaligned) integer
12040 // loads and stores, then do a (aligned) load from the stack slot.
12041 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
12042 unsigned LoadedBytes = LoadedVT.getStoreSize();
12043 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12044 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
12045
12046 // Make sure the stack slot is also aligned for the register type.
12047 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
12048 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
12050 SDValue StackPtr = StackBase;
12051 unsigned Offset = 0;
12052
12053 EVT PtrVT = Ptr.getValueType();
12054 EVT StackPtrVT = StackPtr.getValueType();
12055
12056 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12057 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12058
12059 // Do all but one copies using the full register width.
12060 for (unsigned i = 1; i < NumRegs; i++) {
12061 // Load one integer register's worth from the original location.
12062 SDValue Load = DAG.getLoad(
12063 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12064 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12065 LD->getMMOMetadataForSubAccess());
12066 // Follow the load with a store to the stack slot. Remember the store.
12067 Stores.push_back(DAG.getStore(
12068 Load.getValue(1), dl, Load, StackPtr,
12069 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12070 // Increment the pointers.
12071 Offset += RegBytes;
12072
12073 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12074 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12075 }
12076
12077 // The last copy may be partial. Do an extending load.
12078 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12079 8 * (LoadedBytes - Offset));
12080 SDValue Load = DAG.getExtLoad(
12081 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12082 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12083 LD->getMemOperand()->getFlags(), LD->getMMOMetadataForSubAccess());
12084 // Follow the load with a store to the stack slot. Remember the store.
12085 // On big-endian machines this requires a truncating store to ensure
12086 // that the bits end up in the right place.
12087 Stores.push_back(DAG.getTruncStore(
12088 Load.getValue(1), dl, Load, StackPtr,
12089 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12090
12091 // The order of the stores doesn't matter - say it with a TokenFactor.
12092 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12093
12094 // Finally, perform the original load only redirected to the stack slot.
12095 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12096 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12097 LoadedVT);
12098
12099 // Callers expect a MERGE_VALUES node.
12100 return std::make_pair(Load, TF);
12101 }
12102
12103 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12104 "Unaligned load of unsupported type.");
12105
12106 // Compute the new VT that is half the size of the old one. This is an
12107 // integer MVT.
12108 unsigned NumBits = LoadedVT.getSizeInBits();
12109 EVT NewLoadedVT;
12110 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12111 NumBits >>= 1;
12112
12113 Align Alignment = LD->getBaseAlign();
12114 unsigned IncrementSize = NumBits / 8;
12115 ISD::LoadExtType HiExtType = LD->getExtensionType();
12116
12117 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12118 if (HiExtType == ISD::NON_EXTLOAD)
12119 HiExtType = ISD::ZEXTLOAD;
12120
12121 // Load the value in two parts
12122 SDValue Lo, Hi;
12123 if (DAG.getDataLayout().isLittleEndian()) {
12124 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12125 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12126 LD->getMMOMetadataForSubAccess());
12127
12128 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12129 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12130 LD->getPointerInfo().getWithOffset(IncrementSize),
12131 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12132 LD->getMMOMetadataForSubAccess());
12133 } else {
12134 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12135 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12136 LD->getMMOMetadataForSubAccess());
12137
12138 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12139 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12140 LD->getPointerInfo().getWithOffset(IncrementSize),
12141 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12142 LD->getMMOMetadataForSubAccess());
12143 }
12144
12145 // aggregate the two parts
12146 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12147 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12148 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12149
12150 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12151 Hi.getValue(1));
12152
12153 return std::make_pair(Result, TF);
12154}
12155
12157 SelectionDAG &DAG) const {
12158 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12159 "unaligned indexed stores not implemented!");
12160 SDValue Chain = ST->getChain();
12161 SDValue Ptr = ST->getBasePtr();
12162 SDValue Val = ST->getValue();
12163 EVT VT = Val.getValueType();
12164 Align Alignment = ST->getBaseAlign();
12165 auto &MF = DAG.getMachineFunction();
12166 EVT StoreMemVT = ST->getMemoryVT();
12167
12168 SDLoc dl(ST);
12169 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12170 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12171 if (isTypeLegal(intVT)) {
12172 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12173 StoreMemVT.isVector()) {
12174 // Scalarize the store and let the individual components be handled.
12175 SDValue Result = scalarizeVectorStore(ST, DAG);
12176 return Result;
12177 }
12178 // Expand to a bitconvert of the value to the integer type of the
12179 // same size, then a (misaligned) int store.
12180 // FIXME: Does not handle truncating floating point stores!
12181 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12182 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12183 Alignment, ST->getMemOperand()->getFlags(),
12184 ST->getMMOMetadataForSubAccess());
12185 return Result;
12186 }
12187 // Do a (aligned) store to a stack slot, then copy from the stack slot
12188 // to the final destination using (unaligned) integer loads and stores.
12189 MVT RegVT = getRegisterType(
12190 *DAG.getContext(),
12191 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12192 EVT PtrVT = Ptr.getValueType();
12193 unsigned StoredBytes = StoreMemVT.getStoreSize();
12194 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12195 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12196
12197 // Make sure the stack slot is also aligned for the register type.
12198 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12199 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12200
12201 // Perform the original store, only redirected to the stack slot.
12203 Chain, dl, Val, StackPtr,
12204 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12205
12206 EVT StackPtrVT = StackPtr.getValueType();
12207
12208 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12209 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12211 unsigned Offset = 0;
12212
12213 // Do all but one copies using the full register width.
12214 for (unsigned i = 1; i < NumRegs; i++) {
12215 // Load one integer register's worth from the stack slot.
12216 SDValue Load = DAG.getLoad(
12217 RegVT, dl, Store, StackPtr,
12218 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12219 // Store it to the final location. Remember the store.
12220 Stores.push_back(DAG.getStore(
12221 Load.getValue(1), dl, Load, Ptr,
12222 ST->getPointerInfo().getWithOffset(Offset), ST->getBaseAlign(),
12223 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess()));
12224 // Increment the pointers.
12225 Offset += RegBytes;
12226 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12227 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12228 }
12229
12230 // The last store may be partial. Do a truncating store. On big-endian
12231 // machines this requires an extending load from the stack slot to ensure
12232 // that the bits are in the right place.
12233 EVT LoadMemVT =
12234 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12235
12236 // Load from the stack slot.
12237 SDValue Load = DAG.getExtLoad(
12238 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12239 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12240
12241 Stores.push_back(
12242 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
12243 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12244 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12245 ST->getMMOMetadataForSubAccess()));
12246 // The order of the stores doesn't matter - say it with a TokenFactor.
12247 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12248 return Result;
12249 }
12250
12251 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12252 "Unaligned store of unknown type.");
12253 // Get the half-size VT
12254 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12255 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12256 unsigned IncrementSize = NumBits / 8;
12257
12258 // Divide the stored value in two parts.
12259 SDValue ShiftAmount =
12260 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12261 SDValue Lo = Val;
12262 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12263 // fold and not use the upper bits. A smaller constant may be easier to
12264 // materialize.
12265 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12266 Lo = DAG.getNode(
12267 ISD::AND, dl, VT, Lo,
12268 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12269 VT));
12270 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12271
12272 // Store the two parts
12273 SDValue Store1, Store2;
12274 Store1 = DAG.getTruncStore(
12275 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Lo : Hi, Ptr,
12276 ST->getPointerInfo(), NewStoredVT, Alignment,
12277 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12278
12279 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12280 Store2 = DAG.getTruncStore(
12281 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12282 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12283 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12284
12285 SDValue Result =
12286 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12287 return Result;
12288}
12289
12290SDValue
12292 const SDLoc &DL, EVT DataVT,
12293 SelectionDAG &DAG,
12294 bool IsCompressedMemory) const {
12296 EVT AddrVT = Addr.getValueType();
12297 EVT MaskVT = Mask.getValueType();
12298 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12299 "Incompatible types of Data and Mask");
12300 if (IsCompressedMemory) {
12301 // Incrementing the pointer according to number of '1's in the mask.
12302 if (DataVT.isScalableVector()) {
12303 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12304 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12305 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12306 } else {
12307 EVT MaskIntVT =
12308 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12309 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12310 if (MaskIntVT.getSizeInBits() < 32) {
12311 MaskInIntReg =
12312 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12313 MaskIntVT = MVT::i32;
12314 }
12315 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12316 }
12317 // Scale is an element size in bytes.
12318 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12319 AddrVT);
12320 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12321 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12322 } else
12323 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12324
12325 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12326}
12327
12329 EVT VecVT, const SDLoc &dl,
12330 ElementCount SubEC) {
12331 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12332 "Cannot index a scalable vector within a fixed-width vector");
12333
12334 unsigned NElts = VecVT.getVectorMinNumElements();
12335 unsigned NumSubElts = SubEC.getKnownMinValue();
12336 EVT IdxVT = Idx.getValueType();
12337
12338 if (VecVT.isScalableVector() && !SubEC.isScalable()) {
12339 // If this is a constant index and we know the value plus the number of the
12340 // elements in the subvector minus one is less than the minimum number of
12341 // elements then it's safe to return Idx.
12342 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
12343 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
12344 return Idx;
12345 SDValue VS =
12346 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
12347 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
12348 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
12349 DAG.getConstant(NumSubElts, dl, IdxVT));
12350 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
12351 }
12352 if (isPowerOf2_32(NElts) && NumSubElts == 1) {
12354 return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
12355 DAG.getConstant(Imm, dl, IdxVT));
12356 }
12357 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
12358 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
12359 DAG.getConstant(MaxIndex, dl, IdxVT));
12360}
12361
12362SDValue
12364 EVT VecVT, SDValue Index,
12365 const SDNodeFlags PtrArithFlags) const {
12367 DAG, VecPtr, VecVT,
12369 Index, PtrArithFlags);
12370}
12371
12372SDValue
12374 EVT VecVT, EVT SubVecVT, SDValue Index,
12375 const SDNodeFlags PtrArithFlags) const {
12376 SDLoc dl(Index);
12377 // Make sure the index type is big enough to compute in.
12378 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12379
12380 EVT EltVT = VecVT.getVectorElementType();
12381
12382 // Calculate the element offset and add it to the pointer.
12383 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12384 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12385 "Converting bits to bytes lost precision");
12386 assert(SubVecVT.getVectorElementType() == EltVT &&
12387 "Sub-vector must be a vector with matching element type");
12388
12389 // An out-of-range index only makes the vector operation return poison, but
12390 // a load/store through the pointer computed below would be immediate UB, so
12391 // freeze the index before clamping it into range.
12392 if (!DAG.isGuaranteedNotToBePoison(Index))
12393 Index = DAG.getFreeze(Index);
12394
12395 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12396 SubVecVT.getVectorElementCount());
12397
12398 EVT IdxVT = Index.getValueType();
12399 if (SubVecVT.isScalableVector())
12400 Index =
12401 DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12402 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
12403
12404 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12405 DAG.getConstant(EltSize, dl, IdxVT));
12406 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12407}
12408
12409//===----------------------------------------------------------------------===//
12410// Implementation of Emulated TLS Model
12411//===----------------------------------------------------------------------===//
12412
12414 SelectionDAG &DAG) const {
12415 // Access to address of TLS varialbe xyz is lowered to a function call:
12416 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12417 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12418 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12419 SDLoc dl(GA);
12420
12421 ArgListTy Args;
12422 const GlobalValue *GV =
12424 SmallString<32> NameString("__emutls_v.");
12425 NameString += GV->getName();
12426 StringRef EmuTlsVarName(NameString);
12427 const GlobalVariable *EmuTlsVar =
12428 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12429 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12430 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12431
12432 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12433
12435 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12436 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12437 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12438
12439 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12440 // At last for X86 targets, maybe good for other targets too?
12442 MFI.setAdjustsStack(true); // Is this only for X86 target?
12443 MFI.setHasCalls(true);
12444
12445 assert((GA->getOffset() == 0) &&
12446 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12447 return CallResult.first;
12448}
12449
12451 SelectionDAG &DAG) const {
12452 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12453 if (!isCtlzFast())
12454 return SDValue();
12455 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12456 SDLoc dl(Op);
12457 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12458 EVT VT = Op.getOperand(0).getValueType();
12459 SDValue Zext = Op.getOperand(0);
12460 if (VT.bitsLT(MVT::i32)) {
12461 VT = MVT::i32;
12462 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12463 }
12464 unsigned Log2b = Log2_32(VT.getSizeInBits());
12465 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12466 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12467 DAG.getConstant(Log2b, dl, MVT::i32));
12468 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12469 }
12470 return SDValue();
12471}
12472
12474 SDValue Op0 = Node->getOperand(0);
12475 SDValue Op1 = Node->getOperand(1);
12476 EVT VT = Op0.getValueType();
12477 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12478 unsigned Opcode = Node->getOpcode();
12479 SDLoc DL(Node);
12480
12481 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12482 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12483 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12484 DAG.SignBitIsZero(Op1))
12485 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12486
12487 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12488 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12490 Op0 = DAG.getFreeze(Op0);
12491 SDValue Zero = DAG.getConstant(0, DL, VT);
12492 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12493 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12494 }
12495
12496 // umin(x,y) -> sub(x,usubsat(x,y))
12497 // TODO: Missing freeze(Op0)?
12498 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12500 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12501 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12502 }
12503
12504 // umax(x,y) -> add(x,usubsat(y,x))
12505 // TODO: Missing freeze(Op0)?
12506 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12508 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12509 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12510 }
12511
12512 // FIXME: Should really try to split the vector in case it's legal on a
12513 // subvector.
12515 return DAG.UnrollVectorOp(Node);
12516
12517 // Attempt to find an existing SETCC node that we can reuse.
12518 // TODO: Do we need a generic doesSETCCNodeExist?
12519 // TODO: Missing freeze(Op0)/freeze(Op1)?
12520 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12521 ISD::CondCode PrefCommuteCC,
12522 ISD::CondCode AltCommuteCC) {
12523 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12524 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12525 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12526 {Op0, Op1, DAG.getCondCode(CC)})) {
12527 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12528 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12529 }
12530 }
12531 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12532 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12533 {Op0, Op1, DAG.getCondCode(CC)})) {
12534 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12535 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12536 }
12537 }
12538 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12539 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12540 };
12541
12542 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12543 // -> Y = (A < B) ? B : A
12544 // -> Y = (A >= B) ? A : B
12545 // -> Y = (A <= B) ? B : A
12546 switch (Opcode) {
12547 case ISD::SMAX:
12548 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12549 case ISD::SMIN:
12550 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12551 case ISD::UMAX:
12552 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12553 case ISD::UMIN:
12554 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12555 }
12556
12557 llvm_unreachable("How did we get here?");
12558}
12559
12561 unsigned Opcode = Node->getOpcode();
12562 SDValue LHS = Node->getOperand(0);
12563 SDValue RHS = Node->getOperand(1);
12564 EVT VT = LHS.getValueType();
12565 SDLoc dl(Node);
12566
12567 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12568 assert(VT.isInteger() && "Expected operands to be integers");
12569
12570 // usub.sat(a, b) -> umax(a, b) - b
12571 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12572 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12573 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12574 }
12575
12576 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12577 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12578 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12580 LHS = DAG.getFreeze(LHS);
12581 SDValue Zero = DAG.getConstant(0, dl, VT);
12582 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12583 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12584 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12585 Subtrahend =
12586 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12587 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12588 }
12589
12590 // uadd.sat(a, b) -> umin(a, ~b) + b
12591 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12592 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12593 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12594 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12595 }
12596
12597 unsigned OverflowOp;
12598 switch (Opcode) {
12599 case ISD::SADDSAT:
12600 OverflowOp = ISD::SADDO;
12601 break;
12602 case ISD::UADDSAT:
12603 OverflowOp = ISD::UADDO;
12604 break;
12605 case ISD::SSUBSAT:
12606 OverflowOp = ISD::SSUBO;
12607 break;
12608 case ISD::USUBSAT:
12609 OverflowOp = ISD::USUBO;
12610 break;
12611 default:
12612 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12613 "addition or subtraction node.");
12614 }
12615
12616 // FIXME: Should really try to split the vector in case it's legal on a
12617 // subvector.
12619 return DAG.UnrollVectorOp(Node);
12620
12621 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12622 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12623 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12624 SDValue SumDiff = Result.getValue(0);
12625 SDValue Overflow = Result.getValue(1);
12626 SDValue Zero = DAG.getConstant(0, dl, VT);
12627 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12628
12629 if (Opcode == ISD::UADDSAT) {
12631 // (LHS + RHS) | OverflowMask
12632 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12633 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12634 }
12635 // Overflow ? 0xffff.... : (LHS + RHS)
12636 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12637 }
12638
12639 if (Opcode == ISD::USUBSAT) {
12641 // (LHS - RHS) & ~OverflowMask
12642 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12643 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12644 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12645 }
12646 // Overflow ? 0 : (LHS - RHS)
12647 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12648 }
12649
12650 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12651 "Expected signed saturating add/sub opcode");
12652
12653 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12654 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12655
12656 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12657 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12658
12659 // If either of the operand signs are known, then they are guaranteed to
12660 // only saturate in one direction. If non-negative they will saturate
12661 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12662 //
12663 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12664 // sign of 'y' has to be flipped.
12665
12666 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12667 bool RHSIsNonNegative =
12668 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12669 if (LHSIsNonNegative || RHSIsNonNegative) {
12670 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12671 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12672 }
12673
12674 bool LHSIsNegative = KnownLHS.isNegative();
12675 bool RHSIsNegative =
12676 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12677 if (LHSIsNegative || RHSIsNegative) {
12678 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12679 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
12680 }
12681
12682 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
12683 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12684 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
12685 DAG.getConstant(BitWidth - 1, dl, VT));
12686 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
12687 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
12688}
12689
12691 unsigned Opcode = Node->getOpcode();
12692 SDValue LHS = Node->getOperand(0);
12693 SDValue RHS = Node->getOperand(1);
12694 EVT VT = LHS.getValueType();
12695 EVT ResVT = Node->getValueType(0);
12696 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12697 SDLoc dl(Node);
12698
12699 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
12700 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
12701 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
12702 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
12703
12704 // We can't perform arithmetic on i1 values. Extending them would
12705 // probably result in worse codegen, so let's just use two selects instead.
12706 // Some targets are also just better off using selects rather than subtraction
12707 // because one of the conditions can be merged with one of the selects.
12708 // And finally, if we don't know the contents of high bits of a boolean value
12709 // we can't perform any arithmetic either.
12711 BoolVT.getScalarSizeInBits() == 1 ||
12713 SDValue SelectZeroOrOne =
12714 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
12715 DAG.getConstant(0, dl, ResVT));
12716 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
12717 SelectZeroOrOne);
12718 }
12719
12721 std::swap(IsGT, IsLT);
12722 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
12723 ResVT);
12724}
12725
12727 unsigned Opcode = Node->getOpcode();
12728 bool IsSigned = Opcode == ISD::SSHLSAT;
12729 SDValue LHS = Node->getOperand(0);
12730 SDValue RHS = Node->getOperand(1);
12731 EVT VT = LHS.getValueType();
12732 SDLoc dl(Node);
12733
12734 assert((Node->getOpcode() == ISD::SSHLSAT ||
12735 Node->getOpcode() == ISD::USHLSAT) &&
12736 "Expected a SHLSAT opcode");
12737 assert(VT.isInteger() && "Expected operands to be integers");
12738
12740 return DAG.UnrollVectorOp(Node);
12741
12742 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
12743
12744 unsigned BW = VT.getScalarSizeInBits();
12745 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12746 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
12747 SDValue Orig =
12748 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
12749
12750 SDValue SatVal;
12751 if (IsSigned) {
12752 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
12753 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
12754 SDValue Cond =
12755 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
12756 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
12757 } else {
12758 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
12759 }
12760 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
12761 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
12762}
12763
12765 bool Signed, SDValue &Lo, SDValue &Hi,
12766 SDValue LHS, SDValue RHS,
12767 SDValue HiLHS, SDValue HiRHS) const {
12768 EVT VT = LHS.getValueType();
12769 assert(RHS.getValueType() == VT && "Mismatching operand types");
12770
12771 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
12772 assert((!Signed || !HiLHS) &&
12773 "Signed flag should only be set when HiLHS and RiRHS are null");
12774
12775 // We'll expand the multiplication by brute force because we have no other
12776 // options. This is a trivially-generalized version of the code from
12777 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
12778 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
12779 // sign bits while calculating the Hi half.
12780 unsigned Bits = VT.getScalarSizeInBits();
12781 unsigned HalfBits = Bits / 2;
12782 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
12783 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
12784 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
12785
12786 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
12787 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
12788
12789 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
12790 // This is always an unsigned shift.
12791 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
12792
12793 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
12794 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
12795 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
12796
12797 SDValue U =
12798 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
12799 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
12800 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
12801
12802 SDValue V =
12803 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
12804 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
12805
12806 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
12807 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
12808
12809 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
12810 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
12811
12812 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
12813 // the products to Hi.
12814 if (HiLHS) {
12815 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
12816 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
12817 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
12818 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
12819 }
12820}
12821
12823 bool Signed, const SDValue LHS,
12824 const SDValue RHS, SDValue &Lo,
12825 SDValue &Hi) const {
12826 EVT VT = LHS.getValueType();
12827 assert(RHS.getValueType() == VT && "Mismatching operand types");
12828 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12829 // We can fall back to a libcall with an illegal type for the MUL if we
12830 // have a libcall big enough.
12831 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
12832 if (WideVT == MVT::i16)
12833 LC = RTLIB::MUL_I16;
12834 else if (WideVT == MVT::i32)
12835 LC = RTLIB::MUL_I32;
12836 else if (WideVT == MVT::i64)
12837 LC = RTLIB::MUL_I64;
12838 else if (WideVT == MVT::i128)
12839 LC = RTLIB::MUL_I128;
12840
12841 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
12842 if (LibcallImpl == RTLIB::Unsupported) {
12843 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
12844 return;
12845 }
12846
12847 SDValue HiLHS, HiRHS;
12848 if (Signed) {
12849 // The high part is obtained by SRA'ing all but one of the bits of low
12850 // part.
12851 unsigned LoSize = VT.getFixedSizeInBits();
12852 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
12853 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
12854 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
12855 } else {
12856 HiLHS = DAG.getConstant(0, dl, VT);
12857 HiRHS = DAG.getConstant(0, dl, VT);
12858 }
12859
12860 // Attempt a libcall.
12861 SDValue Ret;
12863 CallOptions.setIsSigned(Signed);
12864 CallOptions.setIsPostTypeLegalization(true);
12866 // Halves of WideVT are packed into registers in different order
12867 // depending on platform endianness. This is usually handled by
12868 // the C calling convention, but we can't defer to it in
12869 // the legalizer.
12870 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
12871 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12872 } else {
12873 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
12874 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12875 }
12877 "Ret value is a collection of constituent nodes holding result.");
12878 if (DAG.getDataLayout().isLittleEndian()) {
12879 // Same as above.
12880 Lo = Ret.getOperand(0);
12881 Hi = Ret.getOperand(1);
12882 } else {
12883 Lo = Ret.getOperand(1);
12884 Hi = Ret.getOperand(0);
12885 }
12886}
12887
12888SDValue
12890 assert((Node->getOpcode() == ISD::SMULFIX ||
12891 Node->getOpcode() == ISD::UMULFIX ||
12892 Node->getOpcode() == ISD::SMULFIXSAT ||
12893 Node->getOpcode() == ISD::UMULFIXSAT) &&
12894 "Expected a fixed point multiplication opcode");
12895
12896 SDLoc dl(Node);
12897 SDValue LHS = Node->getOperand(0);
12898 SDValue RHS = Node->getOperand(1);
12899 EVT VT = LHS.getValueType();
12900 unsigned Scale = Node->getConstantOperandVal(2);
12901 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
12902 Node->getOpcode() == ISD::UMULFIXSAT);
12903 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
12904 Node->getOpcode() == ISD::SMULFIXSAT);
12905 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12906 unsigned VTSize = VT.getScalarSizeInBits();
12907
12908 if (!Scale) {
12909 // [us]mul.fix(a, b, 0) -> mul(a, b)
12910 if (!Saturating) {
12912 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
12913 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
12914 SDValue Result =
12915 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12916 SDValue Product = Result.getValue(0);
12917 SDValue Overflow = Result.getValue(1);
12918 SDValue Zero = DAG.getConstant(0, dl, VT);
12919
12920 APInt MinVal = APInt::getSignedMinValue(VTSize);
12921 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
12922 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12923 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12924 // Xor the inputs, if resulting sign bit is 0 the product will be
12925 // positive, else negative.
12926 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
12927 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
12928 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
12929 return DAG.getSelect(dl, VT, Overflow, Result, Product);
12930 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
12931 SDValue Result =
12932 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12933 SDValue Product = Result.getValue(0);
12934 SDValue Overflow = Result.getValue(1);
12935
12936 APInt MaxVal = APInt::getMaxValue(VTSize);
12937 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12938 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
12939 }
12940 }
12941
12942 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
12943 "Expected scale to be less than the number of bits if signed or at "
12944 "most the number of bits if unsigned.");
12945 assert(LHS.getValueType() == RHS.getValueType() &&
12946 "Expected both operands to be the same type");
12947
12948 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
12949 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
12950 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
12951 SDValue Val, ISD::CondCode CC) {
12952 if (VT.isVector())
12953 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
12954 Sat, Val);
12955 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
12956 };
12957
12958 // Get the upper and lower bits of the result.
12959 SDValue Lo, Hi;
12960 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
12961 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
12962 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12963 if (isOperationLegalOrCustom(LoHiOp, VT)) {
12964 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
12965 Lo = Result.getValue(0);
12966 Hi = Result.getValue(1);
12967 } else if (isOperationLegalOrCustom(HiOp, VT)) {
12968 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
12969 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
12970 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
12971 // Try for a multiplication using a wider type.
12972 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
12973 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
12974 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
12975 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
12976 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
12977 SDValue Shifted =
12978 DAG.getNode(ISD::SRA, dl, WideVT, Res,
12979 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
12980 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
12981 } else if (VT.isVector()) {
12982 return SDValue();
12983 } else {
12984 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
12985 }
12986
12987 if (Scale == VTSize)
12988 // Result is just the top half since we'd be shifting by the width of the
12989 // operand. Overflow impossible so this works for both UMULFIX and
12990 // UMULFIXSAT.
12991 return Hi;
12992
12993 // The result will need to be shifted right by the scale since both operands
12994 // are scaled. The result is given to us in 2 halves, so we only want part of
12995 // both in the result.
12996 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
12997 DAG.getShiftAmountConstant(Scale, VT, dl));
12998 if (!Saturating)
12999 return Result;
13000
13001 if (!Signed) {
13002 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
13003 // widened multiplication) aren't all zeroes.
13004
13005 // Saturate to max if ((Hi >> Scale) != 0),
13006 // which is the same as if (Hi > ((1 << Scale) - 1))
13007 APInt MaxVal = APInt::getMaxValue(VTSize);
13008 SDValue LowMask =
13009 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
13010 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
13011 Result, ISD::SETUGT);
13012 }
13013
13014 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
13015 // widened multiplication) aren't all ones or all zeroes.
13016
13017 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
13018 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
13019
13020 if (Scale == 0) {
13021 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
13022 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
13023 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
13024 // Saturated to SatMin if wide product is negative, and SatMax if wide
13025 // product is positive ...
13026 SDValue Zero = DAG.getConstant(0, dl, VT);
13027 SDValue ResultIfOverflow =
13028 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
13029 // ... but only if we overflowed.
13030 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
13031 }
13032
13033 // We handled Scale==0 above so all the bits to examine is in Hi.
13034
13035 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
13036 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
13037 SDValue LowMask =
13038 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
13039 // Saturate to min if (Hi >> (Scale - 1)) < -1),
13040 // which is the same as if (HI < (-1 << (Scale - 1))
13041 SDValue HighMask = DAG.getConstant(
13042 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
13043 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
13044 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
13045 return Result;
13046}
13047
13048SDValue
13050 SDValue LHS, SDValue RHS,
13051 unsigned Scale, SelectionDAG &DAG) const {
13052 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
13053 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
13054 "Expected a fixed point division opcode");
13055
13056 EVT VT = LHS.getValueType();
13057 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
13058 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
13059 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13060
13061 // If there is enough room in the type to upscale the LHS or downscale the
13062 // RHS before the division, we can perform it in this type without having to
13063 // resize. For signed operations, the LHS headroom is the number of
13064 // redundant sign bits, and for unsigned ones it is the number of zeroes.
13065 // The headroom for the RHS is the number of trailing zeroes.
13066 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
13068 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
13069
13070 // For signed saturating operations, we need to be able to detect true integer
13071 // division overflow; that is, when you have MIN / -EPS. However, this
13072 // is undefined behavior and if we emit divisions that could take such
13073 // values it may cause undesired behavior (arithmetic exceptions on x86, for
13074 // example).
13075 // Avoid this by requiring an extra bit so that we never get this case.
13076 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13077 // signed saturating division, we need to emit a whopping 32-bit division.
13078 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13079 return SDValue();
13080
13081 unsigned LHSShift = std::min(LHSLead, Scale);
13082 unsigned RHSShift = Scale - LHSShift;
13083
13084 // At this point, we know that if we shift the LHS up by LHSShift and the
13085 // RHS down by RHSShift, we can emit a regular division with a final scaling
13086 // factor of Scale.
13087
13088 if (LHSShift)
13089 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13090 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13091 if (RHSShift)
13092 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13093 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13094
13095 SDValue Quot;
13096 if (Signed) {
13097 // For signed operations, if the resulting quotient is negative and the
13098 // remainder is nonzero, subtract 1 from the quotient to round towards
13099 // negative infinity.
13100 SDValue Rem;
13101 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13102 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13103 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13104 if (isTypeLegal(VT) &&
13106 Quot = DAG.getNode(ISD::SDIVREM, dl,
13107 DAG.getVTList(VT, VT),
13108 LHS, RHS);
13109 Rem = Quot.getValue(1);
13110 Quot = Quot.getValue(0);
13111 } else {
13112 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13113 LHS, RHS);
13114 Rem = DAG.getNode(ISD::SREM, dl, VT,
13115 LHS, RHS);
13116 }
13117 SDValue Zero = DAG.getConstant(0, dl, VT);
13118 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13119 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13120 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13121 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13122 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13123 DAG.getConstant(1, dl, VT));
13124 Quot = DAG.getSelect(dl, VT,
13125 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13126 Sub1, Quot);
13127 } else
13128 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13129 LHS, RHS);
13130
13131 return Quot;
13132}
13133
13135 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13136 SDLoc dl(Node);
13137 SDValue LHS = Node->getOperand(0);
13138 SDValue RHS = Node->getOperand(1);
13139 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13140
13141 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13142 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13143 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13144 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13145 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13146 { LHS, RHS, CarryIn });
13147 Result = SDValue(NodeCarry.getNode(), 0);
13148 Overflow = SDValue(NodeCarry.getNode(), 1);
13149 return;
13150 }
13151
13152 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13153 LHS.getValueType(), LHS, RHS);
13154
13155 EVT ResultType = Node->getValueType(1);
13156 EVT SetCCType = getSetCCResultType(
13157 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13158 SDValue SetCC;
13159 if (IsAdd && isOneConstant(RHS)) {
13160 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13161 // the live range of X. We assume comparing with 0 is cheap.
13162 // The general case (X + C) < C is not necessarily beneficial. Although we
13163 // reduce the live range of X, we may introduce the materialization of
13164 // constant C.
13165 SetCC =
13166 DAG.getSetCC(dl, SetCCType, Result,
13167 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13168 } else if (IsAdd && isAllOnesConstant(RHS)) {
13169 // Special case: uaddo X, -1 overflows if X != 0.
13170 SetCC =
13171 DAG.getSetCC(dl, SetCCType, LHS,
13172 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13173 } else {
13174 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
13175 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13176 }
13177 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13178}
13179
13181 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13182 SDLoc dl(Node);
13183 SDValue LHS = Node->getOperand(0);
13184 SDValue RHS = Node->getOperand(1);
13185 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13186
13187 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13188 LHS.getValueType(), LHS, RHS);
13189
13190 EVT ResultType = Node->getValueType(1);
13191 EVT OType = getSetCCResultType(
13192 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13193
13194 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13195 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13196 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13197 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13198 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13199 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13200 return;
13201 }
13202
13203 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13204
13205 if (IsAdd) {
13206 // For an addition, the result should be less than one of the operands (LHS)
13207 // if and only if the other operand (RHS) is negative, otherwise there will
13208 // be overflow.
13209 SDValue ResultLowerThanLHS =
13210 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13211 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13212 Overflow = DAG.getBoolExtOrTrunc(
13213 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13214 ResultType, ResultType);
13215 } else {
13216 // For subtraction, overflow occurs when the signed comparison of operands
13217 // doesn't match the sign of the result.
13218 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13219 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13220 Overflow = DAG.getBoolExtOrTrunc(
13221 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13222 ResultType, ResultType);
13223 }
13224}
13225
13227 SDValue &Overflow, SelectionDAG &DAG) const {
13228 SDLoc dl(Node);
13229 EVT VT = Node->getValueType(0);
13230 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13231 SDValue LHS = Node->getOperand(0);
13232 SDValue RHS = Node->getOperand(1);
13233 bool isSigned = Node->getOpcode() == ISD::SMULO;
13234
13235 // For power-of-two multiplications we can use a simpler shift expansion.
13236 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13237 const APInt &C = RHSC->getAPIntValue();
13238 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13239 if (C.isPowerOf2()) {
13240 // smulo(x, signed_min) is same as umulo(x, signed_min).
13241 bool UseArithShift = isSigned && !C.isMinSignedValue();
13242 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13243 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13244 Overflow = DAG.getSetCC(dl, SetCCVT,
13245 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13246 dl, VT, Result, ShiftAmt),
13247 LHS, ISD::SETNE);
13248 return true;
13249 }
13250 }
13251
13252 SDValue BottomHalf;
13253 SDValue TopHalf;
13254 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13255
13256 static const unsigned Ops[2][3] =
13259 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13260 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13261 RHS);
13262 TopHalf = BottomHalf.getValue(1);
13263 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13264 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13265 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13266 } else if (isTypeLegal(WideVT)) {
13267 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13268 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13269 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13270 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13271 SDValue ShiftAmt =
13272 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13273 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13274 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13275 } else {
13276 if (VT.isVector())
13277 return false;
13278
13279 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13280 }
13281
13282 Result = BottomHalf;
13283 if (isSigned) {
13284 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13285 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13286 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13287 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13288 } else {
13289 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13290 DAG.getConstant(0, dl, VT), ISD::SETNE);
13291 }
13292
13293 // Truncate the result if SetCC returns a larger type than needed.
13294 EVT RType = Node->getValueType(1);
13295 if (RType.bitsLT(Overflow.getValueType()))
13296 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13297
13298 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13299 "Unexpected result type for S/UMULO legalization");
13300 return true;
13301}
13302
13304 SDLoc dl(Node);
13305 EVT VT = Node->getValueType(0);
13306 SDValue LHS = Node->getOperand(0);
13307 SDValue RHS = Node->getOperand(1);
13308 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13309
13310 // Use MUL_LOHI if legal/custom for the original type.
13311 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13312 if (isOperationLegalOrCustom(LoHiOp, VT))
13313 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13314
13315 // Use a wide multiply if available.
13316 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13317 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13318 unsigned BW = VT.getScalarSizeInBits();
13319 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13320 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13321 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13322 DAG.getNode(ISD::SRL, dl, WideVT,
13323 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13324 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13325 }
13326
13327 // Let fixed-length vectors be scalarised by the caller.
13328 // Expand everything else with a wide multiply.
13329 if (!VT.isFixedLengthVector()) {
13330 SDValue Lo, Hi;
13331 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13332 return Hi;
13333 }
13334
13335 return SDValue();
13336}
13337
13339 SDLoc dl(Node);
13340 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13341 SDValue Op = Node->getOperand(0);
13342 SDNodeFlags Flags = Node->getFlags();
13343 EVT VT = Op.getValueType();
13344
13345 // Try to use a shuffle reduction for power of two vectors.
13346 if (VT.isPow2VectorType()) {
13347 // See if the reduction opcode is safe to use with widened types.
13348 bool WidenSrc = false;
13349 switch (Node->getOpcode()) {
13352 case ISD::VECREDUCE_ADD:
13353 case ISD::VECREDUCE_MUL:
13354 case ISD::VECREDUCE_AND:
13355 case ISD::VECREDUCE_OR:
13356 case ISD::VECREDUCE_XOR:
13361 WidenSrc = VT.isFixedLengthVector();
13362 break;
13363 }
13364
13366 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13367 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13368 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13369 // Attempt to widen the source vectors to a legal op.
13370 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13371 if (WideVT.isVector() &&
13372 WideVT.getScalarType() == HalfVT.getScalarType() &&
13373 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13374 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13375 SDValue Lo, Hi;
13376 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13377 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13378 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13379 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13380 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13381 VT = HalfVT;
13382 continue;
13383 }
13384 }
13385 break;
13386 }
13387
13388 SDValue Lo, Hi;
13389 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13390 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13391 VT = HalfVT;
13392
13393 // Stop if splitting is enough to make the reduction legal.
13394 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13395 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13396 Flags);
13397 }
13398 }
13399
13400 if (VT.isScalableVector())
13402 "Expanding reductions for scalable vectors is undefined.");
13403
13404 EVT EltVT = VT.getVectorElementType();
13405 unsigned NumElts = VT.getVectorNumElements();
13406
13408 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13409
13410 SDValue Res = Ops[0];
13411 for (unsigned i = 1; i < NumElts; i++)
13412 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13413
13414 // Result type may be wider than element type.
13415 if (EltVT != Node->getValueType(0))
13416 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13417 return Res;
13418}
13419
13421 SDLoc dl(Node);
13422 SDValue AccOp = Node->getOperand(0);
13423 SDValue VecOp = Node->getOperand(1);
13424 SDNodeFlags Flags = Node->getFlags();
13425
13426 EVT VT = VecOp.getValueType();
13427 EVT EltVT = VT.getVectorElementType();
13428
13429 if (VT.isScalableVector())
13431 "Expanding reductions for scalable vectors is undefined.");
13432
13433 unsigned NumElts = VT.getVectorNumElements();
13434
13436 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13437
13438 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13439
13440 SDValue Res = AccOp;
13441 for (unsigned i = 0; i < NumElts; i++)
13442 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13443
13444 return Res;
13445}
13446
13448 SelectionDAG &DAG) const {
13449 EVT VT = Node->getValueType(0);
13450 SDLoc dl(Node);
13451 bool isSigned = Node->getOpcode() == ISD::SREM;
13452 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13453 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13454 SDValue Dividend = Node->getOperand(0);
13455 SDValue Divisor = Node->getOperand(1);
13456 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13457 SDVTList VTs = DAG.getVTList(VT, VT);
13458 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13459 return true;
13460 }
13461 if (isOperationLegalOrCustom(DivOpc, VT)) {
13462 // X % Y -> X-X/Y*Y
13463 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13464 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13465 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13466 return true;
13467 }
13468 return false;
13469}
13470
13472 SelectionDAG &DAG) const {
13473 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13474 SDLoc dl(SDValue(Node, 0));
13475 SDValue Src = Node->getOperand(0);
13476
13477 // DstVT is the result type, while SatVT is the size to which we saturate
13478 EVT SrcVT = Src.getValueType();
13479 EVT DstVT = Node->getValueType(0);
13480
13481 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13482 unsigned SatWidth = SatVT.getScalarSizeInBits();
13483 unsigned DstWidth = DstVT.getScalarSizeInBits();
13484 assert(SatWidth <= DstWidth &&
13485 "Expected saturation width smaller than result width");
13486
13487 // Determine minimum and maximum integer values and their corresponding
13488 // floating-point values.
13489 APInt MinInt, MaxInt;
13490 if (IsSigned) {
13491 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13492 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13493 } else {
13494 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13495 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13496 }
13497
13498 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13499 // libcall emission cannot handle this. Large result types will fail.
13500 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13501 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13502 SrcVT = Src.getValueType();
13503 }
13504
13505 const fltSemantics &Sem = SrcVT.getFltSemantics();
13506 APFloat MinFloat(Sem);
13507 APFloat MaxFloat(Sem);
13508
13509 APFloat::opStatus MinStatus =
13510 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13511 APFloat::opStatus MaxStatus =
13512 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13513 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13514 !(MaxStatus & APFloat::opStatus::opInexact);
13515
13516 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13517 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13518
13519 // If the integer bounds are exactly representable as floats and min/max are
13520 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13521 // of comparisons and selects.
13522 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13523 bool MayPropagateNaN) {
13524 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13525 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13526 if (!MinMaxLegal)
13527 return SDValue();
13528
13529 SDValue Clamped = Src;
13530
13531 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13532 // then the result is MinFloat.
13533 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13534 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13535 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13536 // Convert clamped value to integer.
13537 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13538 dl, DstVT, Clamped);
13539
13540 // If !MayPropagateNan and the conversion is unsigned case we're done,
13541 // because we mapped NaN to MinFloat, which will cast to zero.
13542 if (!MayPropagateNaN && !IsSigned)
13543 return FpToInt;
13544
13545 // Otherwise, select 0 if Src is NaN.
13546 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13547 EVT SetCCVT =
13548 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13549 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13550 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13551 };
13552 if (AreExactFloatBounds) {
13553 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13554 /*MayPropagateNaN=*/false))
13555 return Res;
13556 // These may propagate NaN for sNaN operands.
13557 if (SDValue Res =
13558 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13559 return Res;
13560 // These always propagate NaN.
13561 if (SDValue Res =
13562 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13563 return Res;
13564 }
13565
13566 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13567 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13568
13569 // Result of direct conversion. The assumption here is that the operation is
13570 // non-trapping and it's fine to apply it to an out-of-range value if we
13571 // select it away later.
13572 SDValue FpToInt =
13573 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13574
13575 SDValue Select = FpToInt;
13576
13577 EVT SetCCVT =
13578 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13579
13580 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13581 // MinInt if Src is NaN.
13582 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13583 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13584 // If Src OGT MaxFloat, select MaxInt.
13585 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13586 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13587
13588 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13589 // is already zero.
13590 if (!IsSigned)
13591 return Select;
13592
13593 // Otherwise, select 0 if Src is NaN.
13594 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13595 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13596 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13597}
13598
13600 const SDLoc &dl,
13601 SelectionDAG &DAG) const {
13602 EVT OperandVT = Op.getValueType();
13603 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13604 return Op;
13605 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13606 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13607 // can induce double-rounding which may alter the results. We can
13608 // correct for this using a trick explained in: Boldo, Sylvie, and
13609 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13610 // World Congress. 2005.
13611 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13612 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13613
13614 // We can keep the narrow value as-is if narrowing was exact (no
13615 // rounding error), the wide value was NaN (the narrow value is also
13616 // NaN and should be preserved) or if we rounded to the odd value.
13617 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13618 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13619 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13620 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13621 EVT ResultIntVTCCVT = getSetCCResultType(
13622 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13623 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13624 // The result is already odd so we don't need to do anything.
13625 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13626
13627 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13628 Op.getValueType());
13629 // We keep results which are exact, odd or NaN.
13630 SDValue KeepNarrow =
13631 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13632 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13633 // We morally performed a round-down if AbsNarrow is smaller than
13634 // AbsWide.
13635 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13636 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13637 SDValue NarrowIsRd =
13638 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13639 // If the narrow value is odd or exact, pick it.
13640 // Otherwise, narrow is even and corresponds to either the rounded-up
13641 // or rounded-down value. If narrow is the rounded-down value, we want
13642 // the rounded-up value as it will be odd.
13643 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13644 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13645 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13646 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13647}
13648
13650 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13651 SDValue Op = Node->getOperand(0);
13652 EVT VT = Node->getValueType(0);
13653 SDLoc dl(Node);
13654 if (VT.getScalarType() == MVT::bf16) {
13655 if (Node->getConstantOperandVal(1) == 1) {
13656 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13657 }
13658 EVT OperandVT = Op.getValueType();
13659 SDValue IsNaN = DAG.getSetCC(
13660 dl,
13661 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
13662 Op, Op, ISD::SETUO);
13663
13664 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13665 // can induce double-rounding which may alter the results. We can
13666 // correct for this using a trick explained in: Boldo, Sylvie, and
13667 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13668 // World Congress. 2005.
13669 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
13670 EVT I32 = F32.changeTypeToInteger();
13671 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
13672 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
13673
13674 // Conversions should set NaN's quiet bit. This also prevents NaNs from
13675 // turning into infinities.
13676 SDValue NaN =
13677 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
13678
13679 // Factor in the contribution of the low 16 bits.
13680 SDValue One = DAG.getConstant(1, dl, I32);
13681 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
13682 DAG.getShiftAmountConstant(16, I32, dl));
13683 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
13684 SDValue RoundingBias =
13685 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
13686 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
13687
13688 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
13689 // 0x80000000.
13690 Op = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
13691
13692 // Now that we have rounded, shift the bits into position.
13693 Op = DAG.getNode(ISD::SRL, dl, I32, Op,
13694 DAG.getShiftAmountConstant(16, I32, dl));
13695 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
13696 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
13697 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13698 }
13699 return SDValue();
13700}
13701
13703 SelectionDAG &DAG) const {
13704 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
13705 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
13706 "Unexpected opcode!");
13707 assert((Node->getValueType(0).isScalableVector() ||
13708 !isa<ConstantSDNode>(Node->getOperand(2))) &&
13709 "Fixed length vector types with constant offsets expected to use "
13710 "SHUFFLE_VECTOR!");
13711
13712 EVT VT = Node->getValueType(0);
13713 SDValue V1 = Node->getOperand(0);
13714 SDValue V2 = Node->getOperand(1);
13715 SDValue Offset = Node->getOperand(2);
13716 SDLoc DL(Node);
13717
13718 // Expand through memory thusly:
13719 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
13720 // Store V1, Ptr
13721 // Store V2, Ptr + sizeof(V1)
13722 // if (VECTOR_SPLICE_LEFT)
13723 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
13724 // else
13725 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
13726 // Res = Load Ptr
13727
13728 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
13729
13731 VT.getVectorElementCount() * 2);
13732 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
13733 EVT PtrVT = StackPtr.getValueType();
13734 auto &MF = DAG.getMachineFunction();
13735 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13736 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
13737
13738 // Store the lo part of CONCAT_VECTORS(V1, V2)
13739 SDValue StoreV1 =
13740 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
13741 // Store the hi part of CONCAT_VECTORS(V1, V2)
13742 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
13743 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
13744 SDValue StoreV2 =
13745 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
13746
13747 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
13748 SDValue EltByteSize =
13749 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
13750 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
13751 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
13752
13753 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
13754
13755 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
13756 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
13757 else
13758 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
13759
13760 // Load the spliced result
13761 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
13763}
13764
13766 SelectionDAG &DAG) const {
13767 SDLoc DL(Node);
13768 SDValue Vec = Node->getOperand(0);
13769 SDValue Mask = Node->getOperand(1);
13770 SDValue Passthru = Node->getOperand(2);
13771
13772 EVT VecVT = Vec.getValueType();
13773 EVT ScalarVT = VecVT.getScalarType();
13774 EVT MaskVT = Mask.getValueType();
13775 EVT MaskScalarVT = MaskVT.getScalarType();
13776
13777 // Needs to be handled by targets that have scalable vector types.
13778 if (VecVT.isScalableVector())
13779 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
13780
13781 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
13782 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
13783 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13784 MachinePointerInfo PtrInfo =
13786
13787 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
13788 SDValue Chain = DAG.getEntryNode();
13789 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
13790
13791 bool HasPassthru = !Passthru.isUndef();
13792
13793 // If we have a passthru vector, store it on the stack, overwrite the matching
13794 // positions and then re-write the last element that was potentially
13795 // overwritten even though mask[i] = false.
13796 if (HasPassthru)
13797 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
13798
13799 SDValue LastWriteVal;
13800 APInt PassthruSplatVal;
13801 bool IsSplatPassthru =
13802 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal);
13803
13804 if (IsSplatPassthru) {
13805 // As we do not know which position we wrote to last, we cannot simply
13806 // access that index from the passthru vector. So we first check if passthru
13807 // is a splat vector, to use any element ...
13808 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
13809 } else if (HasPassthru) {
13810 // ... if it is not a splat vector, we need to get the passthru value at
13811 // position = popcount(mask) and re-load it from the stack before it is
13812 // overwritten in the loop below.
13813 EVT PopcountVT = ScalarVT.changeTypeToInteger();
13814 SDValue Popcount = DAG.getNode(
13816 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
13817 Popcount = DAG.getNode(
13819 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
13820 Popcount);
13821 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
13822 SDValue LastElmtPtr =
13823 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
13824 LastWriteVal = DAG.getLoad(
13825 ScalarVT, DL, Chain, LastElmtPtr,
13827 Chain = LastWriteVal.getValue(1);
13828 }
13829
13830 unsigned NumElms = VecVT.getVectorNumElements();
13831 for (unsigned I = 0; I < NumElms; I++) {
13832 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
13833 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
13834 Chain = DAG.getStore(
13835 Chain, DL, ValI, OutPtr,
13837
13838 // Get the mask value and add it to the current output position. This
13839 // either increments by 1 if MaskI is true or adds 0 otherwise.
13840 // Freeze in case we have poison/undef mask entries.
13841 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
13842 MaskI = DAG.getFreeze(MaskI);
13843 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
13844 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
13845 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
13846
13847 if (HasPassthru && I == NumElms - 1) {
13848 SDValue EndOfVector =
13849 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
13850 SDValue AllLanesSelected =
13851 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
13852 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
13853 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
13854
13855 // Re-write the last ValI if all lanes were selected. Otherwise,
13856 // overwrite the last write it with the passthru value.
13857 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
13858 LastWriteVal, SDNodeFlags::Unpredictable);
13859 Chain = DAG.getStore(
13860 Chain, DL, LastWriteVal, OutPtr,
13862 }
13863 }
13864
13865 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
13866}
13867
13869 SDLoc DL(Node);
13870 EVT VT = Node->getValueType(0);
13871 SDValue Op = Node->getOperand(0);
13872 ElementCount EC = Op.getValueType().getVectorElementCount();
13873
13874 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
13875 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
13876
13877 // No legal step vector: split mask in half and recombine results.
13878 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
13879 // (== LoNumElts when no active lane), allowing the SETNE comparison.
13880 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
13881 if (!StepVec) {
13882 EVT ResVT = Node->getValueType(0);
13883 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
13884 SDValue LoNumElts = DAG.getElementCount(
13885 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
13886 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
13887 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
13888 SDValue ResLoNotNumElts = DAG.getSetCC(
13889 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
13890 ResLo, LoNumElts, ISD::SETNE);
13891 // Per LangRef, ResVT must be wide enough to hold the total element count,
13892 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
13893 // the count is only required to fit unsigned.
13894 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
13896 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
13897 }
13898
13899 EVT StepVecVT = StepVec.getValueType();
13900 EVT StepVT = StepVecVT.getVectorElementType();
13901
13902 // Promote the scalar result type early to avoid redundant zexts.
13904 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
13905
13906 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
13907 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
13908 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
13909 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
13910 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
13912 StepVecVT.getVectorElementType(), Select);
13913 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
13914 DAG.getZExtOrTrunc(Max, DL, StepVT));
13915
13916 return DAG.getZExtOrTrunc(Sub, DL, VT);
13917}
13918
13920 SDLoc DL(N);
13921 SDValue Source = N->getOperand(0);
13922 SDValue Needle = N->getOperand(1);
13923 SDValue Mask = N->getOperand(2);
13924 EVT SourceVT = Source.getValueType();
13925 EVT NeedleVT = Needle.getValueType();
13926 EVT ResVT = N->getValueType(0);
13927 EVT CmpVT =
13928 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
13929
13930 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
13931
13932 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
13933 EVT NeedleEltVT = NeedleVT.getVectorElementType();
13934 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
13935 SDValue Splat;
13936 if (NeedleVT == SourceVT) {
13937 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
13938 Splat = DAG.getVectorShuffle(
13939 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
13941 } else {
13942 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
13943 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
13944 }
13945 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
13946 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
13947 }
13948
13949 EVT UseVT = ResVT;
13950 // If the result is immediately truncated, only extend to that type (to avoid
13951 // unnecessary sign/zero extends).
13952 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
13953 UseVT = N->user_begin()->getValueType(0);
13954
13955 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
13956 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
13957
13958 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
13959 if (UseVT != ResVT)
13960 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
13961 return Ret;
13962}
13963
13965 SelectionDAG &DAG) const {
13966 SDLoc DL(N);
13967 SDValue Acc = N->getOperand(0);
13968 SDValue MulLHS = N->getOperand(1);
13969 SDValue MulRHS = N->getOperand(2);
13970 EVT AccVT = Acc.getValueType();
13971 EVT MulOpVT = MulLHS.getValueType();
13972
13973 EVT ExtMulOpVT =
13975 MulOpVT.getVectorElementCount());
13976
13977 unsigned ExtOpcLHS, ExtOpcRHS;
13978 switch (N->getOpcode()) {
13979 default:
13980 llvm_unreachable("Unexpected opcode");
13982 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
13983 break;
13985 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
13986 break;
13988 ExtOpcLHS = ISD::SIGN_EXTEND;
13989 ExtOpcRHS = ISD::ZERO_EXTEND;
13990 break;
13992 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
13993 break;
13994 }
13995
13996 // A wide partial reduction is built from a ladder of narrower ones, a rung
13997 // at a time, each halving the element count and doubling the width.
13998 unsigned Opc = N->getOpcode();
13999 ElementCount MulEC = MulOpVT.getVectorElementCount();
14000 ElementCount AccEC = AccVT.getVectorElementCount();
14001 unsigned CountRatio =
14002 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
14003 unsigned WidthRatio =
14004 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
14005 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
14006 LLVMContext &Ctx = *DAG.getContext();
14007 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
14008
14009 // A pure reduction peels one rung and re-enters.
14010 if (llvm::isOneOrOneSplat(MulRHS)) {
14011 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
14012 return DAG.getNode(Opc, DL, AccVT, Acc,
14013 DAG.getNode(Opc, DL, RungVT,
14014 DAG.getConstant(0, DL, RungVT), MulLHS,
14015 MulRHS),
14016 DAG.getConstant(1, DL, RungVT));
14017 }
14018
14019 // A multiply widens the products by one rung, which legalizes back into a
14020 // widening multiply per half, and the ladder re-enters as a plain sum.
14021 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
14022 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
14023 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
14024 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
14025 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
14026
14027 // The halves meet at the narrowest rung, so the accumulator is added once.
14028 EVT MidVT = Lo.getValueType()
14029 .widenIntegerVectorElementType(Ctx)
14030 .getHalfNumVectorElementsVT(Ctx);
14032 return DAG.getNode(Opc, DL, AccVT,
14033 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
14034 SDValue Mid =
14035 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
14036 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
14037 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
14038 }
14039
14040 if (ExtMulOpVT != MulOpVT) {
14041 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
14042 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
14043 }
14044 SDValue Input = MulLHS;
14045 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
14046 if (!llvm::isOneOrOneSplatFP(MulRHS))
14047 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14048 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
14049 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14050 }
14051
14052 unsigned Stride = AccVT.getVectorMinNumElements();
14053 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
14054
14055 // Collect all of the subvectors
14056 std::deque<SDValue> Subvectors = {Acc};
14057 for (unsigned I = 0; I < ScaleFactor; I++)
14058 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
14059
14060 unsigned FlatNode =
14061 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
14062
14063 // Flatten the subvector tree
14064 while (Subvectors.size() > 1) {
14065 Subvectors.push_back(
14066 DAG.getNode(FlatNode, DL, AccVT, {Subvectors[0], Subvectors[1]}));
14067 Subvectors.pop_front();
14068 Subvectors.pop_front();
14069 }
14070
14071 assert(Subvectors.size() == 1 &&
14072 "There should only be one subvector after tree flattening");
14073
14074 return Subvectors[0];
14075}
14076
14077/// Given a store node \p StoreNode, return true if it is safe to fold that node
14078/// into \p FPNode, which expands to a library call with output pointers.
14080 SDNode *FPNode) {
14082 SmallVector<const SDNode *, 8> DeferredNodes;
14084
14085 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
14086 for (SDValue Op : StoreNode->ops())
14087 if (Op.getNode() != FPNode)
14088 Worklist.push_back(Op.getNode());
14089
14091 while (!Worklist.empty()) {
14092 const SDNode *Node = Worklist.pop_back_val();
14093 auto [_, Inserted] = Visited.insert(Node);
14094 if (!Inserted)
14095 continue;
14096
14097 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
14098 return false;
14099
14100 // Reached the FPNode (would result in a cycle).
14101 // OR Reached CALLSEQ_START (would result in nested call sequences).
14102 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
14103 return false;
14104
14105 if (Node->getOpcode() == ISD::CALLSEQ_END) {
14106 // Defer looking into call sequences (so we can check we're outside one).
14107 // We still need to look through these for the predecessor check.
14108 DeferredNodes.push_back(Node);
14109 continue;
14110 }
14111
14112 for (SDValue Op : Node->ops())
14113 Worklist.push_back(Op.getNode());
14114 }
14115
14116 // True if we're outside a call sequence and don't have the FPNode as a
14117 // predecessor. No cycles or nested call sequences possible.
14118 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
14119 MaxSteps);
14120}
14121
14123 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
14125 std::optional<unsigned> CallRetResNo) const {
14126 if (LC == RTLIB::UNKNOWN_LIBCALL)
14127 return false;
14128
14129 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
14130 if (LibcallImpl == RTLIB::Unsupported)
14131 return false;
14132
14133 LLVMContext &Ctx = *DAG.getContext();
14134 EVT VT = Node->getValueType(0);
14135 unsigned NumResults = Node->getNumValues();
14136
14137 // Find users of the node that store the results (and share input chains). The
14138 // destination pointers can be used instead of creating stack allocations.
14139 SDValue StoresInChain;
14140 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
14141 for (SDNode *User : Node->users()) {
14143 continue;
14144 auto *ST = cast<StoreSDNode>(User);
14145 SDValue StoreValue = ST->getValue();
14146 unsigned ResNo = StoreValue.getResNo();
14147 // Ensure the store corresponds to an output pointer.
14148 if (CallRetResNo == ResNo)
14149 continue;
14150 // Ensure the store to the default address space and not atomic or volatile.
14151 if (!ST->isSimple() || ST->getAddressSpace() != 0)
14152 continue;
14153 // Ensure all store chains are the same (so they don't alias).
14154 if (StoresInChain && ST->getChain() != StoresInChain)
14155 continue;
14156 // Ensure the store is properly aligned.
14157 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
14158 if (ST->getAlign() <
14159 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
14160 continue;
14161 // Avoid:
14162 // 1. Creating cyclic dependencies.
14163 // 2. Expanding the node to a call within a call sequence.
14165 continue;
14166 ResultStores[ResNo] = ST;
14167 StoresInChain = ST->getChain();
14168 }
14169
14170 ArgListTy Args;
14171
14172 // Pass the arguments.
14173 for (const SDValue &Op : Node->op_values()) {
14174 EVT ArgVT = Op.getValueType();
14175 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
14176 Args.emplace_back(Op, ArgTy);
14177 }
14178
14179 // Pass the output pointers.
14180 SmallVector<SDValue, 2> ResultPtrs(NumResults);
14182 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
14183 if (ResNo == CallRetResNo)
14184 continue;
14185 EVT ResVT = Node->getValueType(ResNo);
14186 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
14187 ResultPtrs[ResNo] = ResultPtr;
14188 Args.emplace_back(ResultPtr, PointerTy);
14189 }
14190
14191 SDLoc DL(Node);
14192
14194 // Pass the vector mask (if required).
14195 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
14196 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
14197 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14198 }
14199
14200 Type *RetType = CallRetResNo.has_value()
14201 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14202 : Type::getVoidTy(Ctx);
14203 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14204 SDValue Callee =
14205 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14207 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14208 getLibcallImplCallingConv(LibcallImpl), RetType, Callee, std::move(Args));
14209
14210 auto [Call, CallChain] = LowerCallTo(CLI);
14211
14212 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14213 if (ResNo == CallRetResNo) {
14214 Results.push_back(Call);
14215 continue;
14216 }
14217 MachinePointerInfo PtrInfo;
14218 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14219 ResultPtr, PtrInfo);
14220 SDValue OutChain = LoadResult.getValue(1);
14221
14222 if (StoreSDNode *ST = ResultStores[ResNo]) {
14223 // Replace store with the library call.
14224 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14225 PtrInfo = ST->getPointerInfo();
14226 } else {
14228 DAG.getMachineFunction(),
14229 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14230 }
14231
14232 Results.push_back(LoadResult);
14233 }
14234
14235 return true;
14236}
14237
14239 SDValue &LHS, SDValue &RHS,
14240 SDValue &CC, bool &NeedInvert,
14241 const SDLoc &dl, SDValue &Chain,
14242 bool IsSignaling) const {
14243 MVT OpVT = LHS.getSimpleValueType();
14244 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14245 NeedInvert = false;
14246 switch (getCondCodeAction(CCCode, OpVT)) {
14247 default:
14248 llvm_unreachable("Unknown condition code action!");
14250 // Nothing to do.
14251 break;
14254 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14255 std::swap(LHS, RHS);
14256 CC = DAG.getCondCode(InvCC);
14257 return true;
14258 }
14259 // Swapping operands didn't work. Try inverting the condition.
14260 bool NeedSwap = false;
14261 InvCC = getSetCCInverse(CCCode, OpVT);
14262 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14263 // If inverting the condition is not enough, try swapping operands
14264 // on top of it.
14265 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14266 NeedSwap = true;
14267 }
14268 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14269 CC = DAG.getCondCode(InvCC);
14270 NeedInvert = true;
14271 if (NeedSwap)
14272 std::swap(LHS, RHS);
14273 return true;
14274 }
14275
14276 // Special case: expand i1 comparisons using logical operations.
14277 if (OpVT == MVT::i1) {
14278 SDValue Ret;
14279 switch (CCCode) {
14280 default:
14281 llvm_unreachable("Unknown integer setcc!");
14282 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14283 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14284 MVT::i1);
14285 break;
14286 case ISD::SETNE: // X != Y --> (X ^ Y)
14287 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14288 break;
14289 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14290 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14291 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14292 DAG.getNOT(dl, LHS, MVT::i1));
14293 break;
14294 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14295 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14296 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14297 DAG.getNOT(dl, RHS, MVT::i1));
14298 break;
14299 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14300 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14301 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14302 DAG.getNOT(dl, LHS, MVT::i1));
14303 break;
14304 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14305 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14306 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14307 DAG.getNOT(dl, RHS, MVT::i1));
14308 break;
14309 }
14310
14311 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14312 RHS = SDValue();
14313 CC = SDValue();
14314 return true;
14315 }
14316
14318 unsigned Opc = 0;
14319 switch (CCCode) {
14320 default:
14321 llvm_unreachable("Don't know how to expand this condition!");
14322 case ISD::SETUO:
14323 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14324 CC1 = ISD::SETUNE;
14325 CC2 = ISD::SETUNE;
14326 Opc = ISD::OR;
14327 break;
14328 }
14330 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14331 NeedInvert = true;
14332 [[fallthrough]];
14333 case ISD::SETO:
14335 "If SETO is expanded, SETOEQ must be legal!");
14336 CC1 = ISD::SETOEQ;
14337 CC2 = ISD::SETOEQ;
14338 Opc = ISD::AND;
14339 break;
14340 case ISD::SETONE:
14341 case ISD::SETUEQ:
14342 // If the SETUO or SETO CC isn't legal, we might be able to use
14343 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14344 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14345 // the operands.
14346 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14347 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14348 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14349 CC1 = ISD::SETOGT;
14350 CC2 = ISD::SETOLT;
14351 Opc = ISD::OR;
14352 NeedInvert = ((unsigned)CCCode & 0x8U);
14353 break;
14354 }
14355 [[fallthrough]];
14356 case ISD::SETOEQ:
14357 case ISD::SETOGT:
14358 case ISD::SETOGE:
14359 case ISD::SETOLT:
14360 case ISD::SETOLE:
14361 case ISD::SETUNE:
14362 case ISD::SETUGT:
14363 case ISD::SETUGE:
14364 case ISD::SETULT:
14365 case ISD::SETULE:
14366 // If we are floating point, assign and break, otherwise fall through.
14367 if (!OpVT.isInteger()) {
14368 // We can use the 4th bit to tell if we are the unordered
14369 // or ordered version of the opcode.
14370 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14371 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14372 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14373 break;
14374 }
14375 // Fallthrough if we are unsigned integer.
14376 [[fallthrough]];
14377 case ISD::SETLE:
14378 case ISD::SETGT:
14379 case ISD::SETGE:
14380 case ISD::SETLT:
14381 case ISD::SETNE:
14382 case ISD::SETEQ:
14383 // If all combinations of inverting the condition and swapping operands
14384 // didn't work then we have no means to expand the condition.
14385 llvm_unreachable("Don't know how to expand this condition!");
14386 }
14387
14388 SDValue SetCC1, SetCC2;
14389 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14390 // If we aren't the ordered or unorder operation,
14391 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14392 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14393 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14394 } else {
14395 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14396 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14397 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14398 }
14399 if (Chain)
14400 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14401 SetCC2.getValue(1));
14402 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14403 RHS = SDValue();
14404 CC = SDValue();
14405 return true;
14406 }
14407 }
14408 return false;
14409}
14410
14412 SelectionDAG &DAG) const {
14413 EVT VT = Node->getValueType(0);
14414 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14415 // split into two equal parts.
14416 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14417 return SDValue();
14418
14419 // Restrict expansion to cases where both parts can be concatenated.
14420 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14421 if (LoVT != HiVT || !isTypeLegal(LoVT))
14422 return SDValue();
14423
14424 SDLoc DL(Node);
14425 unsigned Opcode = Node->getOpcode();
14426
14427 // Don't expand if the result is likely to be unrolled anyway.
14428 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14429 return SDValue();
14430
14431 SmallVector<SDValue, 4> LoOps, HiOps;
14432 for (const SDValue &V : Node->op_values()) {
14433 if (!V.getValueType().isVector()) {
14434 // Scalar operands pass through to both halves unchanged.
14435 LoOps.push_back(V);
14436 HiOps.push_back(V);
14437 continue;
14438 }
14439 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14440 LoOps.push_back(Lo);
14441 HiOps.push_back(Hi);
14442 }
14443
14444 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVT, LoOps, Node->getFlags());
14445 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVT, HiOps, Node->getFlags());
14446 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14447}
14448
14450 const SDLoc &DL,
14451 EVT InVecVT, SDValue EltNo,
14452 LoadSDNode *OriginalLoad,
14453 SelectionDAG &DAG) const {
14454 assert(OriginalLoad->isSimple());
14455
14456 EVT VecEltVT = InVecVT.getVectorElementType();
14457
14458 // If the vector element type is not a multiple of a byte then we are unable
14459 // to correctly compute an address to load only the extracted element as a
14460 // scalar.
14461 if (!VecEltVT.isByteSized())
14462 return SDValue();
14463
14464 ISD::LoadExtType ExtTy =
14465 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14466 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14467 return SDValue();
14468
14469 std::optional<unsigned> ByteOffset;
14470 Align Alignment = OriginalLoad->getAlign();
14472 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14473 int Elt = ConstEltNo->getZExtValue();
14474 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14475 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14476 Alignment = commonAlignment(Alignment, *ByteOffset);
14477 } else {
14478 // Discard the pointer info except the address space because the memory
14479 // operand can't represent this new access since the offset is variable.
14480 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14481 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14482 }
14483
14484 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14485 return SDValue();
14486
14487 unsigned IsFast = 0;
14488 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14489 OriginalLoad->getAddressSpace(), Alignment,
14490 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14491 !IsFast)
14492 return SDValue();
14493
14494 // The original DAG loaded the entire vector from memory, so arithmetic
14495 // within it must be inbounds.
14497 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
14498
14499 // We are replacing a vector load with a scalar load. The new load must have
14500 // identical memory op ordering to the original.
14501 SDValue Load;
14502 if (ResultVT.bitsGT(VecEltVT)) {
14503 // If the result type of vextract is wider than the load, then issue an
14504 // extending load instead.
14505 ISD::LoadExtType ExtType =
14506 isLoadLegal(ResultVT, VecEltVT, Alignment,
14507 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
14509 : ISD::EXTLOAD;
14510 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
14511 NewPtr, MPI, VecEltVT, Alignment,
14512 OriginalLoad->getMemOperand()->getFlags(),
14513 OriginalLoad->getMMOMetadataForSubAccess());
14514 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14515 } else {
14516 // The result type is narrower or the same width as the vector element
14517 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
14518 Alignment, OriginalLoad->getMemOperand()->getFlags(),
14519 OriginalLoad->getMMOMetadataForSubAccess());
14520 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14521 if (ResultVT.bitsLT(VecEltVT))
14522 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
14523 else
14524 Load = DAG.getBitcast(ResultVT, Load);
14525 }
14526
14527 return Load;
14528}
14529
14530// Set type id for call site info and metadata 'call_target'.
14531// We are filtering for:
14532// a) The call-graph-section use case that wants to know about indirect
14533// calls, or
14534// b) We want to annotate indirect calls.
14536 const CallBase *CB, MachineFunction &MF,
14537 MachineFunction::CallSiteInfo &CSInfo) const {
14538 if (CB && CB->isIndirectCall() &&
14541 CSInfo = MachineFunction::CallSiteInfo(*CB);
14542}
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
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:337
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:358
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:393
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:333
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:329
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:370
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
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
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
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:43
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:305
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:311
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:68
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.
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 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 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 MVT::SimpleValueType getCmpLibcallReturnType() const
Return the ValueType for comparison libcalls.
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...
virtual bool hasBitTest(SDValue X, SDValue Y) const
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
EVT getLegalTypeToTransformTo(LLVMContext &Context, EVT VT) const
Perform getTypeToTransformTo repeatedly until a legal type is obtained.
LegalizeAction getCondCodeAction(ISD::CondCode CC, MVT VT) const
Return how the condition code should be treated: either it is legal, needs to be expanded to some oth...
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 isFPImmLegal(const APFloat &, EVT, bool ForCodeSize=false) const
Returns true if the target can instruction select the specified FP immediate natively.
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.
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 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 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:339
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:716
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
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:180
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:265
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
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:273
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
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:837
@ 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
@ 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:797
@ 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:871
@ 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:898
@ 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:757
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:928
@ 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:788
@ 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:806
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:862
@ 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.
@ 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:814
@ 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:779
@ 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 - Perform floating-point minimumNumber or maximumNumber on two values,...
@ 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:868
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:829
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ 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:917
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:906
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:737
@ 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.
Definition ISDOpcodes.h:996
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:823
@ 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:793
@ 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 - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:944
@ 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:749
@ 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:805
@ 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:977
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:939
@ 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:963
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:874
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:851
@ 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,...
@ CTTZ_ELTS_ZERO_POISON
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:732
@ 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:761
@ 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
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:1557
@ 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:1539
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.
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:144
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
@ 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.
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:201
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:197
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
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
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:106
static LLVM_ABI 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