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>
40using namespace llvm;
41using namespace llvm::SDPatternMatch;
42
43/// NOTE: The TargetMachine owns TLOF.
47
48// Define the virtual destructor out-of-line for build efficiency.
50
51const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
52 return nullptr;
53}
54
58
59/// Check whether a given call node is in tail position within its function. If
60/// so, it sets Chain to the input chain of the tail call.
62 SDValue &Chain) const {
64
65 // First, check if tail calls have been disabled in this function.
66 if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
67 return false;
68
69 // Conservatively require the attributes of the call to match those of
70 // the return. Ignore following attributes because they don't affect the
71 // call sequence.
72 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
73 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
74 Attribute::DereferenceableOrNull, Attribute::NoAlias,
75 Attribute::NonNull, Attribute::NoUndef,
76 Attribute::Range, Attribute::NoFPClass})
77 CallerAttrs.removeAttribute(Attr);
78
79 if (CallerAttrs.hasAttributes())
80 return false;
81
82 // It's not safe to eliminate the sign / zero extension of the return value.
83 if (CallerAttrs.contains(Attribute::ZExt) ||
84 CallerAttrs.contains(Attribute::SExt))
85 return false;
86
87 // Check if the only use is a function return node.
88 return isUsedByReturnOnly(Node, Chain);
89}
90
92 const uint32_t *CallerPreservedMask,
93 const SmallVectorImpl<CCValAssign> &ArgLocs,
94 const SmallVectorImpl<SDValue> &OutVals) const {
95 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
96 const CCValAssign &ArgLoc = ArgLocs[I];
97 if (!ArgLoc.isRegLoc())
98 continue;
99 MCRegister Reg = ArgLoc.getLocReg();
100 // Only look at callee saved registers.
101 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
102 continue;
103 // Check that we pass the value used for the caller.
104 // (We look for a CopyFromReg reading a virtual register that is used
105 // for the function live-in value of register Reg)
106 SDValue Value = OutVals[I];
107 if (Value->getOpcode() == ISD::AssertZext)
108 Value = Value.getOperand(0);
109 if (Value->getOpcode() != ISD::CopyFromReg)
110 return false;
111 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
112 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
113 return false;
114 }
115 return true;
116}
117
118static bool paramHasAttr(const CallBase &Call, unsigned ArgIdx,
119 Attribute::AttrKind Kind) {
120 return Call.paramHasAttr(ArgIdx, Kind);
121}
122
123static bool paramHasAttr(const AttributeList &Attrs, unsigned ArgIdx,
124 Attribute::AttrKind Kind) {
125 return Attrs.hasParamAttr(ArgIdx, Kind);
126}
127
128static MaybeAlign getParamStackAlign(const CallBase &Call, unsigned ArgIdx) {
129 return Call.getParamStackAlign(ArgIdx);
130}
131
133 unsigned ArgIdx) {
134 return Attrs.getParamStackAlignment(ArgIdx);
135}
136
137static MaybeAlign getParamAlign(const CallBase &Call, unsigned ArgIdx) {
138 return Call.getParamAlign(ArgIdx);
139}
140
141static MaybeAlign getParamAlign(const AttributeList &Attrs, unsigned ArgIdx) {
142 return Attrs.getParamAlignment(ArgIdx);
143}
144
145/// Set CallLoweringInfo attribute flags based on a call instruction
146/// and called function attributes.
147template <typename SourceT>
149 const SourceT &Src, unsigned ArgIdx) {
150 Entry.IsSExt = paramHasAttr(Src, ArgIdx, Attribute::SExt);
151 Entry.IsZExt = paramHasAttr(Src, ArgIdx, Attribute::ZExt);
152 Entry.IsNoExt = paramHasAttr(Src, ArgIdx, Attribute::NoExt);
153 Entry.IsInReg = paramHasAttr(Src, ArgIdx, Attribute::InReg);
154 Entry.IsSRet = paramHasAttr(Src, ArgIdx, Attribute::StructRet);
155 Entry.IsNest = paramHasAttr(Src, ArgIdx, Attribute::Nest);
156 Entry.IsByVal = paramHasAttr(Src, ArgIdx, Attribute::ByVal);
157 Entry.IsPreallocated = paramHasAttr(Src, ArgIdx, Attribute::Preallocated);
158 Entry.IsInAlloca = paramHasAttr(Src, ArgIdx, Attribute::InAlloca);
159 Entry.IsReturned = paramHasAttr(Src, ArgIdx, Attribute::Returned);
160 Entry.IsSwiftSelf = paramHasAttr(Src, ArgIdx, Attribute::SwiftSelf);
161 Entry.IsSwiftAsync = paramHasAttr(Src, ArgIdx, Attribute::SwiftAsync);
162 Entry.IsSwiftError = paramHasAttr(Src, ArgIdx, Attribute::SwiftError);
163 Entry.Alignment = getParamStackAlign(Src, ArgIdx);
164 Entry.IndirectType = nullptr;
165 assert(Entry.IsByVal + Entry.IsPreallocated + Entry.IsInAlloca +
166 Entry.IsSRet <=
167 1 &&
168 "multiple ABI attributes?");
169 if (Entry.IsByVal) {
170 Entry.IndirectType = Src.getParamByValType(ArgIdx);
171 if (!Entry.Alignment)
172 Entry.Alignment = getParamAlign(Src, ArgIdx);
173 }
174 if (Entry.IsPreallocated)
175 Entry.IndirectType = Src.getParamPreallocatedType(ArgIdx);
176 if (Entry.IsInAlloca)
177 Entry.IndirectType = Src.getParamInAllocaType(ArgIdx);
178 if (Entry.IsSRet)
179 Entry.IndirectType = Src.getParamStructRetType(ArgIdx);
180}
181
183 unsigned ArgIdx) {
184 setArgListEntryAttributes(*this, *Call, ArgIdx);
185}
186
188 unsigned ArgIdx) {
189 setArgListEntryAttributes(*this, Attrs, ArgIdx);
190}
191
194 const AttributeList &FuncAttrs,
196 // TODO: This assumes each parameter maps to exactly one operand node, which
197 // does not hold when an argument requires type splitting.
198 assert(Ops.size() == FuncTy->getNumParams() &&
199 "argument count does not match the function type");
200 ArgListTy Args;
201 Args.reserve(Ops.size());
202 for (unsigned I = 0, E = FuncTy->getNumParams(); I != E; ++I) {
203 ArgListEntry Entry(Ops[I], FuncTy->getParamType(I));
204 Entry.setAttributes(FuncAttrs, I);
205 Args.push_back(Entry);
206 }
207 return Args;
208}
209
210/// Generate a libcall taking the given operands as arguments and returning a
211/// result of type RetVT.
212std::pair<SDValue, SDValue>
213TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl,
215 MakeLibCallOptions CallOptions, const SDLoc &dl,
216 SDValue InChain) const {
217 if (LibcallImpl == RTLIB::Unsupported)
218 reportFatalInternalError("unsupported library call operation");
219
220 if (!InChain)
221 InChain = DAG.getEntryNode();
222
224 Args.reserve(Ops.size());
225
226 ArrayRef<Type *> OpsTypeOverrides = CallOptions.OpsTypeOverrides;
227 for (unsigned i = 0; i < Ops.size(); ++i) {
228 SDValue NewOp = Ops[i];
229 Type *Ty = i < OpsTypeOverrides.size() && OpsTypeOverrides[i]
230 ? OpsTypeOverrides[i]
231 : NewOp.getValueType().getTypeForEVT(*DAG.getContext());
232 TargetLowering::ArgListEntry Entry(NewOp, Ty);
233 if (CallOptions.IsSoften)
234 Entry.OrigTy =
235 CallOptions.OpsVTBeforeSoften[i].getTypeForEVT(*DAG.getContext());
236
237 Entry.IsSExt =
238 shouldSignExtendTypeInLibCall(Entry.Ty, CallOptions.IsSigned);
239 Entry.IsZExt = !Entry.IsSExt;
240
241 if (CallOptions.IsSoften &&
243 Entry.IsSExt = Entry.IsZExt = false;
244 }
245 Args.push_back(Entry);
246 }
247
248 SDValue Callee =
249 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
250
251 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
252 Type *OrigRetTy = RetTy;
254 bool signExtend = shouldSignExtendTypeInLibCall(RetTy, CallOptions.IsSigned);
255 bool zeroExtend = !signExtend;
256
257 if (CallOptions.IsSoften) {
258 OrigRetTy = CallOptions.RetVTBeforeSoften.getTypeForEVT(*DAG.getContext());
260 signExtend = zeroExtend = false;
261 }
262
263 CLI.setDebugLoc(dl)
264 .setChain(InChain)
265 .setLibCallee(getLibcallImplCallingConv(LibcallImpl), RetTy, OrigRetTy,
266 Callee, std::move(Args))
267 .setNoReturn(CallOptions.DoesNotReturn)
270 .setSExtResult(signExtend)
271 .setZExtResult(zeroExtend);
272 return LowerCallTo(CLI);
273}
274
276 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
277 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
278 const AttributeList &FuncAttributes, EVT *LargestVT) const {
279 EVT VT = getOptimalMemOpType(Context, Op, FuncAttributes);
280
281 if (VT == MVT::Other) {
282 // Use the largest integer type whose alignment constraints are satisfied.
283 VT = MVT::LAST_INTEGER_VALUETYPE;
284 if (Op.isFixedDstAlign()) {
285 bool LoadsFromSrc = Op.isMemcpyOrMemmove() && !Op.isMemcpyStrSrc();
286 while (VT != MVT::i8) {
287 unsigned VTSize = VT.getSizeInBits() / 8;
288 bool DstOk =
289 Op.getDstAlign() >= VTSize ||
290 allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign());
291 bool SrcOk =
292 !LoadsFromSrc || Op.getSrcAlign() >= VTSize ||
293 allowsMisalignedMemoryAccesses(VT, SrcAS, Op.getSrcAlign());
294 if (DstOk && SrcOk)
295 break;
297 }
298 }
299 assert(VT.isInteger());
300
301 // Find the largest legal integer type.
302 MVT LVT = MVT::LAST_INTEGER_VALUETYPE;
303 while (!isTypeLegal(LVT))
304 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
305 assert(LVT.isInteger());
306
307 // If the type we've chosen is larger than the largest legal integer type
308 // then use the largest legal type.
309 if (VT.bitsGT(LVT))
310 VT = LVT;
311 }
312
313 unsigned NumMemOps = 0;
314 uint64_t Size = Op.size();
315 while (Size) {
316 unsigned VTSize = VT.getSizeInBits() / 8;
317 while (VTSize > Size) {
318 // For now, only use non-vector load / store's for the left-over pieces.
319 EVT NewVT = VT;
320 unsigned NewVTSize;
321
322 bool Found = false;
323 if (VT.isVector() || VT.isFloatingPoint()) {
324 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
327 Found = true;
328 else if (NewVT == MVT::i64 &&
330 isSafeMemOpType(MVT::f64)) {
331 // i64 is usually not legal on 32-bit targets, but f64 may be.
332 NewVT = MVT::f64;
333 Found = true;
334 }
335 }
336
337 if (!Found) {
338 do {
339 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
340 if (NewVT == MVT::i8)
341 break;
342 } while (!isSafeMemOpType(NewVT.getSimpleVT()));
343 }
344 NewVTSize = NewVT.getSizeInBits() / 8;
345
346 // If the new VT cannot cover all of the remaining bits, then consider
347 // issuing a (or a pair of) unaligned and overlapping load / store.
348 unsigned Fast;
349 if (NumMemOps && !Op.isVolatile() && NewVTSize < Size &&
351 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
353 Fast)
354 VTSize = Size;
355 else {
356 VT = NewVT;
357 VTSize = NewVTSize;
358 }
359 }
360
361 if (++NumMemOps > Limit)
362 return false;
363
364 MemOps.push_back(VT);
365 Size -= VTSize;
366 }
367
368 return true;
369}
370
371/// Soften the operands of a comparison. This code is shared among BR_CC,
372/// SELECT_CC, and SETCC handlers.
374 SDValue &NewLHS, SDValue &NewRHS,
375 ISD::CondCode &CCCode,
376 const SDLoc &dl, const SDValue OldLHS,
377 const SDValue OldRHS) const {
378 SDValue Chain;
379 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
380 OldRHS, Chain);
381}
382
383/// Select the libcall and the condition code to test its result against 0 for
384/// an ordered floating-point compare. \p BoolLC is the boolean helper (result
385/// is 0/1). \p TriStateLC is the per-predicate three-way helper and \p
386/// GenericLC the generic single-symbol three-way helper (both return -1/0/1,
387/// tested against 0 with \p TriStateCC). The boolean form is preferred, then
388/// the per-predicate three-way, then the generic three-way.
389static std::pair<RTLIB::Libcall, ISD::CondCode>
390selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC,
391 RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC,
392 ISD::CondCode TriStateCC) {
393 if (Libcalls.getLibcallImpl(BoolLC) != RTLIB::Unsupported)
394 return {BoolLC, ISD::SETNE};
395 if (Libcalls.getLibcallImpl(TriStateLC) != RTLIB::Unsupported)
396 return {TriStateLC, TriStateCC};
397 return {GenericLC, TriStateCC};
398}
399
401 SDValue &NewLHS, SDValue &NewRHS,
402 ISD::CondCode &CCCode,
403 const SDLoc &dl, const SDValue OldLHS,
404 const SDValue OldRHS,
405 SDValue &Chain,
406 bool IsSignaling) const {
407 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
408 // not supporting it. We can update this code when libgcc provides such
409 // functions.
410
411 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
412 && "Unsupported setcc type!");
413
414 // Expand into one or more soft-fp libcall(s).
415 ISD::CondCode OrigCCCode = CCCode;
416 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
418 bool ShouldInvertCC = false;
419
420 // Expand a compare libcall family name (e.g. OEQ, FCMP3_PRED_OEQ) to the
421 // RTLIB::Libcall for VT.
422#define FP_CMP_LIBCALL(BASE) \
423 RTLIB::getFPLibCall(VT, RTLIB::BASE##_F32, RTLIB::BASE##_F64, \
424 RTLIB::UNKNOWN_LIBCALL, RTLIB::BASE##_F128, \
425 RTLIB::BASE##_PPCF128)
426
427 switch (CCCode) {
428 case ISD::SETEQ:
429 case ISD::SETOEQ:
430 std::tie(LC1, CC1) = selectFPCmpLibcall(
431 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
432 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
433 break;
434 case ISD::SETNE:
435 case ISD::SETUNE:
436 std::tie(LC1, CC1) = selectFPCmpLibcall(
437 DAG.getLibcalls(), FP_CMP_LIBCALL(UNE), FP_CMP_LIBCALL(FCMP3_PRED_UNE),
438 FP_CMP_LIBCALL(FCMP3), ISD::SETNE);
439 // Some ABIs (e.g. AEABI) provide neither a not-equal nor a three-way
440 // compare; obtain not-equal (UNE = !OEQ) by inverting ordered-equal.
441 if (DAG.getLibcalls().getLibcallImpl(LC1) == RTLIB::Unsupported) {
442 std::tie(LC1, CC1) = selectFPCmpLibcall(
443 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ),
444 FP_CMP_LIBCALL(FCMP3_PRED_OEQ), FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
445 ShouldInvertCC = true;
446 }
447 break;
448 case ISD::SETGE:
449 case ISD::SETOGE:
450 std::tie(LC1, CC1) = selectFPCmpLibcall(
451 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE), FP_CMP_LIBCALL(FCMP3_PRED_OGE),
452 FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
453 break;
454 case ISD::SETLT:
455 case ISD::SETOLT:
456 std::tie(LC1, CC1) = selectFPCmpLibcall(
457 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT), FP_CMP_LIBCALL(FCMP3_PRED_OLT),
458 FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
459 break;
460 case ISD::SETLE:
461 case ISD::SETOLE:
462 std::tie(LC1, CC1) = selectFPCmpLibcall(
463 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE), FP_CMP_LIBCALL(FCMP3_PRED_OLE),
464 FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
465 break;
466 case ISD::SETGT:
467 case ISD::SETOGT:
468 std::tie(LC1, CC1) = selectFPCmpLibcall(
469 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT), FP_CMP_LIBCALL(FCMP3_PRED_OGT),
470 FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
471 break;
472 case ISD::SETO:
473 ShouldInvertCC = true;
474 [[fallthrough]];
475 case ISD::SETUO:
476 // Unordered is a boolean everywhere (__unordXf2 returns 0/1).
477 LC1 = FP_CMP_LIBCALL(UO);
478 CC1 = ISD::SETNE;
479 break;
480 case ISD::SETONE:
481 // SETONE = O && UNE
482 ShouldInvertCC = true;
483 [[fallthrough]];
484 case ISD::SETUEQ:
485 LC1 = FP_CMP_LIBCALL(UO);
486 CC1 = ISD::SETNE;
487 std::tie(LC2, CC2) = selectFPCmpLibcall(
488 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
489 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
490 break;
491 default:
492 // Invert CC for unordered comparisons, handled by the ordered inverse.
493 ShouldInvertCC = true;
494 switch (CCCode) {
495 case ISD::SETULT:
496 std::tie(LC1, CC1) = selectFPCmpLibcall(
497 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE),
498 FP_CMP_LIBCALL(FCMP3_PRED_OGE), FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
499 break;
500 case ISD::SETULE:
501 std::tie(LC1, CC1) = selectFPCmpLibcall(
502 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT),
503 FP_CMP_LIBCALL(FCMP3_PRED_OGT), FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
504 break;
505 case ISD::SETUGT:
506 std::tie(LC1, CC1) = selectFPCmpLibcall(
507 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE),
508 FP_CMP_LIBCALL(FCMP3_PRED_OLE), FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
509 break;
510 case ISD::SETUGE:
511 std::tie(LC1, CC1) = selectFPCmpLibcall(
512 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT),
513 FP_CMP_LIBCALL(FCMP3_PRED_OLT), FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
514 break;
515 default:
516 llvm_unreachable("Do not know how to soften this setcc!");
517 }
518 }
519
520#undef FP_CMP_LIBCALL
521
522 // Use the target specific return value for comparison lib calls.
524 SDValue Ops[2] = {NewLHS, NewRHS};
526 EVT OpsVT[2] = { OldLHS.getValueType(),
527 OldRHS.getValueType() };
528 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT);
529
530 auto ReportNoLibcall = [&]() {
531 DAG.getContext()->emitError(
532 Twine("no libcall available to soften floating-point ") +
533 ISD::getCondCodeName(OrigCCCode) + " compare with type " +
534 VT.getEVTString());
535 NewLHS = DAG.getPOISON(RetVT);
536 NewRHS = DAG.getConstant(0, dl, RetVT);
537 CCCode = ISD::SETNE;
538 };
539
540 // Check availability before makeLibCall, which fatally errors otherwise.
541 RTLIB::LibcallImpl LC1Impl = DAG.getLibcalls().getLibcallImpl(LC1);
542 if (LC1Impl == RTLIB::Unsupported) {
543 ReportNoLibcall();
544 return;
545 }
546
547 auto Call = makeLibCall(DAG, LC1Impl, RetVT, Ops, CallOptions, dl, Chain);
548 NewLHS = Call.first;
549 NewRHS = DAG.getConstant(0, dl, RetVT);
550
551 CCCode = CC1;
552 if (ShouldInvertCC) {
553 assert(RetVT.isInteger());
554 CCCode = getSetCCInverse(CCCode, RetVT);
555 }
556
557 if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
558 // Update Chain.
559 Chain = Call.second;
560 } else {
561 RTLIB::LibcallImpl LC2Impl = DAG.getLibcalls().getLibcallImpl(LC2);
562 if (LC2Impl == RTLIB::Unsupported) {
563 ReportNoLibcall();
564 return;
565 }
566
567 assert(CCCode == (ShouldInvertCC ? ISD::SETEQ : ISD::SETNE) &&
568 "unordered call should be simple boolean");
569
570 EVT SetCCVT =
571 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
573 NewLHS = DAG.getNode(ISD::AssertZext, dl, RetVT, Call.first,
574 DAG.getValueType(MVT::i1));
575 }
576
577 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
578 auto Call2 = makeLibCall(DAG, LC2Impl, RetVT, Ops, CallOptions, dl, Chain);
579 CCCode = CC2;
580 if (ShouldInvertCC)
581 CCCode = getSetCCInverse(CCCode, RetVT);
582 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
583 if (Chain)
584 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
585 Call2.second);
586 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
587 Tmp.getValueType(), Tmp, NewLHS);
588 NewRHS = SDValue();
589 }
590}
591
592/// Return the entry encoding for a jump table in the current function. The
593/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
595 // In non-pic modes, just use the address of a block.
598
599 // Otherwise, use a label difference.
601}
602
607
608/// This returns the relocation base for the given PIC jumptable, the same as
609/// getPICJumpTableRelocBase, but as an MCExpr.
610const MCExpr *
612 unsigned JTI,MCContext &Ctx) const{
613 // The normal PIC reloc base is the label at the start of the jump table.
614 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
615}
616
618 SDValue Addr, int JTI,
619 SelectionDAG &DAG) const {
620 SDValue Chain = Value;
621 // Jump table debug info is only needed if CodeView is enabled.
623 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl);
624 }
625 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr);
626}
627
628bool
630 const TargetMachine &TM = getTargetMachine();
631 const GlobalValue *GV = GA->getGlobal();
632
633 // If the address is not even local to this DSO we will have to load it from
634 // a got and then add the offset.
635 if (!TM.shouldAssumeDSOLocal(GV))
636 return false;
637
638 // If the code is position independent we will have to add a base register.
640 return false;
641
642 // Otherwise we can do it.
643 return true;
644}
645
646//===----------------------------------------------------------------------===//
647// Optimization Methods
648//===----------------------------------------------------------------------===//
649
650/// If the specified instruction has a constant integer operand and there are
651/// bits set in that constant that are not demanded, then clear those bits and
652/// return true.
654 const APInt &DemandedBits,
655 const APInt &DemandedElts,
656 TargetLoweringOpt &TLO) const {
657 SDLoc DL(Op);
658 unsigned Opcode = Op.getOpcode();
659
660 // Early-out if we've ended up calling an undemanded node, leave this to
661 // constant folding.
662 if (DemandedBits.isZero() || DemandedElts.isZero())
663 return false;
664
665 // Do target-specific constant optimization.
666 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
667 return TLO.New.getNode();
668
669 // FIXME: ISD::SELECT, ISD::SELECT_CC
670 switch (Opcode) {
671 default:
672 break;
673 case ISD::XOR:
674 case ISD::AND:
675 case ISD::OR: {
676 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
677 if (!Op1C || Op1C->isOpaque())
678 return false;
679
680 // If this is a 'not' op, don't touch it because that's a canonical form.
681 const APInt &C = Op1C->getAPIntValue();
682 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
683 return false;
684
685 if (!C.isSubsetOf(DemandedBits)) {
686 EVT VT = Op.getValueType();
687 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
688 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC,
689 Op->getFlags());
690 return TLO.CombineTo(Op, NewOp);
691 }
692
693 break;
694 }
695 }
696
697 return false;
698}
699
701 const APInt &DemandedBits,
702 TargetLoweringOpt &TLO) const {
703 EVT VT = Op.getValueType();
704 APInt DemandedElts = VT.isVector()
706 : APInt(1, 1);
707 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
708}
709
710/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
711/// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
712/// but it could be generalized for targets with other types of implicit
713/// widening casts.
715 const APInt &DemandedBits,
716 TargetLoweringOpt &TLO) const {
717 assert(Op.getNumOperands() == 2 &&
718 "ShrinkDemandedOp only supports binary operators!");
719 assert(Op.getNode()->getNumValues() == 1 &&
720 "ShrinkDemandedOp only supports nodes with one result!");
721
722 EVT VT = Op.getValueType();
723 SelectionDAG &DAG = TLO.DAG;
724 SDLoc dl(Op);
725
726 // Early return, as this function cannot handle vector types.
727 if (VT.isVector())
728 return false;
729
730 assert(Op.getOperand(0).getValueType().getScalarSizeInBits() == BitWidth &&
731 Op.getOperand(1).getValueType().getScalarSizeInBits() == BitWidth &&
732 "ShrinkDemandedOp only supports operands that have the same size!");
733
734 // Don't do this if the node has another user, which may require the
735 // full value.
736 if (!Op.getNode()->hasOneUse())
737 return false;
738
739 // Search for the smallest integer type with free casts to and from
740 // Op's type. For expedience, just check power-of-2 integer types.
741 unsigned DemandedSize = DemandedBits.getActiveBits();
742 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
743 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
744 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
745 if (isTruncateFree(Op, SmallVT) && isZExtFree(SmallVT, VT)) {
746 // We found a type with free casts.
747
748 // If the operation has the 'disjoint' flag, then the
749 // operands on the new node are also disjoint.
750 SDNodeFlags Flags(Op->getFlags().hasDisjoint() ? SDNodeFlags::Disjoint
752 unsigned Opcode = Op.getOpcode();
753 if (Opcode == ISD::PTRADD) {
754 // It isn't a ptradd anymore if it doesn't operate on the entire
755 // pointer.
756 Opcode = ISD::ADD;
757 }
758 SDValue X = DAG.getNode(
759 Opcode, dl, SmallVT,
760 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
761 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)), Flags);
762 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
763 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X);
764 return TLO.CombineTo(Op, Z);
765 }
766 }
767 return false;
768}
769
771 DAGCombinerInfo &DCI) const {
772 SelectionDAG &DAG = DCI.DAG;
773 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
774 !DCI.isBeforeLegalizeOps());
776
777 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
778 if (Simplified) {
779 DCI.AddToWorklist(Op.getNode());
781 }
782 return Simplified;
783}
784
786 const APInt &DemandedElts,
787 DAGCombinerInfo &DCI) const {
788 SelectionDAG &DAG = DCI.DAG;
789 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
790 !DCI.isBeforeLegalizeOps());
792
793 bool Simplified =
794 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
795 if (Simplified) {
796 DCI.AddToWorklist(Op.getNode());
798 }
799 return Simplified;
800}
801
805 unsigned Depth,
806 bool AssumeSingleUse) const {
807 EVT VT = Op.getValueType();
808
809 // Since the number of lanes in a scalable vector is unknown at compile time,
810 // we track one bit which is implicitly broadcast to all lanes. This means
811 // that all lanes in a scalable vector are considered demanded.
812 APInt DemandedElts = VT.isFixedLengthVector()
814 : APInt(1, 1);
815 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
816 AssumeSingleUse);
817}
818
819// TODO: Under what circumstances can we create nodes? Constant folding?
821 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
822 SelectionDAG &DAG, unsigned Depth) const {
823 EVT VT = Op.getValueType();
824
825 // Limit search depth.
827 return SDValue();
828
829 // Ignore UNDEFs.
830 if (Op.isUndef())
831 return SDValue();
832
833 // Not demanding any bits/elts from Op.
834 if (DemandedBits == 0 || DemandedElts == 0)
835 return DAG.getUNDEF(VT);
836
837 bool IsLE = DAG.getDataLayout().isLittleEndian();
838 unsigned NumElts = DemandedElts.getBitWidth();
839 unsigned BitWidth = DemandedBits.getBitWidth();
840 KnownBits LHSKnown, RHSKnown;
841 switch (Op.getOpcode()) {
842 case ISD::BITCAST: {
843 if (VT.isScalableVector())
844 return SDValue();
845
846 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
847 EVT SrcVT = Src.getValueType();
848 EVT DstVT = Op.getValueType();
849 if (SrcVT == DstVT)
850 return Src;
851
852 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
853 unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
854 if (NumSrcEltBits == NumDstEltBits)
856 Src, DemandedBits, DemandedElts, DAG, Depth + 1))
857 return DAG.getBitcast(DstVT, V);
858
859 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
860 unsigned Scale = NumDstEltBits / NumSrcEltBits;
861 unsigned NumSrcElts = SrcVT.getVectorNumElements();
862 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
863 for (unsigned i = 0; i != Scale; ++i) {
864 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
865 unsigned BitOffset = EltOffset * NumSrcEltBits;
866 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
867 }
868 // Recursive calls below may turn not demanded elements into poison, so we
869 // need to demand all smaller source elements that maps to a demanded
870 // destination element.
871 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
872
874 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
875 return DAG.getBitcast(DstVT, V);
876 }
877
878 // TODO - bigendian once we have test coverage.
879 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
880 unsigned Scale = NumSrcEltBits / NumDstEltBits;
881 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
882 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
883 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
884 for (unsigned i = 0; i != NumElts; ++i)
885 if (DemandedElts[i]) {
886 unsigned Offset = (i % Scale) * NumDstEltBits;
887 DemandedSrcBits.insertBits(DemandedBits, Offset);
888 DemandedSrcElts.setBit(i / Scale);
889 }
890
892 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
893 return DAG.getBitcast(DstVT, V);
894 }
895
896 break;
897 }
899 if (!VT.isScalableVector() && !DemandedElts[0])
900 return DAG.getPOISON(VT);
901 break;
902 }
903 case ISD::AND: {
904 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
905 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
906
907 // If all of the demanded bits are known 1 on one side, return the other.
908 // These bits cannot contribute to the result of the 'and' in this
909 // context.
910 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
911 return Op.getOperand(0);
912 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
913 return Op.getOperand(1);
914 break;
915 }
916 case ISD::OR: {
917 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
918 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
919
920 // If all of the demanded bits are known zero on one side, return the
921 // other. These bits cannot contribute to the result of the 'or' in this
922 // context.
923 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
924 return Op.getOperand(0);
925 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
926 return Op.getOperand(1);
927 break;
928 }
929 case ISD::XOR: {
930 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
931 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
932
933 // If all of the demanded bits are known zero on one side, return the
934 // other.
935 if (DemandedBits.isSubsetOf(RHSKnown.Zero))
936 return Op.getOperand(0);
937 if (DemandedBits.isSubsetOf(LHSKnown.Zero))
938 return Op.getOperand(1);
939 break;
940 }
941 case ISD::ADD:
942 case ISD::MUL:
943 case ISD::SMIN:
944 case ISD::SMAX:
945 case ISD::UMIN:
946 case ISD::UMAX: {
947 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(1),
948 DemandedElts, 1, Depth + 1))
949 return Op.getOperand(0);
950
951 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(0),
952 DemandedElts, 0, Depth + 1))
953 return Op.getOperand(1);
954 break;
955 }
956 case ISD::SHL: {
957 // If we are only demanding sign bits then we can use the shift source
958 // directly.
959 if (std::optional<unsigned> MaxSA =
960 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
961 SDValue Op0 = Op.getOperand(0);
962 unsigned ShAmt = *MaxSA;
963 unsigned NumSignBits =
964 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
965 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
966 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
967 return Op0;
968 }
969 break;
970 }
971 case ISD::SRL: {
972 // If we are only demanding sign bits then we can use the shift source
973 // directly.
974 if (std::optional<unsigned> MaxSA =
975 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
976 SDValue Op0 = Op.getOperand(0);
977 unsigned ShAmt = *MaxSA;
978 // Must already be signbits in DemandedBits bounds, and can't demand any
979 // shifted in zeroes.
980 if (DemandedBits.countl_zero() >= ShAmt) {
981 unsigned NumSignBits =
982 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
983 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
984 return Op0;
985 }
986 }
987 break;
988 }
989 case ISD::SETCC: {
990 SDValue Op0 = Op.getOperand(0);
991 SDValue Op1 = Op.getOperand(1);
992 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
993 // If (1) we only need the sign-bit, (2) the setcc operands are the same
994 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
995 // -1, we may be able to bypass the setcc.
996 if (DemandedBits.isSignMask() &&
1000 // If we're testing X < 0, then this compare isn't needed - just use X!
1001 // FIXME: We're limiting to integer types here, but this should also work
1002 // if we don't care about FP signed-zero. The use of SETLT with FP means
1003 // that we don't care about NaNs.
1004 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1006 return Op0;
1007 }
1008 break;
1009 }
1011 // If none of the extended bits are demanded, eliminate the sextinreg.
1012 SDValue Op0 = Op.getOperand(0);
1013 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1014 unsigned ExBits = ExVT.getScalarSizeInBits();
1015 if (DemandedBits.getActiveBits() <= ExBits &&
1017 return Op0;
1018 // If the input is already sign extended, just drop the extension.
1019 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1020 if (NumSignBits >= (BitWidth - ExBits + 1))
1021 return Op0;
1022 break;
1023 }
1027 if (VT.isScalableVector())
1028 return SDValue();
1029
1030 // If we only want the lowest element and none of extended bits, then we can
1031 // return the bitcasted source vector.
1032 SDValue Src = Op.getOperand(0);
1033 EVT SrcVT = Src.getValueType();
1034 EVT DstVT = Op.getValueType();
1035 if (IsLE && DemandedElts == 1 &&
1036 DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
1037 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
1038 return DAG.getBitcast(DstVT, Src);
1039 }
1040 break;
1041 }
1043 if (VT.isScalableVector())
1044 return SDValue();
1045
1046 // If we don't demand the inserted element, return the base vector.
1047 SDValue Vec = Op.getOperand(0);
1048 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1049 EVT VecVT = Vec.getValueType();
1050 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
1051 !DemandedElts[CIdx->getZExtValue()])
1052 return Vec;
1053 break;
1054 }
1055 case ISD::INSERT_SUBVECTOR: {
1056 if (VT.isScalableVector())
1057 return SDValue();
1058
1059 SDValue Vec = Op.getOperand(0);
1060 SDValue Sub = Op.getOperand(1);
1061 uint64_t Idx = Op.getConstantOperandVal(2);
1062 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1063 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1064 // If we don't demand the inserted subvector, return the base vector.
1065 if (DemandedSubElts == 0)
1066 return Vec;
1067 break;
1068 }
1069 case ISD::VECTOR_SHUFFLE: {
1070 assert(!VT.isScalableVector());
1071 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1072
1073 // If all the demanded elts are from one operand and are inline,
1074 // then we can use the operand directly.
1075 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
1076 for (unsigned i = 0; i != NumElts; ++i) {
1077 int M = ShuffleMask[i];
1078 if (M < 0 || !DemandedElts[i])
1079 continue;
1080 AllUndef = false;
1081 IdentityLHS &= (M == (int)i);
1082 IdentityRHS &= ((M - NumElts) == i);
1083 }
1084
1085 if (AllUndef)
1086 return DAG.getUNDEF(Op.getValueType());
1087 if (IdentityLHS)
1088 return Op.getOperand(0);
1089 if (IdentityRHS)
1090 return Op.getOperand(1);
1091 break;
1092 }
1093 default:
1094 // TODO: Probably okay to remove after audit; here to reduce change size
1095 // in initial enablement patch for scalable vectors
1096 if (VT.isScalableVector())
1097 return SDValue();
1098
1099 if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
1101 Op, DemandedBits, DemandedElts, DAG, Depth))
1102 return V;
1103 break;
1104 }
1105 return SDValue();
1106}
1107
1110 unsigned Depth) const {
1111 EVT VT = Op.getValueType();
1112 // Since the number of lanes in a scalable vector is unknown at compile time,
1113 // we track one bit which is implicitly broadcast to all lanes. This means
1114 // that all lanes in a scalable vector are considered demanded.
1115 APInt DemandedElts = VT.isFixedLengthVector()
1117 : APInt(1, 1);
1118 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1119 Depth);
1120}
1121
1123 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
1124 unsigned Depth) const {
1125 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
1126 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1127 Depth);
1128}
1129
1130// Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
1131// or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
1134 const TargetLowering &TLI,
1135 const APInt &DemandedBits,
1136 const APInt &DemandedElts, unsigned Depth) {
1137 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1138 "SRL or SRA node is required here!");
1139 // Is the right shift using an immediate value of 1?
1140 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1141 if (!N1C || !N1C->isOne())
1142 return SDValue();
1143
1144 // We are looking for an avgfloor
1145 // add(ext, ext)
1146 // or one of these as a avgceil
1147 // add(add(ext, ext), 1)
1148 // add(add(ext, 1), ext)
1149 // add(ext, add(ext, 1))
1150 SDValue Add = Op.getOperand(0);
1151 if (Add.getOpcode() != ISD::ADD)
1152 return SDValue();
1153
1154 SDValue ExtOpA = Add.getOperand(0);
1155 SDValue ExtOpB = Add.getOperand(1);
1156 SDValue Add2;
1157 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) {
1158 ConstantSDNode *ConstOp;
1159 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
1160 ConstOp->isOne()) {
1161 ExtOpA = Op1;
1162 ExtOpB = Op3;
1163 Add2 = A;
1164 return true;
1165 }
1166 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
1167 ConstOp->isOne()) {
1168 ExtOpA = Op1;
1169 ExtOpB = Op2;
1170 Add2 = A;
1171 return true;
1172 }
1173 return false;
1174 };
1175 bool IsCeil =
1176 (ExtOpA.getOpcode() == ISD::ADD &&
1177 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) ||
1178 (ExtOpB.getOpcode() == ISD::ADD &&
1179 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB));
1180
1181 // If the shift is signed (sra):
1182 // - Needs >= 2 sign bit for both operands.
1183 // - Needs >= 2 zero bits.
1184 // If the shift is unsigned (srl):
1185 // - Needs >= 1 zero bit for both operands.
1186 // - Needs 1 demanded bit zero and >= 2 sign bits.
1187 SelectionDAG &DAG = TLO.DAG;
1188 unsigned ShiftOpc = Op.getOpcode();
1189 bool IsSigned = false;
1190 unsigned KnownBits;
1191 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
1192 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
1193 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
1194 unsigned NumZeroA =
1195 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
1196 unsigned NumZeroB =
1197 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
1198 unsigned NumZero = std::min(NumZeroA, NumZeroB);
1199
1200 switch (ShiftOpc) {
1201 default:
1202 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
1203 case ISD::SRA: {
1204 if (NumZero >= 2 && NumSigned < NumZero) {
1205 IsSigned = false;
1206 KnownBits = NumZero;
1207 break;
1208 }
1209 if (NumSigned >= 1) {
1210 IsSigned = true;
1211 KnownBits = NumSigned;
1212 break;
1213 }
1214 return SDValue();
1215 }
1216 case ISD::SRL: {
1217 if (NumZero >= 1 && NumSigned < NumZero) {
1218 IsSigned = false;
1219 KnownBits = NumZero;
1220 break;
1221 }
1222 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1223 IsSigned = true;
1224 KnownBits = NumSigned;
1225 break;
1226 }
1227 return SDValue();
1228 }
1229 }
1230
1231 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1232 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1233
1234 // Find the smallest power-2 type that is legal for this vector size and
1235 // operation, given the original type size and the number of known sign/zero
1236 // bits.
1237 EVT VT = Op.getValueType();
1238 unsigned MinWidth =
1239 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1240 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth));
1242 return SDValue();
1243 if (VT.isVector())
1244 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1245 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) {
1246 // If we could not transform, and (both) adds are nuw/nsw, we can use the
1247 // larger type size to do the transform.
1248 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT))
1249 return SDValue();
1250 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0),
1251 Add.getOperand(1)) &&
1252 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0),
1253 Add2.getOperand(1))))
1254 NVT = VT;
1255 else
1256 return SDValue();
1257 }
1258
1259 // Don't create a AVGFLOOR node with a scalar constant unless its legal as
1260 // this is likely to stop other folds (reassociation, value tracking etc.)
1261 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) &&
1262 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB)))
1263 return SDValue();
1264
1265 SDLoc DL(Op);
1266 SDValue ResultAVG =
1267 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT),
1268 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT));
1269 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT);
1270}
1271
1272/// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1273/// result of Op are ever used downstream. If we can use this information to
1274/// simplify Op, create a new simplified DAG node and return true, returning the
1275/// original and new nodes in Old and New. Otherwise, analyze the expression and
1276/// return a mask of Known bits for the expression (used to simplify the
1277/// caller). The Known bits may only be accurate for those bits in the
1278/// OriginalDemandedBits and OriginalDemandedElts.
1280 SDValue Op, const APInt &OriginalDemandedBits,
1281 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1282 unsigned Depth, bool AssumeSingleUse) const {
1283 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1284 assert(Op.getScalarValueSizeInBits() == BitWidth &&
1285 "Mask size mismatches value type size!");
1286
1287 // Don't know anything.
1289
1290 EVT VT = Op.getValueType();
1291 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1292 unsigned NumElts = OriginalDemandedElts.getBitWidth();
1293 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1294 "Unexpected vector size");
1295
1296 APInt DemandedBits = OriginalDemandedBits;
1297 APInt DemandedElts = OriginalDemandedElts;
1298 SDLoc dl(Op);
1299
1300 // Undef operand.
1301 if (Op.isUndef())
1302 return false;
1303
1304 // We can't simplify target constants.
1305 if (Op.getOpcode() == ISD::TargetConstant)
1306 return false;
1307
1308 if (Op.getOpcode() == ISD::Constant) {
1309 // We know all of the bits for a constant!
1310 Known = KnownBits::makeConstant(Op->getAsAPIntVal());
1311 return false;
1312 }
1313
1314 if (Op.getOpcode() == ISD::ConstantFP) {
1315 // We know all of the bits for a floating point constant!
1317 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1318 return false;
1319 }
1320
1321 // Other users may use these bits.
1322 bool HasMultiUse = false;
1323 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1325 // Limit search depth.
1326 return false;
1327 }
1328 // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1330 DemandedElts = APInt::getAllOnes(NumElts);
1331 HasMultiUse = true;
1332 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1333 // Not demanding any bits/elts from Op.
1334 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1335 } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1336 // Limit search depth.
1337 return false;
1338 }
1339
1340 KnownBits Known2;
1341 switch (Op.getOpcode()) {
1342 case ISD::SCALAR_TO_VECTOR: {
1343 if (VT.isScalableVector())
1344 return false;
1345 if (!DemandedElts[0])
1346 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
1347
1348 KnownBits SrcKnown;
1349 SDValue Src = Op.getOperand(0);
1350 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1351 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1352 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1353 return true;
1354
1355 // Upper elements are poison, so only get the knownbits if we just demand
1356 // the bottom element.
1357 if (DemandedElts == 1)
1358 Known = SrcKnown.anyextOrTrunc(BitWidth);
1359 break;
1360 }
1361 case ISD::BUILD_VECTOR:
1362 // Collect the known bits that are shared by every demanded element.
1363 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1364 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1365 return false; // Don't fall through, will infinitely loop.
1366 case ISD::SPLAT_VECTOR: {
1367 SDValue Scl = Op.getOperand(0);
1368 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1369 KnownBits KnownScl;
1370 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1371 return true;
1372
1373 // Implicitly truncate the bits to match the official semantics of
1374 // SPLAT_VECTOR.
1375 Known = KnownScl.trunc(BitWidth);
1376 break;
1377 }
1378 case ISD::FREEZE: {
1379 SDValue N0 = Op.getOperand(0);
1381 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
1382 return TLO.CombineTo(Op, N0);
1383 break;
1384 }
1385 case ISD::LOAD: {
1386 auto *LD = cast<LoadSDNode>(Op);
1387 if (getTargetConstantFromLoad(LD)) {
1388 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1389 return false; // Don't fall through, will infinitely loop.
1390 }
1391 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1392 // If this is a ZEXTLoad and we are looking at the loaded value.
1393 EVT MemVT = LD->getMemoryVT();
1394 unsigned MemBits = MemVT.getScalarSizeInBits();
1395 Known.Zero.setBitsFrom(MemBits);
1396 return false; // Don't fall through, will infinitely loop.
1397 }
1398 break;
1399 }
1401 if (VT.isScalableVector())
1402 return false;
1403 SDValue Vec = Op.getOperand(0);
1404 SDValue Scl = Op.getOperand(1);
1405 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1406 EVT VecVT = Vec.getValueType();
1407
1408 // If index isn't constant, assume we need all vector elements AND the
1409 // inserted element.
1410 APInt DemandedVecElts(DemandedElts);
1411 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1412 unsigned Idx = CIdx->getZExtValue();
1413 DemandedVecElts.clearBit(Idx);
1414
1415 // Inserted element is not required.
1416 if (!DemandedElts[Idx])
1417 return TLO.CombineTo(Op, Vec);
1418 }
1419
1420 KnownBits KnownScl;
1421 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1422 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1423 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1424 return true;
1425
1426 Known = KnownScl.anyextOrTrunc(BitWidth);
1427
1428 KnownBits KnownVec;
1429 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1430 Depth + 1))
1431 return true;
1432
1433 if (!!DemandedVecElts)
1434 Known = Known.intersectWith(KnownVec);
1435
1436 return false;
1437 }
1438 case ISD::INSERT_SUBVECTOR: {
1439 if (VT.isScalableVector())
1440 return false;
1441 // Demand any elements from the subvector and the remainder from the src its
1442 // inserted into.
1443 SDValue Src = Op.getOperand(0);
1444 SDValue Sub = Op.getOperand(1);
1445 uint64_t Idx = Op.getConstantOperandVal(2);
1446 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1447 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1448 APInt DemandedSrcElts = DemandedElts;
1449 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
1450
1451 KnownBits KnownSub, KnownSrc;
1452 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1453 Depth + 1))
1454 return true;
1455 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1456 Depth + 1))
1457 return true;
1458
1459 Known.setAllConflict();
1460 if (!!DemandedSubElts)
1461 Known = Known.intersectWith(KnownSub);
1462 if (!!DemandedSrcElts)
1463 Known = Known.intersectWith(KnownSrc);
1464
1465 // Attempt to avoid multi-use src if we don't need anything from it.
1466 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1467 !DemandedSrcElts.isAllOnes()) {
1469 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1471 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1472 if (NewSub || NewSrc) {
1473 NewSub = NewSub ? NewSub : Sub;
1474 NewSrc = NewSrc ? NewSrc : Src;
1475 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1476 Op.getOperand(2));
1477 return TLO.CombineTo(Op, NewOp);
1478 }
1479 }
1480 break;
1481 }
1483 if (VT.isScalableVector())
1484 return false;
1485 // Offset the demanded elts by the subvector index.
1486 SDValue Src = Op.getOperand(0);
1487 if (Src.getValueType().isScalableVector())
1488 break;
1489 uint64_t Idx = Op.getConstantOperandVal(1);
1490 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1491 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1492
1493 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1494 Depth + 1))
1495 return true;
1496
1497 // Attempt to avoid multi-use src if we don't need anything from it.
1498 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1500 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1501 if (DemandedSrc) {
1502 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1503 Op.getOperand(1));
1504 return TLO.CombineTo(Op, NewOp);
1505 }
1506 }
1507 break;
1508 }
1509 case ISD::CONCAT_VECTORS: {
1510 if (VT.isScalableVector())
1511 return false;
1512 Known.setAllConflict();
1513 EVT SubVT = Op.getOperand(0).getValueType();
1514 unsigned NumSubVecs = Op.getNumOperands();
1515 unsigned NumSubElts = SubVT.getVectorNumElements();
1516 for (unsigned i = 0; i != NumSubVecs; ++i) {
1517 APInt DemandedSubElts =
1518 DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1519 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1520 Known2, TLO, Depth + 1))
1521 return true;
1522 // Known bits are shared by every demanded subvector element.
1523 if (!!DemandedSubElts)
1524 Known = Known.intersectWith(Known2);
1525 }
1526 break;
1527 }
1528 case ISD::VECTOR_SHUFFLE: {
1529 assert(!VT.isScalableVector());
1530 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1531
1532 // Collect demanded elements from shuffle operands..
1533 APInt DemandedLHS, DemandedRHS;
1534 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1535 DemandedRHS))
1536 break;
1537
1538 if (!!DemandedLHS || !!DemandedRHS) {
1539 SDValue Op0 = Op.getOperand(0);
1540 SDValue Op1 = Op.getOperand(1);
1541
1542 Known.setAllConflict();
1543 if (!!DemandedLHS) {
1544 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1545 Depth + 1))
1546 return true;
1547 Known = Known.intersectWith(Known2);
1548 }
1549 if (!!DemandedRHS) {
1550 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1551 Depth + 1))
1552 return true;
1553 Known = Known.intersectWith(Known2);
1554 }
1555
1556 // Attempt to avoid multi-use ops if we don't need anything from them.
1558 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1560 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1561 if (DemandedOp0 || DemandedOp1) {
1562 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1563 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1564 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1565 return TLO.CombineTo(Op, NewOp);
1566 }
1567 }
1568 break;
1569 }
1570 case ISD::AND: {
1571 SDValue Op0 = Op.getOperand(0);
1572 SDValue Op1 = Op.getOperand(1);
1573
1574 // If the RHS is a constant, check to see if the LHS would be zero without
1575 // using the bits from the RHS. Below, we use knowledge about the RHS to
1576 // simplify the LHS, here we're using information from the LHS to simplify
1577 // the RHS.
1578 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) {
1579 // Do not increment Depth here; that can cause an infinite loop.
1580 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1581 // If the LHS already has zeros where RHSC does, this 'and' is dead.
1582 if ((LHSKnown.Zero & DemandedBits) ==
1583 (~RHSC->getAPIntValue() & DemandedBits))
1584 return TLO.CombineTo(Op, Op0);
1585
1586 // If any of the set bits in the RHS are known zero on the LHS, shrink
1587 // the constant.
1588 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1589 DemandedElts, TLO))
1590 return true;
1591
1592 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1593 // constant, but if this 'and' is only clearing bits that were just set by
1594 // the xor, then this 'and' can be eliminated by shrinking the mask of
1595 // the xor. For example, for a 32-bit X:
1596 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1597 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1598 LHSKnown.One == ~RHSC->getAPIntValue()) {
1599 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1600 return TLO.CombineTo(Op, Xor);
1601 }
1602 }
1603
1604 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2 (or zero).
1605 SDValue X, Y;
1606 if (sd_match(Op,
1607 m_And(m_Value(Y),
1609 m_Sub(m_Value(X), m_Deferred(Y)))))) &&
1610 TLO.DAG.isKnownToBeAPowerOfTwo(Y, DemandedElts, /*OrZero=*/true)) {
1611 return TLO.CombineTo(
1612 Op, TLO.DAG.getNode(ISD::AND, dl, VT, TLO.DAG.getNOT(dl, X, VT), Y));
1613 }
1614
1615 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1616 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1617 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1618 (Op0.getOperand(0).isUndef() ||
1620 Op0->hasOneUse()) {
1621 unsigned NumSubElts =
1623 unsigned SubIdx = Op0.getConstantOperandVal(2);
1624 APInt DemandedSub =
1625 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1626 KnownBits KnownSubMask =
1627 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1628 if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1629 SDValue NewAnd =
1630 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1631 SDValue NewInsert =
1632 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1633 Op0.getOperand(1), Op0.getOperand(2));
1634 return TLO.CombineTo(Op, NewInsert);
1635 }
1636 }
1637
1638 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1639 Depth + 1))
1640 return true;
1641 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1642 Known2, TLO, Depth + 1))
1643 return true;
1644
1645 // If all of the demanded bits are known one on one side, return the other.
1646 // These bits cannot contribute to the result of the 'and'.
1647 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1648 return TLO.CombineTo(Op, Op0);
1649 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1650 return TLO.CombineTo(Op, Op1);
1651 // If all of the demanded bits in the inputs are known zeros, return zero.
1652 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1653 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1654 // If the RHS is a constant, see if we can simplify it.
1655 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1656 TLO))
1657 return true;
1658 // If the operation can be done in a smaller type, do so.
1660 return true;
1661
1662 // Attempt to avoid multi-use ops if we don't need anything from them.
1663 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1665 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1667 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1668 if (DemandedOp0 || DemandedOp1) {
1669 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1670 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1671 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1672 return TLO.CombineTo(Op, NewOp);
1673 }
1674 }
1675
1676 Known &= Known2;
1677 break;
1678 }
1679 case ISD::OR: {
1680 SDValue Op0 = Op.getOperand(0);
1681 SDValue Op1 = Op.getOperand(1);
1682 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1683 Depth + 1)) {
1684 Op->dropFlags(SDNodeFlags::Disjoint);
1685 return true;
1686 }
1687
1688 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1689 Known2, TLO, Depth + 1)) {
1690 Op->dropFlags(SDNodeFlags::Disjoint);
1691 return true;
1692 }
1693
1694 // If all of the demanded bits are known zero on one side, return the other.
1695 // These bits cannot contribute to the result of the 'or'.
1696 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1697 return TLO.CombineTo(Op, Op0);
1698 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1699 return TLO.CombineTo(Op, Op1);
1700 // If the RHS is a constant, see if we can simplify it.
1701 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1702 return true;
1703 // If the operation can be done in a smaller type, do so.
1705 return true;
1706
1707 // Attempt to avoid multi-use ops if we don't need anything from them.
1708 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1710 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1712 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1713 if (DemandedOp0 || DemandedOp1) {
1714 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1715 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1716 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1717 return TLO.CombineTo(Op, NewOp);
1718 }
1719 }
1720
1721 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1722 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1723 SDValue X, Y, C1, C2;
1726 m_Value(C2)))))) {
1727 if (SDValue C12 =
1728 TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, {C1, C2})) {
1729 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1730 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1731 return TLO.CombineTo(Op,
1732 TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1733 }
1734 }
1735
1736 Known |= Known2;
1737 break;
1738 }
1739 case ISD::XOR: {
1740 SDValue Op0 = Op.getOperand(0);
1741 SDValue Op1 = Op.getOperand(1);
1742
1743 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1744 Depth + 1))
1745 return true;
1746 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1747 Depth + 1))
1748 return true;
1749
1750 // If all of the demanded bits are known zero on one side, return the other.
1751 // These bits cannot contribute to the result of the 'xor'.
1752 if (DemandedBits.isSubsetOf(Known.Zero))
1753 return TLO.CombineTo(Op, Op0);
1754 if (DemandedBits.isSubsetOf(Known2.Zero))
1755 return TLO.CombineTo(Op, Op1);
1756 // If the operation can be done in a smaller type, do so.
1758 return true;
1759
1760 // If all of the unknown bits are known to be zero on one side or the other
1761 // turn this into an *inclusive* or.
1762 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1763 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1764 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1765
1766 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1767 if (C) {
1768 // If one side is a constant, and all of the set bits in the constant are
1769 // also known set on the other side, turn this into an AND, as we know
1770 // the bits will be cleared.
1771 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1772 // NB: it is okay if more bits are known than are requested
1773 if (C->getAPIntValue() == Known2.One) {
1774 SDValue ANDC =
1775 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1776 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1777 }
1778
1779 // If the RHS is a constant, see if we can change it. Don't alter a -1
1780 // constant because that's a 'not' op, and that is better for combining
1781 // and codegen.
1782 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1783 // We're flipping all demanded bits. Flip the undemanded bits too.
1784 SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1785 return TLO.CombineTo(Op, New);
1786 }
1787
1788 unsigned Op0Opcode = Op0.getOpcode();
1789 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1790 if (ConstantSDNode *ShiftC =
1791 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1792 // Don't crash on an oversized shift. We can not guarantee that a
1793 // bogus shift has been simplified to undef.
1794 if (ShiftC->getAPIntValue().ult(BitWidth)) {
1795 uint64_t ShiftAmt = ShiftC->getZExtValue();
1797 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1798 : Ones.lshr(ShiftAmt);
1799 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1801 // If the xor constant is a demanded mask, do a 'not' before the
1802 // shift:
1803 // xor (X << ShiftC), XorC --> (not X) << ShiftC
1804 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1805 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1806 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1807 Op0.getOperand(1)));
1808 }
1809 }
1810 }
1811 }
1812 }
1813
1814 // If we can't turn this into a 'not', try to shrink the constant.
1815 if (!C || !C->isAllOnes())
1816 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1817 return true;
1818
1819 // Attempt to avoid multi-use ops if we don't need anything from them.
1820 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1822 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1824 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1825 if (DemandedOp0 || DemandedOp1) {
1826 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1827 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1828 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1829 return TLO.CombineTo(Op, NewOp);
1830 }
1831 }
1832
1833 Known ^= Known2;
1834 break;
1835 }
1836 case ISD::SELECT:
1837 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1838 Known, TLO, Depth + 1))
1839 return true;
1840 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1841 Known2, TLO, Depth + 1))
1842 return true;
1843
1844 // If the operands are constants, see if we can simplify them.
1845 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1846 return true;
1847
1848 // Only known if known in both the LHS and RHS.
1849 Known = Known.intersectWith(Known2);
1850 break;
1851 case ISD::VSELECT:
1852 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1853 Known, TLO, Depth + 1))
1854 return true;
1855 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1856 Known2, TLO, Depth + 1))
1857 return true;
1858
1859 // Only known if known in both the LHS and RHS.
1860 Known = Known.intersectWith(Known2);
1861 break;
1862 case ISD::SELECT_CC:
1863 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts,
1864 Known, TLO, Depth + 1))
1865 return true;
1866 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1867 Known2, TLO, Depth + 1))
1868 return true;
1869
1870 // If the operands are constants, see if we can simplify them.
1871 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1872 return true;
1873
1874 // Only known if known in both the LHS and RHS.
1875 Known = Known.intersectWith(Known2);
1876 break;
1877 case ISD::SETCC: {
1878 SDValue Op0 = Op.getOperand(0);
1879 SDValue Op1 = Op.getOperand(1);
1880 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1881 // If we're testing X < 0, X >= 0, X <= -1 or X > -1
1882 // (X is of integer type) then we only need the sign mask of the previous
1883 // result
1884 if (Op1.getValueType().isInteger() &&
1885 (((CC == ISD::SETLT || CC == ISD::SETGE) && isNullOrNullSplat(Op1)) ||
1886 ((CC == ISD::SETLE || CC == ISD::SETGT) &&
1887 isAllOnesOrAllOnesSplat(Op1)))) {
1888 KnownBits KnownOp0;
1891 DemandedElts, KnownOp0, TLO, Depth + 1))
1892 return true;
1893 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1894 // width as the setcc result, and (3) the result of a setcc conforms to 0
1895 // or -1, we may be able to bypass the setcc.
1896 if (DemandedBits.isSignMask() &&
1900 // If we remove a >= 0 or > -1 (for integers), we need to introduce a
1901 // NOT Operation
1902 if (CC == ISD::SETGE || CC == ISD::SETGT) {
1903 SDLoc DL(Op);
1904 EVT VT = Op0.getValueType();
1905 SDValue NotOp0 = TLO.DAG.getNOT(DL, Op0, VT);
1906 return TLO.CombineTo(Op, NotOp0);
1907 }
1908 return TLO.CombineTo(Op, Op0);
1909 }
1910 }
1911 if (getBooleanContents(Op0.getValueType()) ==
1913 BitWidth > 1)
1914 Known.Zero.setBitsFrom(1);
1915 break;
1916 }
1917 case ISD::SHL: {
1918 SDValue Op0 = Op.getOperand(0);
1919 SDValue Op1 = Op.getOperand(1);
1920 EVT ShiftVT = Op1.getValueType();
1921
1922 if (std::optional<unsigned> KnownSA =
1923 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
1924 unsigned ShAmt = *KnownSA;
1925 if (ShAmt == 0)
1926 return TLO.CombineTo(Op, Op0);
1927
1928 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1929 // single shift. We can do this if the bottom bits (which are shifted
1930 // out) are never demanded.
1931 // TODO - support non-uniform vector amounts.
1932 if (Op0.getOpcode() == ISD::SRL) {
1933 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1934 if (std::optional<unsigned> InnerSA =
1935 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
1936 unsigned C1 = *InnerSA;
1937 unsigned Opc = ISD::SHL;
1938 int Diff = ShAmt - C1;
1939 if (Diff < 0) {
1940 Diff = -Diff;
1941 Opc = ISD::SRL;
1942 }
1943 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1944 return TLO.CombineTo(
1945 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1946 }
1947 }
1948 }
1949
1950 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1951 // are not demanded. This will likely allow the anyext to be folded away.
1952 // TODO - support non-uniform vector amounts.
1953 if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1954 SDValue InnerOp = Op0.getOperand(0);
1955 EVT InnerVT = InnerOp.getValueType();
1956 unsigned InnerBits = InnerVT.getScalarSizeInBits();
1957 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1958 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1959 SDValue NarrowShl = TLO.DAG.getNode(
1960 ISD::SHL, dl, InnerVT, InnerOp,
1961 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
1962 return TLO.CombineTo(
1963 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1964 }
1965
1966 // Repeat the SHL optimization above in cases where an extension
1967 // intervenes: (shl (anyext (shr x, c1)), c2) to
1968 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
1969 // aren't demanded (as above) and that the shifted upper c1 bits of
1970 // x aren't demanded.
1971 // TODO - support non-uniform vector amounts.
1972 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
1973 InnerOp.hasOneUse()) {
1974 if (std::optional<unsigned> SA2 = TLO.DAG.getValidShiftAmount(
1975 InnerOp, DemandedElts, Depth + 2)) {
1976 unsigned InnerShAmt = *SA2;
1977 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1978 DemandedBits.getActiveBits() <=
1979 (InnerBits - InnerShAmt + ShAmt) &&
1980 DemandedBits.countr_zero() >= ShAmt) {
1981 SDValue NewSA =
1982 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1983 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1984 InnerOp.getOperand(0));
1985 return TLO.CombineTo(
1986 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1987 }
1988 }
1989 }
1990 }
1991
1992 APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1993 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1994 Depth + 1)) {
1995 // Disable the nsw and nuw flags. We can no longer guarantee that we
1996 // won't wrap after simplification.
1997 Op->dropFlags(SDNodeFlags::NoWrap);
1998 return true;
1999 }
2000 Known <<= ShAmt;
2001 // low bits known zero.
2002 Known.Zero.setLowBits(ShAmt);
2003
2004 // Attempt to avoid multi-use ops if we don't need anything from them.
2005 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2007 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2008 if (DemandedOp0) {
2009 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
2010 return TLO.CombineTo(Op, NewOp);
2011 }
2012 }
2013
2014 // TODO: Can we merge this fold with the one below?
2015 // Try shrinking the operation as long as the shift amount will still be
2016 // in range.
2017 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() &&
2018 Op.getNode()->hasOneUse()) {
2019 // Search for the smallest integer type with free casts to and from
2020 // Op's type. For expedience, just check power-of-2 integer types.
2021 unsigned DemandedSize = DemandedBits.getActiveBits();
2022 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
2023 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
2024 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits);
2025 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) &&
2026 isTypeDesirableForOp(ISD::SHL, SmallVT) &&
2027 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) &&
2028 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) {
2029 assert(DemandedSize <= SmallVTBits &&
2030 "Narrowed below demanded bits?");
2031 // We found a type with free casts.
2032 SDValue NarrowShl = TLO.DAG.getNode(
2033 ISD::SHL, dl, SmallVT,
2034 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
2035 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl));
2036 return TLO.CombineTo(
2037 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2038 }
2039 }
2040 }
2041
2042 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2043 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
2044 // Only do this if we demand the upper half so the knownbits are correct.
2045 unsigned HalfWidth = BitWidth / 2;
2046 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
2047 DemandedBits.countLeadingOnes() >= HalfWidth) {
2048 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
2049 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2050 isTypeDesirableForOp(ISD::SHL, HalfVT) &&
2051 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2052 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
2053 // If we're demanding the upper bits at all, we must ensure
2054 // that the upper bits of the shift result are known to be zero,
2055 // which is equivalent to the narrow shift being NUW.
2056 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
2057 bool IsNSW = Known.countMinSignBits() > HalfWidth;
2058 SDNodeFlags Flags;
2059 Flags.setNoSignedWrap(IsNSW);
2060 Flags.setNoUnsignedWrap(IsNUW);
2061 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2062 SDValue NewShiftAmt =
2063 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2064 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
2065 NewShiftAmt, Flags);
2066 SDValue NewExt =
2067 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
2068 return TLO.CombineTo(Op, NewExt);
2069 }
2070 }
2071 }
2072 } else {
2073 // This is a variable shift, so we can't shift the demand mask by a known
2074 // amount. But if we are not demanding high bits, then we are not
2075 // demanding those bits from the pre-shifted operand either.
2076 if (unsigned CTLZ = DemandedBits.countl_zero()) {
2077 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
2078 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
2079 Depth + 1)) {
2080 // Disable the nsw and nuw flags. We can no longer guarantee that we
2081 // won't wrap after simplification.
2082 Op->dropFlags(SDNodeFlags::NoWrap);
2083 return true;
2084 }
2085 Known.resetAll();
2086 }
2087 }
2088
2089 // If we are only demanding sign bits then we can use the shift source
2090 // directly.
2091 if (std::optional<unsigned> MaxSA =
2092 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2093 unsigned ShAmt = *MaxSA;
2094 unsigned NumSignBits =
2095 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2096 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
2097 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
2098 return TLO.CombineTo(Op, Op0);
2099 }
2100 break;
2101 }
2102 case ISD::SRL: {
2103 SDValue Op0 = Op.getOperand(0);
2104 SDValue Op1 = Op.getOperand(1);
2105 EVT ShiftVT = Op1.getValueType();
2106
2107 if (std::optional<unsigned> KnownSA =
2108 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2109 unsigned ShAmt = *KnownSA;
2110 if (ShAmt == 0)
2111 return TLO.CombineTo(Op, Op0);
2112
2113 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
2114 // single shift. We can do this if the top bits (which are shifted out)
2115 // are never demanded.
2116 // TODO - support non-uniform vector amounts.
2117 if (Op0.getOpcode() == ISD::SHL) {
2118 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2119 if (std::optional<unsigned> InnerSA =
2120 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2121 unsigned C1 = *InnerSA;
2122 unsigned Opc = ISD::SRL;
2123 int Diff = ShAmt - C1;
2124 if (Diff < 0) {
2125 Diff = -Diff;
2126 Opc = ISD::SHL;
2127 }
2128 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2129 return TLO.CombineTo(
2130 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2131 }
2132 }
2133 }
2134
2135 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a
2136 // single sra. We can do this if the top bits are never demanded.
2137 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) {
2138 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2139 if (std::optional<unsigned> InnerSA =
2140 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2141 unsigned C1 = *InnerSA;
2142 // Clamp the combined shift amount if it exceeds the bit width.
2143 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1);
2144 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT);
2145 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT,
2146 Op0.getOperand(0), NewSA));
2147 }
2148 }
2149 }
2150
2151 APInt InDemandedMask = (DemandedBits << ShAmt);
2152
2153 // If the shift is exact, then it does demand the low bits (and knows that
2154 // they are zero).
2155 if (Op->getFlags().hasExact())
2156 InDemandedMask.setLowBits(ShAmt);
2157
2158 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2159 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
2160 if ((BitWidth % 2) == 0 && !VT.isVector()) {
2162 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
2163 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2164 isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2165 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2166 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
2167 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
2168 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
2169 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2170 SDValue NewShiftAmt =
2171 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2172 SDValue NewShift =
2173 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt);
2174 return TLO.CombineTo(
2175 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
2176 }
2177 }
2178
2179 // Compute the new bits that are at the top now.
2180 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2181 Depth + 1))
2182 return true;
2183 Known >>= ShAmt;
2184 // High bits known zero.
2185 Known.Zero.setHighBits(ShAmt);
2186
2187 // Attempt to avoid multi-use ops if we don't need anything from them.
2188 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2190 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2191 if (DemandedOp0) {
2192 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
2193 return TLO.CombineTo(Op, NewOp);
2194 }
2195 }
2196 } else {
2197 // Use generic knownbits computation as it has support for non-uniform
2198 // shift amounts.
2199 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2200 }
2201
2202 // If we are only demanding sign bits then we can use the shift source
2203 // directly.
2204 if (std::optional<unsigned> MaxSA =
2205 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2206 unsigned ShAmt = *MaxSA;
2207 // Must already be signbits in DemandedBits bounds, and can't demand any
2208 // shifted in zeroes.
2209 if (DemandedBits.countl_zero() >= ShAmt) {
2210 unsigned NumSignBits =
2211 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2212 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
2213 return TLO.CombineTo(Op, Op0);
2214 }
2215 }
2216
2217 // Try to match AVG patterns (after shift simplification).
2218 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2219 DemandedElts, Depth + 1))
2220 return TLO.CombineTo(Op, AVG);
2221
2222 break;
2223 }
2224 case ISD::SRA: {
2225 SDValue Op0 = Op.getOperand(0);
2226 SDValue Op1 = Op.getOperand(1);
2227 EVT ShiftVT = Op1.getValueType();
2228
2229 // If we only want bits that already match the signbit then we don't need
2230 // to shift.
2231 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
2232 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
2233 NumHiDemandedBits)
2234 return TLO.CombineTo(Op, Op0);
2235
2236 // If this is an arithmetic shift right and only the low-bit is set, we can
2237 // always convert this into a logical shr, even if the shift amount is
2238 // variable. The low bit of the shift cannot be an input sign bit unless
2239 // the shift amount is >= the size of the datatype, which is undefined.
2240 if (DemandedBits.isOne())
2241 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2242
2243 if (std::optional<unsigned> KnownSA =
2244 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2245 unsigned ShAmt = *KnownSA;
2246 if (ShAmt == 0)
2247 return TLO.CombineTo(Op, Op0);
2248
2249 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2250 // supports sext_inreg.
2251 if (Op0.getOpcode() == ISD::SHL) {
2252 if (std::optional<unsigned> InnerSA =
2253 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2254 unsigned LowBits = BitWidth - ShAmt;
2255 EVT ExtVT = VT.changeElementType(
2256 *TLO.DAG.getContext(),
2257 EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits));
2258
2259 if (*InnerSA == ShAmt) {
2260 if (!TLO.LegalOperations() ||
2262 return TLO.CombineTo(
2263 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2264 Op0.getOperand(0),
2265 TLO.DAG.getValueType(ExtVT)));
2266
2267 // Even if we can't convert to sext_inreg, we might be able to
2268 // remove this shift pair if the input is already sign extended.
2269 unsigned NumSignBits =
2270 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2271 if (NumSignBits > ShAmt)
2272 return TLO.CombineTo(Op, Op0.getOperand(0));
2273 }
2274 }
2275 }
2276
2277 APInt InDemandedMask = (DemandedBits << ShAmt);
2278
2279 // If the shift is exact, then it does demand the low bits (and knows that
2280 // they are zero).
2281 if (Op->getFlags().hasExact())
2282 InDemandedMask.setLowBits(ShAmt);
2283
2284 // If any of the demanded bits are produced by the sign extension, we also
2285 // demand the input sign bit.
2286 if (DemandedBits.countl_zero() < ShAmt)
2287 InDemandedMask.setSignBit();
2288
2289 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2290 Depth + 1))
2291 return true;
2292 Known >>= ShAmt;
2293
2294 // If the input sign bit is known to be zero, or if none of the top bits
2295 // are demanded, turn this into an unsigned shift right.
2296 if (Known.Zero[BitWidth - ShAmt - 1] ||
2297 DemandedBits.countl_zero() >= ShAmt) {
2298 SDNodeFlags Flags;
2299 Flags.setExact(Op->getFlags().hasExact());
2300 return TLO.CombineTo(
2301 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2302 }
2303
2304 int Log2 = DemandedBits.exactLogBase2();
2305 if (Log2 >= 0) {
2306 // The bit must come from the sign.
2307 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2308 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2309 }
2310
2311 if (Known.One[BitWidth - ShAmt - 1])
2312 // New bits are known one.
2313 Known.One.setHighBits(ShAmt);
2314
2315 // Attempt to avoid multi-use ops if we don't need anything from them.
2316 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2318 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2319 if (DemandedOp0) {
2320 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2321 return TLO.CombineTo(Op, NewOp);
2322 }
2323 }
2324 }
2325
2326 // Try to match AVG patterns (after shift simplification).
2327 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2328 DemandedElts, Depth + 1))
2329 return TLO.CombineTo(Op, AVG);
2330
2331 break;
2332 }
2333 case ISD::FSHL:
2334 case ISD::FSHR: {
2335 SDValue Op0 = Op.getOperand(0);
2336 SDValue Op1 = Op.getOperand(1);
2337 SDValue Op2 = Op.getOperand(2);
2338 bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2339
2340 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2341 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2342
2343 // For fshl, 0-shift returns the 1st arg.
2344 // For fshr, 0-shift returns the 2nd arg.
2345 if (Amt == 0) {
2346 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2347 Known, TLO, Depth + 1))
2348 return true;
2349 break;
2350 }
2351
2352 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2353 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2354 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2355 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2356 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2357 Depth + 1))
2358 return true;
2359 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2360 Depth + 1))
2361 return true;
2362
2363 Known2 <<= (IsFSHL ? Amt : (BitWidth - Amt));
2364 Known >>= (IsFSHL ? (BitWidth - Amt) : Amt);
2365 Known = Known.unionWith(Known2);
2366
2367 // Attempt to avoid multi-use ops if we don't need anything from them.
2368 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2369 !DemandedElts.isAllOnes()) {
2371 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2373 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2374 if (DemandedOp0 || DemandedOp1) {
2375 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2376 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2377 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2378 DemandedOp1, Op2);
2379 return TLO.CombineTo(Op, NewOp);
2380 }
2381 }
2382 }
2383
2384 if (isPowerOf2_32(BitWidth)) {
2385 // Fold FSHR(Op0,Op1,Op2) -> SRL(Op1,Op2)
2386 // iff we're guaranteed not to use Op0.
2387 // TODO: Add FSHL equivalent?
2388 if (!IsFSHL && !DemandedBits.isAllOnes() &&
2389 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT))) {
2390 KnownBits KnownAmt =
2391 TLO.DAG.computeKnownBits(Op2, DemandedElts, Depth + 1);
2392 unsigned MaxShiftAmt =
2393 KnownAmt.getMaxValue().getLimitedValue(BitWidth - 1);
2394 // Check we don't demand any shifted bits outside Op1.
2395 if (DemandedBits.countl_zero() >= MaxShiftAmt) {
2396 EVT AmtVT = Op2.getValueType();
2397 SDValue NewAmt =
2398 TLO.DAG.getNode(ISD::AND, dl, AmtVT, Op2,
2399 TLO.DAG.getConstant(BitWidth - 1, dl, AmtVT));
2400 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, Op1, NewAmt);
2401 return TLO.CombineTo(Op, NewOp);
2402 }
2403 }
2404
2405 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2406 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2407 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, Known2, TLO,
2408 Depth + 1))
2409 return true;
2410 }
2411 break;
2412 }
2413 case ISD::ROTL:
2414 case ISD::ROTR: {
2415 SDValue Op0 = Op.getOperand(0);
2416 SDValue Op1 = Op.getOperand(1);
2417 bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2418
2419 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2420 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2421 return TLO.CombineTo(Op, Op0);
2422
2423 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2424 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2425 unsigned RevAmt = BitWidth - Amt;
2426
2427 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2428 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2429 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2430 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2431 Depth + 1))
2432 return true;
2433
2434 // rot*(x, 0) --> x
2435 if (Amt == 0)
2436 return TLO.CombineTo(Op, Op0);
2437
2438 // See if we don't demand either half of the rotated bits.
2439 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2440 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2441 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2442 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2443 }
2444 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2445 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2446 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2447 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2448 }
2449 }
2450
2451 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2452 if (isPowerOf2_32(BitWidth)) {
2453 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2454 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2455 Depth + 1))
2456 return true;
2457 }
2458 break;
2459 }
2460 case ISD::SMIN:
2461 case ISD::SMAX:
2462 case ISD::UMIN:
2463 case ISD::UMAX: {
2464 unsigned Opc = Op.getOpcode();
2465 SDValue Op0 = Op.getOperand(0);
2466 SDValue Op1 = Op.getOperand(1);
2467
2468 // If we're only demanding signbits, then we can simplify to OR/AND node.
2469 unsigned BitOp =
2470 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2471 unsigned NumSignBits =
2472 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2473 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2474 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2475 if (NumSignBits >= NumDemandedUpperBits)
2476 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2477
2478 // Check if one arg is always less/greater than (or equal) to the other arg.
2479 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2480 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2481 switch (Opc) {
2482 case ISD::SMIN:
2483 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2484 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2485 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2486 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2487 Known = KnownBits::smin(Known0, Known1);
2488 break;
2489 case ISD::SMAX:
2490 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2491 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2492 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2493 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2494 Known = KnownBits::smax(Known0, Known1);
2495 break;
2496 case ISD::UMIN:
2497 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2498 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2499 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2500 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2501 Known = KnownBits::umin(Known0, Known1);
2502 break;
2503 case ISD::UMAX:
2504 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2505 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2506 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2507 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2508 Known = KnownBits::umax(Known0, Known1);
2509 break;
2510 }
2511 break;
2512 }
2513 case ISD::BITREVERSE: {
2514 SDValue Src = Op.getOperand(0);
2515 APInt DemandedSrcBits = DemandedBits.reverseBits();
2516 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2517 Depth + 1))
2518 return true;
2519 Known = Known2.reverseBits();
2520 break;
2521 }
2522 case ISD::BSWAP: {
2523 SDValue Src = Op.getOperand(0);
2524
2525 // If the only bits demanded come from one byte of the bswap result,
2526 // just shift the input byte into position to eliminate the bswap.
2527 unsigned NLZ = DemandedBits.countl_zero();
2528 unsigned NTZ = DemandedBits.countr_zero();
2529
2530 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
2531 // we need all the bits down to bit 8. Likewise, round NLZ. If we
2532 // have 14 leading zeros, round to 8.
2533 NLZ = alignDown(NLZ, 8);
2534 NTZ = alignDown(NTZ, 8);
2535 // If we need exactly one byte, we can do this transformation.
2536 if (BitWidth - NLZ - NTZ == 8) {
2537 // Replace this with either a left or right shift to get the byte into
2538 // the right place.
2539 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2540 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2541 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2542 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
2543 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2544 return TLO.CombineTo(Op, NewOp);
2545 }
2546 }
2547
2548 APInt DemandedSrcBits = DemandedBits.byteSwap();
2549 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2550 Depth + 1))
2551 return true;
2552 Known = Known2.byteSwap();
2553 break;
2554 }
2555 case ISD::CTPOP: {
2556 // If only 1 bit is demanded, replace with PARITY as long as we're before
2557 // op legalization.
2558 // FIXME: Limit to scalars for now.
2559 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2560 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2561 Op.getOperand(0)));
2562
2563 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2564 break;
2565 }
2566 case ISD::PDEP: {
2567 SDValue Op0 = Op.getOperand(0);
2568 SDValue Op1 = Op.getOperand(1);
2569
2570 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2571 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2572
2573 // If the demanded bits has leading zeroes, we don't demand those from the
2574 // mask.
2575 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
2576 return true;
2577
2578 // The number of possible 1s in the mask determines the number of LSBs of
2579 // operand 0 used. Undemanded bits from the mask don't matter so filter
2580 // them before counting.
2581 KnownBits Known2;
2582 uint64_t Count = (~Known.Zero & LoMask).popcount();
2583 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
2584 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
2585 return true;
2586
2587 // Zeroes are retained from the mask, but not ones.
2588 Known.One.clearAllBits();
2589 // The result will have at least as many trailing zeros as the non-mask
2590 // operand since bits can only map to the same or higher bit position.
2591 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
2592 break;
2593 }
2595 SDValue Op0 = Op.getOperand(0);
2596 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2597 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2598
2599 // If we only care about the highest bit, don't bother shifting right.
2600 if (DemandedBits.isSignMask()) {
2601 unsigned MinSignedBits =
2602 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2603 bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2604 // However if the input is already sign extended we expect the sign
2605 // extension to be dropped altogether later and do not simplify.
2606 if (!AlreadySignExtended) {
2607 // Compute the correct shift amount type, which must be getShiftAmountTy
2608 // for scalar types after legalization.
2609 SDValue ShiftAmt =
2610 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl);
2611 return TLO.CombineTo(Op,
2612 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2613 }
2614 }
2615
2616 // If none of the extended bits are demanded, eliminate the sextinreg.
2617 if (DemandedBits.getActiveBits() <= ExVTBits)
2618 return TLO.CombineTo(Op, Op0);
2619
2620 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2621
2622 // Since the sign extended bits are demanded, we know that the sign
2623 // bit is demanded.
2624 InputDemandedBits.setBit(ExVTBits - 1);
2625
2626 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2627 Depth + 1))
2628 return true;
2629
2630 // If the sign bit of the input is known set or clear, then we know the
2631 // top bits of the result.
2632
2633 // If the input sign bit is known zero, convert this into a zero extension.
2634 if (Known.Zero[ExVTBits - 1])
2635 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2636
2637 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2638 if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2639 Known.One.setBitsFrom(ExVTBits);
2640 Known.Zero &= Mask;
2641 } else { // Input sign bit unknown
2642 Known.Zero &= Mask;
2643 Known.One &= Mask;
2644 }
2645 break;
2646 }
2647 case ISD::BUILD_PAIR: {
2648 EVT HalfVT = Op.getOperand(0).getValueType();
2649 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2650
2651 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2652 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2653
2654 KnownBits KnownLo, KnownHi;
2655
2656 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2657 return true;
2658
2659 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2660 return true;
2661
2662 Known = KnownHi.concat(KnownLo);
2663 break;
2664 }
2666 if (VT.isScalableVector())
2667 return false;
2668 [[fallthrough]];
2669 case ISD::ZERO_EXTEND: {
2670 SDValue Src = Op.getOperand(0);
2671 EVT SrcVT = Src.getValueType();
2672 unsigned InBits = SrcVT.getScalarSizeInBits();
2673 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2674 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2675
2676 // If none of the top bits are demanded, convert this into an any_extend.
2677 if (DemandedBits.getActiveBits() <= InBits) {
2678 // If we only need the non-extended bits of the bottom element
2679 // then we can just bitcast to the result.
2680 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2681 VT.getSizeInBits() == SrcVT.getSizeInBits())
2682 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2683
2684 unsigned Opc =
2686 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2687 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2688 }
2689
2690 APInt InDemandedBits = DemandedBits.trunc(InBits);
2691 APInt InDemandedElts = DemandedElts.zext(InElts);
2692 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2693 Depth + 1)) {
2694 Op->dropFlags(SDNodeFlags::NonNeg);
2695 return true;
2696 }
2697 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2698 Known = Known.zext(BitWidth);
2699
2700 // Attempt to avoid multi-use ops if we don't need anything from them.
2702 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2703 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2704 break;
2705 }
2707 if (VT.isScalableVector())
2708 return false;
2709 [[fallthrough]];
2710 case ISD::SIGN_EXTEND: {
2711 SDValue Src = Op.getOperand(0);
2712 EVT SrcVT = Src.getValueType();
2713 unsigned InBits = SrcVT.getScalarSizeInBits();
2714 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2715 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2716
2717 APInt InDemandedElts = DemandedElts.zext(InElts);
2718 APInt InDemandedBits = DemandedBits.trunc(InBits);
2719
2720 // Since some of the sign extended bits are demanded, we know that the sign
2721 // bit is demanded.
2722 InDemandedBits.setBit(InBits - 1);
2723
2724 // If none of the top bits are demanded, convert this into an any_extend.
2725 if (DemandedBits.getActiveBits() <= InBits) {
2726 // If we only need the non-extended bits of the bottom element
2727 // then we can just bitcast to the result.
2728 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2729 VT.getSizeInBits() == SrcVT.getSizeInBits())
2730 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2731
2732 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans.
2734 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) !=
2735 InBits) {
2736 unsigned Opc =
2738 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2739 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2740 }
2741 }
2742
2743 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2744 Depth + 1))
2745 return true;
2746 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2747
2748 // If the sign bit is known one, the top bits match.
2749 Known = Known.sext(BitWidth);
2750
2751 // If the sign bit is known zero, convert this to a zero extend.
2752 if (Known.isNonNegative()) {
2753 unsigned Opc =
2755 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) {
2756 SDNodeFlags Flags;
2757 if (!IsVecInReg)
2758 Flags |= SDNodeFlags::NonNeg;
2759 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags));
2760 }
2761 }
2762
2763 // Attempt to avoid multi-use ops if we don't need anything from them.
2765 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2766 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2767 break;
2768 }
2770 if (VT.isScalableVector())
2771 return false;
2772 [[fallthrough]];
2773 case ISD::ANY_EXTEND: {
2774 SDValue Src = Op.getOperand(0);
2775 EVT SrcVT = Src.getValueType();
2776 unsigned InBits = SrcVT.getScalarSizeInBits();
2777 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2778 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2779
2780 // If we only need the bottom element then we can just bitcast.
2781 // TODO: Handle ANY_EXTEND?
2782 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2783 VT.getSizeInBits() == SrcVT.getSizeInBits())
2784 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2785
2786 APInt InDemandedBits = DemandedBits.trunc(InBits);
2787 APInt InDemandedElts = DemandedElts.zext(InElts);
2788 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2789 Depth + 1))
2790 return true;
2791 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2792 Known = Known.anyext(BitWidth);
2793
2794 // Attempt to avoid multi-use ops if we don't need anything from them.
2796 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2797 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2798 break;
2799 }
2800 case ISD::TRUNCATE: {
2801 SDValue Src = Op.getOperand(0);
2802
2803 // Simplify the input, using demanded bit information, and compute the known
2804 // zero/one bits live out.
2805 unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2806 APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2807 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2808 Depth + 1)) {
2809 // Disable the nsw and nuw flags. We can no longer guarantee that we
2810 // won't wrap after simplification.
2811 Op->dropFlags(SDNodeFlags::NoWrap);
2812 return true;
2813 }
2814 Known = Known.trunc(BitWidth);
2815
2816 // Attempt to avoid multi-use ops if we don't need anything from them.
2818 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2819 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2820
2821 // If the input is only used by this truncate, see if we can shrink it based
2822 // on the known demanded bits.
2823 switch (Src.getOpcode()) {
2824 default:
2825 break;
2826 case ISD::SRL:
2827 // Shrink SRL by a constant if none of the high bits shifted in are
2828 // demanded.
2829 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2830 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2831 // undesirable.
2832 break;
2833
2834 if (Src.getNode()->hasOneUse()) {
2835 if (isTruncateFree(Src, VT) &&
2836 !isTruncateFree(Src.getValueType(), VT)) {
2837 // If truncate is only free at trunc(srl), do not turn it into
2838 // srl(trunc). The check is done by first check the truncate is free
2839 // at Src's opcode(srl), then check the truncate is not done by
2840 // referencing sub-register. In test, if both trunc(srl) and
2841 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only
2842 // trunc(srl)'s trunc is free, trunc(srl) is better.
2843 break;
2844 }
2845
2846 std::optional<unsigned> ShAmtC =
2847 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2);
2848 if (!ShAmtC || *ShAmtC >= BitWidth)
2849 break;
2850 unsigned ShVal = *ShAmtC;
2851
2852 APInt HighBits =
2853 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2854 HighBits.lshrInPlace(ShVal);
2855 HighBits = HighBits.trunc(BitWidth);
2856 if (!(HighBits & DemandedBits)) {
2857 // None of the shifted in bits are needed. Add a truncate of the
2858 // shift input, then shift it.
2859 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2860 SDValue NewTrunc =
2861 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2862 return TLO.CombineTo(
2863 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2864 }
2865 }
2866 break;
2867 }
2868
2869 break;
2870 }
2871 case ISD::AssertZext: {
2872 // AssertZext demands all of the high bits, plus any of the low bits
2873 // demanded by its users.
2874 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2876 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2877 TLO, Depth + 1))
2878 return true;
2879
2880 Known.Zero |= ~InMask;
2881 Known.One &= (~Known.Zero);
2882 break;
2883 }
2885 SDValue Src = Op.getOperand(0);
2886 SDValue Idx = Op.getOperand(1);
2887 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2888 unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2889
2890 if (SrcEltCnt.isScalable())
2891 return false;
2892
2893 // Demand the bits from every vector element without a constant index.
2894 unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2895 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2896 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2897 if (CIdx->getAPIntValue().ult(NumSrcElts))
2898 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2899
2900 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2901 // anything about the extended bits.
2902 APInt DemandedSrcBits = DemandedBits;
2903 if (BitWidth > EltBitWidth)
2904 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2905
2906 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2907 Depth + 1))
2908 return true;
2909
2910 // Attempt to avoid multi-use ops if we don't need anything from them.
2911 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2912 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2913 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2914 SDValue NewOp =
2915 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2916 return TLO.CombineTo(Op, NewOp);
2917 }
2918 }
2919
2920 Known = Known2;
2921 if (BitWidth > EltBitWidth)
2922 Known = Known.anyext(BitWidth);
2923 break;
2924 }
2925 case ISD::BITCAST: {
2926 if (VT.isScalableVector())
2927 return false;
2928 SDValue Src = Op.getOperand(0);
2929 EVT SrcVT = Src.getValueType();
2930 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2931
2932 // If this is an FP->Int bitcast and if the sign bit is the only
2933 // thing demanded, turn this into a FGETSIGN.
2934 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2935 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2936 SrcVT.isFloatingPoint()) {
2938 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2939 // place. We expect the SHL to be eliminated by other optimizations.
2940 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, VT, Src);
2941 unsigned ShVal = Op.getValueSizeInBits() - 1;
2942 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2943 return TLO.CombineTo(Op,
2944 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2945 }
2946 }
2947
2948 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2949 // Demand the elt/bit if any of the original elts/bits are demanded.
2950 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2951 unsigned Scale = BitWidth / NumSrcEltBits;
2952 unsigned NumSrcElts = SrcVT.getVectorNumElements();
2953 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2954 for (unsigned i = 0; i != Scale; ++i) {
2955 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2956 unsigned BitOffset = EltOffset * NumSrcEltBits;
2957 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2958 }
2959 // Recursive calls below may turn not demanded elements into poison, so we
2960 // need to demand all smaller source elements that maps to a demanded
2961 // destination element.
2962 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2963
2964 APInt KnownSrcUndef, KnownSrcZero;
2965 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2966 KnownSrcZero, TLO, Depth + 1))
2967 return true;
2968
2969 KnownBits KnownSrcBits;
2970 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2971 KnownSrcBits, TLO, Depth + 1))
2972 return true;
2973 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2974 // TODO - bigendian once we have test coverage.
2975 unsigned Scale = NumSrcEltBits / BitWidth;
2976 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2977 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2978 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2979 for (unsigned i = 0; i != NumElts; ++i)
2980 if (DemandedElts[i]) {
2981 unsigned Offset = (i % Scale) * BitWidth;
2982 DemandedSrcBits.insertBits(DemandedBits, Offset);
2983 DemandedSrcElts.setBit(i / Scale);
2984 }
2985
2986 if (SrcVT.isVector()) {
2987 APInt KnownSrcUndef, KnownSrcZero;
2988 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2989 KnownSrcZero, TLO, Depth + 1))
2990 return true;
2991 }
2992
2993 KnownBits KnownSrcBits;
2994 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2995 KnownSrcBits, TLO, Depth + 1))
2996 return true;
2997
2998 // Attempt to avoid multi-use ops if we don't need anything from them.
2999 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
3000 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
3001 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
3002 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
3003 return TLO.CombineTo(Op, NewOp);
3004 }
3005 }
3006 }
3007
3008 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
3009 // recursive call where Known may be useful to the caller.
3010 if (Depth > 0) {
3011 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3012 return false;
3013 }
3014 break;
3015 }
3016 case ISD::MUL:
3017 if (DemandedBits.isPowerOf2()) {
3018 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
3019 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
3020 // odd (has LSB set), then the left-shifted low bit of X is the answer.
3021 unsigned CTZ = DemandedBits.countr_zero();
3022 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
3023 if (C && C->getAPIntValue().countr_zero() == CTZ) {
3024 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl);
3025 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
3026 return TLO.CombineTo(Op, Shl);
3027 }
3028 }
3029 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
3030 // X * X is odd iff X is odd.
3031 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
3032 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
3033 SDValue One = TLO.DAG.getConstant(1, dl, VT);
3034 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
3035 return TLO.CombineTo(Op, And1);
3036 }
3037 [[fallthrough]];
3038 case ISD::PTRADD:
3039 if (Op.getOperand(0).getValueType() != Op.getOperand(1).getValueType())
3040 break;
3041 // PTRADD behaves like ADD if pointers are represented as integers.
3042 [[fallthrough]];
3043 case ISD::ADD:
3044 case ISD::SUB: {
3045 // Add, Sub, and Mul don't demand any bits in positions beyond that
3046 // of the highest bit demanded of them.
3047 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
3048 SDNodeFlags Flags = Op.getNode()->getFlags();
3049 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
3050 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
3051 KnownBits KnownOp0, KnownOp1;
3052 auto GetDemandedBitsLHSMask = [&](APInt Demanded,
3053 const KnownBits &KnownRHS) {
3054 if (Op.getOpcode() == ISD::MUL)
3055 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros());
3056 return Demanded;
3057 };
3058 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
3059 Depth + 1) ||
3060 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1),
3061 DemandedElts, KnownOp0, TLO, Depth + 1) ||
3062 // See if the operation should be performed at a smaller bit width.
3064 // Disable the nsw and nuw flags. We can no longer guarantee that we
3065 // won't wrap after simplification.
3066 Op->dropFlags(SDNodeFlags::NoWrap);
3067 return true;
3068 }
3069
3070 // neg x with only low bit demanded is simply x.
3071 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
3072 isNullConstant(Op0))
3073 return TLO.CombineTo(Op, Op1);
3074
3075 // Attempt to avoid multi-use ops if we don't need anything from them.
3076 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
3078 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3080 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3081 if (DemandedOp0 || DemandedOp1) {
3082 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
3083 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
3084 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
3085 Flags & ~SDNodeFlags::NoWrap);
3086 return TLO.CombineTo(Op, NewOp);
3087 }
3088 }
3089
3090 // If we have a constant operand, we may be able to turn it into -1 if we
3091 // do not demand the high bits. This can make the constant smaller to
3092 // encode, allow more general folding, or match specialized instruction
3093 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
3094 // is probably not useful (and could be detrimental).
3096 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
3097 if (C && !C->isAllOnes() && !C->isOne() &&
3098 (C->getAPIntValue() | HighMask).isAllOnes()) {
3099 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
3100 // Disable the nsw and nuw flags. We can no longer guarantee that we
3101 // won't wrap after simplification.
3102 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1,
3103 Flags & ~SDNodeFlags::NoWrap);
3104 return TLO.CombineTo(Op, NewOp);
3105 }
3106
3107 // Match a multiply with a disguised negated-power-of-2 and convert to a
3108 // an equivalent shift-left amount.
3109 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3110 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
3111 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
3112 return 0;
3113
3114 // Don't touch opaque constants. Also, ignore zero and power-of-2
3115 // multiplies. Those will get folded later.
3116 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
3117 if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
3118 !MulC->getAPIntValue().isPowerOf2()) {
3119 APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
3120 if (UnmaskedC.isNegatedPowerOf2())
3121 return (-UnmaskedC).logBase2();
3122 }
3123 return 0;
3124 };
3125
3126 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y,
3127 unsigned ShlAmt) {
3128 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl);
3129 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
3130 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
3131 return TLO.CombineTo(Op, Res);
3132 };
3133
3135 if (Op.getOpcode() == ISD::ADD) {
3136 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3137 if (unsigned ShAmt = getShiftLeftAmt(Op0))
3138 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
3139 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
3140 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3141 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
3142 }
3143 if (Op.getOpcode() == ISD::SUB) {
3144 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
3145 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3146 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
3147 }
3148 }
3149
3150 if (Op.getOpcode() == ISD::MUL) {
3151 Known = KnownBits::mul(KnownOp0, KnownOp1);
3152 } else { // Op.getOpcode() is either ISD::ADD, ISD::PTRADD, or ISD::SUB.
3154 Op.getOpcode() != ISD::SUB, Flags.hasNoSignedWrap(),
3155 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1);
3156 }
3157 break;
3158 }
3159 case ISD::FABS: {
3160 SDValue Op0 = Op.getOperand(0);
3161 APInt SignMask = APInt::getSignMask(BitWidth);
3162
3163 if (!DemandedBits.intersects(SignMask))
3164 return TLO.CombineTo(Op, Op0);
3165
3166 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3167 Depth + 1))
3168 return true;
3169
3170 if (Known.isNonNegative())
3171 return TLO.CombineTo(Op, Op0);
3172 if (Known.isNegative())
3173 return TLO.CombineTo(
3174 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT, Op0, Op->getFlags()));
3175
3176 Known.Zero |= SignMask;
3177 Known.One &= ~SignMask;
3178
3179 break;
3180 }
3181 case ISD::FCOPYSIGN: {
3182 SDValue Op0 = Op.getOperand(0);
3183 SDValue Op1 = Op.getOperand(1);
3184
3185 unsigned BitWidth0 = Op0.getScalarValueSizeInBits();
3186 unsigned BitWidth1 = Op1.getScalarValueSizeInBits();
3187 APInt SignMask0 = APInt::getSignMask(BitWidth0);
3188 APInt SignMask1 = APInt::getSignMask(BitWidth1);
3189
3190 if (!DemandedBits.intersects(SignMask0))
3191 return TLO.CombineTo(Op, Op0);
3192
3193 if (SimplifyDemandedBits(Op0, ~SignMask0 & DemandedBits, DemandedElts,
3194 Known, TLO, Depth + 1) ||
3195 SimplifyDemandedBits(Op1, SignMask1, DemandedElts, Known2, TLO,
3196 Depth + 1))
3197 return true;
3198
3199 if (Known2.isNonNegative())
3200 return TLO.CombineTo(
3201 Op, TLO.DAG.getNode(ISD::FABS, dl, VT, Op0, Op->getFlags()));
3202
3203 if (Known2.isNegative())
3204 return TLO.CombineTo(
3205 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT,
3206 TLO.DAG.getNode(ISD::FABS, SDLoc(Op0), VT, Op0)));
3207
3208 Known.Zero &= ~SignMask0;
3209 Known.One &= ~SignMask0;
3210 break;
3211 }
3212 case ISD::FNEG: {
3213 SDValue Op0 = Op.getOperand(0);
3214 APInt SignMask = APInt::getSignMask(BitWidth);
3215
3216 if (!DemandedBits.intersects(SignMask))
3217 return TLO.CombineTo(Op, Op0);
3218
3219 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3220 Depth + 1))
3221 return true;
3222
3223 if (!Known.isSignUnknown()) {
3224 Known.Zero ^= SignMask;
3225 Known.One ^= SignMask;
3226 }
3227
3228 break;
3229 }
3230 default:
3231 // We also ask the target about intrinsics (which could be specific to it).
3232 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3233 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
3234 // TODO: Probably okay to remove after audit; here to reduce change size
3235 // in initial enablement patch for scalable vectors
3236 if (Op.getValueType().isScalableVector())
3237 break;
3239 Known, TLO, Depth))
3240 return true;
3241 break;
3242 }
3243
3244 // Just use computeKnownBits to compute output bits.
3245 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3246 break;
3247 }
3248
3249 // If we know the value of all of the demanded bits, return this as a
3250 // constant.
3252 DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
3253 // Avoid folding to a constant if any OpaqueConstant is involved.
3254 if (llvm::any_of(Op->ops(), [](SDValue V) {
3255 auto *C = dyn_cast<ConstantSDNode>(V);
3256 return C && C->isOpaque();
3257 }))
3258 return false;
3259 if (VT.isInteger())
3260 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
3261 if (VT.isFloatingPoint())
3262 return TLO.CombineTo(
3264 dl, VT));
3265 }
3266
3267 // A multi use 'all demanded elts' simplify failed to find any knownbits.
3268 // Try again just for the original demanded elts.
3269 // Ensure we do this AFTER constant folding above.
3270 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
3271 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
3272
3273 return false;
3274}
3275
3277 const APInt &DemandedElts,
3278 DAGCombinerInfo &DCI) const {
3279 SelectionDAG &DAG = DCI.DAG;
3280 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3281 !DCI.isBeforeLegalizeOps());
3282
3283 APInt KnownUndef, KnownZero;
3284 bool Simplified =
3285 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
3286 if (Simplified) {
3287 DCI.AddToWorklist(Op.getNode());
3288 DCI.CommitTargetLoweringOpt(TLO);
3289 }
3290
3291 return Simplified;
3292}
3293
3294/// Given a vector binary operation and known undefined elements for each input
3295/// operand, compute whether each element of the output is undefined.
3297 const APInt &UndefOp0,
3298 const APInt &UndefOp1) {
3299 EVT VT = BO.getValueType();
3301 "Vector binop only");
3302
3303 EVT EltVT = VT.getVectorElementType();
3304 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
3305 assert(UndefOp0.getBitWidth() == NumElts &&
3306 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
3307
3308 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
3309 const APInt &UndefVals) {
3310 if (UndefVals[Index])
3311 return DAG.getUNDEF(EltVT);
3312
3313 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
3314 // Try hard to make sure that the getNode() call is not creating temporary
3315 // nodes. Ignore opaque integers because they do not constant fold.
3316 SDValue Elt = BV->getOperand(Index);
3317 auto *C = dyn_cast<ConstantSDNode>(Elt);
3318 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
3319 return Elt;
3320 }
3321
3322 return SDValue();
3323 };
3324
3325 APInt KnownUndef = APInt::getZero(NumElts);
3326 for (unsigned i = 0; i != NumElts; ++i) {
3327 // If both inputs for this element are either constant or undef and match
3328 // the element type, compute the constant/undef result for this element of
3329 // the vector.
3330 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
3331 // not handle FP constants. The code within getNode() should be refactored
3332 // to avoid the danger of creating a bogus temporary node here.
3333 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
3334 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
3335 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
3336 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
3337 KnownUndef.setBit(i);
3338 }
3339 return KnownUndef;
3340}
3341
3343 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3344 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3345 bool AssumeSingleUse) const {
3346 EVT VT = Op.getValueType();
3347 unsigned Opcode = Op.getOpcode();
3348 APInt DemandedElts = OriginalDemandedElts;
3349 unsigned NumElts = DemandedElts.getBitWidth();
3350 assert(VT.isVector() && "Expected vector op");
3351
3352 KnownUndef = KnownZero = APInt::getZero(NumElts);
3353
3355 return false;
3356
3357 // TODO: For now we assume we know nothing about scalable vectors.
3358 if (VT.isScalableVector())
3359 return false;
3360
3361 assert(VT.getVectorNumElements() == NumElts &&
3362 "Mask size mismatches value type element count!");
3363
3364 // Undef operand.
3365 if (Op.isUndef()) {
3366 KnownUndef.setAllBits();
3367 return false;
3368 }
3369
3370 // If Op has other users, assume that all elements are needed.
3371 if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3372 DemandedElts.setAllBits();
3373
3374 // Not demanding any elements from Op.
3375 if (DemandedElts == 0) {
3376 KnownUndef.setAllBits();
3377 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3378 }
3379
3380 // Limit search depth.
3382 return false;
3383
3384 SDLoc DL(Op);
3385 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3386 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3387
3388 auto TryShrinkBinOp = [&](SDValue Op0, SDValue Op1) {
3389 unsigned ShrunkSize = getPreferredShrunkVectorSizeInBits(Op, DemandedElts);
3390 if (!ShrunkSize)
3391 return false;
3392
3393 assert(ShrunkSize % EltSizeInBits == 0 &&
3394 "Shrunk size not a multiple of element size");
3395 assert(ShrunkSize < VT.getSizeInBits() &&
3396 "Shrunk size must be < original vector size");
3397 assert(ShrunkSize >= EltSizeInBits * DemandedElts.getActiveBits() &&
3398 "Shrunk size must be >= demanded size");
3399
3400 EVT ShrunkVT = VT.changeVectorElementCount(
3401 *TLO.DAG.getContext(),
3402 ElementCount::getFixed(ShrunkSize / EltSizeInBits));
3403 Op0 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op0, 0);
3404 Op1 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op1, 0);
3405 SDValue NewOp =
3406 TLO.DAG.getNode(Opcode, DL, ShrunkVT, Op0, Op1, Op->getFlags());
3407 return TLO.CombineTo(
3408 Op, TLO.DAG.getInsertSubvector(DL, TLO.DAG.getUNDEF(VT), NewOp, 0));
3409 };
3410
3411 // Helper for demanding the specified elements and all the bits of both binary
3412 // operands.
3413 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3414 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3415 TLO.DAG, Depth + 1);
3416 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3417 TLO.DAG, Depth + 1);
3418 if (NewOp0 || NewOp1) {
3419 SDValue NewOp =
3420 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3421 NewOp1 ? NewOp1 : Op1, Op->getFlags());
3422 return TLO.CombineTo(Op, NewOp);
3423 }
3424
3425 if (TryShrinkBinOp(Op0, Op1))
3426 return true;
3427
3428 return false;
3429 };
3430
3431 switch (Opcode) {
3432 case ISD::SCALAR_TO_VECTOR: {
3433 if (!DemandedElts[0])
3434 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
3435 // Upper elements are poison, not undef - don't mark them as KnownUndef.
3436 break;
3437 }
3438 case ISD::BITCAST: {
3439 SDValue Src = Op.getOperand(0);
3440 EVT SrcVT = Src.getValueType();
3441
3442 if (!SrcVT.isVector()) {
3443 // TODO - bigendian once we have test coverage.
3444 if (IsLE) {
3445 APInt DemandedSrcBits = APInt::getZero(SrcVT.getSizeInBits());
3446 unsigned EltSize = VT.getScalarSizeInBits();
3447 for (unsigned I = 0; I != NumElts; ++I) {
3448 if (DemandedElts[I]) {
3449 unsigned Offset = I * EltSize;
3450 DemandedSrcBits.setBits(Offset, Offset + EltSize);
3451 }
3452 }
3454 if (SimplifyDemandedBits(Src, DemandedSrcBits, Known, TLO, Depth + 1))
3455 return true;
3456 }
3457 break;
3458 }
3459
3460 // Fast handling of 'identity' bitcasts.
3461 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3462 if (NumSrcElts == NumElts)
3463 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3464 KnownZero, TLO, Depth + 1);
3465
3466 APInt SrcDemandedElts, SrcZero, SrcUndef;
3467
3468 // Bitcast from 'large element' src vector to 'small element' vector, we
3469 // must demand a source element if any DemandedElt maps to it.
3470 if ((NumElts % NumSrcElts) == 0) {
3471 unsigned Scale = NumElts / NumSrcElts;
3472 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3473 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3474 TLO, Depth + 1))
3475 return true;
3476
3477 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3478 // of the large element.
3479 // TODO - bigendian once we have test coverage.
3480 if (IsLE) {
3481 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3482 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3483 for (unsigned i = 0; i != NumElts; ++i)
3484 if (DemandedElts[i]) {
3485 unsigned Ofs = (i % Scale) * EltSizeInBits;
3486 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3487 }
3488
3490 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3491 TLO, Depth + 1))
3492 return true;
3493
3494 // The bitcast has split each wide element into a number of
3495 // narrow subelements. We have just computed the Known bits
3496 // for wide elements. See if element splitting results in
3497 // some subelements being zero. Only for demanded elements!
3498 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3499 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3500 .isAllOnes())
3501 continue;
3502 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3503 unsigned Elt = Scale * SrcElt + SubElt;
3504 // A wholly-undef source lane is reported as undef below; don't also
3505 // flag it as zero, keeping the undef and zero sets disjoint.
3506 if (DemandedElts[Elt] && !SrcUndef[SrcElt])
3507 KnownZero.setBit(Elt);
3508 }
3509 }
3510 }
3511
3512 // If the src element is zero/undef then all the output elements will be -
3513 // only demanded elements are guaranteed to be correct.
3514 for (unsigned i = 0; i != NumSrcElts; ++i) {
3515 if (SrcDemandedElts[i]) {
3516 if (SrcZero[i])
3517 KnownZero.setBits(i * Scale, (i + 1) * Scale);
3518 if (SrcUndef[i])
3519 KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3520 }
3521 }
3522 }
3523
3524 // Bitcast from 'small element' src vector to 'large element' vector, we
3525 // demand all smaller source elements covered by the larger demanded element
3526 // of this vector.
3527 if ((NumSrcElts % NumElts) == 0) {
3528 unsigned Scale = NumSrcElts / NumElts;
3529 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3530 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3531 TLO, Depth + 1))
3532 return true;
3533
3534 // If all the src elements covering an output element are zero/undef, then
3535 // the output element will be as well, assuming it was demanded.
3536 for (unsigned i = 0; i != NumElts; ++i) {
3537 if (DemandedElts[i]) {
3538 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3539 KnownZero.setBit(i);
3540 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3541 KnownUndef.setBit(i);
3542 }
3543 }
3544 }
3545 break;
3546 }
3547 case ISD::FREEZE: {
3548 SDValue N0 = Op.getOperand(0);
3550 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
3551 return TLO.CombineTo(Op, N0);
3552
3553 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE
3554 // freeze(op(x, ...)) -> op(freeze(x), ...).
3555 // Don't sink the freeze below SCALAR_TO_VECTOR when the scalar is a load
3556 // of a promoted (wider than the element) type: freeze(load) can never be
3557 // folded away (the loaded value may be poison in memory), and the extra
3558 // freeze node then blocks ISel patterns matching scalar_to_vector of a
3559 // load, e.g. the AArch64 scalar_to_vector(extload) -> ldr b/h forms.
3560 // freeze(scalar_to_vector(load)) is equivalent for the demanded element
3561 // zero, and ISel selects the freeze as a plain copy.
3562 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) {
3563 SDValue Scalar = N0.getOperand(0);
3564 bool IsPromotedLoad = Scalar.getOpcode() == ISD::LOAD &&
3565 Scalar.getValueType() != VT.getVectorElementType();
3566 if (!IsPromotedLoad)
3567 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
3568 TLO.DAG.getFreeze(Scalar)));
3569 }
3570 break;
3571 }
3572 case ISD::BUILD_VECTOR: {
3573 // Check all elements and simplify any unused elements with UNDEF.
3574 if (!DemandedElts.isAllOnes()) {
3575 // Don't simplify BROADCASTS.
3576 if (llvm::any_of(Op->op_values(),
3577 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3579 bool Updated = false;
3580 for (unsigned i = 0; i != NumElts; ++i) {
3581 if (!DemandedElts[i] && !Ops[i].isUndef()) {
3582 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3583 KnownUndef.setBit(i);
3584 Updated = true;
3585 }
3586 }
3587 if (Updated)
3588 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3589 }
3590 }
3591 for (unsigned i = 0; i != NumElts; ++i) {
3592 SDValue SrcOp = Op.getOperand(i);
3593 if (SrcOp.isUndef()) {
3594 KnownUndef.setBit(i);
3595 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3597 KnownZero.setBit(i);
3598 }
3599 }
3600 break;
3601 }
3602 case ISD::CONCAT_VECTORS: {
3603 EVT SubVT = Op.getOperand(0).getValueType();
3604 unsigned NumSubVecs = Op.getNumOperands();
3605 unsigned NumSubElts = SubVT.getVectorNumElements();
3606 for (unsigned i = 0; i != NumSubVecs; ++i) {
3607 SDValue SubOp = Op.getOperand(i);
3608 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3609 APInt SubUndef, SubZero;
3610 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3611 Depth + 1))
3612 return true;
3613 KnownUndef.insertBits(SubUndef, i * NumSubElts);
3614 KnownZero.insertBits(SubZero, i * NumSubElts);
3615 }
3616
3617 // Attempt to avoid multi-use ops if we don't need anything from them.
3618 if (!DemandedElts.isAllOnes()) {
3619 bool FoundNewSub = false;
3620 SmallVector<SDValue, 2> DemandedSubOps;
3621 for (unsigned i = 0; i != NumSubVecs; ++i) {
3622 SDValue SubOp = Op.getOperand(i);
3623 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3625 SubOp, SubElts, TLO.DAG, Depth + 1);
3626 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3627 FoundNewSub = NewSubOp ? true : FoundNewSub;
3628 }
3629 if (FoundNewSub) {
3630 SDValue NewOp =
3631 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3632 return TLO.CombineTo(Op, NewOp);
3633 }
3634 }
3635 break;
3636 }
3637 case ISD::INSERT_SUBVECTOR: {
3638 // Demand any elements from the subvector and the remainder from the src it
3639 // is inserted into.
3640 SDValue Src = Op.getOperand(0);
3641 SDValue Sub = Op.getOperand(1);
3642 uint64_t Idx = Op.getConstantOperandVal(2);
3643 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3644 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3645 APInt DemandedSrcElts = DemandedElts;
3646 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3647
3648 // If none of the sub operand elements are demanded, bypass the insert.
3649 if (!DemandedSubElts)
3650 return TLO.CombineTo(Op, Src);
3651
3652 APInt SubUndef, SubZero;
3653 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3654 Depth + 1))
3655 return true;
3656
3657 // If none of the src operand elements are demanded, replace it with undef.
3658 if (!DemandedSrcElts && !Src.isUndef())
3659 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3660 TLO.DAG.getUNDEF(VT), Sub,
3661 Op.getOperand(2)));
3662
3663 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3664 TLO, Depth + 1))
3665 return true;
3666 KnownUndef.insertBits(SubUndef, Idx);
3667 KnownZero.insertBits(SubZero, Idx);
3668
3669 // Attempt to avoid multi-use ops if we don't need anything from them.
3670 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3672 Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3674 Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3675 if (NewSrc || NewSub) {
3676 NewSrc = NewSrc ? NewSrc : Src;
3677 NewSub = NewSub ? NewSub : Sub;
3678 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3679 NewSub, Op.getOperand(2));
3680 return TLO.CombineTo(Op, NewOp);
3681 }
3682 }
3683 break;
3684 }
3686 // Offset the demanded elts by the subvector index.
3687 SDValue Src = Op.getOperand(0);
3688 if (Src.getValueType().isScalableVector())
3689 break;
3690 uint64_t Idx = Op.getConstantOperandVal(1);
3691 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3692 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3693
3694 APInt SrcUndef, SrcZero;
3695 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3696 Depth + 1))
3697 return true;
3698 KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3699 KnownZero = SrcZero.extractBits(NumElts, Idx);
3700
3701 // Attempt to avoid multi-use ops if we don't need anything from them.
3702 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(Src, DemandedSrcElts,
3703 TLO.DAG, Depth + 1);
3704 if (NewSrc) {
3705 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3706 Op.getOperand(1));
3707 return TLO.CombineTo(Op, NewOp);
3708 }
3709 break;
3710 }
3712 SDValue Vec = Op.getOperand(0);
3713 SDValue Scl = Op.getOperand(1);
3714 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3715
3716 // For a legal, constant insertion index, if we don't need this insertion
3717 // then strip it, else remove it from the demanded elts.
3718 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3719 unsigned Idx = CIdx->getZExtValue();
3720 if (!DemandedElts[Idx])
3721 return TLO.CombineTo(Op, Vec);
3722
3723 APInt DemandedVecElts(DemandedElts);
3724 DemandedVecElts.clearBit(Idx);
3725 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3726 KnownZero, TLO, Depth + 1))
3727 return true;
3728
3729 KnownUndef.setBitVal(Idx, Scl.isUndef());
3730
3731 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3732 break;
3733 }
3734
3735 APInt VecUndef, VecZero;
3736 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3737 Depth + 1))
3738 return true;
3739 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3740 break;
3741 }
3742 case ISD::VSELECT: {
3743 SDValue Sel = Op.getOperand(0);
3744 SDValue LHS = Op.getOperand(1);
3745 SDValue RHS = Op.getOperand(2);
3746
3747 // Try to transform the select condition based on the current demanded
3748 // elements.
3749 APInt UndefSel, ZeroSel;
3750 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3751 Depth + 1))
3752 return true;
3753
3754 // See if we can simplify either vselect operand.
3755 APInt DemandedLHS(DemandedElts);
3756 APInt DemandedRHS(DemandedElts);
3757 APInt UndefLHS, ZeroLHS;
3758 APInt UndefRHS, ZeroRHS;
3759 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3760 Depth + 1))
3761 return true;
3762 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3763 Depth + 1))
3764 return true;
3765
3766 KnownUndef = UndefLHS & UndefRHS;
3767 KnownZero = ZeroLHS & ZeroRHS;
3768
3769 // If we know that the selected element is always zero, we don't need the
3770 // select value element.
3771 APInt DemandedSel = DemandedElts & ~KnownZero;
3772 if (DemandedSel != DemandedElts)
3773 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3774 Depth + 1))
3775 return true;
3776
3777 break;
3778 }
3779 case ISD::VECTOR_SHUFFLE: {
3780 SDValue LHS = Op.getOperand(0);
3781 SDValue RHS = Op.getOperand(1);
3782 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3783
3784 // Collect demanded elements from shuffle operands..
3785 APInt DemandedLHS(NumElts, 0);
3786 APInt DemandedRHS(NumElts, 0);
3787 for (unsigned i = 0; i != NumElts; ++i) {
3788 int M = ShuffleMask[i];
3789 if (M < 0 || !DemandedElts[i])
3790 continue;
3791 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3792 if (M < (int)NumElts)
3793 DemandedLHS.setBit(M);
3794 else
3795 DemandedRHS.setBit(M - NumElts);
3796 }
3797
3798 // If either side isn't demanded, replace it by UNDEF. We handle this
3799 // explicitly here to also simplify in case of multiple uses (on the
3800 // contrary to the SimplifyDemandedVectorElts calls below).
3801 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
3802 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
3803 if (FoldLHS || FoldRHS) {
3804 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
3805 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
3806 SDValue NewOp =
3807 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
3808 return TLO.CombineTo(Op, NewOp);
3809 }
3810
3811 // See if we can simplify either shuffle operand.
3812 APInt UndefLHS, ZeroLHS;
3813 APInt UndefRHS, ZeroRHS;
3814 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3815 Depth + 1))
3816 return true;
3817 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3818 Depth + 1))
3819 return true;
3820
3821 // Simplify mask using undef elements from LHS/RHS.
3822 bool Updated = false;
3823 bool IdentityLHS = true, IdentityRHS = true;
3824 SmallVector<int, 32> NewMask(ShuffleMask);
3825 for (unsigned i = 0; i != NumElts; ++i) {
3826 int &M = NewMask[i];
3827 if (M < 0)
3828 continue;
3829 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3830 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3831 Updated = true;
3832 M = -1;
3833 }
3834 IdentityLHS &= (M < 0) || (M == (int)i);
3835 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3836 }
3837
3838 // Update legal shuffle masks based on demanded elements if it won't reduce
3839 // to Identity which can cause premature removal of the shuffle mask.
3840 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3841 SDValue LegalShuffle =
3842 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
3843 if (LegalShuffle)
3844 return TLO.CombineTo(Op, LegalShuffle);
3845 }
3846
3847 // Propagate undef/zero elements from LHS/RHS.
3848 for (unsigned i = 0; i != NumElts; ++i) {
3849 int M = ShuffleMask[i];
3850 if (M < 0) {
3851 KnownUndef.setBit(i);
3852 } else if (M < (int)NumElts) {
3853 if (UndefLHS[M])
3854 KnownUndef.setBit(i);
3855 if (ZeroLHS[M])
3856 KnownZero.setBit(i);
3857 } else {
3858 if (UndefRHS[M - NumElts])
3859 KnownUndef.setBit(i);
3860 if (ZeroRHS[M - NumElts])
3861 KnownZero.setBit(i);
3862 }
3863 }
3864 break;
3865 }
3869 APInt SrcUndef, SrcZero;
3870 SDValue Src = Op.getOperand(0);
3871 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3872 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3873 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3874 Depth + 1))
3875 return true;
3876 KnownZero = SrcZero.zextOrTrunc(NumElts);
3877 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3878
3879 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3880 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3881 DemandedSrcElts == 1) {
3882 // aext - if we just need the bottom element then we can bitcast.
3883 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3884 }
3885
3886 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3887 // zext(undef) upper bits are guaranteed to be zero.
3888 if (DemandedElts.isSubsetOf(KnownUndef))
3889 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3890 KnownUndef.clearAllBits();
3891
3892 // zext - if we just need the bottom element then we can mask:
3893 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3894 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3895 Op->isOnlyUserOf(Src.getNode()) &&
3896 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3897 SDLoc DL(Op);
3898 EVT SrcVT = Src.getValueType();
3899 EVT SrcSVT = SrcVT.getScalarType();
3900
3901 // If we're after type legalization and SrcSVT is not legal, use the
3902 // promoted type for creating constants to avoid creating nodes with
3903 // illegal types.
3904 if (TLO.LegalTypes())
3905 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
3906
3907 SmallVector<SDValue> MaskElts;
3908 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3909 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3910 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3911 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3912 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3913 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3914 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3915 }
3916 }
3917 }
3918 break;
3919 }
3920
3921 // TODO: There are more binop opcodes that could be handled here - MIN,
3922 // MAX, saturated math, etc.
3923 case ISD::ADD: {
3924 SDValue Op0 = Op.getOperand(0);
3925 SDValue Op1 = Op.getOperand(1);
3926 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3927 APInt UndefLHS, ZeroLHS;
3928 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3929 Depth + 1, /*AssumeSingleUse*/ true))
3930 return true;
3931 }
3932 [[fallthrough]];
3933 }
3934 case ISD::AVGCEILS:
3935 case ISD::AVGCEILU:
3936 case ISD::AVGFLOORS:
3937 case ISD::AVGFLOORU:
3938 case ISD::OR:
3939 case ISD::XOR:
3940 case ISD::SUB:
3941 case ISD::FADD:
3942 case ISD::FSUB:
3943 case ISD::FMUL:
3944 case ISD::FDIV:
3945 case ISD::FREM:
3946 case ISD::PSEUDO_FMIN:
3947 case ISD::PSEUDO_FMAX: {
3948 SDValue Op0 = Op.getOperand(0);
3949 SDValue Op1 = Op.getOperand(1);
3950
3951 APInt UndefRHS, ZeroRHS;
3952 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3953 Depth + 1))
3954 return true;
3955 APInt UndefLHS, ZeroLHS;
3956 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3957 Depth + 1))
3958 return true;
3959
3960 KnownZero = ZeroLHS & ZeroRHS;
3961 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3962
3963 // Attempt to avoid multi-use ops if we don't need anything from them.
3964 // TODO - use KnownUndef to relax the demandedelts?
3965 if (!DemandedElts.isAllOnes())
3966 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3967 return true;
3968 break;
3969 }
3970 case ISD::SHL:
3971 case ISD::SRL:
3972 case ISD::SRA:
3973 case ISD::ROTL:
3974 case ISD::ROTR: {
3975 SDValue Op0 = Op.getOperand(0);
3976 SDValue Op1 = Op.getOperand(1);
3977
3978 APInt UndefRHS, ZeroRHS;
3979 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3980 Depth + 1))
3981 return true;
3982 APInt UndefLHS, ZeroLHS;
3983 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3984 Depth + 1))
3985 return true;
3986
3987 KnownZero = ZeroLHS;
3988 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3989
3990 // Attempt to avoid multi-use ops if we don't need anything from them.
3991 // TODO - use KnownUndef to relax the demandedelts?
3992 if (!DemandedElts.isAllOnes())
3993 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3994 return true;
3995 break;
3996 }
3997 case ISD::MUL:
3998 case ISD::MULHU:
3999 case ISD::MULHS:
4000 case ISD::AND: {
4001 SDValue Op0 = Op.getOperand(0);
4002 SDValue Op1 = Op.getOperand(1);
4003
4004 APInt SrcUndef, SrcZero;
4005 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
4006 Depth + 1))
4007 return true;
4008 // FIXME: If we know that a demanded element was zero in Op1 we don't need
4009 // to demand it in Op0 - its guaranteed to be zero. There is however a
4010 // restriction, as we must not make any of the originally demanded elements
4011 // more poisonous. We could reduce amount of elements demanded, but then we
4012 // also need a to inform SimplifyDemandedVectorElts that some elements must
4013 // not be made more poisonous.
4014 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
4015 TLO, Depth + 1))
4016 return true;
4017
4018 KnownUndef &= DemandedElts;
4019 KnownZero &= DemandedElts;
4020
4021 // If every element pair has a zero/undef/poison then just fold to zero.
4022 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
4023 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
4024 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
4025 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4026
4027 // If either side has a zero element, then the result element is zero, even
4028 // if the other is an UNDEF.
4029 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
4030 // and then handle 'and' nodes with the rest of the binop opcodes.
4031 KnownZero |= SrcZero;
4032 KnownUndef &= SrcUndef;
4033 KnownUndef &= ~KnownZero;
4034
4035 // Attempt to avoid multi-use ops if we don't need anything from them.
4036 if (!DemandedElts.isAllOnes())
4037 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4038 return true;
4039 break;
4040 }
4041 case ISD::TRUNCATE:
4042 case ISD::SIGN_EXTEND:
4043 case ISD::ZERO_EXTEND:
4044 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4045 KnownZero, TLO, Depth + 1))
4046 return true;
4047
4048 if (!DemandedElts.isAllOnes())
4050 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
4051 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
4052
4053 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
4054 // zext(undef) upper bits are guaranteed to be zero.
4055 if (DemandedElts.isSubsetOf(KnownUndef))
4056 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4057 KnownUndef.clearAllBits();
4058 }
4059 break;
4060 case ISD::SINT_TO_FP:
4061 case ISD::UINT_TO_FP:
4062 case ISD::FP_TO_SINT:
4063 case ISD::FP_TO_UINT:
4064 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4065 KnownZero, TLO, Depth + 1))
4066 return true;
4067 // Don't fall through to generic undef -> undef handling.
4068 return false;
4069 default: {
4070 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
4071 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
4072 KnownZero, TLO, Depth))
4073 return true;
4074 } else {
4076 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
4077 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
4078 TLO, Depth, AssumeSingleUse))
4079 return true;
4080 }
4081 break;
4082 }
4083 }
4084
4085 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
4086
4087 // Constant fold all undef cases.
4088 // TODO: Handle zero cases as well.
4089 if (DemandedElts.isSubsetOf(KnownUndef))
4090 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
4091
4092 return false;
4093}
4094
4095/// Determine which of the bits specified in Mask are known to be either zero or
4096/// one and return them in the Known.
4099 const APInt &DemandedElts,
4100 const SelectionDAG &DAG,
4101 unsigned Depth) const {
4102 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4103 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4104 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4105 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4106 "Should use MaskedValueIsZero if you don't know whether Op"
4107 " is a target node!");
4108 Known.resetAll();
4109}
4110
4113 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4114 unsigned Depth) const {
4115 Known.resetAll();
4116}
4117
4120 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4121 unsigned Depth) const {
4122 Known.resetAll();
4123}
4124
4126 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4127 // The low bits are known zero if the pointer is aligned.
4128 Known.Zero.setLowBits(Log2(Alignment));
4129}
4130
4132 SelectionDAG &DAG,
4133 const SDLoc &DL,
4134 Align Alignment) const {
4135 // Materialize leading-zero stack object pointer facts as AssertZext.
4136 // Alignment-derived low zero bits are not represented on the returned DAG
4137 // value here.
4138 EVT PtrVT = Ptr.getValueType();
4139
4140 unsigned RegSize = PtrVT.getScalarSizeInBits();
4143 Alignment);
4144
4145 unsigned NumZeroBits = Known.countMinLeadingZeros();
4146 if (!NumZeroBits)
4147 return Ptr;
4148
4149 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4150 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4151}
4152
4158
4159/// This method can be implemented by targets that want to expose additional
4160/// information about sign bits to the DAG Combiner.
4162 const APInt &,
4163 const SelectionDAG &,
4164 unsigned Depth) const {
4165 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4166 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4167 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4168 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4169 "Should use ComputeNumSignBits if you don't know whether Op"
4170 " is a target node!");
4171 return 1;
4172}
4173
4175 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4176 const MachineRegisterInfo &MRI, unsigned Depth) const {
4177 return 1;
4178}
4179
4181 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4182 TargetLoweringOpt &TLO, unsigned Depth) const {
4183 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4184 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4185 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4186 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4187 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4188 " is a target node!");
4189 return false;
4190}
4191
4193 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4194 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4195 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4196 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4197 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4198 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4199 "Should use SimplifyDemandedBits if you don't know whether Op"
4200 " is a target node!");
4201 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4202 return false;
4203}
4204
4206 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4207 SelectionDAG &DAG, unsigned Depth) const {
4208 assert(
4209 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4210 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4211 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4212 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4213 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4214 " is a target node!");
4215 return SDValue();
4216}
4217
4218SDValue
4221 SelectionDAG &DAG) const {
4222 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4223 if (!LegalMask) {
4224 std::swap(N0, N1);
4226 LegalMask = isShuffleMaskLegal(Mask, VT);
4227 }
4228
4229 if (!LegalMask)
4230 return SDValue();
4231
4232 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4233}
4234
4236 return nullptr;
4237}
4238
4240 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4241 UndefPoisonKind Kind, unsigned Depth) const {
4242 assert(
4243 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4244 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4245 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4246 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4247 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4248 " is a target node!");
4249
4250 // If Op can't create undef/poison and none of its operands are undef/poison
4251 // then Op is never undef/poison.
4252 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4253 /*ConsiderFlags*/ true, Depth) &&
4254 all_of(Op->ops(), [&](SDValue V) {
4255 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4256 });
4257}
4258
4260 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4261 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4262 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4263 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4264 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4265 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4266 "Should use canCreateUndefOrPoison if you don't know whether Op"
4267 " is a target node!");
4268 // Be conservative and return true.
4269 return true;
4270}
4271
4274 const APInt &DemandedElts,
4275 const SelectionDAG &DAG,
4276 unsigned Depth) const {
4277 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4278 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4279 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4280 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4281 "Should use computeKnownFPClass if you don't know whether Op"
4282 " is a target node!");
4283}
4284
4286 const APInt &DemandedElts,
4287 const SelectionDAG &DAG,
4288 bool SNaN,
4289 unsigned Depth) const {
4290 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4291 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4292 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4293 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4294 "Should use isKnownNeverNaN if you don't know whether Op"
4295 " is a target node!");
4296 return false;
4297}
4298
4300 const APInt &DemandedElts,
4301 APInt &UndefElts,
4302 const SelectionDAG &DAG,
4303 unsigned Depth) const {
4304 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4305 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4306 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4307 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4308 "Should use isSplatValue if you don't know whether Op"
4309 " is a target node!");
4310 return false;
4311}
4312
4313// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4314// work with truncating build vectors and vectors with elements of less than
4315// 8 bits.
4317 if (!N)
4318 return false;
4319
4320 unsigned EltWidth;
4321 APInt CVal;
4322 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4323 /*AllowTruncation=*/true)) {
4324 CVal = CN->getAPIntValue();
4325 EltWidth = N.getValueType().getScalarSizeInBits();
4326 } else
4327 return false;
4328
4329 // If this is a truncating splat, truncate the splat value.
4330 // Otherwise, we may fail to match the expected values below.
4331 if (EltWidth < CVal.getBitWidth())
4332 CVal = CVal.trunc(EltWidth);
4333
4334 switch (getBooleanContents(N.getValueType())) {
4336 return CVal[0];
4338 return CVal.isOne();
4340 return CVal.isAllOnes();
4341 }
4342
4343 llvm_unreachable("Invalid boolean contents");
4344}
4345
4347 if (!N)
4348 return false;
4349
4351 if (!CN) {
4353 if (!BV)
4354 return false;
4355
4356 // Only interested in constant splats, we don't care about undef
4357 // elements in identifying boolean constants and getConstantSplatNode
4358 // returns NULL if all ops are undef;
4359 CN = BV->getConstantSplatNode();
4360 if (!CN)
4361 return false;
4362 }
4363
4364 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4365 return !CN->getAPIntValue()[0];
4366
4367 return CN->isZero();
4368}
4369
4371 bool SExt) const {
4372 if (VT == MVT::i1)
4373 return N->isOne();
4374
4376 switch (Cnt) {
4378 // An extended value of 1 is always true, unless its original type is i1,
4379 // in which case it will be sign extended to -1.
4380 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4383 return N->isAllOnes() && SExt;
4384 }
4385 llvm_unreachable("Unexpected enumeration.");
4386}
4387
4388/// This helper function of SimplifySetCC tries to optimize the comparison when
4389/// either operand of the SetCC node is a bitwise-and instruction.
4390SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4391 ISD::CondCode Cond, const SDLoc &DL,
4392 DAGCombinerInfo &DCI) const {
4393 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4394 std::swap(N0, N1);
4395
4396 SelectionDAG &DAG = DCI.DAG;
4397 EVT OpVT = N0.getValueType();
4398 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4399 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4400 return SDValue();
4401
4402 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4403 // iff everything but LSB is known zero:
4404 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4407 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4408 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4409 if (DAG.MaskedValueIsZero(N0, UpperBits))
4410 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4411 }
4412
4413 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4414 // test in a narrow type that we can truncate to with no cost. Examples:
4415 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4416 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4417 // TODO: This conservatively checks for type legality on the source and
4418 // destination types. That may inhibit optimizations, but it also
4419 // allows setcc->shift transforms that may be more beneficial.
4420 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4421 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4422 isTypeLegal(OpVT) && N0.hasOneUse()) {
4423 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4424 AndC->getAPIntValue().getActiveBits());
4425 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4426 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4427 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4428 return DAG.getSetCC(DL, VT, Trunc, Zero,
4430 }
4431 }
4432
4433 // Match these patterns in any of their permutations:
4434 // (X & Y) == Y
4435 // (X & Y) != Y
4436 SDValue X, Y;
4437 if (N0.getOperand(0) == N1) {
4438 X = N0.getOperand(1);
4439 Y = N0.getOperand(0);
4440 } else if (N0.getOperand(1) == N1) {
4441 X = N0.getOperand(0);
4442 Y = N0.getOperand(1);
4443 } else {
4444 return SDValue();
4445 }
4446
4447 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4448 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4449 // its liable to create and infinite loop.
4450 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4451 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4453 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4454 // Note that where Y is variable and is known to have at most one bit set
4455 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4456 // equivalent when Y == 0.
4457 assert(OpVT.isInteger());
4459 if (DCI.isBeforeLegalizeOps() ||
4461 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4462 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4463 // If the target supports an 'and-not' or 'and-complement' logic operation,
4464 // try to use that to make a comparison operation more efficient.
4465 // But don't do this transform if the mask is a single bit because there are
4466 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4467 // 'rlwinm' on PPC).
4468
4469 // Bail out if the compare operand that we want to turn into a zero is
4470 // already a zero (otherwise, infinite loop).
4471 if (isNullConstant(Y))
4472 return SDValue();
4473
4474 // Transform this into: ~X & Y == 0.
4475 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4476 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4477 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4478 }
4479
4480 return SDValue();
4481}
4482
4483/// This helper function of SimplifySetCC tries to optimize the comparison when
4484/// either operand of the SetCC node is a bitwise-or instruction.
4485/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4486SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4487 ISD::CondCode Cond, const SDLoc &DL,
4488 DAGCombinerInfo &DCI) const {
4489 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4490 std::swap(N0, N1);
4491
4492 SelectionDAG &DAG = DCI.DAG;
4493 EVT OpVT = N0.getValueType();
4494 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4495 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4496 return SDValue();
4497
4498 // (X | Y) == Y
4499 // (X | Y) != Y
4500 SDValue X;
4501 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4502 // If the target supports an 'and-not' or 'and-complement' logic operation,
4503 // try to use that to make a comparison operation more efficient.
4504
4505 // Bail out if the compare operand that we want to turn into a zero is
4506 // already a zero (otherwise, infinite loop).
4507 if (isNullConstant(N1))
4508 return SDValue();
4509
4510 // Transform this into: X & ~Y ==/!= 0.
4511 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4512 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4513 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4514 }
4515
4516 return SDValue();
4517}
4518
4519/// There are multiple IR patterns that could be checking whether certain
4520/// truncation of a signed number would be lossy or not. The pattern which is
4521/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4522/// We are looking for the following pattern: (KeptBits is a constant)
4523/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4524/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4525/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4526/// We will unfold it into the natural trunc+sext pattern:
4527/// ((%x << C) a>> C) dstcond %x
4528/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4529SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4530 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4531 const SDLoc &DL) const {
4532 // We must be comparing with a constant.
4533 ConstantSDNode *C1;
4534 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4535 return SDValue();
4536
4537 // N0 should be: add %x, (1 << (KeptBits-1))
4538 if (N0->getOpcode() != ISD::ADD)
4539 return SDValue();
4540
4541 // And we must be 'add'ing a constant.
4542 ConstantSDNode *C01;
4543 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4544 return SDValue();
4545
4546 SDValue X = N0->getOperand(0);
4547 EVT XVT = X.getValueType();
4548
4549 // Validate constants ...
4550
4551 APInt I1 = C1->getAPIntValue();
4552
4553 ISD::CondCode NewCond;
4554 if (Cond == ISD::CondCode::SETULT) {
4555 NewCond = ISD::CondCode::SETEQ;
4556 } else if (Cond == ISD::CondCode::SETULE) {
4557 NewCond = ISD::CondCode::SETEQ;
4558 // But need to 'canonicalize' the constant.
4559 I1 += 1;
4560 } else if (Cond == ISD::CondCode::SETUGT) {
4561 NewCond = ISD::CondCode::SETNE;
4562 // But need to 'canonicalize' the constant.
4563 I1 += 1;
4564 } else if (Cond == ISD::CondCode::SETUGE) {
4565 NewCond = ISD::CondCode::SETNE;
4566 } else
4567 return SDValue();
4568
4569 APInt I01 = C01->getAPIntValue();
4570
4571 auto checkConstants = [&I1, &I01]() -> bool {
4572 // Both of them must be power-of-two, and the constant from setcc is bigger.
4573 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4574 };
4575
4576 if (checkConstants()) {
4577 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4578 } else {
4579 // What if we invert constants? (and the target predicate)
4580 I1.negate();
4581 I01.negate();
4582 assert(XVT.isInteger());
4583 NewCond = getSetCCInverse(NewCond, XVT);
4584 if (!checkConstants())
4585 return SDValue();
4586 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4587 }
4588
4589 // They are power-of-two, so which bit is set?
4590 const unsigned KeptBits = I1.logBase2();
4591 const unsigned KeptBitsMinusOne = I01.logBase2();
4592
4593 // Magic!
4594 if (KeptBits != (KeptBitsMinusOne + 1))
4595 return SDValue();
4596 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4597
4598 // We don't want to do this in every single case.
4599 SelectionDAG &DAG = DCI.DAG;
4600 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4601 return SDValue();
4602
4603 // Unfold into: sext_inreg(%x) cond %x
4604 // Where 'cond' will be either 'eq' or 'ne'.
4605 SDValue SExtInReg = DAG.getNode(
4607 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4608 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4609}
4610
4611// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4612SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4613 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4614 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4616 "Should be a comparison with 0.");
4617 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4618 "Valid only for [in]equality comparisons.");
4619
4620 unsigned NewShiftOpcode;
4621 SDValue X, C, Y;
4622
4623 SelectionDAG &DAG = DCI.DAG;
4624
4625 // Look for '(C l>>/<< Y)'.
4626 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4627 // The shift should be one-use.
4628 if (!V.hasOneUse())
4629 return false;
4630 unsigned OldShiftOpcode = V.getOpcode();
4631 switch (OldShiftOpcode) {
4632 case ISD::SHL:
4633 NewShiftOpcode = ISD::SRL;
4634 break;
4635 case ISD::SRL:
4636 NewShiftOpcode = ISD::SHL;
4637 break;
4638 default:
4639 return false; // must be a logical shift.
4640 }
4641 // We should be shifting a constant.
4642 // FIXME: best to use isConstantOrConstantVector().
4643 C = V.getOperand(0);
4644 ConstantSDNode *CC =
4645 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4646 if (!CC)
4647 return false;
4648 Y = V.getOperand(1);
4649
4650 ConstantSDNode *XC =
4651 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4653 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4654 };
4655
4656 // LHS of comparison should be an one-use 'and'.
4657 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4658 return SDValue();
4659
4660 X = N0.getOperand(0);
4661 SDValue Mask = N0.getOperand(1);
4662
4663 // 'and' is commutative!
4664 if (!Match(Mask)) {
4665 std::swap(X, Mask);
4666 if (!Match(Mask))
4667 return SDValue();
4668 }
4669
4670 EVT VT = X.getValueType();
4671
4672 // Produce:
4673 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4674 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4675 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4676 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4677 return T2;
4678}
4679
4680/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4681/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4682/// handle the commuted versions of these patterns.
4683SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4684 ISD::CondCode Cond, const SDLoc &DL,
4685 DAGCombinerInfo &DCI) const {
4686 unsigned BOpcode = N0.getOpcode();
4687 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4688 "Unexpected binop");
4689 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4690
4691 // (X + Y) == X --> Y == 0
4692 // (X - Y) == X --> Y == 0
4693 // (X ^ Y) == X --> Y == 0
4694 SelectionDAG &DAG = DCI.DAG;
4695 EVT OpVT = N0.getValueType();
4696 SDValue X = N0.getOperand(0);
4697 SDValue Y = N0.getOperand(1);
4698 if (X == N1)
4699 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4700
4701 if (Y != N1)
4702 return SDValue();
4703
4704 // (X + Y) == Y --> X == 0
4705 // (X ^ Y) == Y --> X == 0
4706 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4707 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4708
4709 // The shift would not be valid if the operands are boolean (i1).
4710 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4711 return SDValue();
4712
4713 // (X - Y) == Y --> X == Y << 1
4714 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4715 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4716 if (!DCI.isCalledByLegalizer())
4717 DCI.AddToWorklist(YShl1.getNode());
4718 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4719}
4720
4722 SDValue N0, const APInt &C1,
4723 ISD::CondCode Cond, const SDLoc &dl,
4724 SelectionDAG &DAG) {
4725 // Look through truncs that don't change the value of a ctpop.
4726 // FIXME: Add vector support? Need to be careful with setcc result type below.
4727 SDValue CTPOP = N0;
4728 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4730 CTPOP = N0.getOperand(0);
4731
4732 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4733 return SDValue();
4734
4735 EVT CTVT = CTPOP.getValueType();
4736 SDValue CTOp = CTPOP.getOperand(0);
4737
4738 // Expand a power-of-2-or-zero comparison based on ctpop:
4739 // (ctpop x) u< 2 -> (x & x-1) == 0
4740 // (ctpop x) u> 1 -> (x & x-1) != 0
4741 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4742 // Keep the CTPOP if it is a cheap vector op.
4743 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4744 return SDValue();
4745
4746 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4747 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4748 return SDValue();
4749 if (C1 == 0 && (Cond == ISD::SETULT))
4750 return SDValue(); // This is handled elsewhere.
4751
4752 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4753
4754 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4755 SDValue Result = CTOp;
4756 for (unsigned i = 0; i < Passes; i++) {
4757 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4758 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4759 }
4761 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4762 }
4763
4764 // Expand a power-of-2 comparison based on ctpop
4765 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4766 // Keep the CTPOP if it is cheap.
4767 if (TLI.isCtpopFast(CTVT))
4768 return SDValue();
4769
4770 SDValue Zero = DAG.getConstant(0, dl, CTVT);
4771 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4772 assert(CTVT.isInteger());
4773 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4774
4775 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4776 // check before emitting a potentially unnecessary op.
4777 if (DAG.isKnownNeverZero(CTOp)) {
4778 // (ctpop x) == 1 --> (x & x-1) == 0
4779 // (ctpop x) != 1 --> (x & x-1) != 0
4780 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4781 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4782 return RHS;
4783 }
4784
4785 // (ctpop x) == 1 --> (x ^ x-1) > x-1
4786 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4787 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4789 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4790 }
4791
4792 return SDValue();
4793}
4794
4796 ISD::CondCode Cond, const SDLoc &dl,
4797 SelectionDAG &DAG) {
4798 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4799 return SDValue();
4800
4801 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4802 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
4803 return SDValue();
4804
4805 auto getRotateSource = [](SDValue X) {
4806 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
4807 return X.getOperand(0);
4808 return SDValue();
4809 };
4810
4811 // Peek through a rotated value compared against 0 or -1:
4812 // (rot X, Y) == 0/-1 --> X == 0/-1
4813 // (rot X, Y) != 0/-1 --> X != 0/-1
4814 if (SDValue R = getRotateSource(N0))
4815 return DAG.getSetCC(dl, VT, R, N1, Cond);
4816
4817 // Peek through an 'or' of a rotated value compared against 0:
4818 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
4819 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
4820 //
4821 // TODO: Add the 'and' with -1 sibling.
4822 // TODO: Recurse through a series of 'or' ops to find the rotate.
4823 EVT OpVT = N0.getValueType();
4824 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
4825 if (SDValue R = getRotateSource(N0.getOperand(0))) {
4826 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
4827 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4828 }
4829 if (SDValue R = getRotateSource(N0.getOperand(1))) {
4830 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
4831 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4832 }
4833 }
4834
4835 return SDValue();
4836}
4837
4839 ISD::CondCode Cond, const SDLoc &dl,
4840 SelectionDAG &DAG) {
4841 // If we are testing for all-bits-clear, we might be able to do that with
4842 // less shifting since bit-order does not matter.
4843 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4844 return SDValue();
4845
4846 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4847 if (!C1 || !C1->isZero())
4848 return SDValue();
4849
4850 if (!N0.hasOneUse() ||
4851 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
4852 return SDValue();
4853
4854 unsigned BitWidth = N0.getScalarValueSizeInBits();
4855 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
4856 if (!ShAmtC)
4857 return SDValue();
4858
4859 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
4860 if (ShAmt == 0)
4861 return SDValue();
4862
4863 // Canonicalize fshr as fshl to reduce pattern-matching.
4864 if (N0.getOpcode() == ISD::FSHR)
4865 ShAmt = BitWidth - ShAmt;
4866
4867 // Match an 'or' with a specific operand 'Other' in either commuted variant.
4868 SDValue X, Y;
4869 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
4870 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
4871 return false;
4872 if (Or.getOperand(0) == Other) {
4873 X = Or.getOperand(0);
4874 Y = Or.getOperand(1);
4875 return true;
4876 }
4877 if (Or.getOperand(1) == Other) {
4878 X = Or.getOperand(1);
4879 Y = Or.getOperand(0);
4880 return true;
4881 }
4882 return false;
4883 };
4884
4885 EVT OpVT = N0.getValueType();
4886 EVT ShAmtVT = N0.getOperand(2).getValueType();
4887 SDValue F0 = N0.getOperand(0);
4888 SDValue F1 = N0.getOperand(1);
4889 if (matchOr(F0, F1)) {
4890 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4891 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4892 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4893 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4894 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4895 }
4896 if (matchOr(F1, F0)) {
4897 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4898 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4899 SDValue Shift = DAG.getNode(ISD::SRL, 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
4904 return SDValue();
4905}
4906
4907/// Try to simplify a setcc built with the specified operands and cc. If it is
4908/// unable to simplify it, return a null SDValue.
4910 ISD::CondCode Cond, bool foldBooleans,
4911 DAGCombinerInfo &DCI,
4912 const SDLoc &dl) const {
4913 SelectionDAG &DAG = DCI.DAG;
4914 const DataLayout &Layout = DAG.getDataLayout();
4915 EVT OpVT = N0.getValueType();
4917
4918 // Constant fold or commute setcc.
4919 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
4920 return Fold;
4921
4922 bool N0ConstOrSplat =
4923 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4924 bool N1ConstOrSplat =
4925 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4926
4927 // Canonicalize toward having the constant on the RHS.
4928 // TODO: Handle non-splat vector constants. All undef causes trouble.
4929 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
4930 // infinite loop here when we encounter one.
4932 if (N0ConstOrSplat && !N1ConstOrSplat &&
4933 (DCI.isBeforeLegalizeOps() ||
4934 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
4935 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4936
4937 // If we have a subtract with the same 2 non-constant operands as this setcc
4938 // -- but in reverse order -- then try to commute the operands of this setcc
4939 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
4940 // instruction on some targets.
4941 if (!N0ConstOrSplat && !N1ConstOrSplat &&
4942 (DCI.isBeforeLegalizeOps() ||
4943 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
4944 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
4945 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
4946 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4947
4948 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
4949 return V;
4950
4951 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
4952 return V;
4953
4954 if (auto *N1C = isConstOrConstSplat(N1)) {
4955 const APInt &C1 = N1C->getAPIntValue();
4956
4957 // Optimize some CTPOP cases.
4958 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
4959 return V;
4960
4961 // For equality to 0 of a no-wrap multiply, decompose and test each op:
4962 // X * Y == 0 --> (X == 0) || (Y == 0)
4963 // X * Y != 0 --> (X != 0) && (Y != 0)
4964 // TODO: This bails out if minsize is set, but if the target doesn't have a
4965 // single instruction multiply for this type, it would likely be
4966 // smaller to decompose.
4967 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4968 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
4969 (N0->getFlags().hasNoUnsignedWrap() ||
4970 N0->getFlags().hasNoSignedWrap()) &&
4971 !Attr.hasFnAttr(Attribute::MinSize)) {
4972 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4973 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
4974 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
4975 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
4976 }
4977
4978 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
4979 // equality comparison, then we're just comparing whether X itself is
4980 // zero.
4981 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
4982 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
4984 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
4985 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4986 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
4987 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
4988 // (srl (ctlz x), 5) == 0 -> X != 0
4989 // (srl (ctlz x), 5) != 1 -> X != 0
4990 Cond = ISD::SETNE;
4991 } else {
4992 // (srl (ctlz x), 5) != 0 -> X == 0
4993 // (srl (ctlz x), 5) == 1 -> X == 0
4994 Cond = ISD::SETEQ;
4995 }
4996 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
4997 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
4998 Cond);
4999 }
5000 }
5001 }
5002 }
5003
5004 // setcc X, 0, setlt --> X (when X is all sign bits)
5005 // setcc X, 0, setne --> X (when X is all sign bits)
5006 //
5007 // When we know that X has 0 or -1 in each element (or scalar), this
5008 // comparison will produce X. This is only true when boolean contents are
5009 // represented via 0s and -1s.
5010 if (VT == OpVT &&
5011 // Check that the result of setcc is 0 and -1.
5013 // Match only for checks X < 0 and X != 0
5014 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
5015 // The identity holds iff we know all sign bits for all lanes.
5017 return N0;
5018
5019 // FIXME: Support vectors.
5020 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5021 const APInt &C1 = N1C->getAPIntValue();
5022
5023 // (zext x) == C --> x == (trunc C)
5024 // (sext x) == C --> x == (trunc C)
5025 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5026 DCI.isBeforeLegalize() && N0->hasOneUse()) {
5027 unsigned MinBits = N0.getValueSizeInBits();
5028 SDValue PreExt;
5029 bool Signed = false;
5030 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
5031 // ZExt
5032 MinBits = N0->getOperand(0).getValueSizeInBits();
5033 PreExt = N0->getOperand(0);
5034 } else if (N0->getOpcode() == ISD::AND) {
5035 // DAGCombine turns costly ZExts into ANDs
5036 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
5037 if ((C->getAPIntValue()+1).isPowerOf2()) {
5038 MinBits = C->getAPIntValue().countr_one();
5039 PreExt = N0->getOperand(0);
5040 }
5041 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
5042 // SExt
5043 MinBits = N0->getOperand(0).getValueSizeInBits();
5044 PreExt = N0->getOperand(0);
5045 Signed = true;
5046 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
5047 // ZEXTLOAD / SEXTLOAD
5048 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
5049 MinBits = LN0->getMemoryVT().getSizeInBits();
5050 PreExt = N0;
5051 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
5052 Signed = true;
5053 MinBits = LN0->getMemoryVT().getSizeInBits();
5054 PreExt = N0;
5055 }
5056 }
5057
5058 // Figure out how many bits we need to preserve this constant.
5059 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
5060
5061 // Make sure we're not losing bits from the constant.
5062 if (MinBits > 0 &&
5063 MinBits < C1.getBitWidth() &&
5064 MinBits >= ReqdBits) {
5065 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
5066 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
5067 // Will get folded away.
5068 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
5069 if (MinBits == 1 && C1 == 1)
5070 // Invert the condition.
5071 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
5073 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
5074 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
5075 }
5076
5077 // If truncating the setcc operands is not desirable, we can still
5078 // simplify the expression in some cases:
5079 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
5080 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
5081 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
5082 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
5083 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
5084 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
5085 SDValue TopSetCC = N0->getOperand(0);
5086 unsigned N0Opc = N0->getOpcode();
5087 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
5088 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
5089 TopSetCC.getOpcode() == ISD::SETCC &&
5090 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
5091 (isConstFalseVal(N1) ||
5092 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
5093
5094 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
5095 (!N1C->isZero() && Cond == ISD::SETNE);
5096
5097 if (!Inverse)
5098 return TopSetCC;
5099
5101 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
5102 TopSetCC.getOperand(0).getValueType());
5103 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
5104 TopSetCC.getOperand(1),
5105 InvCond);
5106 }
5107 }
5108 }
5109
5110 // If the LHS is '(and load, const)', the RHS is 0, the test is for
5111 // equality or unsigned, and all 1 bits of the const are in the same
5112 // partial word, see if we can shorten the load.
5113 if (DCI.isBeforeLegalize() &&
5115 N0.getOpcode() == ISD::AND && C1 == 0 &&
5116 N0.getNode()->hasOneUse() &&
5117 isa<LoadSDNode>(N0.getOperand(0)) &&
5118 N0.getOperand(0).getNode()->hasOneUse() &&
5120 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5121 APInt bestMask;
5122 unsigned bestWidth = 0, bestOffset = 0;
5123 if (Lod->isSimple() && Lod->isUnindexed() &&
5124 (Lod->getMemoryVT().isByteSized() ||
5125 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5126 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5127 unsigned origWidth = N0.getValueSizeInBits();
5128 unsigned maskWidth = origWidth;
5129 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5130 // 8 bits, but have to be careful...
5131 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5132 origWidth = Lod->getMemoryVT().getSizeInBits();
5133 const APInt &Mask = N0.getConstantOperandAPInt(1);
5134 // Only consider power-of-2 widths (and at least one byte) as candiates
5135 // for the narrowed load.
5136 for (unsigned width = 8; width < origWidth; width *= 2) {
5137 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5138 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5139 // Avoid accessing any padding here for now (we could use memWidth
5140 // instead of origWidth here otherwise).
5141 unsigned maxOffset = origWidth - width;
5142 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5143 if (Mask.isSubsetOf(newMask)) {
5144 unsigned ptrOffset =
5145 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5146 unsigned IsFast = 0;
5147 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5148 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5150 ptrOffset / 8) &&
5152 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5153 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5154 IsFast) {
5155 bestOffset = ptrOffset / 8;
5156 bestMask = Mask.lshr(offset);
5157 bestWidth = width;
5158 break;
5159 }
5160 }
5161 newMask <<= 8;
5162 }
5163 if (bestWidth)
5164 break;
5165 }
5166 }
5167 if (bestWidth) {
5168 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5169 SDValue Ptr = Lod->getBasePtr();
5170 if (bestOffset != 0)
5171 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5172 SDValue NewLoad =
5173 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5174 Lod->getPointerInfo().getWithOffset(bestOffset),
5175 Lod->getBaseAlign());
5176 SDValue And =
5177 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5178 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5179 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5180 }
5181 }
5182
5183 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5184 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5185 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5186
5187 // If the comparison constant has bits in the upper part, the
5188 // zero-extended value could never match.
5190 C1.getBitWidth() - InSize))) {
5191 switch (Cond) {
5192 case ISD::SETUGT:
5193 case ISD::SETUGE:
5194 case ISD::SETEQ:
5195 return DAG.getConstant(0, dl, VT);
5196 case ISD::SETULT:
5197 case ISD::SETULE:
5198 case ISD::SETNE:
5199 return DAG.getConstant(1, dl, VT);
5200 case ISD::SETGT:
5201 case ISD::SETGE:
5202 // True if the sign bit of C1 is set.
5203 return DAG.getConstant(C1.isNegative(), dl, VT);
5204 case ISD::SETLT:
5205 case ISD::SETLE:
5206 // True if the sign bit of C1 isn't set.
5207 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5208 default:
5209 break;
5210 }
5211 }
5212
5213 // Otherwise, we can perform the comparison with the low bits.
5214 switch (Cond) {
5215 case ISD::SETEQ:
5216 case ISD::SETNE:
5217 case ISD::SETUGT:
5218 case ISD::SETUGE:
5219 case ISD::SETULT:
5220 case ISD::SETULE: {
5221 EVT newVT = N0.getOperand(0).getValueType();
5222 // FIXME: Should use isNarrowingProfitable.
5223 if (DCI.isBeforeLegalizeOps() ||
5224 (isOperationLegal(ISD::SETCC, newVT) &&
5225 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5227 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5228 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5229
5230 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5231 NewConst, Cond);
5232 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5233 }
5234 break;
5235 }
5236 default:
5237 break; // todo, be more careful with signed comparisons
5238 }
5239 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5240 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5242 OpVT)) {
5243 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5244 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5245 EVT ExtDstTy = N0.getValueType();
5246 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5247
5248 // If the constant doesn't fit into the number of bits for the source of
5249 // the sign extension, it is impossible for both sides to be equal.
5250 if (C1.getSignificantBits() > ExtSrcTyBits)
5251 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5252
5253 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5254 ExtDstTy != ExtSrcTy && "Unexpected types!");
5255 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5256 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5257 DAG.getConstant(Imm, dl, ExtDstTy));
5258 if (!DCI.isCalledByLegalizer())
5259 DCI.AddToWorklist(ZextOp.getNode());
5260 // Otherwise, make this a use of a zext.
5261 return DAG.getSetCC(dl, VT, ZextOp,
5262 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5263 } else if ((N1C->isZero() || N1C->isOne()) &&
5264 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5265 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5266 // excluded as they are handled below whilst checking for foldBooleans.
5267 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5268 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5269 (N0.getValueType() == MVT::i1 ||
5273 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5274 if (TrueWhenTrue)
5275 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5276 // Invert the condition.
5277 if (N0.getOpcode() == ISD::SETCC) {
5280 if (DCI.isBeforeLegalizeOps() ||
5282 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5283 }
5284 }
5285
5286 if ((N0.getOpcode() == ISD::XOR ||
5287 (N0.getOpcode() == ISD::AND &&
5288 N0.getOperand(0).getOpcode() == ISD::XOR &&
5289 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5290 isOneConstant(N0.getOperand(1))) {
5291 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5292 // can only do this if the top bits are known zero.
5293 unsigned BitWidth = N0.getValueSizeInBits();
5294 if (DAG.MaskedValueIsZero(N0,
5296 BitWidth-1))) {
5297 // Okay, get the un-inverted input value.
5298 SDValue Val;
5299 if (N0.getOpcode() == ISD::XOR) {
5300 Val = N0.getOperand(0);
5301 } else {
5302 assert(N0.getOpcode() == ISD::AND &&
5303 N0.getOperand(0).getOpcode() == ISD::XOR);
5304 // ((X^1)&1)^1 -> X & 1
5305 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5306 N0.getOperand(0).getOperand(0),
5307 N0.getOperand(1));
5308 }
5309
5310 return DAG.getSetCC(dl, VT, Val, N1,
5312 }
5313 } else if (N1C->isOne()) {
5314 SDValue Op0 = N0;
5315 if (Op0.getOpcode() == ISD::TRUNCATE)
5316 Op0 = Op0.getOperand(0);
5317
5318 if ((Op0.getOpcode() == ISD::XOR) &&
5319 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5320 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5321 SDValue XorLHS = Op0.getOperand(0);
5322 SDValue XorRHS = Op0.getOperand(1);
5323 // Ensure that the input setccs return an i1 type or 0/1 value.
5324 if (Op0.getValueType() == MVT::i1 ||
5329 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5331 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5332 }
5333 }
5334 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5335 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5336 if (Op0.getValueType().bitsGT(VT))
5337 Op0 = DAG.getNode(ISD::AND, dl, VT,
5338 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5339 DAG.getConstant(1, dl, VT));
5340 else if (Op0.getValueType().bitsLT(VT))
5341 Op0 = DAG.getNode(ISD::AND, dl, VT,
5342 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5343 DAG.getConstant(1, dl, VT));
5344
5345 return DAG.getSetCC(dl, VT, Op0,
5346 DAG.getConstant(0, dl, Op0.getValueType()),
5348 }
5349 if (Op0.getOpcode() == ISD::AssertZext &&
5350 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5351 return DAG.getSetCC(dl, VT, Op0,
5352 DAG.getConstant(0, dl, Op0.getValueType()),
5354 }
5355 }
5356
5357 // Given:
5358 // icmp eq/ne (urem %x, %y), 0
5359 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5360 // icmp eq/ne %x, 0
5361 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5362 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5363 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5364 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5365 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5366 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5367 }
5368
5369 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5370 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5371 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5373 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5374 N1C->isAllOnes()) {
5375 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5376 DAG.getConstant(0, dl, OpVT),
5378 }
5379
5380 // fold (setcc (trunc x) c) -> (setcc x c)
5381 if (N0.getOpcode() == ISD::TRUNCATE &&
5383 (N0->getFlags().hasNoSignedWrap() &&
5386 EVT NewVT = N0.getOperand(0).getValueType();
5387 SDValue NewConst = DAG.getConstant(
5389 ? C1.sext(NewVT.getSizeInBits())
5390 : C1.zext(NewVT.getSizeInBits()),
5391 dl, NewVT);
5392 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5393 }
5394
5395 if (SDValue V =
5396 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5397 return V;
5398 }
5399
5400 // These simplifications apply to splat vectors as well.
5401 // TODO: Handle more splat vector cases.
5402 if (auto *N1C = isConstOrConstSplat(N1)) {
5403 const APInt &C1 = N1C->getAPIntValue();
5404
5405 APInt MinVal, MaxVal;
5406 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5408 MinVal = APInt::getSignedMinValue(OperandBitSize);
5409 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5410 } else {
5411 MinVal = APInt::getMinValue(OperandBitSize);
5412 MaxVal = APInt::getMaxValue(OperandBitSize);
5413 }
5414
5415 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5416 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5417 // X >= MIN --> true
5418 if (C1 == MinVal)
5419 return DAG.getBoolConstant(true, dl, VT, OpVT);
5420
5421 if (!VT.isVector()) { // TODO: Support this for vectors.
5422 // X >= C0 --> X > (C0 - 1)
5423 APInt C = C1 - 1;
5425 if ((DCI.isBeforeLegalizeOps() ||
5426 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5427 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5428 isLegalICmpImmediate(C.getSExtValue())))) {
5429 return DAG.getSetCC(dl, VT, N0,
5430 DAG.getConstant(C, dl, N1.getValueType()),
5431 NewCC);
5432 }
5433 }
5434 }
5435
5436 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5437 // X <= MAX --> true
5438 if (C1 == MaxVal)
5439 return DAG.getBoolConstant(true, dl, VT, OpVT);
5440
5441 // X <= C0 --> X < (C0 + 1)
5442 if (!VT.isVector()) { // TODO: Support this for vectors.
5443 APInt C = C1 + 1;
5445 if ((DCI.isBeforeLegalizeOps() ||
5446 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5447 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5448 isLegalICmpImmediate(C.getSExtValue())))) {
5449 return DAG.getSetCC(dl, VT, N0,
5450 DAG.getConstant(C, dl, N1.getValueType()),
5451 NewCC);
5452 }
5453 }
5454 }
5455
5456 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5457 if (C1 == MinVal)
5458 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5459
5460 // TODO: Support this for vectors after legalize ops.
5461 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5462 // Canonicalize setlt X, Max --> setne X, Max
5463 if (C1 == MaxVal)
5464 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5465
5466 // If we have setult X, 1, turn it into seteq X, 0
5467 if (C1 == MinVal+1)
5468 return DAG.getSetCC(dl, VT, N0,
5469 DAG.getConstant(MinVal, dl, N0.getValueType()),
5470 ISD::SETEQ);
5471 }
5472 }
5473
5474 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5475 if (C1 == MaxVal)
5476 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5477
5478 // TODO: Support this for vectors after legalize ops.
5479 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5480 // Canonicalize setgt X, Min --> setne X, Min
5481 if (C1 == MinVal)
5482 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5483
5484 // If we have setugt X, Max-1, turn it into seteq X, Max
5485 if (C1 == MaxVal-1)
5486 return DAG.getSetCC(dl, VT, N0,
5487 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5488 ISD::SETEQ);
5489 }
5490 }
5491
5492 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5493 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5494 if (C1.isZero())
5495 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5496 VT, N0, N1, Cond, DCI, dl))
5497 return CC;
5498
5499 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5500 // For example, when high 32-bits of i64 X are known clear:
5501 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5502 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5503 bool CmpZero = N1C->isZero();
5504 bool CmpNegOne = N1C->isAllOnes();
5505 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5506 // Match or(lo,shl(hi,bw/2)) pattern.
5507 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5508 unsigned EltBits = V.getScalarValueSizeInBits();
5509 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5510 return false;
5511 SDValue LHS = V.getOperand(0);
5512 SDValue RHS = V.getOperand(1);
5513 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5514 // Unshifted element must have zero upperbits.
5515 if (RHS.getOpcode() == ISD::SHL &&
5516 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5517 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5518 DAG.MaskedValueIsZero(LHS, HiBits)) {
5519 Lo = LHS;
5520 Hi = RHS.getOperand(0);
5521 return true;
5522 }
5523 if (LHS.getOpcode() == ISD::SHL &&
5524 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5525 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5526 DAG.MaskedValueIsZero(RHS, HiBits)) {
5527 Lo = RHS;
5528 Hi = LHS.getOperand(0);
5529 return true;
5530 }
5531 return false;
5532 };
5533
5534 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5535 unsigned EltBits = N0.getScalarValueSizeInBits();
5536 unsigned HalfBits = EltBits / 2;
5537 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5538 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5539 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5540 SDValue NewN0 =
5541 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5542 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5543 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5544 };
5545
5546 SDValue Lo, Hi;
5547 if (IsConcat(N0, Lo, Hi))
5548 return MergeConcat(Lo, Hi);
5549
5550 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5551 SDValue Lo0, Lo1, Hi0, Hi1;
5552 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5553 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5554 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5555 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5556 }
5557 }
5558 }
5559 }
5560
5561 // If we have "setcc X, C0", check to see if we can shrink the immediate
5562 // by changing cc.
5563 // TODO: Support this for vectors after legalize ops.
5564 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5565 // SETUGT X, SINTMAX -> SETLT X, 0
5566 // SETUGE X, SINTMIN -> SETLT X, 0
5567 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5568 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5569 return DAG.getSetCC(dl, VT, N0,
5570 DAG.getConstant(0, dl, N1.getValueType()),
5571 ISD::SETLT);
5572
5573 // SETULT X, SINTMIN -> SETGT X, -1
5574 // SETULE X, SINTMAX -> SETGT X, -1
5575 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5576 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5577 return DAG.getSetCC(dl, VT, N0,
5578 DAG.getAllOnesConstant(dl, N1.getValueType()),
5579 ISD::SETGT);
5580 }
5581 }
5582
5583 // Back to non-vector simplifications.
5584 // TODO: Can we do these for vector splats?
5585 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5586 const APInt &C1 = N1C->getAPIntValue();
5587 EVT ShValTy = N0.getValueType();
5588
5589 // Fold bit comparisons when we can. This will result in an
5590 // incorrect value when boolean false is negative one, unless
5591 // the bitsize is 1 in which case the false value is the same
5592 // in practice regardless of the representation.
5593 if ((VT.getSizeInBits() == 1 ||
5595 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5596 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5597 N0.getOpcode() == ISD::AND) {
5598 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5599 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5600 // Perform the xform if the AND RHS is a single bit.
5601 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5602 if (AndRHS->getAPIntValue().isPowerOf2() &&
5603 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5604 return DAG.getNode(
5605 ISD::TRUNCATE, dl, VT,
5606 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5607 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5608 }
5609 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5610 // (X & 8) == 8 --> (X & 8) >> 3
5611 // Perform the xform if C1 is a single bit.
5612 unsigned ShCt = C1.logBase2();
5613 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5614 return DAG.getNode(
5615 ISD::TRUNCATE, dl, VT,
5616 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5617 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5618 }
5619 }
5620 }
5621 }
5622
5623 if (C1.getSignificantBits() <= 64 &&
5625 // (X & -256) == 256 -> (X >> 8) == 1
5626 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5627 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5628 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5629 const APInt &AndRHSC = AndRHS->getAPIntValue();
5630 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5631 unsigned ShiftBits = AndRHSC.countr_zero();
5632 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5633 // If using an unsigned shift doesn't yield a legal compare
5634 // immediate, try using sra instead.
5635 APInt NewC = C1.lshr(ShiftBits);
5636 if (NewC.getSignificantBits() <= 64 &&
5638 APInt SignedC = C1.ashr(ShiftBits);
5639 if (SignedC.getSignificantBits() <= 64 &&
5641 SDValue Shift = DAG.getNode(
5642 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5643 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5644 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5645 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5646 }
5647 }
5648 SDValue Shift = DAG.getNode(
5649 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5650 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5651 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5652 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5653 }
5654 }
5655 }
5656 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5657 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5658 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5659 // X < 0x100000000 -> (X >> 32) < 1
5660 // X >= 0x100000000 -> (X >> 32) >= 1
5661 // X <= 0x0ffffffff -> (X >> 32) < 1
5662 // X > 0x0ffffffff -> (X >> 32) >= 1
5663 unsigned ShiftBits;
5664 APInt NewC = C1;
5665 ISD::CondCode NewCond = Cond;
5666 if (AdjOne) {
5667 ShiftBits = C1.countr_one();
5668 NewC = NewC + 1;
5669 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5670 } else {
5671 ShiftBits = C1.countr_zero();
5672 }
5673 APInt RangeWidth = NewC;
5674 NewC.lshrInPlace(ShiftBits);
5675 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5677 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5678 // If this is an offset range check, try to move the offset after the
5679 // shift to avoid preserving the pre-shift add with a mask.
5680 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse()) {
5681 if (auto *AddC = isConstOrConstSplat(N0.getOperand(1))) {
5682 const APInt &AddVal = AddC->getAPIntValue();
5683 if (AddVal.countr_zero() >= ShiftBits) {
5684 APInt RangeLower = -AddVal;
5685 bool Overflow;
5686 (void)RangeLower.uadd_ov(RangeWidth, Overflow);
5687 if (!RangeWidth.isZero() && !Overflow) {
5688 SDValue Shift = DAG.getNode(
5689 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5690 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5691 APInt Offset = -RangeLower.lshr(ShiftBits);
5692 SDValue ShiftedAdd =
5693 DAG.getNode(ISD::ADD, dl, ShValTy, Shift,
5694 DAG.getConstant(Offset, dl, ShValTy));
5695 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5696 return DAG.getSetCC(dl, VT, ShiftedAdd, CmpRHS, NewCond);
5697 }
5698 }
5699 }
5700 }
5701 SDValue Shift =
5702 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5703 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5704 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5705 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5706 }
5707 }
5708 }
5709 }
5710
5712 auto *CFP = cast<ConstantFPSDNode>(N1);
5713 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5714
5715 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5716 // constant if knowing that the operand is non-nan is enough. We prefer to
5717 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5718 // materialize 0.0.
5719 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5720 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5721
5722 // setcc (fneg x), C -> setcc swap(pred) x, -C
5723 if (N0.getOpcode() == ISD::FNEG) {
5725 if (DCI.isBeforeLegalizeOps() ||
5726 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5727 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5728 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5729 }
5730 }
5731
5732 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5734 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5735 bool IsFabs = N0.getOpcode() == ISD::FABS;
5736 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5737 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5738 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5739 : (IsFabs ? fcInf : fcPosInf);
5740 if (Cond == ISD::SETUEQ)
5741 Flag |= fcNan;
5742 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5743 DAG.getTargetConstant(Flag, dl, MVT::i32));
5744 }
5745 }
5746
5747 // If the condition is not legal, see if we can find an equivalent one
5748 // which is legal.
5750 // If the comparison was an awkward floating-point == or != and one of
5751 // the comparison operands is infinity or negative infinity, convert the
5752 // condition to a less-awkward <= or >=.
5753 if (CFP->getValueAPF().isInfinity()) {
5754 bool IsNegInf = CFP->getValueAPF().isNegative();
5756 switch (Cond) {
5757 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5758 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5759 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5760 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5761 default: break;
5762 }
5763 if (NewCond != ISD::SETCC_INVALID &&
5764 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5765 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5766 }
5767 }
5768 }
5769
5770 if (N0 == N1) {
5771 // The sext(setcc()) => setcc() optimization relies on the appropriate
5772 // constant being emitted.
5773 assert(!N0.getValueType().isInteger() &&
5774 "Integer types should be handled by FoldSetCC");
5775
5776 bool EqTrue = ISD::isTrueWhenEqual(Cond);
5777 unsigned UOF = ISD::getUnorderedFlavor(Cond);
5778 if (UOF == 2) // FP operators that are undefined on NaNs.
5779 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5780 if (UOF == unsigned(EqTrue))
5781 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5782 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
5783 // if it is not already.
5784 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5785 if (NewCond != Cond &&
5786 (DCI.isBeforeLegalizeOps() ||
5787 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5788 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5789 }
5790
5791 // ~X > ~Y --> Y > X
5792 // ~X < ~Y --> Y < X
5793 // ~X < C --> X > ~C
5794 // ~X > C --> X < ~C
5795 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5796 N0.getValueType().isInteger()) {
5797 if (isBitwiseNot(N0)) {
5798 if (isBitwiseNot(N1))
5799 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
5800
5803 SDValue Not = DAG.getNOT(dl, N1, OpVT);
5804 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
5805 }
5806 }
5807 }
5808
5809 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5810 N0.getValueType().isInteger()) {
5811 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
5812 N0.getOpcode() == ISD::XOR) {
5813 // Simplify (X+Y) == (X+Z) --> Y == Z
5814 if (N0.getOpcode() == N1.getOpcode()) {
5815 if (N0.getOperand(0) == N1.getOperand(0))
5816 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
5817 if (N0.getOperand(1) == N1.getOperand(1))
5818 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5819 if (isCommutativeBinOp(N0.getOpcode())) {
5820 // If X op Y == Y op X, try other combinations.
5821 if (N0.getOperand(0) == N1.getOperand(1))
5822 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
5823 Cond);
5824 if (N0.getOperand(1) == N1.getOperand(0))
5825 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
5826 Cond);
5827 }
5828 }
5829
5830 // If RHS is a legal immediate value for a compare instruction, we need
5831 // to be careful about increasing register pressure needlessly.
5832 bool LegalRHSImm = false;
5833
5834 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
5835 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5836 // Turn (X+C1) == C2 --> X == C2-C1
5837 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
5838 return DAG.getSetCC(
5839 dl, VT, N0.getOperand(0),
5840 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
5841 dl, N0.getValueType()),
5842 Cond);
5843
5844 // Turn (X^C1) == C2 --> X == C1^C2
5845 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
5846 return DAG.getSetCC(
5847 dl, VT, N0.getOperand(0),
5848 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
5849 dl, N0.getValueType()),
5850 Cond);
5851 }
5852
5853 // Turn (C1-X) == C2 --> X == C1-C2
5854 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
5855 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
5856 return DAG.getSetCC(
5857 dl, VT, N0.getOperand(1),
5858 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
5859 dl, N0.getValueType()),
5860 Cond);
5861
5862 // Could RHSC fold directly into a compare?
5863 if (RHSC->getValueType(0).getSizeInBits() <= 64)
5864 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
5865 }
5866
5867 // (X+Y) == X --> Y == 0 and similar folds.
5868 // Don't do this if X is an immediate that can fold into a cmp
5869 // instruction and X+Y has other uses. It could be an induction variable
5870 // chain, and the transform would increase register pressure.
5871 if (!LegalRHSImm || N0.hasOneUse())
5872 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
5873 return V;
5874 }
5875
5876 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
5877 N1.getOpcode() == ISD::XOR)
5878 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
5879 return V;
5880
5881 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
5882 return V;
5883
5884 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
5885 return V;
5886 }
5887
5888 // Fold remainder of division by a constant.
5889 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
5890 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5891 // When division is cheap or optimizing for minimum size,
5892 // fall through to DIVREM creation by skipping this fold.
5893 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
5894 if (N0.getOpcode() == ISD::UREM) {
5895 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
5896 return Folded;
5897 } else if (N0.getOpcode() == ISD::SREM) {
5898 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
5899 return Folded;
5900 }
5901 }
5902 }
5903
5904 // Fold away ALL boolean setcc's.
5905 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
5906 SDValue Temp;
5907 switch (Cond) {
5908 default: llvm_unreachable("Unknown integer setcc!");
5909 case ISD::SETEQ: // X == Y -> ~(X^Y)
5910 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5911 N0 = DAG.getNOT(dl, Temp, OpVT);
5912 if (!DCI.isCalledByLegalizer())
5913 DCI.AddToWorklist(Temp.getNode());
5914 break;
5915 case ISD::SETNE: // X != Y --> (X^Y)
5916 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5917 break;
5918 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
5919 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
5920 Temp = DAG.getNOT(dl, N0, OpVT);
5921 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
5922 if (!DCI.isCalledByLegalizer())
5923 DCI.AddToWorklist(Temp.getNode());
5924 break;
5925 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
5926 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
5927 Temp = DAG.getNOT(dl, N1, OpVT);
5928 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
5929 if (!DCI.isCalledByLegalizer())
5930 DCI.AddToWorklist(Temp.getNode());
5931 break;
5932 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
5933 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
5934 Temp = DAG.getNOT(dl, N0, OpVT);
5935 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
5936 if (!DCI.isCalledByLegalizer())
5937 DCI.AddToWorklist(Temp.getNode());
5938 break;
5939 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
5940 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
5941 Temp = DAG.getNOT(dl, N1, OpVT);
5942 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
5943 break;
5944 }
5945 if (VT.getScalarType() != MVT::i1) {
5946 if (!DCI.isCalledByLegalizer())
5947 DCI.AddToWorklist(N0.getNode());
5948 // FIXME: If running after legalize, we probably can't do this.
5950 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
5951 }
5952 return N0;
5953 }
5954
5955 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
5956 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
5957 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
5959 N1->getFlags().hasNoUnsignedWrap()) ||
5961 N1->getFlags().hasNoSignedWrap())) &&
5963 if (VT.getScalarType() == MVT::i1)
5964 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5965 // For (legal) non vXi1 cases - ensure we adjust the cmp and result types.
5966 EVT OldCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5967 N0.getValueType());
5968 if (VT == OldCCVT) {
5969 EVT NewCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5970 N0.getOperand(0).getValueType());
5971 return DAG.getBoolExtOrTrunc(
5972 DAG.getSetCC(dl, NewCCVT, N0.getOperand(0), N1.getOperand(0), Cond),
5973 dl, VT, N0.getOperand(0).getValueType());
5974 }
5975 }
5976
5977 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
5978 // TODO: Remove that .isVector() check
5979 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
5981 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
5982 }
5983
5984 // Could not fold it.
5985 return SDValue();
5986}
5987
5988/// Returns true (and the GlobalValue and the offset) if the node is a
5989/// GlobalAddress + offset.
5991 int64_t &Offset) const {
5992
5993 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
5994
5995 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
5996 GA = GASD->getGlobal();
5997 Offset += GASD->getOffset();
5998 return true;
5999 }
6000
6001 if (N->isAnyAdd()) {
6002 SDValue N1 = N->getOperand(0);
6003 SDValue N2 = N->getOperand(1);
6004 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
6005 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
6006 Offset += V->getSExtValue();
6007 return true;
6008 }
6009 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
6010 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
6011 Offset += V->getSExtValue();
6012 return true;
6013 }
6014 }
6015 }
6016
6017 return false;
6018}
6019
6021 DAGCombinerInfo &DCI) const {
6022 // Default implementation: no optimization.
6023 return SDValue();
6024}
6025
6026//===----------------------------------------------------------------------===//
6027// Inline Assembler Implementation Methods
6028//===----------------------------------------------------------------------===//
6029
6032 unsigned S = Constraint.size();
6033
6034 if (S == 1) {
6035 switch (Constraint[0]) {
6036 default: break;
6037 case 'r':
6038 return C_RegisterClass;
6039 case 'm': // memory
6040 case 'o': // offsetable
6041 case 'V': // not offsetable
6042 return C_Memory;
6043 case 'p': // Address.
6044 return C_Address;
6045 case 'n': // Simple Integer
6046 case 'E': // Floating Point Constant
6047 case 'F': // Floating Point Constant
6048 return C_Immediate;
6049 case 'i': // Simple Integer or Relocatable Constant
6050 case 's': // Relocatable Constant
6051 case 'X': // Allow ANY value.
6052 case 'I': // Target registers.
6053 case 'J':
6054 case 'K':
6055 case 'L':
6056 case 'M':
6057 case 'N':
6058 case 'O':
6059 case 'P':
6060 case '<':
6061 case '>':
6062 return C_Other;
6063 }
6064 }
6065
6066 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
6067 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
6068 return C_Memory;
6069 return C_Register;
6070 }
6071 return C_Unknown;
6072}
6073
6074/// Try to replace an X constraint, which matches anything, with another that
6075/// has more specific requirements based on the type of the corresponding
6076/// operand.
6077const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6078 if (ConstraintVT.isInteger())
6079 return "r";
6080 if (ConstraintVT.isFloatingPoint())
6081 return "f"; // works for many targets
6082 return nullptr;
6083}
6084
6086 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
6087 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
6088 return SDValue();
6089}
6090
6091/// Lower the specified operand into the Ops vector.
6092/// If it is invalid, don't add anything to Ops.
6094 StringRef Constraint,
6095 std::vector<SDValue> &Ops,
6096 SelectionDAG &DAG) const {
6097
6098 if (Constraint.size() > 1)
6099 return;
6100
6101 char ConstraintLetter = Constraint[0];
6102 switch (ConstraintLetter) {
6103 default: break;
6104 case 'X': // Allows any operand
6105 case 'i': // Simple Integer or Relocatable Constant
6106 case 'n': // Simple Integer
6107 case 's': { // Relocatable Constant
6108
6110 uint64_t Offset = 0;
6111
6112 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
6113 // etc., since getelementpointer is variadic. We can't use
6114 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
6115 // while in this case the GA may be furthest from the root node which is
6116 // likely an ISD::ADD.
6117 while (true) {
6118 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
6119 // gcc prints these as sign extended. Sign extend value to 64 bits
6120 // now; without this it would get ZExt'd later in
6121 // ScheduleDAGSDNodes::EmitNode, which is very generic.
6122 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
6123 BooleanContent BCont = getBooleanContents(MVT::i64);
6124 ISD::NodeType ExtOpc =
6125 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
6126 int64_t ExtVal =
6127 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
6128 Ops.push_back(
6129 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
6130 return;
6131 }
6132 if (ConstraintLetter != 'n') {
6133 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6134 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6135 GA->getValueType(0),
6136 Offset + GA->getOffset()));
6137 return;
6138 }
6139 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
6140 Ops.push_back(DAG.getTargetBlockAddress(
6141 BA->getBlockAddress(), BA->getValueType(0),
6142 Offset + BA->getOffset(), BA->getTargetFlags()));
6143 return;
6144 }
6146 Ops.push_back(Op);
6147 return;
6148 }
6149 }
6150 const unsigned OpCode = Op.getOpcode();
6151 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6152 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6153 Op = Op.getOperand(1);
6154 // Subtraction is not commutative.
6155 else if (OpCode == ISD::ADD &&
6156 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6157 Op = Op.getOperand(0);
6158 else
6159 return;
6160 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6161 continue;
6162 }
6163 return;
6164 }
6165 break;
6166 }
6167 }
6168}
6169
6173
6174std::pair<unsigned, const TargetRegisterClass *>
6176 StringRef Constraint,
6177 MVT VT) const {
6178 if (!Constraint.starts_with("{"))
6179 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6180 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6181
6182 // Remove the braces from around the name.
6183 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6184
6185 std::pair<unsigned, const TargetRegisterClass *> R =
6186 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6187
6188 // Figure out which register class contains this reg.
6189 for (const TargetRegisterClass &RC : RI->regclasses()) {
6190 // If none of the value types for this register class are valid, we
6191 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6192 if (!isLegalRC(*RI, RC))
6193 continue;
6194
6195 for (const MCPhysReg &PR : RC) {
6196 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6197 std::pair<unsigned, const TargetRegisterClass *> S =
6198 std::make_pair(PR, &RC);
6199
6200 // If this register class has the requested value type, return it,
6201 // otherwise keep searching and return the first class found
6202 // if no other is found which explicitly has the requested type.
6203 if (RI->isTypeLegalForClass(RC, VT))
6204 return S;
6205 if (!R.second)
6206 R = S;
6207 }
6208 }
6209 }
6210
6211 return R;
6212}
6213
6214//===----------------------------------------------------------------------===//
6215// Constraint Selection.
6216
6217/// Return true of this is an input operand that is a matching constraint like
6218/// "4".
6220 assert(!ConstraintCode.empty() && "No known constraint!");
6221 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6222}
6223
6224/// If this is an input matching constraint, this method returns the output
6225/// operand it matches.
6227 assert(!ConstraintCode.empty() && "No known constraint!");
6228 return atoi(ConstraintCode.c_str());
6229}
6230
6231/// Split up the constraint string from the inline assembly value into the
6232/// specific constraints and their prefixes, and also tie in the associated
6233/// operand values.
6234/// If this returns an empty vector, and if the constraint string itself
6235/// isn't empty, there was an error parsing.
6238 const TargetRegisterInfo *TRI,
6239 const CallBase &Call) const {
6240 /// Information about all of the constraints.
6241 AsmOperandInfoVector ConstraintOperands;
6242 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6243 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6244
6245 // Do a prepass over the constraints, canonicalizing them, and building up the
6246 // ConstraintOperands list.
6247 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6248 unsigned ResNo = 0; // ResNo - The result number of the next output.
6249 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6250
6251 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6252 ConstraintOperands.emplace_back(std::move(CI));
6253 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6254
6255 // Update multiple alternative constraint count.
6256 if (OpInfo.multipleAlternatives.size() > maCount)
6257 maCount = OpInfo.multipleAlternatives.size();
6258
6259 OpInfo.ConstraintVT = MVT::Other;
6260
6261 // Compute the value type for each operand.
6262 switch (OpInfo.Type) {
6263 case InlineAsm::isOutput: {
6264 // Indirect outputs just consume an argument.
6265 if (OpInfo.isIndirect) {
6266 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6267 break;
6268 }
6269
6270 // The return value of the call is this value. As such, there is no
6271 // corresponding argument.
6272 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6273 EVT VT;
6274 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6275 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6276 } else {
6277 assert(ResNo == 0 && "Asm only has one result!");
6278 VT = getAsmOperandValueType(DL, Call.getType());
6279 }
6280 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6281 ++ResNo;
6282 break;
6283 }
6284 case InlineAsm::isInput:
6285 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6286 break;
6287 case InlineAsm::isLabel:
6288 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6289 ++LabelNo;
6290 continue;
6292 // Nothing to do.
6293 break;
6294 }
6295
6296 if (OpInfo.CallOperandVal) {
6297 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6298 if (OpInfo.isIndirect) {
6299 OpTy = Call.getParamElementType(ArgNo);
6300 assert(OpTy && "Indirect operand must have elementtype attribute");
6301 }
6302
6303 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6305 if (STy->getNumElements() == 1)
6306 OpTy = STy->getElementType(0);
6307
6308 // If OpTy is not a single value, it may be a struct/union that we
6309 // can tile with integers.
6310 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6311 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6312 switch (BitSize) {
6313 default: break;
6314 case 1:
6315 case 8:
6316 case 16:
6317 case 32:
6318 case 64:
6319 case 128:
6320 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6321 break;
6322 }
6323 }
6324
6325 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6326 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6327 ArgNo++;
6328 }
6329 }
6330
6331 // If we have multiple alternative constraints, select the best alternative.
6332 if (!ConstraintOperands.empty()) {
6333 if (maCount) {
6334 unsigned bestMAIndex = 0;
6335 int bestWeight = -1;
6336 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6337 int weight = -1;
6338 unsigned maIndex;
6339 // Compute the sums of the weights for each alternative, keeping track
6340 // of the best (highest weight) one so far.
6341 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6342 int weightSum = 0;
6343 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6344 cIndex != eIndex; ++cIndex) {
6345 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6346 if (OpInfo.Type == InlineAsm::isClobber)
6347 continue;
6348
6349 // If this is an output operand with a matching input operand,
6350 // look up the matching input. If their types mismatch, e.g. one
6351 // is an integer, the other is floating point, or their sizes are
6352 // different, flag it as an maCantMatch.
6353 if (OpInfo.hasMatchingInput()) {
6354 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6355 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6356 if ((OpInfo.ConstraintVT.isInteger() !=
6357 Input.ConstraintVT.isInteger()) ||
6358 (OpInfo.ConstraintVT.getSizeInBits() !=
6359 Input.ConstraintVT.getSizeInBits())) {
6360 weightSum = -1; // Can't match.
6361 break;
6362 }
6363 }
6364 }
6365 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6366 if (weight == -1) {
6367 weightSum = -1;
6368 break;
6369 }
6370 weightSum += weight;
6371 }
6372 // Update best.
6373 if (weightSum > bestWeight) {
6374 bestWeight = weightSum;
6375 bestMAIndex = maIndex;
6376 }
6377 }
6378
6379 // Now select chosen alternative in each constraint.
6380 for (AsmOperandInfo &cInfo : ConstraintOperands)
6381 if (cInfo.Type != InlineAsm::isClobber)
6382 cInfo.selectAlternative(bestMAIndex);
6383 }
6384 }
6385
6386 // Check and hook up tied operands, choose constraint code to use.
6387 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6388 cIndex != eIndex; ++cIndex) {
6389 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6390
6391 // If this is an output operand with a matching input operand, look up the
6392 // matching input. If their types mismatch, e.g. one is an integer, the
6393 // other is floating point, or their sizes are different, flag it as an
6394 // error.
6395 if (OpInfo.hasMatchingInput()) {
6396 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6397
6398 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6399 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6400 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6401 OpInfo.ConstraintVT);
6402 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6403 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6404 Input.ConstraintVT);
6405 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6406 OpInfo.ConstraintVT.isFloatingPoint();
6407 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6408 Input.ConstraintVT.isFloatingPoint();
6409 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6410 (MatchRC.second != InputRC.second)) {
6411 report_fatal_error("Unsupported asm: input constraint"
6412 " with a matching output constraint of"
6413 " incompatible type!");
6414 }
6415 }
6416 }
6417 }
6418
6419 return ConstraintOperands;
6420}
6421
6422/// Return a number indicating our preference for chosing a type of constraint
6423/// over another, for the purpose of sorting them. Immediates are almost always
6424/// preferrable (when they can be emitted). A higher return value means a
6425/// stronger preference for one constraint type relative to another.
6426/// FIXME: We should prefer registers over memory but doing so may lead to
6427/// unrecoverable register exhaustion later.
6428/// https://github.com/llvm/llvm-project/issues/20571
6430 switch (CT) {
6433 return 4;
6436 return 3;
6438 return 2;
6440 return 1;
6442 return 0;
6443 }
6444 llvm_unreachable("Invalid constraint type");
6445}
6446
6447/// Examine constraint type and operand type and determine a weight value.
6448/// This object must already have been set up with the operand type
6449/// and the current alternative constraint selected.
6452 AsmOperandInfo &info, int maIndex) const {
6454 if (maIndex >= (int)info.multipleAlternatives.size())
6455 rCodes = &info.Codes;
6456 else
6457 rCodes = &info.multipleAlternatives[maIndex].Codes;
6458 ConstraintWeight BestWeight = CW_Invalid;
6459
6460 // Loop over the options, keeping track of the most general one.
6461 for (const std::string &rCode : *rCodes) {
6462 ConstraintWeight weight =
6463 getSingleConstraintMatchWeight(info, rCode.c_str());
6464 if (weight > BestWeight)
6465 BestWeight = weight;
6466 }
6467
6468 return BestWeight;
6469}
6470
6471/// Examine constraint type and operand type and determine a weight value.
6472/// This object must already have been set up with the operand type
6473/// and the current alternative constraint selected.
6476 AsmOperandInfo &info, const char *constraint) const {
6478 Value *CallOperandVal = info.CallOperandVal;
6479 // If we don't have a value, we can't do a match,
6480 // but allow it at the lowest weight.
6481 if (!CallOperandVal)
6482 return CW_Default;
6483 // Look at the constraint type.
6484 switch (*constraint) {
6485 case 'i': // immediate integer.
6486 case 'n': // immediate integer with a known value.
6487 if (isa<ConstantInt>(CallOperandVal))
6488 weight = CW_Constant;
6489 break;
6490 case 's': // non-explicit intregal immediate.
6491 if (isa<GlobalValue>(CallOperandVal))
6492 weight = CW_Constant;
6493 break;
6494 case 'E': // immediate float if host format.
6495 case 'F': // immediate float.
6496 if (isa<ConstantFP>(CallOperandVal))
6497 weight = CW_Constant;
6498 break;
6499 case '<': // memory operand with autodecrement.
6500 case '>': // memory operand with autoincrement.
6501 case 'm': // memory operand.
6502 case 'o': // offsettable memory operand
6503 case 'V': // non-offsettable memory operand
6504 weight = CW_Memory;
6505 break;
6506 case 'r': // general register.
6507 case 'g': // general register, memory operand or immediate integer.
6508 // note: Clang converts "g" to "imr".
6509 if (CallOperandVal->getType()->isIntegerTy())
6510 weight = CW_Register;
6511 break;
6512 case 'X': // any operand.
6513 default:
6514 weight = CW_Default;
6515 break;
6516 }
6517 return weight;
6518}
6519
6520/// If there are multiple different constraints that we could pick for this
6521/// operand (e.g. "imr") try to pick the 'best' one.
6522/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6523/// into seven classes:
6524/// Register -> one specific register
6525/// RegisterClass -> a group of regs
6526/// Memory -> memory
6527/// Address -> a symbolic memory reference
6528/// Immediate -> immediate values
6529/// Other -> magic values (such as "Flag Output Operands")
6530/// Unknown -> something we don't recognize yet and can't handle
6531/// Ideally, we would pick the most specific constraint possible: if we have
6532/// something that fits into a register, we would pick it. The problem here
6533/// is that if we have something that could either be in a register or in
6534/// memory that use of the register could cause selection of *other*
6535/// operands to fail: they might only succeed if we pick memory. Because of
6536/// this the heuristic we use is:
6537///
6538/// 1) If there is an 'other' constraint, and if the operand is valid for
6539/// that constraint, use it. This makes us take advantage of 'i'
6540/// constraints when available.
6541/// 2) Otherwise, pick the most general constraint present. This prefers
6542/// 'm' over 'r', for example.
6543///
6545 TargetLowering::AsmOperandInfo &OpInfo) const {
6546 ConstraintGroup Ret;
6547
6548 Ret.reserve(OpInfo.Codes.size());
6549 for (StringRef Code : OpInfo.Codes) {
6551
6552 // Indirect 'other' or 'immediate' constraints are not allowed.
6553 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6554 CType == TargetLowering::C_Register ||
6556 continue;
6557
6558 // Things with matching constraints can only be registers, per gcc
6559 // documentation. This mainly affects "g" constraints.
6560 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6561 continue;
6562
6563 Ret.emplace_back(Code, CType);
6564 }
6565
6567 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6568 });
6569
6570 return Ret;
6571}
6572
6573/// If we have an immediate, see if we can lower it. Return true if we can,
6574/// false otherwise.
6576 SDValue Op, SelectionDAG *DAG,
6577 const TargetLowering &TLI) {
6578
6579 assert((P.second == TargetLowering::C_Other ||
6580 P.second == TargetLowering::C_Immediate) &&
6581 "need immediate or other");
6582
6583 if (!Op.getNode())
6584 return false;
6585
6586 std::vector<SDValue> ResultOps;
6587 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6588 return !ResultOps.empty();
6589}
6590
6591/// Determines the constraint code and constraint type to use for the specific
6592/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6594 SDValue Op,
6595 SelectionDAG *DAG) const {
6596 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6597
6598 // Single-letter constraints ('r') are very common.
6599 if (OpInfo.Codes.size() == 1) {
6600 OpInfo.ConstraintCode = OpInfo.Codes[0];
6601 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6602 } else {
6604 if (G.empty())
6605 return;
6606
6607 unsigned BestIdx = 0;
6608 for (const unsigned E = G.size();
6609 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6610 G[BestIdx].second == TargetLowering::C_Immediate);
6611 ++BestIdx) {
6612 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6613 break;
6614 // If we're out of constraints, just pick the first one.
6615 if (BestIdx + 1 == E) {
6616 BestIdx = 0;
6617 break;
6618 }
6619 }
6620
6621 OpInfo.ConstraintCode = G[BestIdx].first;
6622 OpInfo.ConstraintType = G[BestIdx].second;
6623 }
6624
6625 // 'X' matches anything.
6626 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6627 // Constants are handled elsewhere. For Functions, the type here is the
6628 // type of the result, which is not what we want to look at; leave them
6629 // alone.
6630 Value *v = OpInfo.CallOperandVal;
6631 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6632 return;
6633 }
6634
6635 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6636 OpInfo.ConstraintCode = "i";
6637 return;
6638 }
6639
6640 // Otherwise, try to resolve it to something we know about by looking at
6641 // the actual operand type.
6642 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6643 OpInfo.ConstraintCode = Repl;
6644 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6645 }
6646 }
6647}
6648
6649/// Given an exact SDIV by a constant, create a multiplication
6650/// with the multiplicative inverse of the constant.
6651/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6653 const SDLoc &dl, SelectionDAG &DAG,
6654 SmallVectorImpl<SDNode *> &Created) {
6655 SDValue Op0 = N->getOperand(0);
6656 SDValue Op1 = N->getOperand(1);
6657 EVT VT = N->getValueType(0);
6658 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6659 EVT ShSVT = ShVT.getScalarType();
6660
6661 bool UseSRA = false;
6662 SmallVector<SDValue, 16> Shifts, Factors;
6663
6664 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6665 if (C->isZero())
6666 return false;
6667
6668 EVT CT = C->getValueType(0);
6669 APInt Divisor = C->getAPIntValue();
6670 unsigned Shift = Divisor.countr_zero();
6671 if (Shift) {
6672 Divisor.ashrInPlace(Shift);
6673 UseSRA = true;
6674 }
6675 APInt Factor = Divisor.multiplicativeInverse();
6676 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6677 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6678 return true;
6679 };
6680
6681 // Collect all magic values from the build vector.
6682 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6683 return SDValue();
6684
6685 SDValue Shift, Factor;
6686 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6687 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6688 Factor = DAG.getBuildVector(VT, dl, Factors);
6689 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6690 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6691 "Expected matchUnaryPredicate to return one element for scalable "
6692 "vectors");
6693 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6694 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6695 } else {
6696 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6697 Shift = Shifts[0];
6698 Factor = Factors[0];
6699 }
6700
6701 SDValue Res = Op0;
6702 if (UseSRA) {
6703 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6704 Created.push_back(Res.getNode());
6705 }
6706
6707 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6708}
6709
6710/// Given an exact UDIV by a constant, create a multiplication
6711/// with the multiplicative inverse of the constant.
6712/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6714 const SDLoc &dl, SelectionDAG &DAG,
6715 SmallVectorImpl<SDNode *> &Created) {
6716 EVT VT = N->getValueType(0);
6717 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6718 EVT ShSVT = ShVT.getScalarType();
6719
6720 bool UseSRL = false;
6721 SmallVector<SDValue, 16> Shifts, Factors;
6722
6723 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6724 if (C->isZero())
6725 return false;
6726
6727 EVT CT = C->getValueType(0);
6728 APInt Divisor = C->getAPIntValue();
6729 unsigned Shift = Divisor.countr_zero();
6730 if (Shift) {
6731 Divisor.lshrInPlace(Shift);
6732 UseSRL = true;
6733 }
6734 // Calculate the multiplicative inverse modulo BW.
6735 APInt Factor = Divisor.multiplicativeInverse();
6736 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6737 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6738 return true;
6739 };
6740
6741 SDValue Op1 = N->getOperand(1);
6742
6743 // Collect all magic values from the build vector.
6744 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6745 return SDValue();
6746
6747 SDValue Shift, Factor;
6748 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6749 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6750 Factor = DAG.getBuildVector(VT, dl, Factors);
6751 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6752 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6753 "Expected matchUnaryPredicate to return one element for scalable "
6754 "vectors");
6755 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6756 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6757 } else {
6758 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6759 Shift = Shifts[0];
6760 Factor = Factors[0];
6761 }
6762
6763 SDValue Res = N->getOperand(0);
6764 if (UseSRL) {
6765 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
6766 Created.push_back(Res.getNode());
6767 }
6768
6769 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6770}
6771
6773 SelectionDAG &DAG,
6774 SmallVectorImpl<SDNode *> &Created) const {
6776 if (isIntDivCheap(N->getValueType(0), Attr))
6777 return SDValue(N, 0); // Lower SDIV as SDIV
6778 return SDValue();
6779}
6780
6781SDValue
6783 SelectionDAG &DAG,
6784 SmallVectorImpl<SDNode *> &Created) const {
6786 if (isIntDivCheap(N->getValueType(0), Attr))
6787 return SDValue(N, 0); // Lower SREM as SREM
6788 return SDValue();
6789}
6790
6791/// Build sdiv by power-of-2 with conditional move instructions
6792/// Ref: "Hacker's Delight" by Henry Warren 10-1
6793/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6794/// bgez x, label
6795/// add x, x, 2**k-1
6796/// label:
6797/// sra res, x, k
6798/// neg res, res (when the divisor is negative)
6800 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
6801 SmallVectorImpl<SDNode *> &Created) const {
6802 unsigned Lg2 = Divisor.countr_zero();
6803 EVT VT = N->getValueType(0);
6804
6805 SDLoc DL(N);
6806 SDValue N0 = N->getOperand(0);
6807 SDValue Zero = DAG.getConstant(0, DL, VT);
6808 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
6809 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
6810
6811 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
6812 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6813 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
6814 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6815 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
6816
6817 Created.push_back(Cmp.getNode());
6818 Created.push_back(Add.getNode());
6819 Created.push_back(CMov.getNode());
6820
6821 // Divide by pow2.
6822 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
6823 DAG.getShiftAmountConstant(Lg2, VT, DL));
6824
6825 // If we're dividing by a positive value, we're done. Otherwise, we must
6826 // negate the result.
6827 if (Divisor.isNonNegative())
6828 return SRA;
6829
6830 Created.push_back(SRA.getNode());
6831 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
6832}
6833
6834/// Given an ISD::SDIV node expressing a divide by constant,
6835/// return a DAG expression to select that will generate the same value by
6836/// multiplying by a magic number.
6837/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6839 bool IsAfterLegalization,
6840 bool IsAfterLegalTypes,
6841 SmallVectorImpl<SDNode *> &Created) const {
6842 SDLoc dl(N);
6843
6844 // If the sdiv has an 'exact' bit we can use a simpler lowering.
6845 if (N->getFlags().hasExact())
6846 return BuildExactSDIV(*this, N, dl, DAG, Created);
6847
6848 EVT VT = N->getValueType(0);
6849 EVT SVT = VT.getScalarType();
6850 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6851 EVT ShSVT = ShVT.getScalarType();
6852 unsigned EltBits = VT.getScalarSizeInBits();
6853 EVT MulVT;
6854
6855 // Check to see if we can do this.
6856 // FIXME: We should be more aggressive here.
6857 EVT QueryVT = VT;
6858 if (VT.isVector()) {
6859 // If the vector type will be legalized to a vector type with the same
6860 // element type, allow the transform before type legalization if MULHS or
6861 // SMUL_LOHI are supported.
6862 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
6863 if (!QueryVT.isVector() ||
6865 return SDValue();
6866 } else if (!isTypeLegal(VT)) {
6867 // Limit this to simple scalars for now.
6868 if (!VT.isSimple())
6869 return SDValue();
6870
6871 // If this type will be promoted to a large enough type with a legal
6872 // multiply operation, we can go ahead and do this transform.
6874 return SDValue();
6875
6876 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6877 if (MulVT.getSizeInBits() < (2 * EltBits) ||
6878 !isOperationLegal(ISD::MUL, MulVT))
6879 return SDValue();
6880 }
6881
6882 bool HasMULHS =
6883 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
6884 bool HasSMUL_LOHI =
6885 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
6886
6887 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
6888 // If type twice as wide legal, widen and use a mul plus a shift.
6889 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
6890 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
6891 // custom lowered. This is very expensive so avoid it at all costs for
6892 // constant divisors.
6893 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
6896 MulVT = WideVT;
6897 }
6898
6899 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
6900 return SDValue();
6901
6902 // If we're after type legalization and SVT is not legal, use the
6903 // promoted type for creating constants to avoid creating nodes with
6904 // illegal types.
6905 if (IsAfterLegalTypes && VT.isVector()) {
6906 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
6907 if (SVT.bitsLT(VT.getScalarType()))
6908 return SDValue();
6909 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
6910 if (ShSVT.bitsLT(ShVT.getScalarType()))
6911 return SDValue();
6912 }
6913 const unsigned SVTBits = SVT.getSizeInBits();
6914
6915 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
6916
6917 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6918 if (C->isZero())
6919 return false;
6920 // Truncate the divisor to the target scalar type in case it was promoted
6921 // during type legalization.
6922 APInt Divisor = C->getAPIntValue().trunc(EltBits);
6924 int NumeratorFactor = 0;
6925 int ShiftMask = -1;
6926
6927 if (Divisor.isOne() || Divisor.isAllOnes()) {
6928 // If d is +1/-1, we just multiply the numerator by +1/-1.
6929 NumeratorFactor = Divisor.getSExtValue();
6930 magics.Magic = 0;
6931 magics.ShiftAmount = 0;
6932 ShiftMask = 0;
6933 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
6934 // If d > 0 and m < 0, add the numerator.
6935 NumeratorFactor = 1;
6936 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
6937 // If d < 0 and m > 0, subtract the numerator.
6938 NumeratorFactor = -1;
6939 }
6940
6941 MagicFactors.push_back(
6942 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
6943 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
6944 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
6945 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
6946 return true;
6947 };
6948
6949 SDValue N0 = N->getOperand(0);
6950 SDValue N1 = N->getOperand(1);
6951
6952 // Collect the shifts / magic values from each element.
6953 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
6954 /*AllowTruncation=*/true))
6955 return SDValue();
6956
6957 SDValue MagicFactor, Factor, Shift, ShiftMask;
6958 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
6959 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
6960 Factor = DAG.getBuildVector(VT, dl, Factors);
6961 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6962 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
6963 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
6964 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
6965 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
6966 "Expected matchUnaryPredicate to return one element for scalable "
6967 "vectors");
6968 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
6969 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6970 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6971 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
6972 } else {
6973 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
6974 MagicFactor = MagicFactors[0];
6975 Factor = Factors[0];
6976 Shift = Shifts[0];
6977 ShiftMask = ShiftMasks[0];
6978 }
6979
6980 // Multiply the numerator (operand 0) by the magic value.
6981 auto GetMULHS = [&](SDValue X, SDValue Y) {
6982 if (HasMULHS)
6983 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
6984 if (HasSMUL_LOHI) {
6985 SDValue LoHi =
6986 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
6987 return LoHi.getValue(1);
6988 }
6989
6990 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
6991 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
6992 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
6993 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
6994 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
6995 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6996 };
6997
6998 SDValue Q = GetMULHS(N0, MagicFactor);
6999 if (!Q)
7000 return SDValue();
7001
7002 Created.push_back(Q.getNode());
7003
7004 // (Optionally) Add/subtract the numerator using Factor.
7005 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
7006 Created.push_back(Factor.getNode());
7007 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
7008 Created.push_back(Q.getNode());
7009
7010 // Shift right algebraic by shift value.
7011 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
7012 Created.push_back(Q.getNode());
7013
7014 // Extract the sign bit, mask it and add it to the quotient.
7015 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
7016 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
7017 Created.push_back(T.getNode());
7018 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
7019 Created.push_back(T.getNode());
7020 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
7021}
7022
7023/// Given an ISD::UDIV node expressing a divide by constant,
7024/// return a DAG expression to select that will generate the same value by
7025/// multiplying by a magic number.
7026/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7028 bool IsAfterLegalization,
7029 bool IsAfterLegalTypes,
7030 SmallVectorImpl<SDNode *> &Created) const {
7031 SDLoc dl(N);
7032
7033 // If the udiv has an 'exact' bit we can use a simpler lowering.
7034 if (N->getFlags().hasExact())
7035 return BuildExactUDIV(*this, N, dl, DAG, Created);
7036
7037 EVT VT = N->getValueType(0);
7038 EVT SVT = VT.getScalarType();
7039 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7040 EVT ShSVT = ShVT.getScalarType();
7041 unsigned EltBits = VT.getScalarSizeInBits();
7042 EVT MulVT;
7043
7044 // Check to see if we can do this.
7045 // FIXME: We should be more aggressive here.
7046 EVT QueryVT = VT;
7047 if (VT.isVector()) {
7048 // If the vector type will be legalized to a vector type with the same
7049 // element type, allow the transform before type legalization if MULHU or
7050 // UMUL_LOHI are supported.
7051 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7052 if (!QueryVT.isVector() ||
7054 return SDValue();
7055 } else if (!isTypeLegal(VT)) {
7056 // Limit this to simple scalars for now.
7057 if (!VT.isSimple())
7058 return SDValue();
7059
7060 // If this type will be promoted to a large enough type with a legal
7061 // multiply operation, we can go ahead and do this transform.
7063 return SDValue();
7064
7065 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7066 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7067 !isOperationLegal(ISD::MUL, MulVT))
7068 return SDValue();
7069 }
7070
7071 bool HasMULHU =
7072 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
7073 bool HasUMUL_LOHI =
7074 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
7075
7076 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
7077 // If type twice as wide legal, widen and use a mul plus a shift.
7078 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7079 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
7080 // custom lowered. This is very expensive so avoid it at all costs for
7081 // constant divisors.
7082 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
7085 MulVT = WideVT;
7086 }
7087
7088 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
7089 return SDValue();
7090
7091 SDValue N0 = N->getOperand(0);
7092 SDValue N1 = N->getOperand(1);
7093
7094 // Try to use leading zeros of the dividend to reduce the multiplier and
7095 // avoid expensive fixups.
7096 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
7097
7098 // If we're after type legalization and SVT is not legal, use the
7099 // promoted type for creating constants to avoid creating nodes with
7100 // illegal types.
7101 if (IsAfterLegalTypes && VT.isVector()) {
7102 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7103 if (SVT.bitsLT(VT.getScalarType()))
7104 return SDValue();
7105 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7106 if (ShSVT.bitsLT(ShVT.getScalarType()))
7107 return SDValue();
7108 }
7109 const unsigned SVTBits = SVT.getSizeInBits();
7110
7111 // Allow i32 to be widened to i64 for uncooperative divisors if i64 MULHU or
7112 // UMUL_LOHI is supported.
7113 const EVT WideSVT = MVT::i64;
7114 const bool HasWideMULHU =
7115 VT == MVT::i32 &&
7116 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
7117 const bool HasWideUMUL_LOHI =
7118 VT == MVT::i32 &&
7119 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
7120 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
7121
7122 // For even divisors with a 33-bit magic number, the widened high-multiply
7123 // path is only worthwhile over the even-divisor rewrite on targets that
7124 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
7125 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
7126 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
7127
7128 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
7129 bool UseWiden = false;
7130 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
7131
7132 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
7133 if (C->isZero())
7134 return false;
7135 // Truncate the divisor to the target scalar type in case it was promoted
7136 // during type legalization.
7137 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7138
7139 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
7140
7141 // Magic algorithm doesn't work for division by 1. We need to emit a select
7142 // at the end.
7143 if (Divisor.isOne()) {
7144 PreShift = PostShift = DAG.getUNDEF(ShSVT);
7145 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
7146 } else {
7149 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7150 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7151 /*AllowWidenOptimization=*/AllowWiden);
7152
7153 if (magics.Widen) {
7154 UseWiden = true;
7155 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7156 } else {
7157 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7158 }
7159
7160 assert(magics.PreShift < Divisor.getBitWidth() &&
7161 "We shouldn't generate an undefined shift!");
7162 assert(magics.PostShift < Divisor.getBitWidth() &&
7163 "We shouldn't generate an undefined shift!");
7164 assert((!magics.IsAdd || magics.PreShift == 0) &&
7165 "Unexpected pre-shift");
7166 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7167 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7168 NPQFactor = DAG.getConstant(
7169 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7170 : APInt::getZero(SVTBits),
7171 dl, SVT);
7172 UseNPQ |= magics.IsAdd;
7173 UsePreShift |= magics.PreShift != 0;
7174 UsePostShift |= magics.PostShift != 0;
7175 }
7176
7177 PreShifts.push_back(PreShift);
7178 MagicFactors.push_back(MagicFactor);
7179 NPQFactors.push_back(NPQFactor);
7180 PostShifts.push_back(PostShift);
7181 return true;
7182 };
7183
7184 // Collect the shifts/magic values from each element.
7185 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7186 /*AllowTruncation=*/true))
7187 return SDValue();
7188
7189 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7190 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7191 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7192 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7193 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7194 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7195 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7196 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7197 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7198 "Expected matchUnaryPredicate to return one for scalable vectors");
7199 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7200 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7201 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7202 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7203 } else {
7204 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7205 PreShift = PreShifts[0];
7206 MagicFactor = MagicFactors[0];
7207 PostShift = PostShifts[0];
7208 }
7209
7210 if (UseWiden) {
7211 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7212 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7213
7214 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7215 // WideSVT bits
7216 SDValue High;
7217 if (HasWideMULHU) {
7218 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7219 } else {
7220 assert(HasWideUMUL_LOHI);
7221 SDValue LoHi =
7222 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7223 WideN0, MagicFactor);
7224 High = LoHi.getValue(1);
7225 }
7226
7227 Created.push_back(High.getNode());
7228 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7229 }
7230
7231 SDValue Q = N0;
7232 if (UsePreShift) {
7233 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7234 Created.push_back(Q.getNode());
7235 }
7236
7237 auto GetMULHU = [&](SDValue X, SDValue Y) {
7238 if (HasMULHU)
7239 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7240 if (HasUMUL_LOHI) {
7241 SDValue LoHi =
7242 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7243 return LoHi.getValue(1);
7244 }
7245
7246 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7247 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7248 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7249 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7250 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7251 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7252 };
7253
7254 // Multiply the numerator (operand 0) by the magic value.
7255 Q = GetMULHU(Q, MagicFactor);
7256 if (!Q)
7257 return SDValue();
7258
7259 Created.push_back(Q.getNode());
7260
7261 if (UseNPQ) {
7262 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7263 Created.push_back(NPQ.getNode());
7264
7265 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7266 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7267 if (VT.isVector())
7268 NPQ = GetMULHU(NPQ, NPQFactor);
7269 else
7270 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7271
7272 Created.push_back(NPQ.getNode());
7273
7274 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7275 Created.push_back(Q.getNode());
7276 }
7277
7278 if (UsePostShift) {
7279 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7280 Created.push_back(Q.getNode());
7281 }
7282
7283 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7284
7285 SDValue One = DAG.getConstant(1, dl, VT);
7286 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7287 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7288}
7289
7290/// If all values in Values that *don't* match the predicate are same 'splat'
7291/// value, then replace all values with that splat value.
7292/// Else, if AlternativeReplacement was provided, then replace all values that
7293/// do match predicate with AlternativeReplacement value.
7294static void
7296 std::function<bool(SDValue)> Predicate,
7297 SDValue AlternativeReplacement = SDValue()) {
7298 SDValue Replacement;
7299 // Is there a value for which the Predicate does *NOT* match? What is it?
7300 auto SplatValue = llvm::find_if_not(Values, Predicate);
7301 if (SplatValue != Values.end()) {
7302 // Does Values consist only of SplatValue's and values matching Predicate?
7303 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7304 return Value == *SplatValue || Predicate(Value);
7305 })) // Then we shall replace values matching predicate with SplatValue.
7306 Replacement = *SplatValue;
7307 }
7308 if (!Replacement) {
7309 // Oops, we did not find the "baseline" splat value.
7310 if (!AlternativeReplacement)
7311 return; // Nothing to do.
7312 // Let's replace with provided value then.
7313 Replacement = AlternativeReplacement;
7314 }
7315 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7316}
7317
7318/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7319/// where the divisor and comparison target are constants,
7320/// return a DAG expression that will generate the same comparison result
7321/// using only multiplications, additions and shifts/rotations.
7322/// Ref: "Hacker's Delight" 10-17.
7323SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7324 SDValue CompTargetNode,
7326 DAGCombinerInfo &DCI,
7327 const SDLoc &DL) const {
7329 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7330 DCI, DL, Built)) {
7331 for (SDNode *N : Built)
7332 DCI.AddToWorklist(N);
7333 return Folded;
7334 }
7335
7336 return SDValue();
7337}
7338
7339SDValue
7340TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7341 SDValue CompTargetNode, ISD::CondCode Cond,
7342 DAGCombinerInfo &DCI, const SDLoc &DL,
7343 SmallVectorImpl<SDNode *> &Created) const {
7344 // fold (seteq/ne (urem N, D), C) ->
7345 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7346 // - D must be constant, with D = D0 * 2^K where D0 is odd
7347 // - P is the multiplicative inverse of D0 modulo 2^W
7348 // - Q = floor(((2^W) - 1) / D)
7349 // where W is the width of the common type of N and D.
7350 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7351 "Only applicable for (in)equality comparisons.");
7352
7353 SelectionDAG &DAG = DCI.DAG;
7354
7355 EVT VT = REMNode.getValueType();
7356 EVT SVT = VT.getScalarType();
7357 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7358 EVT ShSVT = ShVT.getScalarType();
7359
7360 // If MUL is unavailable, we cannot proceed in any case.
7361 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7362 return SDValue();
7363
7364 bool ComparingWithAllZeros = true;
7365 bool AllComparisonsWithNonZerosAreTautological = true;
7366 bool HadTautologicalLanes = false;
7367 bool AllLanesAreTautological = true;
7368 bool HadEvenDivisor = false;
7369 bool AllDivisorsArePowerOfTwo = true;
7370 bool HadTautologicalInvertedLanes = false;
7371 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7372
7373 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7374 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7375 if (CDiv->isZero())
7376 return false;
7377
7378 const APInt &D = CDiv->getAPIntValue();
7379 const APInt &Cmp = CCmp->getAPIntValue();
7380
7381 ComparingWithAllZeros &= Cmp.isZero();
7382
7383 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7384 // if C2 is not less than C1, the comparison is always false.
7385 // But we will only be able to produce the comparison that will give the
7386 // opposive tautological answer. So this lane would need to be fixed up.
7387 bool TautologicalInvertedLane = D.ule(Cmp);
7388 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7389
7390 // If all lanes are tautological (either all divisors are ones, or divisor
7391 // is not greater than the constant we are comparing with),
7392 // we will prefer to avoid the fold.
7393 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7394 HadTautologicalLanes |= TautologicalLane;
7395 AllLanesAreTautological &= TautologicalLane;
7396
7397 // If we are comparing with non-zero, we need'll need to subtract said
7398 // comparison value from the LHS. But there is no point in doing that if
7399 // every lane where we are comparing with non-zero is tautological..
7400 if (!Cmp.isZero())
7401 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7402
7403 // Decompose D into D0 * 2^K
7404 unsigned K = D.countr_zero();
7405 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7406 APInt D0 = D.lshr(K);
7407
7408 // D is even if it has trailing zeros.
7409 HadEvenDivisor |= (K != 0);
7410 // D is a power-of-two if D0 is one.
7411 // If all divisors are power-of-two, we will prefer to avoid the fold.
7412 AllDivisorsArePowerOfTwo &= D0.isOne();
7413
7414 // P = inv(D0, 2^W)
7415 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7416 unsigned W = D.getBitWidth();
7417 APInt P = D0.multiplicativeInverse();
7418 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7419
7420 // Q = floor((2^W - 1) u/ D)
7421 // R = ((2^W - 1) u% D)
7422 APInt Q, R;
7424
7425 // If we are comparing with zero, then that comparison constant is okay,
7426 // else it may need to be one less than that.
7427 if (Cmp.ugt(R))
7428 Q -= 1;
7429
7431 "We are expecting that K is always less than all-ones for ShSVT");
7432
7433 // If the lane is tautological the result can be constant-folded.
7434 if (TautologicalLane) {
7435 // Set P and K amount to a bogus values so we can try to splat them.
7436 P = 0;
7437 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7438 // And ensure that comparison constant is tautological,
7439 // it will always compare true/false.
7440 Q.setAllBits();
7441 } else {
7442 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7443 }
7444
7445 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7446 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7447 return true;
7448 };
7449
7450 SDValue N = REMNode.getOperand(0);
7451 SDValue D = REMNode.getOperand(1);
7452
7453 // Collect the values from each element.
7454 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7455 return SDValue();
7456
7457 // If all lanes are tautological, the result can be constant-folded.
7458 if (AllLanesAreTautological)
7459 return SDValue();
7460
7461 // If this is a urem by a powers-of-two, avoid the fold since it can be
7462 // best implemented as a bit test.
7463 if (AllDivisorsArePowerOfTwo)
7464 return SDValue();
7465
7466 SDValue PVal, KVal, QVal;
7467 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7468 if (HadTautologicalLanes) {
7469 // Try to turn PAmts into a splat, since we don't care about the values
7470 // that are currently '0'. If we can't, just keep '0'`s.
7472 // Try to turn KAmts into a splat, since we don't care about the values
7473 // that are currently '-1'. If we can't, change them to '0'`s.
7475 DAG.getConstant(0, DL, ShSVT));
7476 }
7477
7478 PVal = DAG.getBuildVector(VT, DL, PAmts);
7479 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7480 QVal = DAG.getBuildVector(VT, DL, QAmts);
7481 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7482 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7483 "Expected matchBinaryPredicate to return one element for "
7484 "SPLAT_VECTORs");
7485 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7486 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7487 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7488 } else {
7489 PVal = PAmts[0];
7490 KVal = KAmts[0];
7491 QVal = QAmts[0];
7492 }
7493
7494 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7495 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7496 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7497 assert(CompTargetNode.getValueType() == N.getValueType() &&
7498 "Expecting that the types on LHS and RHS of comparisons match.");
7499 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7500 }
7501
7502 // (mul N, P)
7503 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7504 Created.push_back(Op0.getNode());
7505
7506 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7507 // divisors as a performance improvement, since rotating by 0 is a no-op.
7508 if (HadEvenDivisor) {
7509 // We need ROTR to do this.
7510 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7511 return SDValue();
7512 // UREM: (rotr (mul N, P), K)
7513 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7514 Created.push_back(Op0.getNode());
7515 }
7516
7517 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7518 SDValue NewCC =
7519 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7521 if (!HadTautologicalInvertedLanes)
7522 return NewCC;
7523
7524 // If any lanes previously compared always-false, the NewCC will give
7525 // always-true result for them, so we need to fixup those lanes.
7526 // Or the other way around for inequality predicate.
7527 assert(VT.isVector() && "Can/should only get here for vectors.");
7528 Created.push_back(NewCC.getNode());
7529
7530 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7531 // if C2 is not less than C1, the comparison is always false.
7532 // But we have produced the comparison that will give the
7533 // opposive tautological answer. So these lanes would need to be fixed up.
7534 SDValue TautologicalInvertedChannels =
7535 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7536 Created.push_back(TautologicalInvertedChannels.getNode());
7537
7538 // NOTE: we avoid letting illegal types through even if we're before legalize
7539 // ops – legalization has a hard time producing good code for this.
7540 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7541 // If we have a vector select, let's replace the comparison results in the
7542 // affected lanes with the correct tautological result.
7543 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7544 DL, SETCCVT, SETCCVT);
7545 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7546 Replacement, NewCC);
7547 }
7548
7549 // Else, we can just invert the comparison result in the appropriate lanes.
7550 //
7551 // NOTE: see the note above VSELECT above.
7552 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7553 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7554 TautologicalInvertedChannels);
7555
7556 return SDValue(); // Don't know how to lower.
7557}
7558
7559/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7560/// where the divisor is constant and the comparison target is zero,
7561/// return a DAG expression that will generate the same comparison result
7562/// using only multiplications, additions and shifts/rotations.
7563/// Ref: "Hacker's Delight" 10-17.
7564SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7565 SDValue CompTargetNode,
7567 DAGCombinerInfo &DCI,
7568 const SDLoc &DL) const {
7570 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7571 DCI, DL, Built)) {
7572 assert(Built.size() <= 7 && "Max size prediction failed.");
7573 for (SDNode *N : Built)
7574 DCI.AddToWorklist(N);
7575 return Folded;
7576 }
7577
7578 return SDValue();
7579}
7580
7581SDValue
7582TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7583 SDValue CompTargetNode, ISD::CondCode Cond,
7584 DAGCombinerInfo &DCI, const SDLoc &DL,
7585 SmallVectorImpl<SDNode *> &Created) const {
7586 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7587 // Fold:
7588 // (seteq/ne (srem N, D), 0)
7589 // To:
7590 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7591 //
7592 // - D must be constant, with D = D0 * 2^K where D0 is odd
7593 // - P is the multiplicative inverse of D0 modulo 2^W
7594 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7595 // - Q = floor((2 * A) / (2^K))
7596 // where W is the width of the common type of N and D.
7597 //
7598 // When D is a power of two (and thus D0 is 1), the normal
7599 // formula for A and Q don't apply, because the derivation
7600 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7601 // does not apply. This specifically fails when N = INT_MIN.
7602 //
7603 // Instead, for power-of-two D, we use:
7604 // - A = 0
7605 // | -> No offset needed. We're effectively treating it the same as urem.
7606 // - Q = 2^(W-K) - 1
7607 // |-> Test that the top K bits are zero after rotation
7608 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7609 "Only applicable for (in)equality comparisons.");
7610
7611 SelectionDAG &DAG = DCI.DAG;
7612
7613 EVT VT = REMNode.getValueType();
7614 EVT SVT = VT.getScalarType();
7615 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7616 EVT ShSVT = ShVT.getScalarType();
7617
7618 // If we are after ops legalization, and MUL is unavailable, we can not
7619 // proceed.
7620 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7621 return SDValue();
7622
7623 // TODO: Could support comparing with non-zero too.
7624 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7625 if (!CompTarget || !CompTarget->isZero())
7626 return SDValue();
7627
7628 bool HadOneDivisor = false;
7629 bool AllDivisorsAreOnes = true;
7630 bool HadEvenDivisor = false;
7631 bool AllDivisorsArePowerOfTwo = true;
7632 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7633
7634 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7635 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7636 if (C->isZero())
7637 return false;
7638
7639 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7640
7641 // WARNING: this fold is only valid for positive divisors!
7642 // `rem %X, -C` is equivalent to `rem %X, C`
7643 APInt D = C->getAPIntValue().abs();
7644
7645 // If all divisors are ones, we will prefer to avoid the fold.
7646 HadOneDivisor |= D.isOne();
7647 AllDivisorsAreOnes &= D.isOne();
7648
7649 // Decompose D into D0 * 2^K
7650 unsigned K = D.countr_zero();
7651 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7652 APInt D0 = D.lshr(K);
7653
7654 // D is even if it has trailing zeros.
7655 HadEvenDivisor |= (K != 0);
7656
7657 // D is a power-of-two if D0 is one. This includes INT_MIN.
7658 // If all divisors are power-of-two, we will prefer to avoid the fold.
7659 AllDivisorsArePowerOfTwo &= D0.isOne();
7660
7661 // P = inv(D0, 2^W)
7662 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7663 unsigned W = D.getBitWidth();
7664 APInt P = D0.multiplicativeInverse();
7665 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7666
7667 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7668 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7669 A.clearLowBits(K);
7670
7671 // Q = floor((2 * A) / (2^K))
7672 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7673
7675 "We are expecting that A is always less than all-ones for SVT");
7677 "We are expecting that K is always less than all-ones for ShSVT");
7678
7679 // If D was a power of two, apply the alternate constant derivation.
7680 if (D0.isOne()) {
7681 // A = 0
7682 A = APInt(W, 0);
7683 // - Q = 2^(W-K) - 1
7684 Q = APInt::getLowBitsSet(W, W - K);
7685 }
7686
7687 // If the divisor is 1 the result can be constant-folded.
7688 if (D.isOne()) {
7689 // Set P, A and K to a bogus values so we can try to splat them.
7690 P = 0;
7691 A.setAllBits();
7692 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7693
7694 // x ?% 1 == 0 <--> true <--> x u<= -1
7695 Q.setAllBits();
7696 } else {
7697 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7698 }
7699
7700 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7701 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7702 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7703 return true;
7704 };
7705
7706 SDValue N = REMNode.getOperand(0);
7707 SDValue D = REMNode.getOperand(1);
7708
7709 // Collect the values from each element.
7710 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7711 return SDValue();
7712
7713 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7714 if (AllDivisorsAreOnes)
7715 return SDValue();
7716
7717 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7718 // since it can be best implemented as a bit test.
7719 if (AllDivisorsArePowerOfTwo)
7720 return SDValue();
7721
7722 SDValue PVal, AVal, KVal, QVal;
7723 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7724 if (HadOneDivisor) {
7725 // Try to turn PAmts into a splat, since we don't care about the values
7726 // that are currently '0'. If we can't, just keep '0'`s.
7728 // Try to turn AAmts into a splat, since we don't care about the
7729 // values that are currently '-1'. If we can't, change them to '0'`s.
7731 DAG.getConstant(0, DL, SVT));
7732 // Try to turn KAmts into a splat, since we don't care about the values
7733 // that are currently '-1'. If we can't, change them to '0'`s.
7735 DAG.getConstant(0, DL, ShSVT));
7736 }
7737
7738 PVal = DAG.getBuildVector(VT, DL, PAmts);
7739 AVal = DAG.getBuildVector(VT, DL, AAmts);
7740 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7741 QVal = DAG.getBuildVector(VT, DL, QAmts);
7742 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7743 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7744 QAmts.size() == 1 &&
7745 "Expected matchUnaryPredicate to return one element for scalable "
7746 "vectors");
7747 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7748 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7749 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7750 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7751 } else {
7752 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7753 PVal = PAmts[0];
7754 AVal = AAmts[0];
7755 KVal = KAmts[0];
7756 QVal = QAmts[0];
7757 }
7758
7759 // (mul N, P)
7760 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7761 Created.push_back(Op0.getNode());
7762
7763 // We need ADD to do this.
7764 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
7765 return SDValue();
7766
7767 // (add (mul N, P), A)
7768 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
7769 Created.push_back(Op0.getNode());
7770
7771 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7772 // divisors as a performance improvement, since rotating by 0 is a no-op.
7773 if (HadEvenDivisor) {
7774 // We need ROTR to do this.
7775 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7776 return SDValue();
7777 // SREM: (rotr (add (mul N, P), A), K)
7778 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7779 Created.push_back(Op0.getNode());
7780 }
7781
7782 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
7783 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7785}
7786
7788 const DenormalMode &Mode,
7789 SDNodeFlags Flags) const {
7790 SDLoc DL(Op);
7791 EVT VT = Op.getValueType();
7792 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7793 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7794
7795 // This is specifically a check for the handling of denormal inputs, not the
7796 // result.
7797 if (Mode.Input == DenormalMode::PreserveSign ||
7798 Mode.Input == DenormalMode::PositiveZero) {
7799 // Test = X == 0.0
7800 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
7801 /*Signaling=*/false, Flags);
7802 }
7803
7804 // Testing it with denormal inputs to avoid wrong estimate.
7805 //
7806 // Test = fabs(X) < SmallestNormal
7807 const fltSemantics &FltSem = VT.getFltSemantics();
7808 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
7809 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
7810 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
7811 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
7812 /*Signaling=*/false, Flags);
7813}
7814
7816 bool LegalOps, bool OptForSize,
7818 unsigned Depth) const {
7819 // fneg is removable even if it has multiple uses.
7820 if (Op.getOpcode() == ISD::FNEG) {
7822 return Op.getOperand(0);
7823 }
7824
7825 // Don't recurse exponentially.
7827 return SDValue();
7828
7829 // Pre-increment recursion depth for use in recursive calls.
7830 ++Depth;
7831 const SDNodeFlags Flags = Op->getFlags();
7832 EVT VT = Op.getValueType();
7833 unsigned Opcode = Op.getOpcode();
7834
7835 // Don't allow anything with multiple uses unless we know it is free.
7836 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
7837 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
7838 isFPExtFree(VT, Op.getOperand(0).getValueType());
7839 if (!IsFreeExtend)
7840 return SDValue();
7841 }
7842
7843 auto RemoveDeadNode = [&](SDValue N) {
7844 if (N && N.getNode()->use_empty())
7845 DAG.RemoveDeadNode(N.getNode());
7846 };
7847
7848 SDLoc DL(Op);
7849
7850 // Because getNegatedExpression can delete nodes we need a handle to keep
7851 // temporary nodes alive in case the recursion manages to create an identical
7852 // node.
7853 std::list<HandleSDNode> Handles;
7854
7855 switch (Opcode) {
7856 case ISD::ConstantFP: {
7857 // Don't invert constant FP values after legalization unless the target says
7858 // the negated constant is legal.
7859 bool IsOpLegal =
7861 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
7862 OptForSize);
7863
7864 if (LegalOps && !IsOpLegal)
7865 break;
7866
7867 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
7868 V.changeSign();
7869 SDValue CFP = DAG.getConstantFP(V, DL, VT);
7870
7871 // If we already have the use of the negated floating constant, it is free
7872 // to negate it even it has multiple uses.
7873 if (!Op.hasOneUse() && CFP.use_empty())
7874 break;
7876 return CFP;
7877 }
7878 case ISD::SPLAT_VECTOR: {
7879 // fold splat_vector(fneg(X)) -> splat_vector(-X)
7880 SDValue X = Op.getOperand(0);
7882 break;
7883
7884 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
7885 if (!NegX)
7886 break;
7888 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
7889 }
7890 case ISD::BUILD_VECTOR: {
7891 // Only permit BUILD_VECTOR of constants.
7892 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
7893 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
7894 }))
7895 break;
7896
7897 bool IsOpLegal =
7900 llvm::all_of(Op->op_values(), [&](SDValue N) {
7901 return N.isUndef() ||
7902 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
7903 OptForSize);
7904 });
7905
7906 if (LegalOps && !IsOpLegal)
7907 break;
7908
7910 for (SDValue C : Op->op_values()) {
7911 if (C.isUndef()) {
7912 Ops.push_back(C);
7913 continue;
7914 }
7915 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
7916 V.changeSign();
7917 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
7918 }
7920 return DAG.getBuildVector(VT, DL, Ops);
7921 }
7922 case ISD::FADD: {
7923 if (!Flags.hasNoSignedZeros())
7924 break;
7925
7926 // After operation legalization, it might not be legal to create new FSUBs.
7927 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
7928 break;
7929 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7930
7931 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
7933 SDValue NegX =
7934 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7935 // Prevent this node from being deleted by the next call.
7936 if (NegX)
7937 Handles.emplace_back(NegX);
7938
7939 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
7941 SDValue NegY =
7942 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7943
7944 // We're done with the handles.
7945 Handles.clear();
7946
7947 // Negate the X if its cost is less or equal than Y.
7948 if (NegX && (CostX <= CostY)) {
7949 Cost = CostX;
7950 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
7951 if (NegY != N)
7952 RemoveDeadNode(NegY);
7953 return N;
7954 }
7955
7956 // Negate the Y if it is not expensive.
7957 if (NegY) {
7958 Cost = CostY;
7959 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
7960 if (NegX != N)
7961 RemoveDeadNode(NegX);
7962 return N;
7963 }
7964 break;
7965 }
7966 case ISD::FSUB: {
7967 // We can't turn -(A-B) into B-A when we honor signed zeros.
7968 if (!Flags.hasNoSignedZeros())
7969 break;
7970
7971 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7972 // fold (fneg (fsub 0, Y)) -> Y
7973 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
7974 if (C->isZero()) {
7976 return Y;
7977 }
7978
7979 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
7981 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
7982 }
7983 case ISD::FMUL:
7984 case ISD::FDIV: {
7985 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7986
7987 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
7989 SDValue NegX =
7990 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7991 // Prevent this node from being deleted by the next call.
7992 if (NegX)
7993 Handles.emplace_back(NegX);
7994
7995 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
7997 SDValue NegY =
7998 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7999
8000 // We're done with the handles.
8001 Handles.clear();
8002
8003 // Negate the X if its cost is less or equal than Y.
8004 if (NegX && (CostX <= CostY)) {
8005 Cost = CostX;
8006 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
8007 if (NegY != N)
8008 RemoveDeadNode(NegY);
8009 return N;
8010 }
8011
8012 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
8013 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
8014 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
8015 break;
8016
8017 // Negate the Y if it is not expensive.
8018 if (NegY) {
8019 Cost = CostY;
8020 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
8021 if (NegX != N)
8022 RemoveDeadNode(NegX);
8023 return N;
8024 }
8025 break;
8026 }
8027 case ISD::FMA:
8028 case ISD::FMULADD:
8029 case ISD::FMAD: {
8030 if (!Flags.hasNoSignedZeros())
8031 break;
8032
8033 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
8035 SDValue NegZ =
8036 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
8037 // Give up if fail to negate the Z.
8038 if (!NegZ)
8039 break;
8040
8041 // Prevent this node from being deleted by the next two calls.
8042 Handles.emplace_back(NegZ);
8043
8044 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
8046 SDValue NegX =
8047 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8048 // Prevent this node from being deleted by the next call.
8049 if (NegX)
8050 Handles.emplace_back(NegX);
8051
8052 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
8054 SDValue NegY =
8055 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8056
8057 // We're done with the handles.
8058 Handles.clear();
8059
8060 // Negate the X if its cost is less or equal than Y.
8061 if (NegX && (CostX <= CostY)) {
8062 Cost = std::min(CostX, CostZ);
8063 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
8064 if (NegY != N)
8065 RemoveDeadNode(NegY);
8066 return N;
8067 }
8068
8069 // Negate the Y if it is not expensive.
8070 if (NegY) {
8071 Cost = std::min(CostY, CostZ);
8072 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
8073 if (NegX != N)
8074 RemoveDeadNode(NegX);
8075 return N;
8076 }
8077 break;
8078 }
8079
8080 case ISD::FP_EXTEND:
8081 case ISD::FSIN:
8082 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8083 OptForSize, Cost, Depth))
8084 return DAG.getNode(Opcode, DL, VT, NegV);
8085 break;
8086 case ISD::FP_ROUND:
8087 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8088 OptForSize, Cost, Depth))
8089 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
8090 break;
8091 case ISD::SELECT:
8092 case ISD::VSELECT: {
8093 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
8094 // iff at least one cost is cheaper and the other is neutral/cheaper
8095 SDValue LHS = Op.getOperand(1);
8097 SDValue NegLHS =
8098 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
8099 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
8100 RemoveDeadNode(NegLHS);
8101 break;
8102 }
8103
8104 // Prevent this node from being deleted by the next call.
8105 Handles.emplace_back(NegLHS);
8106
8107 SDValue RHS = Op.getOperand(2);
8109 SDValue NegRHS =
8110 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
8111
8112 // We're done with the handles.
8113 Handles.clear();
8114
8115 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
8116 (CostLHS != NegatibleCost::Cheaper &&
8117 CostRHS != NegatibleCost::Cheaper)) {
8118 RemoveDeadNode(NegLHS);
8119 RemoveDeadNode(NegRHS);
8120 break;
8121 }
8122
8123 Cost = std::min(CostLHS, CostRHS);
8124 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
8125 }
8126 }
8127
8128 return SDValue();
8129}
8130
8131//===----------------------------------------------------------------------===//
8132// Legalization Utilities
8133//===----------------------------------------------------------------------===//
8134
8135bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
8136 SDValue LHS, SDValue RHS,
8138 EVT HiLoVT, SelectionDAG &DAG,
8139 MulExpansionKind Kind, SDValue LL,
8140 SDValue LH, SDValue RL, SDValue RH) const {
8141 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
8142 Opcode == ISD::SMUL_LOHI);
8143
8144 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
8146 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8148 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8150 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8152
8153 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8154 return false;
8155
8156 unsigned OuterBitSize = VT.getScalarSizeInBits();
8157 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8158
8159 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8160 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8161 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8162
8163 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8164 bool Signed) -> bool {
8165 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8166 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8167 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8168 Hi = Lo.getValue(1);
8169 return true;
8170 }
8171 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8172 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8173 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8174 return true;
8175 }
8176 return false;
8177 };
8178
8179 SDValue Lo, Hi;
8180
8181 if (!LL.getNode() && !RL.getNode() &&
8183 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8184 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8185 }
8186
8187 if (!LL.getNode())
8188 return false;
8189
8190 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8191 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8192 DAG.MaskedValueIsZero(RHS, HighMask)) {
8193 // The inputs are both zero-extended.
8194 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8195 Result.push_back(Lo);
8196 Result.push_back(Hi);
8197 if (Opcode != ISD::MUL) {
8198 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8199 Result.push_back(Zero);
8200 Result.push_back(Zero);
8201 }
8202 return true;
8203 }
8204 }
8205
8206 if (!VT.isVector() && Opcode == ISD::MUL &&
8207 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8208 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8209 // The input values are both sign-extended.
8210 // TODO non-MUL case?
8211 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8212 Result.push_back(Lo);
8213 Result.push_back(Hi);
8214 return true;
8215 }
8216 }
8217
8218 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8219 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8220
8221 if (!LH.getNode() && !RH.getNode() &&
8224 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8225 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8226 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8227 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8228 }
8229
8230 if (!LH.getNode())
8231 return false;
8232
8233 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8234 return false;
8235
8236 Result.push_back(Lo);
8237
8238 if (Opcode == ISD::MUL) {
8239 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8240 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8241 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8242 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8243 Result.push_back(Hi);
8244 return true;
8245 }
8246
8247 // Compute the full width result.
8248 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8249 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8250 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8251 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8252 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8253 };
8254
8255 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8256 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8257 return false;
8258
8259 // This is effectively the add part of a multiply-add of half-sized operands,
8260 // so it cannot overflow.
8261 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8262
8263 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8264 return false;
8265
8266 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8267 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8268
8269 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8271 if (UseGlue)
8272 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8273 Merge(Lo, Hi));
8274 else
8275 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8276 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8277
8278 SDValue Carry = Next.getValue(1);
8279 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8280 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8281
8282 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8283 return false;
8284
8285 if (UseGlue)
8286 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8287 Carry);
8288 else
8289 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8290 Zero, Carry);
8291
8292 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8293
8294 if (Opcode == ISD::SMUL_LOHI) {
8295 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8296 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8297 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8298
8299 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8300 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8301 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8302 }
8303
8304 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8305 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8306 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8307 return true;
8308}
8309
8311 SelectionDAG &DAG, MulExpansionKind Kind,
8312 SDValue LL, SDValue LH, SDValue RL,
8313 SDValue RH) const {
8315 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8316 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8317 DAG, Kind, LL, LH, RL, RH);
8318 if (Ok) {
8319 assert(Result.size() == 2);
8320 Lo = Result[0];
8321 Hi = Result[1];
8322 }
8323 return Ok;
8324}
8325
8326// Optimize unsigned division or remainder by constants for types twice as large
8327// as a legal VT.
8328//
8329// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8330// can be computed
8331// as:
8332// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8333// Remainder = Sum % Constant;
8334//
8335// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8336// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8337// High:Low into 3 chunks of W bits and compute remainder as
8338// Sum = Chunk0 + Chunk1 + Chunk2;
8339// Remainder = Sum % Constant;
8340//
8341// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8342//
8343// For division, we can compute the remainder using the algorithm described
8344// above, subtract it from the dividend to get an exact multiple of Constant.
8345// Then multiply that exact multiply by the multiplicative inverse modulo
8346// (1 << (BitWidth / 2)) to get the quotient.
8347
8348// If Constant is even, we can shift right the dividend and the divisor by the
8349// number of trailing zeros in Constant before applying the remainder algorithm.
8350// If we're after the quotient, we can subtract this value from the shifted
8351// dividend and multiply by the multiplicative inverse of the shifted divisor.
8352// If we want the remainder, we shift the value left by the number of trailing
8353// zeros and add the bits that were shifted out of the dividend.
8354bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8355 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8356 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8357 unsigned Opcode = N->getOpcode();
8358 EVT VT = N->getValueType(0);
8359
8360 unsigned BitWidth = Divisor.getBitWidth();
8361 unsigned HBitWidth = BitWidth / 2;
8363 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8364
8365 // If the divisor is even, shift it until it becomes odd.
8366 unsigned TrailingZeros = 0;
8367 if (!Divisor[0]) {
8368 TrailingZeros = Divisor.countr_zero();
8369 Divisor.lshrInPlace(TrailingZeros);
8370 }
8371
8372 // After removing trailing zeros, the divisor needs to be less than
8373 // (1 << HBitWidth).
8374 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8375 if (Divisor.uge(HalfMaxPlus1))
8376 return false;
8377
8378 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8379 // (1 << W) % Divisor == -1.
8380 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8381 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8382 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8383 if (I == HBitWidth - 1)
8384 continue;
8385
8386 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8387
8388 if (Mod.isOne()) {
8389 BestChunkWidth = I;
8390 break;
8391 }
8392
8393 // We have an alternate strategy for Remainder == Divisor - 1.
8394 // FIXME: Support HBitWidth.
8395 if (I != HBitWidth && Mod == Divisor - 1)
8396 AltChunkWidth = I;
8397 }
8398
8399 bool Alternate = false;
8400 if (!BestChunkWidth) {
8401 if (!AltChunkWidth)
8402 return false;
8403 Alternate = true;
8404 BestChunkWidth = AltChunkWidth;
8405 }
8406
8407 SDLoc dl(N);
8408
8409 assert(!LL == !LH && "Expected both input halves or no input halves!");
8410 if (!LL)
8411 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8412
8413 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8414
8415 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8416 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8417 if (HasFSHR)
8418 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8419 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8420 return DAG.getNode(
8421 ISD::OR, dl, HiLoVT,
8422 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8423 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8424 DAG.getNode(
8425 ISD::SHL, dl, HiLoVT, Hi,
8426 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8427 };
8428
8429 // Helper to perform a right shift on a 128-bit value split into two halves.
8430 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8431 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8432 if (ShiftAmt == 0)
8433 return;
8434 if (ShiftAmt < HBitWidth) {
8435 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8436 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8437 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8438 } else if (ShiftAmt == HBitWidth) {
8439 Lo = Hi;
8440 Hi = DAG.getConstant(0, dl, HiLoVT);
8441 } else {
8442 Lo = DAG.getNode(
8443 ISD::SRL, dl, HiLoVT, Hi,
8444 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8445 Hi = DAG.getConstant(0, dl, HiLoVT);
8446 }
8447 };
8448
8449 // Shift the input by the number of TrailingZeros in the divisor. The
8450 // shifted out bits will be added to the remainder later.
8451 SDValue PartialRemL, PartialRemH;
8452 if (TrailingZeros && Opcode != ISD::UDIV) {
8453 // Save the shifted off bits if we need the remainder.
8454 if (TrailingZeros < HBitWidth) {
8455 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8456 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8457 DAG.getConstant(Mask, dl, HiLoVT));
8458 } else if (TrailingZeros == HBitWidth) {
8459 // All of LL is part of the remainder.
8460 PartialRemL = LL;
8461 } else {
8462 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8463 PartialRemL = LL;
8464 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8465 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8466 DAG.getConstant(Mask, dl, HiLoVT));
8467 }
8468 }
8469
8470 SDValue Sum;
8471 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8472 // out, add that to the final sum.
8473 if (BestChunkWidth == HBitWidth) {
8474 assert(!Alternate);
8475 // Shift LH:LL right if there were trailing zeros in the divisor.
8476 ShiftRight(LL, LH, TrailingZeros);
8477
8478 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8479 EVT SetCCType =
8480 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8482 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8483 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8484 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8485 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8486 } else {
8487 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8488 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8489 // If the boolean for the target is 0 or 1, we can add the setcc result
8490 // directly.
8491 if (getBooleanContents(HiLoVT) ==
8493 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8494 else
8495 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8496 DAG.getConstant(0, dl, HiLoVT));
8497 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8498 }
8499 } else {
8500 // Otherwise split into multple chunks and add them together. We chose
8501 // BestChunkWidth so that the sum will not overflow.
8502 SDValue Mask = DAG.getConstant(
8503 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8504
8505 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8506 // If there were trailing zeros in the divisor, increase the shift amount.
8507 unsigned Shift = I + TrailingZeros;
8508 SDValue Chunk;
8509 if (Shift == 0)
8510 Chunk = LL;
8511 else if (Shift >= HBitWidth)
8512 Chunk = DAG.getNode(
8513 ISD::SRL, dl, HiLoVT, LH,
8514 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8515 else
8516 Chunk = GetFSHR(LL, LH, Shift);
8517 // If we're on the last chunk, we don't need an AND.
8518 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8519 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8520 if (!Sum) {
8521 Sum = Chunk;
8522 } else {
8523 // For Alternate, we need to subtract odd chunks.
8524 unsigned ChunkNum = I / BestChunkWidth;
8525 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8526 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8527 }
8528 }
8529
8530 // For Alternate, the sum may be negative, but we need a positive sum. We
8531 // can increase it by a multiple of the divisor to make it positive. For 3
8532 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8533 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8534 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8535 // positive.
8536 if (Alternate) {
8537 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8538 assert(NumChunks <= 4);
8539
8540 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8541 Adjust.setBit(0);
8542 // If there are 4 chunks, we need to adjust twice.
8543 if (NumChunks == 4)
8544 Adjust <<= 1;
8545 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8546 DAG.getConstant(Adjust, dl, HiLoVT));
8547 }
8548 }
8549
8550 // Perform a HiLoVT urem on the Sum using truncated divisor.
8551 SDValue RemL =
8552 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8553 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8554 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8555
8556 if (Opcode != ISD::UREM) {
8557 // If we didn't shift LH/LR earlier, do it now.
8558 if (BestChunkWidth != HBitWidth)
8559 ShiftRight(LL, LH, TrailingZeros);
8560
8561 // Subtract the remainder from the shifted dividend.
8562 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8563 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8564
8565 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8566
8567 // Multiply by the multiplicative inverse of the divisor modulo
8568 // (1 << BitWidth).
8569 APInt MulFactor = Divisor.multiplicativeInverse();
8570
8571 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8572 DAG.getConstant(MulFactor, dl, VT));
8573
8574 // Split the quotient into low and high parts.
8575 SDValue QuotL, QuotH;
8576 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8577 Result.push_back(QuotL);
8578 Result.push_back(QuotH);
8579 }
8580
8581 if (Opcode != ISD::UDIV) {
8582 // If we shifted the input, shift the remainder left and add the bits we
8583 // shifted off the input.
8584 if (TrailingZeros) {
8585 if (TrailingZeros < HBitWidth) {
8586 // Shift RemH:RemL left by TrailingZeros.
8587 // RemH gets the high bits shifted out of RemL.
8588 RemH = DAG.getNode(
8589 ISD::SRL, dl, HiLoVT, RemL,
8590 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8591 RemL =
8592 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8593 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8594 // OR in the partial remainder.
8595 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8597 } else if (TrailingZeros == HBitWidth) {
8598 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8599 // PartialRemL.
8600 RemH = RemL;
8601 RemL = PartialRemL;
8602 } else {
8603 // Shift left by more than HBitWidth.
8604 RemH = DAG.getNode(
8605 ISD::SHL, dl, HiLoVT, RemL,
8606 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8607 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8609 RemL = PartialRemL;
8610 }
8611 }
8612 Result.push_back(RemL);
8613 Result.push_back(RemH);
8614 }
8615
8616 return true;
8617}
8618
8619bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8620 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8621 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8622
8623 SDValue N0 = N->getOperand(0);
8624 EVT VT = N0->getValueType(0);
8625 SDLoc DL{N};
8626
8627 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8628
8629 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8630 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8631 const APInt &Const,
8632 SmallVectorImpl<SDValue> &Result) {
8633 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8634 SDValue RHS = DAG.getConstant(Const, DL, VT);
8635 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8636 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8638 LL, LH, RL, RH);
8639 };
8640
8641 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8642 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8643 SDValue RH) {
8644 SDValue AddSubNode =
8646 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8647 SDValue OutL = AddSubNode.getValue(0);
8648 SDValue Overflow = AddSubNode.getValue(1);
8649 SDValue AddSubWithOverflow =
8651 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8652 SDValue OutH = AddSubWithOverflow.getValue(0);
8653 return std::make_pair(OutL, OutH);
8654 };
8655
8656 // This helper creates a SRL of the pair (LL, LH) by Shift.
8657 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8658 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8659 if (Shift < HBitWidth) {
8660 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8661 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8662 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8663 return std::make_pair(ResL, ResH);
8664 }
8665 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8666 if (Shift == HBitWidth)
8667 return std::make_pair(LH, Zero);
8668 assert(Shift - HBitWidth < HBitWidth &&
8669 "We shouldn't generate an undefined shift");
8670 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8671 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8672 };
8673
8674 // Knowledge of leading zeros may help to reduce the multiplier.
8675 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8676
8677 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8678 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8679
8680 assert(!LL == !LH && "Expected both input halves or no input halves!");
8681 if (!LL)
8682 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8683 SDValue QL = LL;
8684 SDValue QH = LH;
8685 if (Magics.PreShift != 0)
8686 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8687
8688 SmallVector<SDValue, 4> UMulResult;
8689 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8690 return false;
8691
8692 QL = UMulResult[2];
8693 QH = UMulResult[3];
8694
8695 if (Magics.IsAdd) {
8696 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8697 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8698 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8699 }
8700
8701 if (Magics.PostShift != 0)
8702 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8703
8704 unsigned Opcode = N->getOpcode();
8705 if (Opcode != ISD::UREM) {
8706 Result.push_back(QL);
8707 Result.push_back(QH);
8708 }
8709
8710 if (Opcode != ISD::UDIV) {
8711 SmallVector<SDValue, 2> MulResult;
8712 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8713 return false;
8714
8715 assert(MulResult.size() == 2);
8716
8717 auto [RemL, RemH] =
8718 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8719
8720 Result.push_back(RemL);
8721 Result.push_back(RemH);
8722 }
8723
8724 return true;
8725}
8726
8729 EVT HiLoVT, SelectionDAG &DAG,
8730 SDValue LL, SDValue LH) const {
8731 unsigned Opcode = N->getOpcode();
8732
8733 // TODO: Support signed division/remainder.
8734 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8735 return false;
8736 assert(
8737 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8738 "Unexpected opcode");
8739
8740 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8741 if (!CN)
8742 return false;
8743
8744 APInt Divisor = CN->getAPIntValue();
8745
8746 // The generated half-width UREM is normally optimized using high multiply.
8747 // If the wide UREM libcall is unavailable, a legal or custom half-width
8748 // UDIVREM can lower it instead.
8749 bool CanDecomposeUREMWithoutMulHi =
8750 Opcode == ISD::UREM &&
8751 getLibcallImpl(RTLIB::getUREM(N->getValueType(0))) ==
8752 RTLIB::Unsupported &&
8754 if (!CanDecomposeUREMWithoutMulHi &&
8757 return false;
8758
8759 // Prefer the smaller libcall when one is available.
8760 if (DAG.shouldOptForSize() && !CanDecomposeUREMWithoutMulHi)
8761 return false;
8762
8763 // Early out for 0 or 1 divisors.
8764 if (Divisor.ule(1))
8765 return false;
8766
8767 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
8768 DAG, LL, LH))
8769 return true;
8770
8771 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
8772 LH))
8773 return true;
8774
8775 return false;
8776}
8777
8778// Check that (every element of) Z is undef or not an exact multiple of BW.
8779static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
8781 Z,
8782 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
8783 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
8784}
8785
8787 SelectionDAG &DAG) const {
8788 EVT VT = Node->getValueType(0);
8789
8790 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
8794 return SDValue();
8795
8796 SDValue X = Node->getOperand(0);
8797 SDValue Y = Node->getOperand(1);
8798 SDValue Z = Node->getOperand(2);
8799
8800 unsigned BW = VT.getScalarSizeInBits();
8801 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
8802 SDLoc DL(SDValue(Node, 0));
8803
8804 EVT ShVT = Z.getValueType();
8805
8806 // If a funnel shift in the other direction is more supported, use it.
8807 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
8808 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8809 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
8810 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8811 // fshl X, Y, Z -> fshr X, Y, -Z
8812 // fshr X, Y, Z -> fshl X, Y, -Z
8813 Z = DAG.getNegative(Z, DL, ShVT);
8814 } else {
8815 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
8816 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
8817 SDValue One = DAG.getConstant(1, DL, ShVT);
8818 if (IsFSHL) {
8819 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8820 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
8821 } else {
8822 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8823 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
8824 }
8825 Z = DAG.getNOT(DL, Z, ShVT);
8826 }
8827 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
8828 }
8829
8830 SDValue ShX, ShY;
8831 SDValue ShAmt, InvShAmt;
8832 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8833 // fshl: X << C | Y >> (BW - C)
8834 // fshr: X << (BW - C) | Y >> C
8835 // where C = Z % BW is not zero
8836 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8837 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8838 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
8839 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
8840 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
8841 } else {
8842 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
8843 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
8844 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
8845 if (isPowerOf2_32(BW)) {
8846 // Z % BW -> Z & (BW - 1)
8847 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
8848 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
8849 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
8850 } else {
8851 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8852 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8853 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
8854 }
8855
8856 SDValue One = DAG.getConstant(1, DL, ShVT);
8857 if (IsFSHL) {
8858 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
8859 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
8860 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
8861 } else {
8862 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
8863 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
8864 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
8865 }
8866 }
8867 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
8868}
8869
8870// TODO: Merge with expandFunnelShift.
8872 SelectionDAG &DAG) const {
8873 EVT VT = Node->getValueType(0);
8874 unsigned EltSizeInBits = VT.getScalarSizeInBits();
8875 bool IsLeft = Node->getOpcode() == ISD::ROTL;
8876 SDValue Op0 = Node->getOperand(0);
8877 SDValue Op1 = Node->getOperand(1);
8878 SDLoc DL(SDValue(Node, 0));
8879
8880 EVT ShVT = Op1.getValueType();
8881 SDValue Zero = DAG.getConstant(0, DL, ShVT);
8882
8883 // If a rotate in the other direction is more supported, use it.
8884 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
8885 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8886 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
8887 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8888 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
8889 }
8890
8891 if (!AllowVectorOps && VT.isVector() &&
8897 return SDValue();
8898
8899 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
8900 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
8901 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
8902 SDValue ShVal;
8903 SDValue HsVal;
8904 if (isPowerOf2_32(EltSizeInBits)) {
8905 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
8906 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
8907 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8908 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
8909 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8910 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
8911 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
8912 } else {
8913 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
8914 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
8915 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
8916 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
8917 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8918 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
8919 SDValue One = DAG.getConstant(1, DL, ShVT);
8920 HsVal =
8921 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
8922 }
8923 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
8924}
8925
8926/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
8927/// a chain of halving decompositions (halving element width) and/or vector
8928/// widening (doubling element count). This guides expansion strategy selection:
8929/// if true, the halving/widening path produces better code than bit-by-bit.
8930///
8931/// HalveDepth tracks halving steps only (each creates ~4x more operations).
8932/// Widening steps are cheap (O(1) pad/extract) and don't count.
8933/// Limiting halvings to 2 prevents exponential blowup:
8934/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
8935/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
8936/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
8938 EVT VT, unsigned HalveDepth = 0,
8939 unsigned TotalDepth = 0) {
8940 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
8941 return false;
8943 return true;
8944 if (!TLI.isTypeLegal(VT))
8945 return false;
8946
8947 unsigned BW = VT.getScalarSizeInBits();
8948
8949 // Halve: halve element width, same element count.
8950 // This is the expensive step -- each halving creates ~4x more operations.
8951 if (BW % 2 == 0) {
8952 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
8953 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
8954 if (TLI.isTypeLegal(HalfVT) &&
8955 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
8956 return true;
8957 }
8958
8959 // Widen: double element count (fixed-width vectors only).
8960 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
8961 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
8962 if (TLI.isTypeLegal(WideVT) &&
8963 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
8964 return true;
8965
8966 return false;
8967}
8968
8970 SDLoc DL(Node);
8971 EVT VT = Node->getValueType(0);
8972 SDValue X = Node->getOperand(0);
8973 SDValue Y = Node->getOperand(1);
8974 unsigned BW = VT.getScalarSizeInBits();
8975 unsigned Opcode = Node->getOpcode();
8976 LLVMContext &Ctx = *DAG.getContext();
8977
8978 switch (Opcode) {
8979 case ISD::CLMUL: {
8980 // For vector types, try decomposition strategies that leverage legal
8981 // CLMUL on narrower or wider element types, avoiding the expensive
8982 // bit-by-bit expansion.
8983 if (VT.isVector()) {
8984 // Strategy 1: Halving decomposition to half-element-width CLMUL.
8985 // Applies ExpandIntRes_CLMUL's identity element-wise:
8986 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
8987 // where:
8988 // Lo = CLMUL(XLo, YLo)
8989 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
8990 unsigned HalfBW = BW / 2;
8991 if (BW % 2 == 0) {
8992 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
8993 EVT HalfVT =
8994 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
8995 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
8996 /*HalveDepth=*/1)) {
8997 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
8998
8999 // Extract low and high halves of each element.
9000 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
9001 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9002 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
9003 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
9004 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9005 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
9006
9007 // Lo = CLMUL(XLo, YLo)
9008 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
9009
9010 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9011 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
9012 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
9013 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
9014 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
9015 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
9016
9017 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
9018 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
9019 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
9020 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
9021 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
9022 }
9023 }
9024
9025 // Strategy 2: Promote to double-element-width CLMUL.
9026 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
9027 {
9028 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9029 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
9030 // If CLMUL on ExtVT is Custom (not Legal), the target may
9031 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
9032 // fallback costs O(BW) vectorized iterations. Only widen when
9033 // element count is small enough that scalarization is cheaper.
9034 unsigned NumElts = VT.getVectorMinNumElements();
9035 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
9036 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
9037 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
9038 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9039 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
9040 }
9041 }
9042 }
9043
9044 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
9045 // vector, extract lower result). CLMUL is element-wise, so upper
9046 // (undef) lanes don't affect the lower results.
9047 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
9048 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
9049 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
9050 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
9051 SDValue Undef = DAG.getUNDEF(WideVT);
9052 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9053 X, DAG.getVectorIdxConstant(0, DL));
9054 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9055 Y, DAG.getVectorIdxConstant(0, DL));
9056 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
9057 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
9058 DAG.getVectorIdxConstant(0, DL));
9059 }
9060 }
9061 }
9062
9063 // Special case: clmul(X, Y) where Y is a known constant (splat) that forms
9064 // a contiguous block of trailing ones whose length N is a power of two
9065 // (e.g. i8 0xFF, i8 0x0F, ...) or equal to the operand width. In this
9066 // special case, clmul(X, Y) is equivalent to a "parallel prefix XOR" or
9067 // "bitwise parity" operation on X.
9068 //
9069 // Note: This special currently dose NOT apply when the mask is neither a
9070 // power of two nor equal to the operand width because the loop inside
9071 // behaves as if the mask was bit-ceiled, and "undoing" the XOR with parts
9072 // of that CLMUL is a recursive problem (e.g. CLMUL with a 20-bit mask
9073 // requires correction XOR with CLMUL with 12-bit mask).
9074 if (auto *C = isConstOrConstSplat(Y, /*AllowUndefs=*/true)) {
9075 const APInt &YVal = C->getAPIntValue();
9076 unsigned N = YVal.countr_one();
9077 if (YVal.isAllOnes() || (YVal.isMask() && isPowerOf2_32(N))) {
9078 SDValue R = X;
9079 for (unsigned I = 1; I < N; I <<= 1) {
9080 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
9081 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
9082 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
9083 }
9084 return R;
9085 }
9086 }
9087
9088 // NOTE: If you change this expansion, please update the cost model
9089 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
9090 // Intrinsic::clmul.
9091
9092 // Strategy 4: multiplication with holes.
9093 //
9094 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
9095 // do occur, they wind up in a "hole" and are subsequently masked out of the
9096 // result.
9097 //
9098 // https://www.bearssl.org/constanttime.html#ghash-for-gcm describes this
9099 // approach.
9100
9101 // Stride S handles operands up to S·2^S bits using S² multiplies.
9102 //
9103 // * BW <= 8 uses S = 2 (holes of 1 bit)
9104 // * BW <= 24 uses S = 3 (holes of 2 bits)
9105 // * BW <= 64 uses S = 4 (holes of 3 bits)
9106 // * BW <= 160 uses S = 5 (holes of 4 bits)
9107 // * BW <= 384 uses S = 6 (holes of 5 bits)
9108 //
9109 // We distribute the BW bits over S phases:
9110 //
9111 // phase 0 keeps bits: 0, S, 2S, ...
9112 // phase 1 keeps bits: 1, S + 1, 2S + 1, ...
9113 // ...
9114 //
9115 // Each phase has up to n = ceil(BW / S) bits set, and the holes are S-1
9116 // bits wide.
9117 //
9118 // Take BW = 4, S = 2, n = 2. The worst case is a fully populated phase (all
9119 // non-hole bits are set to 1) multiplied by itself, 0b0101 * 0b0101. Each
9120 // set bit of one operand shifts a copy of the other, and we add the copies:
9121 //
9122 // col: 4 3 2 1 0
9123 // 0b0101 << 0: 0 0 1 0 1
9124 // 0b0101 << 2: 1 0 1 0 0
9125 // ----------------- +
9126 // count: 1 0 2 0 1
9127 //
9128 // Counting the number of one-bits in each column gives a triangle: the
9129 // counts climb 1, 2, ..., n and back down (here 1, 2, 1 across the data
9130 // columns). So a column holds at most n one-bits, and that maximum n is
9131 // reached in only one column: the peak. Every other column holds at most n
9132 // - 1 one-bits.
9133 //
9134 // A stack of one-bits in a column turns into carries: column 2 above really
9135 // stores the value 1 + 1 = 2 = n. A column spans S bits, its kept bit
9136 // plus S-1 hole bits, and the count is written from the kept bit upward,
9137 // so any count <= 2^S - 1 stays within the column and never interferes with
9138 // the next data bit S positions up. Every non-peak column holds at most n -
9139 // 1, so they all fit as soon as n - 1 <= 2^S - 1.
9140 //
9141 // That leaves only the peak column. Because both operands set all data
9142 // bits, the triangle peaks at the top of the word at the highest data bit
9143 // still inside BW. Here the count reaches exactly n = 2^S and overflows.
9144 // But its carry lands at bit n*S >= BW, off the top, where it (and the
9145 // whole descending half of the triangle) is truncated.
9146 //
9147 // Hence the holes suffice exactly when n = ceil(BW / S) <= 2^S, i.e. BW <=
9148 // S*2^S.
9149 //
9150 // Here we find the smallest S that satisfies this inequality.
9151 unsigned S = 1;
9152 while (S < 32 && divideCeil(BW, S) > (1u << S))
9153 ++S;
9154
9155 // The "multiplication with holes" expansion emits S*S MULs, 3*S ANDs,
9156 // S*(S-1) XORs and S-1 ORs.
9157 unsigned HolesCost = S * S + 3 * S + S * (S - 1) + (S - 1);
9158
9159 // Estimate the cost of the naive algorithm.
9160 KnownBits KnownY = DAG.computeKnownBits(Y);
9161 unsigned NaiveCost = 0;
9162 for (unsigned I = 0; I < BW; ++I) {
9163 // The iteration folds away entirely and is free.
9164 if (KnownY.Zero[I])
9165 continue;
9166
9167 // On targets with a fast bit test instruction more instructions are used
9168 // to not need a (potentially expensive) multiplication. See also below.
9169 if (hasBitTest(Y, DAG.getShiftAmountConstant(I, VT, DL))) {
9170 // AND + SETCC + SHL + SELECT + XOR.
9171 NaiveCost += 5;
9172 } else {
9173 // AND + MUL + XOR.
9174 NaiveCost += 3;
9175 }
9176 }
9177
9178 // Only use multiplication with holes when it is cheaper, else use the naive
9179 // fallback below.
9180 if (HolesCost < NaiveCost &&
9182
9183 // Set a bit every S positions, e.g. for S = 4 this is equivalent to
9184 // 0b...00010001...0001.
9185 APInt MaskVal = APInt::getSplat(BW, APInt(S, 1));
9186
9187 // Create versions of X and Y that keep only the I-th bit of each S-bit
9188 // slice.
9189 SmallVector<SDValue, 4> M(S), Xp(S), Yp(S);
9190 for (unsigned I = 0; I < S; ++I) {
9191 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9192 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9193 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9194 }
9195
9196 // Codegens these expressions (S*S multiplications), e.g. for S=4:
9197 //
9198 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9199 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9200 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9201 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9202 SDValue Res = DAG.getConstant(0, DL, VT);
9203 for (unsigned I = 0; I < S; ++I) {
9204 SDValue Zi = DAG.getConstant(0, DL, VT);
9205 for (unsigned J = 0; J < S; ++J) {
9206 unsigned K = (I + S - J) % S;
9207 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9208 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9209 }
9210
9211 // Keep only the bits belonging to this iteration, and bitwise or it all
9212 // together.
9213 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9214 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9215 }
9216 return Res;
9217 }
9218
9219 // Strategy 5: the naive fallback.
9220 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9221
9222 SDValue Res = DAG.getConstant(0, DL, VT);
9223 for (unsigned I = 0; I < BW; ++I) {
9224 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9225 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9226 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9227
9228 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9229 // multiply, use a shift-based expansion to avoid expensive MUL
9230 // instructions.
9231 SDValue Part;
9232 if (!hasBitTest(Y, ShiftAmt) &&
9235 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9236 } else {
9237 // Canonical bit test: (Y & (1 << I)) != 0
9238 SDValue Zero = DAG.getConstant(0, DL, VT);
9239 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9240 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9241 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9242 }
9243 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9244 }
9245 return Res;
9246 }
9247 case ISD::CLMULR:
9248 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9251 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9252 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9253 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9254 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9255 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9256 DAG.getShiftAmountConstant(1, VT, DL));
9257 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9258 }
9259 [[fallthrough]];
9260 case ISD::CLMULH: {
9261 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9262 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9263 // when any of these hold:
9264 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9265 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9266 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9267 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9268 // path creates CLMUL(VT) which will be expanded efficiently. The
9269 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9270 // causing a cycle.
9271 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9272 // => trunc path is preferred over the bitreverse path, as it avoids the
9273 // cost of 3 bitreverse operations.
9278 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9279 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9280 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9281 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9282 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9283 if (Opcode == ISD::CLMULH)
9284 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9285 DAG.getShiftAmountConstant(1, VT, DL));
9286 return Res;
9287 }
9288 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9289 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9290 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9291 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9292 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9293 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9294 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9295 }
9296 }
9297 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9298}
9299
9301 SDLoc DL(Node);
9302 EVT VT = Node->getValueType(0);
9303 SDValue Val = Node->getOperand(0);
9304 SDValue Msk = Node->getOperand(1);
9305 unsigned BW = VT.getScalarSizeInBits();
9306
9307 // Just scalarize if scalar PEXT is legal
9309 return DAG.UnrollVectorOp(Node);
9310
9311 // Hacker's Delight §7-4: Compress, or Generalized Extract
9312 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9313 SDValue M = Msk;
9314 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9315 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9316
9317 // Repeatedly compute which bits would shift to the right by an odd amount,
9318 // shift all such bits in parallel using a mask, and double the shift amount.
9319 for (unsigned I = 1; I < BW; I *= 2) {
9320 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9321 SDValue Mp =
9322 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9323 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9324 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9325 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9326 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9328 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9329 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9330 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9332 if (I * 2 < BW)
9333 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9334 }
9335
9336 return X;
9337}
9338
9340 SDLoc DL(Node);
9341 EVT VT = Node->getValueType(0);
9342 SDValue Val = Node->getOperand(0);
9343 SDValue Msk = Node->getOperand(1);
9344 unsigned BW = VT.getScalarSizeInBits();
9345
9346 // Just scalarize if scalar PDEP is legal
9348 return DAG.UnrollVectorOp(Node);
9349
9350 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9351 unsigned LogBW = Log2_32_Ceil(BW);
9352 SmallVector<SDValue, 8> MvArray(LogBW);
9353 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9354 SDValue Mc = Msk;
9355 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9356
9357 // First pass: compute move masks for each power of two that a bit moves by.
9358 for (unsigned S = 0; S < LogBW; ++S) {
9359 unsigned ShiftS = 1u << S;
9360 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9361 SDValue Mp =
9362 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9363 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9364 MvArray[S] = Mv;
9365 if (S + 1 < LogBW) {
9366 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9367 SDValue MvShifted = DAG.getNode(
9368 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9369 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9371 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9372 }
9373 }
9374
9375 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9376 // Each pass handles half the shift amount of the previous pass.
9377 SDValue X = Val;
9378 for (int S = (int)LogBW - 1; S >= 0; --S) {
9379 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9380 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9381 SDValue UnshiftedBits =
9382 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9383 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9384 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9386 }
9387
9388 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9389}
9390
9392 SelectionDAG &DAG) const {
9393 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9394 EVT VT = Node->getValueType(0);
9395 unsigned VTBits = VT.getScalarSizeInBits();
9396 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9397
9398 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9399 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9400 SDValue ShOpLo = Node->getOperand(0);
9401 SDValue ShOpHi = Node->getOperand(1);
9402 SDValue ShAmt = Node->getOperand(2);
9403 EVT ShAmtVT = ShAmt.getValueType();
9404 EVT ShAmtCCVT =
9405 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9406 SDLoc dl(Node);
9407
9408 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9409 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9410 // away during isel.
9411 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9412 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9413 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9414 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9415 : DAG.getConstant(0, dl, VT);
9416
9417 SDValue Tmp2, Tmp3;
9418 if (IsSHL) {
9419 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9420 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9421 } else {
9422 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9423 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9424 }
9425
9426 // If the shift amount is larger or equal than the width of a part we don't
9427 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9428 // values for large shift amounts.
9429 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9430 DAG.getConstant(VTBits, dl, ShAmtVT));
9431 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9432 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9433
9434 if (IsSHL) {
9435 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9436 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9437 } else {
9438 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9439 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9440 }
9441}
9442
9444 SelectionDAG &DAG) const {
9445 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9446 // suggested in
9447 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9448 // It uses strict_fp operations even outside a strict_fp context in order
9449 // to guarantee that the canonicalization is not optimized away by later
9450 // passes. The result chain introduced by that is intentionally ignored
9451 // since no ordering requirement is intended here.
9452 EVT VT = Node->getValueType(0);
9453 SDLoc DL(Node);
9454 SDNodeFlags Flags = Node->getFlags();
9455 Flags.setNoFPExcept(true);
9456 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9457 SDValue Mul =
9458 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9459 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9460 return Mul;
9461}
9462
9464 SelectionDAG &DAG) const {
9465 // Expand conversion from a native IEEE float type to an arbitrary FP format
9466 // returning the result as an integer using bit manipulation.
9467 EVT ResVT = Node->getValueType(0);
9468 SDLoc dl(Node);
9469
9470 SDValue FloatVal = Node->getOperand(0);
9471 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9472 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9473 const auto RoundMode =
9474 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9475 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9476
9477 // Supported destination formats.
9478 switch (Sem) {
9485 break;
9486 default:
9487 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9488 "destination format (semantics enum " +
9489 Twine(SemEnum) + ")");
9490 return SDValue();
9491 }
9492
9493 // Supported rounding modes.
9494 switch (RoundMode) {
9500 break;
9501 default:
9502 DAG.getContext()->emitError(
9503 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9504 Twine(static_cast<int>(RoundMode)) + ")");
9505 return SDValue();
9506 }
9507
9508 // Destination format parameters.
9509 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9510 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9511 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9512 const unsigned DstMant = DstPrecision - 1;
9513 // Unsigned formats spend no bit on the sign.
9514 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9515 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9516 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9517 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9518 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9519 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9520 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9521
9522 // Compute the maximum normal exponent for the destination format.
9523 const unsigned DstExpMaxNormal =
9524 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9525 : DstExpMax;
9526
9527 // For NanOnly formats the max exponent field for finite values
9528 // is DstExpMax, but the encoding with exp = DstExpMax and
9529 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9530 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9531 // avoid the NaN encoding.
9532 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9533 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9534 DstNanEnc == fltNanEncoding::AllOnes)
9535 DstMaxMantAtMaxExp = DstMantMask - 1;
9536
9537 // Source format parameters.
9538 EVT SrcVT = FloatVal.getValueType();
9539 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9540 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9541 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9542 const unsigned SrcMant = SrcPrecision - 1;
9543 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9544
9545 // Work in the source integer type. Match the destination shape so the
9546 // expansion stays vector when ResVT is a vector.
9547 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9548 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9549 EVT SetCCVT =
9550 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9551 EVT FPSetCCVT =
9552 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9553
9554 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9555 SDValue One = DAG.getConstant(1, dl, IntVT);
9556
9557 // Bitcast source float to integer to extract the sign bit.
9558 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9559 SDValue SignBit =
9560 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9561 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9562
9563 // Classify the input.
9564 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9565 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9566 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9567 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9568 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9569 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9570
9571 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9572 // source denormals automatically. The result is unspecified for Inf/NaN, but
9573 // those inputs are detected above and override the final result.
9574 EVT FrexpExpScalarVT =
9576 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9577 SDValue Frexp =
9578 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9579 SDValue FrexpFrac = Frexp.getValue(0);
9580 SDValue FrexpExp = Frexp.getValue(1);
9581
9582 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9583 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9584 DAG.getConstant(SrcMantMask, dl, IntVT));
9585
9586 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9587 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9588 DAG.getConstant(DstBias - 1, dl, IntVT));
9589
9590 // Compute rounding increment given the round bit, sticky bits, and LSB
9591 // of the truncated mantissa.
9592 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9593 SDValue LSB) -> SDValue {
9594 switch (RoundMode) {
9596 // Round up if round_bit && (sticky || lsb)
9597 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9598 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9599 }
9601 return Zero;
9603 // Round up if positive and any truncated bits are set.
9604 SDValue AnyTruncBits =
9605 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9606 SDValue HasTruncBits =
9607 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9608 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9609 SDValue DoRound =
9610 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9611 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9612 }
9614 // Round up if negative and any truncated bits are set (to -Inf).
9615 SDValue AnyTruncBits =
9616 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9617 SDValue HasTruncBits =
9618 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9619 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9620 SDValue DoRound =
9621 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9622 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9623 }
9625 return RoundBit;
9626 default:
9627 llvm_unreachable("unsupported rounding mode");
9628 }
9629 };
9630
9631 // Round mantissa from SrcMant bits to DstMant bits.
9632 SDValue TruncMant;
9633 SDValue RoundUp;
9634 if (SrcMant > DstMant) {
9635 const unsigned Shift = SrcMant - DstMant;
9636 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9637 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9638
9639 // Check bit at position Shift - 1 aka the round bit.
9640 SDValue RoundBit;
9641 if (Shift >= 1) {
9642 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9643 SDValue ShiftedMant =
9644 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9645 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9646 } else {
9647 RoundBit = Zero;
9648 }
9649
9650 // OR of all bits below the round bit to get sticky bits.
9651 SDValue StickyBits;
9652 if (Shift >= 2) {
9653 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9654 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9655 DAG.getConstant(StickyMask, dl, IntVT));
9656 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9657 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9658 } else {
9659 StickyBits = Zero;
9660 }
9661
9662 // LSB of truncated mantissa.
9663 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9664
9665 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9666 } else {
9667 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9668 SDValue MantShift =
9669 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9670 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9671 RoundUp = Zero;
9672 }
9673
9674 // Apply rounding.
9675 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9676
9677 // Handle mantissa overflow from rounding.
9678 // If rounded_mant > DstMantMask, carry into exponent.
9679 SDValue MantOverflow =
9680 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9681 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9682 // On overflow: mant = 0, exp += 1.
9683 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9684 SDValue AdjExp =
9685 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9686 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9687
9688 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9689 // sign bit to merge in.
9690 SDValue SignShifted =
9691 DstHasSign
9692 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9693 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9694 : Zero;
9695
9696 // Destination denormal conversion (when new_exp <= 0).
9697 // Shift the mantissa right by 1 - new_exp additional bits and set the
9698 // exponent field to 0.
9699 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9700 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9701
9702 SDValue DenormResult;
9703 {
9704 // denorm_shift = 1 - NewExp.
9705 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9706
9707 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9708 SDValue ImplicitOne =
9709 DAG.getNode(ISD::SHL, dl, IntVT, One,
9710 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9711 SDValue FullSrcMant =
9712 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9713
9714 // Total right shift = DenormShift + (SrcMant - DstMant).
9715 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9716 SDValue TotalShift =
9717 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9718 DAG.getSignedConstant(MantDelta, dl, IntVT));
9719
9720 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9721 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9722 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9723 SDValue ClampedShift =
9724 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9725 SDValue DenormTruncMant =
9726 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9727 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9728
9729 // Rounding for denorm path.
9730 SDValue DenormRoundUp;
9731 {
9732 // Round bit is at position TotalShift - 1 of FullSrcMant.
9733 // Clamp to at least 1 so the subtraction doesn't underflow and create
9734 // shift nodes with invalid shift amounts.
9735 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
9736 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
9737 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
9738 SDValue DenormRoundBit = DAG.getNode(
9739 ISD::AND, dl, IntVT,
9740 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
9741
9742 // Sticky: all bits below round bit.
9743 // sticky_mask = (1 << RoundBitPos) - 1
9744 SDValue StickyMask = DAG.getNode(
9745 ISD::SUB, dl, IntVT,
9746 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
9747 SDValue DenormStickyBits =
9748 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
9749 SDValue HasSticky = DAG.getNode(
9750 ISD::ZERO_EXTEND, dl, IntVT,
9751 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
9752
9753 SDValue DenormLSB =
9754 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
9755
9756 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
9757
9758 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
9759 SDValue ShiftGEOne =
9760 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
9761 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
9762 }
9763
9764 SDValue DenormRoundedMant =
9765 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
9766
9767 // If rounding caused overflow into the normal range, then we get the
9768 // smallest normal number.
9769 SDValue DenormMantOF =
9770 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
9771 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9772 SDValue DenormFinalMant =
9773 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
9774 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
9775
9776 // Assemble: sign | (exp << DstMant) | mant
9777 SDValue DenormExpShifted =
9778 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
9779 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9780 DenormResult = DAG.getNode(
9781 ISD::OR, dl, IntVT,
9782 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
9783 DenormFinalMant);
9784 }
9785
9786 // Exponent overflow detection.
9787 SDValue ExpOF =
9788 DAG.getSetCC(dl, SetCCVT, AdjExp,
9789 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
9790
9791 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
9792 // a value that exceeds the max allowed mantissa at that exponent.
9793 SDValue ExpAtMax =
9794 DAG.getSetCC(dl, SetCCVT, AdjExp,
9795 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
9796 SDValue MantExceedsMax =
9797 DAG.getSetCC(dl, SetCCVT, AdjMant,
9798 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
9799 SDValue ExpMantOF =
9800 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
9801 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
9802
9803 // Build overflow result.
9805
9806 if (Saturate) {
9807 // Clamp to max finite value:
9808 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
9809 uint64_t MaxFinite =
9810 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9811 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9812 DAG.getConstant(MaxFinite, dl, IntVT));
9813 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9814 // Produce infinity.
9815 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9816 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9817 DAG.getConstant(InfBits, dl, IntVT));
9818 } else {
9819 // Emit poison if no Inf in format and not saturating.
9820 OverflowResult = DAG.getPOISON(IntVT);
9821 }
9822
9823 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
9824 SDValue NormExpShifted =
9825 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
9826 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9827 SDValue NormResult = DAG.getNode(
9828 ISD::OR, dl, IntVT,
9829 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
9830
9831 // Build special-value results.
9832 SDValue NaNResult;
9833 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9834 // Produce canonical NaN.
9835 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
9836 NaNResult =
9837 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
9838 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9839 DstNanEnc == fltNanEncoding::AllOnes) {
9840 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
9841 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
9842 dl, IntVT);
9843 } else {
9844 // NaN -> poison for finite only values.
9845 NaNResult = DAG.getPOISON(IntVT);
9846 }
9847
9848 // Inf handling.
9849 SDValue InfResult;
9850 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9851 // Produce signed infinity.
9852 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9853 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9854 DAG.getConstant(InfBits, dl, IntVT));
9855 } else if (Saturate) {
9856 // Inf saturates to max finite.
9857 uint64_t MaxFinite =
9858 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9859 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9860 DAG.getConstant(MaxFinite, dl, IntVT));
9861 } else {
9862 // No Inf and not saturating -> poison.
9863 InfResult = DAG.getPOISON(IntVT);
9864 }
9865
9866 SDValue ZeroResult = SignShifted;
9867
9868 // Final selection in an order: NaN takes priority, then Inf, then Zero.
9869 SDValue FiniteResult =
9870 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
9871 FiniteResult =
9872 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
9873
9874 SDValue Result = FiniteResult;
9875 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
9876 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
9877
9878 // Negative values are unrepresentable in an unsigned format: clamp to zero
9879 // when saturating, poison otherwise so no select is needed. -0.0 is handled
9880 // by IsZero above. Run before the NaN case so a negative NaN still yields
9881 // NaN.
9882 if (!DstHasSign && Saturate) {
9883 SDValue IsNegative =
9884 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
9885 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
9886 }
9887
9888 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
9889
9890 // Truncate to destination integer type.
9891 return DAG.getZExtOrTrunc(Result, dl, ResVT);
9892}
9893
9894SDValue
9896 SelectionDAG &DAG) const {
9897 SDLoc dl(Node);
9898 EVT DstVT = Node->getValueType(0);
9899 EVT DstScalarVT = DstVT.getScalarType();
9900
9901 SDValue IntVal = Node->getOperand(0);
9902 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9903 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9904
9905 // Supported source formats.
9906 switch (Sem) {
9913 break;
9914 default:
9915 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
9916 "source format (semantics enum " +
9917 Twine(SemEnum) + ")");
9918 return SDValue();
9919 }
9920
9921 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
9922 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9923 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9924 const unsigned SrcMant = SrcPrecision - 1;
9925 // Unsigned formats spend no bit on the sign.
9926 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
9927 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
9928 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
9929 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
9930
9931 // Destination format parameters.
9932 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
9933 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9934 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
9935 const unsigned DstExpBits = DstBits - DstMant - 1;
9936 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
9937 const int DstBias = 1 - DstMinExp;
9938 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
9939
9940 // Work in an integer type matching the destination float width.
9941 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
9942 EVT IntVT = IntScalarVT;
9943 if (DstVT.isVector()) {
9944 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
9945 DstVT.getVectorElementCount());
9946 } else if (!isTypeLegal(IntScalarVT)) {
9947 // Avoid generating illegal type as there is no other places that'll
9948 // legalize it. Vector types don't have this problem because they
9949 // are subject to LegalizeVectorOps and another type legalization phase
9950 // will follow.
9951 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
9952 // We only know how to handle situations where the legal type is wider.
9953 DAG.getContext()->emitError(
9954 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
9955 "legalization is not supported");
9956 return SDValue();
9957 }
9958 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
9959 }
9960
9961 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
9962
9963 EVT SetCCVT =
9964 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9965
9966 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9967 SDValue One = DAG.getConstant(1, dl, IntVT);
9968
9969 // Extract bit fields.
9970 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
9971 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
9972
9973 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
9974 DAG.getConstant(MantMask, dl, IntVT));
9975
9976 SDValue ExpField =
9977 DAG.getNode(ISD::AND, dl, IntVT,
9978 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9979 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
9980 DAG.getConstant(ExpMask, dl, IntVT));
9981
9982 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
9983 // exponent.
9984 SDValue SignShifted =
9985 SrcHasSign
9986 ? DAG.getNode(
9987 ISD::SHL, dl, IntVT,
9988 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9989 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
9990 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9991 : Zero;
9992
9993 // Classify the input.
9994 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
9995 SDValue IsExpAllOnes =
9996 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
9997 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
9998 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
9999 SDValue IsMantNonZero =
10000 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
10001
10002 SDValue IsNaN;
10003 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
10004 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10005 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
10006 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
10007 } else {
10009 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
10010 SDValue IsMantAllOnes =
10011 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
10012 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
10013 }
10014
10015 SDValue IsInf;
10016 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
10017 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
10018 else
10019 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10020
10021 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
10022 SDValue IsDenorm =
10023 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
10024
10025 // Normal value conversion.
10026 const int BiasAdjust = DstBias - SrcBias;
10027 SDValue NormDstExp = DAG.getNode(
10028 ISD::ADD, dl, IntVT, ExpField,
10029 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
10030 IntVT));
10031
10032 SDValue NormDstMant;
10033 if (DstMant > SrcMant) {
10034 SDValue NormDstMantShift =
10035 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
10036 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
10037 } else {
10038 NormDstMant = MantField;
10039 }
10040
10041 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
10042 SDValue NormExpShifted =
10043 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
10044 SDValue NormResult =
10045 DAG.getNode(ISD::OR, dl, IntVT,
10046 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
10047 NormDstMant);
10048
10049 // With identical exponent biases, denormal values remain denormal and the
10050 // normal conversion's mantissa shift is sufficient.
10051 SDValue DenormResult = NormResult;
10052 if (BiasAdjust != 0) {
10053 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
10054 SDValue LeadingZeros =
10055 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
10056
10057 const int DenormExpConst =
10058 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
10059 SDValue DenormDstExp = DAG.getNode(
10060 ISD::SUB, dl, IntVT,
10061 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
10062 LeadingZeros);
10063
10064 SDValue MantMSB =
10065 DAG.getNode(ISD::SUB, dl, IntVT,
10066 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
10067
10068 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
10069 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
10070
10071 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
10072 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
10073 DAG.getConstant(ShiftSub, dl, IntVT));
10074
10075 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
10076
10077 SDValue DenormExpShifted =
10078 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
10079 DenormResult = DAG.getNode(
10080 ISD::OR, dl, IntVT,
10081 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10082 DenormDstMant);
10083 }
10084
10085 SDValue FiniteResult =
10086 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
10087
10088 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10089 SDValue NaNResult =
10090 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
10091
10092 SDValue InfResult =
10093 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10094 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
10095
10096 // A source format may have a larger finite exponent range despite having
10097 // fewer bits, as with Float8E5M3FNU converted to half. Its overflowing finite
10098 // values become infinity. The NaN selection below still takes precedence.
10099 if (APFloat::semanticsMaxExponent(SrcSem) >
10101 SDValue IsOverflow =
10102 DAG.getSetCC(dl, SetCCVT, NormDstExp,
10103 DAG.getConstant(DstExpAllOnes, dl, IntVT), ISD::SETUGE);
10104 FiniteResult =
10105 DAG.getSelect(dl, IntVT, IsOverflow, InfResult, FiniteResult);
10106 }
10107
10108 SDValue ZeroResult = SignShifted;
10109
10110 SDValue Result = FiniteResult;
10111 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10112 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10113 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10114
10115 if (!DstVT.bitsEq(IntVT)) {
10116 // Store to stack before loading it back.
10117 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
10118 // IntScalarVT is the original type that has the same width as DstVT.
10119 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
10120 SDValue StackPtr =
10121 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
10122 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10124 MachinePointerInfo PtrInfo =
10125 MachinePointerInfo::getFixedStack(MF, FrameIndex);
10126 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
10127 PtrInfo, IntScalarVT, Alignment);
10128
10129 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
10130 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
10131 }
10132
10133 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
10134}
10135
10137 SelectionDAG &DAG) const {
10138 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10139 SDValue Src = Node->getOperand(OpNo);
10140 EVT SrcVT = Src.getValueType();
10141 EVT DstVT = Node->getValueType(0);
10142 SDLoc dl(SDValue(Node, 0));
10143
10144 // FIXME: Only f32 to i64 conversions are supported.
10145 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
10146 return false;
10147
10148 if (Node->isStrictFPOpcode())
10149 // When a NaN is converted to an integer a trap is allowed. We can't
10150 // use this expansion here because it would eliminate that trap. Other
10151 // traps are also allowed and cannot be eliminated. See
10152 // IEEE 754-2008 sec 5.8.
10153 return false;
10154
10155 // Expand f32 -> i64 conversion
10156 // This algorithm comes from compiler-rt's implementation of fixsfdi:
10157 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
10158 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
10159 EVT IntVT = SrcVT.changeTypeToInteger();
10160 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
10161
10162 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
10163 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
10164 SDValue Bias = DAG.getConstant(127, dl, IntVT);
10165 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
10166 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
10167 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
10168
10169 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
10170
10171 SDValue ExponentBits = DAG.getNode(
10172 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
10173 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
10174 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
10175
10176 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
10177 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
10178 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
10179 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10180
10181 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10182 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10183 DAG.getConstant(0x00800000, dl, IntVT));
10184
10185 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10186
10187 R = DAG.getSelectCC(
10188 dl, Exponent, ExponentLoBit,
10189 DAG.getNode(ISD::SHL, dl, DstVT, R,
10190 DAG.getZExtOrTrunc(
10191 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10192 dl, IntShVT)),
10193 DAG.getNode(ISD::SRL, dl, DstVT, R,
10194 DAG.getZExtOrTrunc(
10195 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10196 dl, IntShVT)),
10197 ISD::SETGT);
10198
10199 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10200 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10201
10202 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10203 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10204 return true;
10205}
10206
10208 SDValue &Chain,
10209 SelectionDAG &DAG) const {
10210 SDLoc dl(SDValue(Node, 0));
10211 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10212 SDValue Src = Node->getOperand(OpNo);
10213
10214 EVT SrcVT = Src.getValueType();
10215 EVT DstVT = Node->getValueType(0);
10216 EVT SetCCVT =
10217 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10218 EVT DstSetCCVT =
10219 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10220
10221 // Only expand vector types if we have the appropriate vector bit operations.
10222 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10224 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10226 return false;
10227
10228 // If the maximum float value is smaller then the signed integer range,
10229 // the destination signmask can't be represented by the float, so we can
10230 // just use FP_TO_SINT directly.
10231 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10232 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10233 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10235 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10236 if (Node->isStrictFPOpcode()) {
10237 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10238 { Node->getOperand(0), Src });
10239 Chain = Result.getValue(1);
10240 } else
10241 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10242 return true;
10243 }
10244
10245 // Don't expand it if there isn't cheap fsub instruction.
10247 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10248 return false;
10249
10250 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10251 SDValue Sel;
10252
10253 if (Node->isStrictFPOpcode()) {
10254 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10255 Node->getOperand(0), /*IsSignaling*/ true);
10256 Chain = Sel.getValue(1);
10257 } else {
10258 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10259 }
10260
10261 bool Strict = Node->isStrictFPOpcode() ||
10262 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10263
10264 if (Strict) {
10265 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10266 // signmask then offset (the result of which should be fully representable).
10267 // Sel = Src < 0x8000000000000000
10268 // FltOfs = select Sel, 0, 0x8000000000000000
10269 // IntOfs = select Sel, 0, 0x8000000000000000
10270 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10271
10272 // TODO: Should any fast-math-flags be set for the FSUB?
10273 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10274 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10275 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10276 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10277 DAG.getConstant(0, dl, DstVT),
10278 DAG.getConstant(SignMask, dl, DstVT));
10279 SDValue SInt;
10280 if (Node->isStrictFPOpcode()) {
10281 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10282 { Chain, Src, FltOfs });
10283 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10284 { Val.getValue(1), Val });
10285 Chain = SInt.getValue(1);
10286 } else {
10287 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10288 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10289 }
10290 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10291 } else {
10292 // Expand based on maximum range of FP_TO_SINT:
10293 // True = fp_to_sint(Src)
10294 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10295 // Result = select (Src < 0x8000000000000000), True, False
10296
10297 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10298 // TODO: Should any fast-math-flags be set for the FSUB?
10299 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10300 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10301 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10302 DAG.getConstant(SignMask, dl, DstVT));
10303 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10304 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10305 }
10306 return true;
10307}
10308
10310 SDValue &Chain, SelectionDAG &DAG) const {
10311 // This transform is not correct for converting 0 when rounding mode is set
10312 // to round toward negative infinity which will produce -0.0. So disable
10313 // under strictfp.
10314 if (Node->isStrictFPOpcode())
10315 return false;
10316
10317 SDValue Src = Node->getOperand(0);
10318 EVT SrcVT = Src.getValueType();
10319 EVT DstVT = Node->getValueType(0);
10320
10321 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10322 // it.
10323 if (Node->getFlags().hasNonNeg() &&
10325 Result =
10326 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10327 return true;
10328 }
10329
10330 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10331 return false;
10332
10333 // Only expand vector types if we have the appropriate vector bit
10334 // operations.
10335 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10340 return false;
10341
10342 SDLoc dl(SDValue(Node, 0));
10343
10344 // Implementation of unsigned i64 to f64 following the algorithm in
10345 // __floatundidf in compiler_rt. This implementation performs rounding
10346 // correctly in all rounding modes with the exception of converting 0
10347 // when rounding toward negative infinity. In that case the fsub will
10348 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10349 // incorrect.
10350 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10351 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10352 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10353 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10354 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10355 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10356
10357 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10358 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10359 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10360 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10361 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10362 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10363 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10364 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10365 return true;
10366}
10367
10368SDValue
10370 SelectionDAG &DAG) const {
10371 unsigned Opcode = Node->getOpcode();
10372 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10373 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10374 "Wrong opcode");
10375
10376 if (Node->getFlags().hasNoNaNs()) {
10377 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10378 EVT VT = Node->getValueType(0);
10379 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10381 VT.isVector())
10382 return SDValue();
10383 SDValue Op1 = Node->getOperand(0);
10384 SDValue Op2 = Node->getOperand(1);
10385 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10386 Node->getFlags());
10387 }
10388
10389 return SDValue();
10390}
10391
10393 SelectionDAG &DAG) const {
10394 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10395 return Expanded;
10396
10397 EVT VT = Node->getValueType(0);
10398 if (VT.isScalableVector())
10400 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10401
10402 SDLoc dl(Node);
10403 unsigned NewOp =
10405
10406 if (isOperationLegalOrCustom(NewOp, VT)) {
10407 SDValue Quiet0 = Node->getOperand(0);
10408 SDValue Quiet1 = Node->getOperand(1);
10409
10410 if (!Node->getFlags().hasNoNaNs()) {
10411 // Insert canonicalizes if it's possible we need to quiet to get correct
10412 // sNaN behavior.
10413 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10414 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10415 Node->getFlags());
10416 }
10417 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10418 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10419 Node->getFlags());
10420 }
10421 }
10422
10423 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10424 }
10425
10426 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10427 // instead if there are no NaNs.
10428 if (Node->getFlags().hasNoNaNs() ||
10429 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10430 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10431 unsigned IEEE2018Op =
10432 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10433 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10434 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10435 Node->getOperand(1), Node->getFlags());
10436 }
10437
10439 return SelCC;
10440
10441 return SDValue();
10442}
10443
10445 const TargetLowering &TLI,
10446 const SDLoc &DL, SDValue Val,
10447 FPClassTest FPClass) {
10448 EVT VT = Val.getValueType();
10449 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10450 EVT IntVT = VT.changeTypeToInteger();
10451 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10452 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10453 if (!TLI.isTypeLegal(IntVT) &&
10455 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10456 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10457 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10458}
10459
10461 SelectionDAG &DAG) const {
10462 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10463 return Expanded;
10464
10465 SDLoc DL(N);
10466 SDValue LHS = N->getOperand(0);
10467 SDValue RHS = N->getOperand(1);
10468 unsigned Opc = N->getOpcode();
10469 EVT VT = N->getValueType(0);
10470 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10471 bool IsMax = Opc == ISD::FMAXIMUM;
10472 SDNodeFlags Flags = N->getFlags();
10473
10474 // First, implement comparison not propagating NaN. If no native fmin or fmax
10475 // available, use plain select with setcc instead.
10477 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10478 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10479
10480 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10481 // signed zero behavior.
10482 bool MinMaxMustRespectOrderedZero = false;
10483
10484 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10485 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10486 MinMaxMustRespectOrderedZero = true;
10487 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10488 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10489 } else {
10491 return DAG.UnrollVectorOp(N);
10492
10493 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10494 SDValue Compare =
10495 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10496 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10497 }
10498
10499 // Propagate any NaN of both operands
10500 if (!N->getFlags().hasNoNaNs() &&
10501 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10502 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10504 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10505 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10506 }
10507
10508 // fminimum/fmaximum requires -0.0 less than +0.0
10509 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10510 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10511 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10513 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10514 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10515 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10516 }
10517
10518 return MinMax;
10519}
10520
10522 SelectionDAG &DAG) const {
10523 SDLoc DL(Node);
10524 SDValue LHS = Node->getOperand(0);
10525 SDValue RHS = Node->getOperand(1);
10526 unsigned Opc = Node->getOpcode();
10527 EVT VT = Node->getValueType(0);
10528 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10529 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10530 SDNodeFlags Flags = Node->getFlags();
10531
10532 unsigned NewOp =
10534
10535 if (isOperationLegalOrCustom(NewOp, VT)) {
10536 if (!Flags.hasNoNaNs()) {
10537 // Insert canonicalizes if it's possible we need to quiet to get correct
10538 // sNaN behavior.
10539 if (!DAG.isKnownNeverSNaN(LHS)) {
10540 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10541 }
10542 if (!DAG.isKnownNeverSNaN(RHS)) {
10543 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10544 }
10545 }
10546
10547 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10548 }
10549
10550 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10551 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10552 if (Flags.hasNoNaNs() ||
10553 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10554 unsigned IEEE2019Op =
10556 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10557 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10558 }
10559
10560 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10561 // either one for +0.0 vs -0.0.
10562 if ((Flags.hasNoNaNs() ||
10563 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10564 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10565 DAG.isKnownNeverLogicalZero(RHS))) {
10566 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10567 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10568 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10569 }
10570
10571 if (VT.isVector() &&
10574 return DAG.UnrollVectorOp(Node);
10575
10576 // If only one operand is NaN, override it with another operand.
10577 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10578 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10579 }
10580 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10581 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10582 }
10583
10584 // Always prefer RHS if equal.
10585 SDValue MinMax =
10586 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10587
10588 // TODO: We need quiet sNaN if strictfp.
10589
10590 // Fixup signed zero behavior.
10591 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10592 DAG.isKnownNeverLogicalZero(RHS)) {
10593 return MinMax;
10594 }
10595 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10596 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10598 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10599 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10600 // we preferred RHS when generate MinMax, if the operands are equal.
10601 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10602 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10603}
10604
10605/// Returns a true value if if this FPClassTest can be performed with an ordered
10606/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10607/// std::nullopt if it cannot be performed as a compare with 0.
10608static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10609 const fltSemantics &Semantics,
10610 const MachineFunction &MF) {
10611 FPClassTest OrderedMask = Test & ~fcNan;
10612 FPClassTest NanTest = Test & fcNan;
10613 bool IsOrdered = NanTest == fcNone;
10614 bool IsUnordered = NanTest == fcNan;
10615
10616 // Skip cases that are testing for only a qnan or snan.
10617 if (!IsOrdered && !IsUnordered)
10618 return std::nullopt;
10619
10620 if (OrderedMask == fcZero &&
10621 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10622 return IsOrdered;
10623 if (OrderedMask == (fcZero | fcSubnormal) &&
10624 MF.getDenormalMode(Semantics).inputsAreZero())
10625 return IsOrdered;
10626 return std::nullopt;
10627}
10628
10630 const FPClassTest OrigTestMask,
10631 SDNodeFlags Flags, const SDLoc &DL,
10632 SelectionDAG &DAG) const {
10633 EVT OperandVT = Op.getValueType();
10634 assert(OperandVT.isFloatingPoint());
10635 FPClassTest Test = OrigTestMask;
10636
10637 // Degenerated cases.
10638 if (Test == fcNone)
10639 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10640 if (Test == fcAllFlags)
10641 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10642
10643 // PPC double double is a pair of doubles, of which the higher part determines
10644 // the value class.
10645 if (OperandVT == MVT::ppcf128) {
10646 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10647 DAG.getConstant(1, DL, MVT::i32));
10648 OperandVT = MVT::f64;
10649 }
10650
10651 // Floating-point type properties.
10652 EVT ScalarFloatVT = OperandVT.getScalarType();
10653 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10654 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10655 bool IsF80 = (ScalarFloatVT == MVT::f80);
10656
10657 // Some checks can be implemented using float comparisons, if floating point
10658 // exceptions are ignored.
10659 if (Flags.hasNoFPExcept() &&
10661 FPClassTest FPTestMask = Test;
10662 bool IsInvertedFP = false;
10663
10664 if (FPClassTest InvertedFPCheck =
10665 invertFPClassTestIfSimpler(FPTestMask, true)) {
10666 FPTestMask = InvertedFPCheck;
10667 IsInvertedFP = true;
10668 }
10669
10670 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10671 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10672
10673 // See if we can fold an | fcNan into an unordered compare.
10674 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10675
10676 // Can't fold the ordered check if we're only testing for snan or qnan
10677 // individually.
10678 if ((FPTestMask & fcNan) != fcNan)
10679 OrderedFPTestMask = FPTestMask;
10680
10681 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10682
10683 if (std::optional<bool> IsCmp0 =
10684 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10685 IsCmp0 && (isCondCodeLegalOrCustom(
10686 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10687 OperandVT.getScalarType().getSimpleVT()))) {
10688
10689 // If denormals could be implicitly treated as 0, this is not equivalent
10690 // to a compare with 0 since it will also be true for denormals.
10691 return DAG.getSetCC(DL, ResultVT, Op,
10692 DAG.getConstantFP(0.0, DL, OperandVT),
10693 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10694 }
10695
10696 if (FPTestMask == fcNan &&
10698 OperandVT.getScalarType().getSimpleVT()))
10699 return DAG.getSetCC(DL, ResultVT, Op, Op,
10700 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10701
10702 bool IsOrderedInf = FPTestMask == fcInf;
10703 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10704 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10705 : UnorderedCmpOpcode,
10706 OperandVT.getScalarType().getSimpleVT()) &&
10709 (OperandVT.isVector() &&
10711 // isinf(x) --> fabs(x) == inf
10712 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10713 SDValue Inf =
10714 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10715 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10716 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10717 }
10718
10719 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10720 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10721 : UnorderedCmpOpcode,
10722 OperandVT.getSimpleVT())) {
10723 // isposinf(x) --> x == inf
10724 // isneginf(x) --> x == -inf
10725 // isposinf(x) || nan --> x u== inf
10726 // isneginf(x) || nan --> x u== -inf
10727
10728 SDValue Inf = DAG.getConstantFP(
10729 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
10730 OperandVT);
10731 return DAG.getSetCC(DL, ResultVT, Op, Inf,
10732 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
10733 }
10734
10735 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
10736 // TODO: Could handle ordered case, but it produces worse code for
10737 // x86. Maybe handle ordered if fabs is free?
10738
10739 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10740 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
10741
10742 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
10743 OperandVT.getScalarType().getSimpleVT())) {
10744 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
10745
10746 // TODO: Maybe only makes sense if fabs is free. Integer test of
10747 // exponent bits seems better for x86.
10748 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10749 SDValue SmallestNormal = DAG.getConstantFP(
10750 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10751 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
10752 IsOrdered ? OrderedOp : UnorderedOp);
10753 }
10754 }
10755
10756 if (FPTestMask == fcNormal) {
10757 // TODO: Handle unordered
10758 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10759 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
10760
10761 if (isCondCodeLegalOrCustom(IsFiniteOp,
10762 OperandVT.getScalarType().getSimpleVT()) &&
10763 isCondCodeLegalOrCustom(IsNormalOp,
10764 OperandVT.getScalarType().getSimpleVT()) &&
10765 isFAbsFree(OperandVT)) {
10766 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
10767 SDValue Inf =
10768 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10769 SDValue SmallestNormal = DAG.getConstantFP(
10770 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10771
10772 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10773 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
10774 SDValue IsNormal =
10775 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
10776 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
10777 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
10778 }
10779 }
10780 }
10781
10782 // Some checks may be represented as inversion of simpler check, for example
10783 // "inf|normal|subnormal|zero" => !"nan".
10784 bool IsInverted = false;
10785
10786 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
10787 Test = InvertedCheck;
10788 IsInverted = true;
10789 }
10790
10791 // In the general case use integer operations.
10792 unsigned BitSize = OperandVT.getScalarSizeInBits();
10793 EVT IntVT = OperandVT.changeElementType(
10794 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
10795 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
10796
10797 // Various masks.
10798 APInt SignBit = APInt::getSignMask(BitSize);
10799 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
10800 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
10801 const unsigned ExplicitIntBitInF80 = 63;
10802 APInt ExpMask = Inf;
10803 if (IsF80)
10804 ExpMask.clearBit(ExplicitIntBitInF80);
10805 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
10806 APInt QNaNBitMask =
10807 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
10808 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
10809
10810 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
10811 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
10812 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
10813 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
10814 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
10815 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
10816
10817 SDValue Res;
10818 const auto appendResult = [&](SDValue PartialRes) {
10819 if (PartialRes) {
10820 if (Res)
10821 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
10822 else
10823 Res = PartialRes;
10824 }
10825 };
10826
10827 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
10828 const auto getIntBitIsSet = [&]() -> SDValue {
10829 if (!IntBitIsSetV) {
10830 APInt IntBitMask(BitSize, 0);
10831 IntBitMask.setBit(ExplicitIntBitInF80);
10832 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
10833 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
10834 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
10835 }
10836 return IntBitIsSetV;
10837 };
10838
10839 // Split the value into sign bit and absolute value.
10840 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
10841 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
10842 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
10843
10844 // Tests that involve more than one class should be processed first.
10845 SDValue PartialRes;
10846
10847 if (IsF80)
10848 ; // Detect finite numbers of f80 by checking individual classes because
10849 // they have different settings of the explicit integer bit.
10850 else if ((Test & fcFinite) == fcFinite) {
10851 // finite(V) ==> (a << 1) < (inf << 1)
10852 //
10853 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
10854 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
10855
10857 "finite check requires IEEE-like FP");
10858
10859 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
10860 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
10861 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
10862
10863 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
10864 Test &= ~fcFinite;
10865 } else if ((Test & fcFinite) == fcPosFinite) {
10866 // finite(V) && V > 0 ==> V < exp_mask
10867 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
10868 Test &= ~fcPosFinite;
10869 } else if ((Test & fcFinite) == fcNegFinite) {
10870 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
10871 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
10872 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10873 Test &= ~fcNegFinite;
10874 }
10875 appendResult(PartialRes);
10876
10877 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
10878 // fcZero | fcSubnormal => test all exponent bits are 0
10879 // TODO: Handle sign bit specific cases
10880 if (PartialCheck == (fcZero | fcSubnormal)) {
10881 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
10882 SDValue ExpIsZero =
10883 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10884 appendResult(ExpIsZero);
10885 Test &= ~PartialCheck & fcAllFlags;
10886 }
10887 }
10888
10889 // Check for individual classes.
10890
10891 if (unsigned PartialCheck = Test & fcZero) {
10892 if (PartialCheck == fcPosZero)
10893 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
10894 else if (PartialCheck == fcZero)
10895 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
10896 else // ISD::fcNegZero
10897 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
10898 appendResult(PartialRes);
10899 }
10900
10901 if (unsigned PartialCheck = Test & fcSubnormal) {
10902 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
10903 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
10904 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
10905 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
10906 SDValue VMinusOneV =
10907 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
10908 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
10909 if (PartialCheck == fcNegSubnormal)
10910 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10911 appendResult(PartialRes);
10912 }
10913
10914 if (unsigned PartialCheck = Test & fcInf) {
10915 if (PartialCheck == fcPosInf)
10916 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
10917 else if (PartialCheck == fcInf)
10918 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
10919 else { // ISD::fcNegInf
10920 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
10921 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
10922 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
10923 }
10924 appendResult(PartialRes);
10925 }
10926
10927 if (unsigned PartialCheck = Test & fcNan) {
10928 APInt InfWithQnanBit = Inf | QNaNBitMask;
10929 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
10930 if (PartialCheck == fcNan) {
10931 // isnan(V) ==> abs(V) > int(inf)
10932 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
10933 if (IsF80) {
10934 // Recognize unsupported values as NaNs for compatibility with glibc.
10935 // In them (exp(V)==0) == int_bit.
10936 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
10937 SDValue ExpIsZero =
10938 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10939 SDValue IsPseudo =
10940 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
10941 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
10942 }
10943 } else if (PartialCheck == fcQNan) {
10944 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
10945 PartialRes =
10946 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
10947 } else { // ISD::fcSNan
10948 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
10949 // abs(V) < (unsigned(Inf) | quiet_bit)
10950 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
10951 SDValue IsNotQnan =
10952 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
10953 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
10954 }
10955 appendResult(PartialRes);
10956 }
10957
10958 if (unsigned PartialCheck = Test & fcNormal) {
10959 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
10960 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
10961 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
10962 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
10963 APInt ExpLimit = ExpMask - ExpLSB;
10964 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
10965 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
10966 if (PartialCheck == fcNegNormal)
10967 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10968 else if (PartialCheck == fcPosNormal) {
10969 SDValue PosSignV =
10970 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
10971 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
10972 }
10973 if (IsF80)
10974 PartialRes =
10975 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
10976 appendResult(PartialRes);
10977 }
10978
10979 if (!Res)
10980 return DAG.getConstant(IsInverted, DL, ResultVT);
10981 if (IsInverted)
10982 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
10983 return Res;
10984}
10985
10986// Only expand vector types if we have the appropriate vector bit operations.
10987static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
10988 assert(VT.isVector() && "Expected vector type");
10989 unsigned Len = VT.getScalarSizeInBits();
10990 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
10993 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
10995}
10996
10998 SDLoc dl(Node);
10999 EVT VT = Node->getValueType(0);
11000 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11001 SDValue Op = Node->getOperand(0);
11002 unsigned Len = VT.getScalarSizeInBits();
11003
11004 // Compute effective bit width from known bits, allowing us to shift the
11005 // active bits down if necessary to fit into smaller specialized expansions.
11007 unsigned LZ = Known.countMinLeadingZeros();
11008 unsigned TZ = Known.countMinTrailingZeros();
11009 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
11010
11011 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
11012 unsigned EffectiveLen = Len;
11013 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
11014 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
11015
11016 assert(VT.isInteger() && "CTPOP not implemented for this type.");
11017
11018 // TODO: Add support for irregular type lengths.
11019 if (!(Len <= 128 && Len % 8 == 0))
11020 return SDValue();
11021
11022 // Only expand vector types if we have the appropriate vector bit operations.
11023 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
11024 return SDValue();
11025
11026 // If the active bits are not at the low end, shift them down
11027 if (EffectiveLen < Len && TZ > 0) {
11028 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
11029 DAG.getShiftAmountConstant(TZ, VT, dl));
11030 }
11031
11032 // This is the "best" algorithm from
11033 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
11034 SDValue Mask55 =
11035 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
11036 SDValue Mask33 =
11037 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
11038 SDValue Mask0F =
11039 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
11040
11041 // v = v - ((v >> 1) & 0x55555555...)
11042 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
11043 DAG.getNode(ISD::AND, dl, VT,
11044 DAG.getNode(ISD::SRL, dl, VT, Op,
11045 DAG.getConstant(1, dl, ShVT)),
11046 Mask55));
11047 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
11048 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
11049 DAG.getNode(ISD::AND, dl, VT,
11050 DAG.getNode(ISD::SRL, dl, VT, Op,
11051 DAG.getConstant(2, dl, ShVT)),
11052 Mask33));
11053 // v = (v + (v >> 4)) & 0x0F0F0F0F...
11054 Op = DAG.getNode(ISD::AND, dl, VT,
11055 DAG.getNode(ISD::ADD, dl, VT, Op,
11056 DAG.getNode(ISD::SRL, dl, VT, Op,
11057 DAG.getConstant(4, dl, ShVT))),
11058 Mask0F);
11059
11060 if (EffectiveLen <= 8)
11061 return Op;
11062
11063 // Avoid the multiply if we only have 2 bytes to add.
11064 // TODO: Only doing this for scalars because vectors weren't as obviously
11065 // improved.
11066 if (EffectiveLen == 16 && !VT.isVector()) {
11067 // v = (v + (v >> 8)) & 0x00FF;
11068 return DAG.getNode(ISD::AND, dl, VT,
11069 DAG.getNode(ISD::ADD, dl, VT, Op,
11070 DAG.getNode(ISD::SRL, dl, VT, Op,
11071 DAG.getConstant(8, dl, ShVT))),
11072 DAG.getConstant(0xFF, dl, VT));
11073 }
11074
11075 // v = (v * 0x01010101...) >> (Len - 8)
11076 SDValue V;
11079 SDValue Mask01 =
11080 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
11081 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
11082 } else {
11083 V = Op;
11084 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
11085 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
11086 V = DAG.getNode(ISD::ADD, dl, VT, V,
11087 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
11088 }
11089 }
11090 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
11091}
11092
11094 SDLoc dl(Node);
11095 EVT VT = Node->getValueType(0);
11096 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11097 SDValue Op = Node->getOperand(0);
11098 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11099
11100 // If the non-ZERO_POISON version is supported we can use that instead.
11101 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
11103 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
11104
11105 // If the ZERO_POISON version is supported use that and handle the zero case.
11107 EVT SetCCVT =
11108 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11109 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
11110 SDValue Zero = DAG.getConstant(0, dl, VT);
11111 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11112 return DAG.getSelect(dl, VT, SrcIsZero,
11113 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
11114 }
11115
11116 // Only expand vector types if we have the appropriate vector bit operations.
11117 // This includes the operations needed to expand CTPOP if it isn't supported.
11118 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11120 !canExpandVectorCTPOP(*this, VT)) ||
11123 return SDValue();
11124
11125 // for now, we do this:
11126 // x = x | (x >> 1);
11127 // x = x | (x >> 2);
11128 // ...
11129 // x = x | (x >>16);
11130 // x = x | (x >>32); // for 64-bit input
11131 // return popcount(~x);
11132 //
11133 // Ref: "Hacker's Delight" by Henry Warren
11134 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
11135 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
11136 Op = DAG.getNode(ISD::OR, dl, VT, Op,
11137 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
11138 }
11139 Op = DAG.getNOT(dl, Op, VT);
11140 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
11141}
11142
11144 SDLoc dl(Node);
11145 EVT VT = Node->getValueType(0);
11146 SDValue Op = DAG.getFreeze(Node->getOperand(0));
11147 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11148
11149 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
11150 // This transforms the sign bits into leading zeros that can be counted.
11151 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
11152 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
11153 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
11154 SDValue Shl =
11155 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11156 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
11157 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
11158}
11159
11161 const SDLoc &DL, EVT VT, SDValue Op,
11162 unsigned BitWidth) const {
11163 if (BitWidth != 32 && BitWidth != 64)
11164 return SDValue();
11165
11166 const DataLayout &TD = DAG.getDataLayout();
11168 return SDValue();
11169
11170 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
11171 : APInt(64, 0x0218A392CD3D5DBFULL);
11172 MachinePointerInfo PtrInfo =
11174 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
11175 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11176 SDValue Lookup = DAG.getNode(
11177 ISD::SRL, DL, VT,
11178 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
11179 DAG.getConstant(DeBruijn, DL, VT)),
11180 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11182
11184 for (unsigned i = 0; i < BitWidth; i++) {
11185 APInt Shl = DeBruijn.shl(i);
11186 APInt Lshr = Shl.lshr(ShiftAmt);
11187 Table[Lshr.getZExtValue()] = i;
11188 }
11189
11190 // Create a ConstantArray in Constant Pool
11191 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11192 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11193 TD.getPrefTypeAlign(CA->getType()));
11194 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11195 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11196 PtrInfo, MVT::i8);
11197 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11198 return ExtLoad;
11199
11200 EVT SetCCVT =
11201 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11202 SDValue Zero = DAG.getConstant(0, DL, VT);
11203 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11204 return DAG.getSelect(DL, VT, SrcIsZero,
11205 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11206}
11207
11209 SDLoc dl(Node);
11210 EVT VT = Node->getValueType(0);
11211 SDValue Op = Node->getOperand(0);
11212 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11213
11214 // If the non-ZERO_POISON version is supported we can use that instead.
11215 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11217 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11218
11219 // If the ZERO_POISON version is supported use that and handle the zero case.
11221 EVT SetCCVT =
11222 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11223 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11224 SDValue Zero = DAG.getConstant(0, dl, VT);
11225 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11226 return DAG.getSelect(dl, VT, SrcIsZero,
11227 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11228 }
11229
11230 // Only expand vector types if we have the appropriate vector bit operations.
11231 // This includes the operations needed to expand CTPOP if it isn't supported.
11232 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11235 !canExpandVectorCTPOP(*this, VT)) ||
11239 return SDValue();
11240
11241 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11242 // to be expanded or converted to a libcall.
11245 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11246 return V;
11247
11248 bool UseCTLZ =
11250
11251 // When only ctlz is available and the operand is nonzero we can use:
11252 // { return nlz(x & -x) ^ 31; }
11253 // which is more efficient than:
11254 // { return 32 - nlz(~x & (x - 1)); }.
11255 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11256 SDValue LowestBit =
11257 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11258 return DAG.getNode(ISD::XOR, dl, VT,
11259 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11260 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11261 }
11262
11263 // If ctpop is available, we use:
11264 // { return popcount(~x & (x-1)); }
11265 // If the target has ctlz but not ctpop, we use:
11266 // { return 32 - nlz(~x & (x-1)); }
11267 // Ref: "Hacker's Delight" by Henry Warren
11268 SDValue Tmp = DAG.getNode(
11269 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11270 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11271
11272 if (UseCTLZ)
11273 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11274 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11275
11276 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11277}
11278
11280 SelectionDAG &DAG) const {
11281 // %cond = to_bool_vec %source
11282 // %splat = splat /*val=*/VL
11283 // %tz = step_vector
11284 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11285 // %r = vp.reduce.umin %v
11286 SDLoc DL(N);
11287 SDValue Source = N->getOperand(0);
11288 SDValue Mask = N->getOperand(1);
11289 SDValue EVL = N->getOperand(2);
11290 EVT SrcVT = Source.getValueType();
11291 EVT ResVT = N->getValueType(0);
11292 EVT ResVecVT =
11293 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11294
11295 // Convert to boolean vector.
11296 if (SrcVT.getScalarType() != MVT::i1) {
11297 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11298 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11299 SrcVT.getVectorElementCount());
11300 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11301 }
11302
11303 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11304 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11305 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11306 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11307 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11308}
11309
11310/// Returns a type-legalized version of \p Mask as the first item in the
11311/// pair. The second item contains a type-legalized step vector that's
11312/// guaranteed to fit the number of elements in \p Mask.
11313/// If the stepvector would require splitting, returns an empty SDValue
11314/// as the second item to signal that the operation should be split instead.
11315static std::pair<SDValue, SDValue>
11317 SelectionDAG &DAG) {
11318 EVT MaskVT = Mask.getValueType();
11319 EVT BoolVT = MaskVT.getScalarType();
11320
11321 // Find a suitable type for a stepvector.
11322 // If zero is poison, we can assume the upper limit of the result is VF-1.
11323 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11324 if (MaskVT.isScalableVector())
11325 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11326 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11327 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11328 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11329 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11330 // If the step vector element type is smaller than the mask element type,
11331 // use the mask type directly to avoid widening issues.
11332 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11333 EVT StepVT = MVT::getIntegerVT(EltWidth);
11334 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11335
11336 // If promotion or widening is required to make the type legal, do it here.
11337 // Promotion of integers within LegalizeVectorOps is looking for types of
11338 // the same size but with a smaller number of larger elements, not the usual
11339 // larger size with the same number of larger elements.
11341 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11342 SDValue StepVec;
11343 if (TypeAction == TargetLowering::TypePromoteInteger) {
11344 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11345 StepVec = DAG.getStepVector(DL, StepVecVT);
11346 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11347 // For widening, the element count changes. Create a step vector with only
11348 // the original elements valid and zeros for padding. Also widen the mask.
11349 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11350 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11351
11352 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11353 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11354 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11355 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11356
11357 // Widen mask: pad with zeros.
11358 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11359 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11360 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11361 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11362 // The stepvector type would require splitting. Signal to the caller
11363 // that the operation should be split instead of expanded.
11364 return {Mask, SDValue()};
11365 } else {
11366 StepVec = DAG.getStepVector(DL, StepVecVT);
11367 }
11368
11369 return {Mask, StepVec};
11370}
11371
11373 SelectionDAG &DAG) const {
11374 SDLoc DL(N);
11375 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11376 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11377
11378 // If StepVec is empty, the stepvector would require splitting.
11379 // Split the operation instead and let it be recursively legalized.
11380 if (!StepVec) {
11381 EVT MaskVT = N->getOperand(0).getValueType();
11382 EVT ResVT = N->getValueType(0);
11383
11384 // Split the mask
11385 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11386 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11387
11388 // Create split VECTOR_FIND_LAST_ACTIVE operations
11389 SDValue LoResult =
11390 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11391 SDValue HiResult =
11392 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11393
11394 // Check if any lane is active in the high mask.
11395 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11397 AnyHiActive, DL,
11398 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11399 MVT::i1);
11400
11401 // Adjust HiResult by adding the number of elements in Lo
11402 SDValue LoNumElts =
11403 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11404 SDValue AdjustedHiResult =
11405 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11406
11407 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11408 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11409 LoResult);
11410 }
11411
11412 EVT StepVecVT = StepVec.getValueType();
11413 EVT StepVT = StepVec.getValueType().getVectorElementType();
11414
11415 // Zero out lanes with inactive elements, then find the highest remaining
11416 // value from the stepvector.
11417 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11418 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11419 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11420 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11421}
11422
11424 SelectionDAG &DAG) const {
11425 SDLoc DL(N);
11426 EVT VT = N->getValueType(0);
11427 SDValue SourceValue = N->getOperand(0);
11428 SDValue SinkValue = N->getOperand(1);
11429 SDValue EltSizeInBytes = N->getOperand(2);
11430
11431 // Note: The lane offset is scalable if the mask is scalable.
11432 ElementCount LaneOffsetEC =
11433 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11434
11435 EVT AddrVT = SourceValue->getValueType(0);
11436 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11437
11438 EVT CmpVT =
11439 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11440
11441 // Unsigned compare: Source >= Sink.
11442 SDValue SourceAheadOfOrEqualToSink =
11443 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11444
11445 // Take the difference between the pointers and divided by the element size,
11446 // to see how many lanes separate them.
11447 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11448
11449 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11450 if (IsReadAfterWrite)
11451 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11452 DAG.getNegative(Diff, DL, AddrVT), Diff);
11453
11454 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11455
11456 // The pointers do not alias if:
11457 // - Source >= Sink (WAR_MASK)
11458 // - Source == Sink (RAW_MASK)
11459 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11460 if (IsReadAfterWrite)
11461 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11462
11463 // The pointers do not alias if:
11464 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11465 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11466 SDValue MaskN = DAG.getSelect(
11467 DL, AddrVT, NoAlias,
11469 AddrVT),
11470 Diff);
11471
11472 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11473}
11474
11476 bool IsNegative) const {
11477 SDLoc dl(N);
11478 EVT VT = N->getValueType(0);
11479 SDValue Op = N->getOperand(0);
11480
11481 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11482 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11484 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11485 if (IsNegative)
11486 return DAG.getNegative(AbsVal, dl, VT);
11487 return AbsVal;
11488 }
11489
11490 // abs(x) -> smax(x,sub(0,x))
11491 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11493 SDValue Zero = DAG.getConstant(0, dl, VT);
11494 Op = DAG.getFreeze(Op);
11495 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11496 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11497 }
11498
11499 // abs(x) -> umin(x,sub(0,x))
11500 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11502 SDValue Zero = DAG.getConstant(0, dl, VT);
11503 Op = DAG.getFreeze(Op);
11504 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11505 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11506 }
11507
11508 // 0 - abs(x) -> smin(x, sub(0,x))
11509 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11511 SDValue Zero = DAG.getConstant(0, dl, VT);
11512 Op = DAG.getFreeze(Op);
11513 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11514 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11515 }
11516
11517 // Only expand vector types if we have the appropriate vector operations.
11518 if (VT.isVector() &&
11520 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11521 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11523 return SDValue();
11524
11525 Op = DAG.getFreeze(Op);
11526 SDValue Shift = DAG.getNode(
11527 ISD::SRA, dl, VT, Op,
11528 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11529 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11530
11531 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11532 if (!IsNegative)
11533 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11534
11535 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11536 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11537}
11538
11540 SDLoc dl(N);
11541 EVT VT = N->getValueType(0);
11542 SDValue LHS = N->getOperand(0);
11543 SDValue RHS = N->getOperand(1);
11544 bool IsSigned = N->getOpcode() == ISD::ABDS;
11545
11546 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11547 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11548 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11549 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11550 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11551 LHS = DAG.getFreeze(LHS);
11552 RHS = DAG.getFreeze(RHS);
11553 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11554 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11555 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11556 }
11557
11558 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11559 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11560 LHS = DAG.getFreeze(LHS);
11561 RHS = DAG.getFreeze(RHS);
11562 return DAG.getNode(ISD::OR, dl, VT,
11563 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11564 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11565 }
11566
11567 // If the subtract doesn't overflow then just use abs(sub())
11568 bool IsNonNegative = DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS);
11569
11570 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, LHS, RHS))
11571 return DAG.getNode(ISD::ABS, dl, VT,
11572 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11573
11574 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, RHS, LHS))
11575 return DAG.getNode(ISD::ABS, dl, VT,
11576 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11577
11578 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11580 LHS = DAG.getFreeze(LHS);
11581 RHS = DAG.getFreeze(RHS);
11582 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11583
11584 // Branchless expansion iff cmp result is allbits:
11585 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11586 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11587 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11588 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11589 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11590 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11591 }
11592
11593 // Similar to the branchless expansion, if we don't prefer selects, use the
11594 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11595 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11596 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11597 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11599 SDValue USubO =
11600 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11601 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11602 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11603 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11604 }
11605
11606 // FIXME: Should really try to split the vector in case it's legal on a
11607 // subvector.
11609 return DAG.UnrollVectorOp(N);
11610
11611 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11612 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11613 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11614 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11615}
11616
11618 SDLoc dl(N);
11619 EVT VT = N->getValueType(0);
11620 SDValue LHS = N->getOperand(0);
11621 SDValue RHS = N->getOperand(1);
11622
11623 unsigned Opc = N->getOpcode();
11624 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11625 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11626 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11627 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11628 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11629 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11631 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11632 "Unknown AVG node");
11633
11634 // If the operands are already extended, we can add+shift.
11635 bool IsExt =
11636 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11637 DAG.ComputeNumSignBits(RHS) >= 2) ||
11638 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11639 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11640 if (IsExt) {
11641 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11642 if (!IsFloor)
11643 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11644 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11645 DAG.getShiftAmountConstant(1, VT, dl));
11646 }
11647
11648 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11649 if (VT.isScalarInteger()) {
11650 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11651 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11652 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11653 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11654 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11655 if (!IsFloor)
11656 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11657 DAG.getConstant(1, dl, ExtVT));
11658 // Just use SRL as we will be truncating away the extended sign bits.
11659 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11660 DAG.getShiftAmountConstant(1, ExtVT, dl));
11661 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11662 }
11663 }
11664
11665 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11666 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11669 SDValue UAddWithOverflow =
11670 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11671
11672 SDValue Sum = UAddWithOverflow.getValue(0);
11673 SDValue Overflow = UAddWithOverflow.getValue(1);
11674
11675 // Right shift the sum by 1
11676 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
11677 DAG.getShiftAmountConstant(1, VT, dl));
11678
11679 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
11680 SDValue OverflowShl = DAG.getNode(
11681 ISD::SHL, dl, VT, ZeroExtOverflow,
11682 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11683
11684 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
11685 }
11686
11687 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
11688 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
11689 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
11690 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
11691 LHS = DAG.getFreeze(LHS);
11692 RHS = DAG.getFreeze(RHS);
11693 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
11694 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
11695 SDValue Shift =
11696 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11697 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
11698}
11699
11701 SDLoc dl(N);
11702 EVT VT = N->getValueType(0);
11703 SDValue Op = N->getOperand(0);
11704
11705 if (!VT.isSimple())
11706 return SDValue();
11707
11708 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11709 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11710 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11711 default:
11712 return SDValue();
11713 case MVT::i16:
11714 // Use a rotate by 8. This can be further expanded if necessary.
11715 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11716 case MVT::i32:
11717 // This is meant for ARM specifically, which has ROTR but no ROTL.
11718 // t = x ^ rotr(x, 16)
11719 // t = bic(t, 0x00ff0000)
11720 // t = lshr(t, 8)
11721 // x = t ^ rotr(x, 8)
11723 SDValue Rotr16 =
11724 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
11725 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
11726 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
11727 DAG.getConstant(0xFF00FFFF, dl, VT));
11728 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
11729 SDValue Rotr8 =
11730 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11731 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
11732 }
11733 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11734 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
11735 DAG.getConstant(0xFF00, dl, VT));
11736 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
11737 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11738 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
11739 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11740 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11741 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11742 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11743 case MVT::i64:
11744 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11745 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
11746 DAG.getConstant(255ULL<<8, dl, VT));
11747 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
11748 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
11749 DAG.getConstant(255ULL<<16, dl, VT));
11750 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
11751 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
11752 DAG.getConstant(255ULL<<24, dl, VT));
11753 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
11754 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11755 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
11756 DAG.getConstant(255ULL<<24, dl, VT));
11757 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11758 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
11759 DAG.getConstant(255ULL<<16, dl, VT));
11760 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
11761 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
11762 DAG.getConstant(255ULL<<8, dl, VT));
11763 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11764 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
11765 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
11766 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11767 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11768 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
11769 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11770 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
11771 }
11772}
11773
11775 SDLoc dl(N);
11776 EVT VT = N->getValueType(0);
11777 SDValue Op = N->getOperand(0);
11778 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11779 unsigned Sz = VT.getScalarSizeInBits();
11780
11781 SDValue Tmp, Tmp2, Tmp3;
11782
11783 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
11784 // and finally the i1 pairs.
11785 // TODO: We can easily support i4/i2 legal types if any target ever does.
11786 if (Sz >= 8 && isPowerOf2_32(Sz)) {
11787 // Create the masks - repeating the pattern every byte.
11788 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
11789 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
11790 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
11791
11792 // BSWAP if the type is wider than a single byte.
11793 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
11794
11795 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
11796 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
11797 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
11798 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
11799 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
11800 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11801
11802 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
11803 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
11804 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
11805 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
11806 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
11807 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11808
11809 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
11810 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
11811 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
11812 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
11813 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
11814 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11815 return Tmp;
11816 }
11817
11818 Tmp = DAG.getConstant(0, dl, VT);
11819 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
11820 if (I < J)
11821 Tmp2 =
11822 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
11823 else
11824 Tmp2 =
11825 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
11826
11827 APInt Shift = APInt::getOneBitSet(Sz, J);
11828 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
11829 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
11830 }
11831
11832 return Tmp;
11833}
11834
11835std::pair<SDValue, SDValue>
11837 SelectionDAG &DAG) const {
11838 SDLoc SL(LD);
11839 SDValue Chain = LD->getChain();
11840 SDValue BasePTR = LD->getBasePtr();
11841 EVT SrcVT = LD->getMemoryVT();
11842 EVT DstVT = LD->getValueType(0);
11843 ISD::LoadExtType ExtType = LD->getExtensionType();
11844
11845 if (SrcVT.isScalableVector())
11846 report_fatal_error("Cannot scalarize scalable vector loads");
11847
11848 unsigned NumElem = SrcVT.getVectorNumElements();
11849
11850 EVT SrcEltVT = SrcVT.getScalarType();
11851 EVT DstEltVT = DstVT.getScalarType();
11852
11853 // A vector must always be stored in memory as-is, i.e. without any padding
11854 // between the elements, since various code depend on it, e.g. in the
11855 // handling of a bitcast of a vector type to int, which may be done with a
11856 // vector store followed by an integer load. A vector that does not have
11857 // elements that are byte-sized must therefore be stored as an integer
11858 // built out of the extracted vector elements.
11859 if (!SrcEltVT.isByteSized()) {
11860 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
11861 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
11862
11863 unsigned NumSrcBits = SrcVT.getSizeInBits();
11864 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
11865
11866 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
11867 SDValue SrcEltBitMask = DAG.getConstant(
11868 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
11869
11870 // Load the whole vector and avoid masking off the top bits as it makes
11871 // the codegen worse.
11872 SDValue Load =
11873 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
11874 LD->getPointerInfo(), SrcIntVT, LD->getBaseAlign(),
11875 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11876
11878 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11879 unsigned ShiftIntoIdx =
11880 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
11881 SDValue ShiftAmount = DAG.getShiftAmountConstant(
11882 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
11883 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
11884 SDValue Elt =
11885 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
11886 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
11887
11888 if (ExtType != ISD::NON_EXTLOAD) {
11889 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
11890 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
11891 }
11892
11893 Vals.push_back(Scalar);
11894 }
11895
11896 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
11897 return std::make_pair(Value, Load.getValue(1));
11898 }
11899
11900 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
11901 assert(SrcEltVT.isByteSized());
11902
11904 SmallVector<SDValue, 8> LoadChains;
11905
11906 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11907 SDValue ScalarLoad = DAG.getExtLoad(
11908 ExtType, SL, DstEltVT, Chain, BasePTR,
11909 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
11910 LD->getBaseAlign(), LD->getMemOperand()->getFlags(), LD->getAAInfo());
11911
11912 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
11913
11914 Vals.push_back(ScalarLoad.getValue(0));
11915 LoadChains.push_back(ScalarLoad.getValue(1));
11916 }
11917
11918 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
11919 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
11920
11921 return std::make_pair(Value, NewChain);
11922}
11923
11925 SelectionDAG &DAG) const {
11926 SDLoc SL(ST);
11927
11928 SDValue Chain = ST->getChain();
11929 SDValue BasePtr = ST->getBasePtr();
11930 SDValue Value = ST->getValue();
11931 EVT StVT = ST->getMemoryVT();
11932
11933 if (StVT.isScalableVector())
11934 report_fatal_error("Cannot scalarize scalable vector stores");
11935
11936 // The type of the data we want to save
11937 EVT RegVT = Value.getValueType();
11938 EVT RegSclVT = RegVT.getScalarType();
11939
11940 // The type of data as saved in memory.
11941 EVT MemSclVT = StVT.getScalarType();
11942
11943 unsigned NumElem = StVT.getVectorNumElements();
11944
11945 // A vector must always be stored in memory as-is, i.e. without any padding
11946 // between the elements, since various code depend on it, e.g. in the
11947 // handling of a bitcast of a vector type to int, which may be done with a
11948 // vector store followed by an integer load. A vector that does not have
11949 // elements that are byte-sized must therefore be stored as an integer
11950 // built out of the extracted vector elements.
11951 if (!MemSclVT.isByteSized()) {
11952 unsigned NumBits = StVT.getSizeInBits();
11953 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
11954
11955 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
11956
11957 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11958 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
11959 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
11960 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
11961 unsigned ShiftIntoIdx =
11962 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
11963 SDValue ShiftAmount =
11964 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
11965 SDValue ShiftedElt =
11966 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
11967 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
11968 }
11969
11970 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
11971 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
11972 ST->getAAInfo());
11973 }
11974
11975 // Store Stride in bytes
11976 unsigned Stride = MemSclVT.getSizeInBits() / 8;
11977 assert(Stride && "Zero stride!");
11978 // Extract each of the elements from the original vector and save them into
11979 // memory individually.
11981 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11982 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
11983
11984 SDValue Ptr =
11985 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
11986
11987 // This scalar TruncStore may be illegal, but we legalize it later.
11989 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
11990 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
11991 ST->getAAInfo());
11992
11993 Stores.push_back(Store);
11994 }
11995
11996 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
11997}
11998
11999std::pair<SDValue, SDValue>
12001 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
12002 "unaligned indexed loads not implemented!");
12003 SDValue Chain = LD->getChain();
12004 SDValue Ptr = LD->getBasePtr();
12005 EVT VT = LD->getValueType(0);
12006 EVT LoadedVT = LD->getMemoryVT();
12007 SDLoc dl(LD);
12008 auto &MF = DAG.getMachineFunction();
12009
12010 if (VT.isFloatingPoint() || VT.isVector()) {
12011 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
12012 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
12013 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
12014 LoadedVT.isVector()) {
12015 // Scalarize the load and let the individual components be handled.
12016 return scalarizeVectorLoad(LD, DAG);
12017 }
12018
12019 // Expand to a (misaligned) integer load of the same size,
12020 // then bitconvert to floating point or vector.
12021 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
12022 LD->getMemOperand());
12023 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
12024 if (LoadedVT != VT)
12025 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
12026 ISD::ANY_EXTEND, dl, VT, Result);
12027
12028 return std::make_pair(Result, newLoad.getValue(1));
12029 }
12030
12031 // Copy the value to a (aligned) stack slot using (unaligned) integer
12032 // loads and stores, then do a (aligned) load from the stack slot.
12033 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
12034 unsigned LoadedBytes = LoadedVT.getStoreSize();
12035 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12036 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
12037
12038 // Make sure the stack slot is also aligned for the register type.
12039 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
12040 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
12042 SDValue StackPtr = StackBase;
12043 unsigned Offset = 0;
12044
12045 EVT PtrVT = Ptr.getValueType();
12046 EVT StackPtrVT = StackPtr.getValueType();
12047
12048 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12049 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12050
12051 // Do all but one copies using the full register width.
12052 for (unsigned i = 1; i < NumRegs; i++) {
12053 // Load one integer register's worth from the original location.
12054 SDValue Load = DAG.getLoad(
12055 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12056 LD->getBaseAlign(), LD->getMemOperand()->getFlags(), LD->getAAInfo());
12057 // Follow the load with a store to the stack slot. Remember the store.
12058 Stores.push_back(DAG.getStore(
12059 Load.getValue(1), dl, Load, StackPtr,
12060 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12061 // Increment the pointers.
12062 Offset += RegBytes;
12063
12064 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12065 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12066 }
12067
12068 // The last copy may be partial. Do an extending load.
12069 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12070 8 * (LoadedBytes - Offset));
12071 SDValue Load = DAG.getExtLoad(
12072 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12073 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12074 LD->getMemOperand()->getFlags(), LD->getAAInfo());
12075 // Follow the load with a store to the stack slot. Remember the store.
12076 // On big-endian machines this requires a truncating store to ensure
12077 // that the bits end up in the right place.
12078 Stores.push_back(DAG.getTruncStore(
12079 Load.getValue(1), dl, Load, StackPtr,
12080 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12081
12082 // The order of the stores doesn't matter - say it with a TokenFactor.
12083 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12084
12085 // Finally, perform the original load only redirected to the stack slot.
12086 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12087 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12088 LoadedVT);
12089
12090 // Callers expect a MERGE_VALUES node.
12091 return std::make_pair(Load, TF);
12092 }
12093
12094 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12095 "Unaligned load of unsupported type.");
12096
12097 // Compute the new VT that is half the size of the old one. This is an
12098 // integer MVT.
12099 unsigned NumBits = LoadedVT.getSizeInBits();
12100 EVT NewLoadedVT;
12101 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12102 NumBits >>= 1;
12103
12104 Align Alignment = LD->getBaseAlign();
12105 unsigned IncrementSize = NumBits / 8;
12106 ISD::LoadExtType HiExtType = LD->getExtensionType();
12107
12108 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12109 if (HiExtType == ISD::NON_EXTLOAD)
12110 HiExtType = ISD::ZEXTLOAD;
12111
12112 // Load the value in two parts
12113 SDValue Lo, Hi;
12114 if (DAG.getDataLayout().isLittleEndian()) {
12115 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12116 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12117 LD->getAAInfo());
12118
12119 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12120 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12121 LD->getPointerInfo().getWithOffset(IncrementSize),
12122 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12123 LD->getAAInfo());
12124 } else {
12125 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12126 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12127 LD->getAAInfo());
12128
12129 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12130 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12131 LD->getPointerInfo().getWithOffset(IncrementSize),
12132 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12133 LD->getAAInfo());
12134 }
12135
12136 // aggregate the two parts
12137 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12138 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12139 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12140
12141 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12142 Hi.getValue(1));
12143
12144 return std::make_pair(Result, TF);
12145}
12146
12148 SelectionDAG &DAG) const {
12149 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12150 "unaligned indexed stores not implemented!");
12151 SDValue Chain = ST->getChain();
12152 SDValue Ptr = ST->getBasePtr();
12153 SDValue Val = ST->getValue();
12154 EVT VT = Val.getValueType();
12155 Align Alignment = ST->getBaseAlign();
12156 auto &MF = DAG.getMachineFunction();
12157 EVT StoreMemVT = ST->getMemoryVT();
12158
12159 SDLoc dl(ST);
12160 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12161 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12162 if (isTypeLegal(intVT)) {
12163 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12164 StoreMemVT.isVector()) {
12165 // Scalarize the store and let the individual components be handled.
12166 SDValue Result = scalarizeVectorStore(ST, DAG);
12167 return Result;
12168 }
12169 // Expand to a bitconvert of the value to the integer type of the
12170 // same size, then a (misaligned) int store.
12171 // FIXME: Does not handle truncating floating point stores!
12172 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12173 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12174 Alignment, ST->getMemOperand()->getFlags());
12175 return Result;
12176 }
12177 // Do a (aligned) store to a stack slot, then copy from the stack slot
12178 // to the final destination using (unaligned) integer loads and stores.
12179 MVT RegVT = getRegisterType(
12180 *DAG.getContext(),
12181 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12182 EVT PtrVT = Ptr.getValueType();
12183 unsigned StoredBytes = StoreMemVT.getStoreSize();
12184 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12185 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12186
12187 // Make sure the stack slot is also aligned for the register type.
12188 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12189 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12190
12191 // Perform the original store, only redirected to the stack slot.
12193 Chain, dl, Val, StackPtr,
12194 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12195
12196 EVT StackPtrVT = StackPtr.getValueType();
12197
12198 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12199 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12201 unsigned Offset = 0;
12202
12203 // Do all but one copies using the full register width.
12204 for (unsigned i = 1; i < NumRegs; i++) {
12205 // Load one integer register's worth from the stack slot.
12206 SDValue Load = DAG.getLoad(
12207 RegVT, dl, Store, StackPtr,
12208 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12209 // Store it to the final location. Remember the store.
12210 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
12211 ST->getPointerInfo().getWithOffset(Offset),
12212 ST->getBaseAlign(),
12213 ST->getMemOperand()->getFlags()));
12214 // Increment the pointers.
12215 Offset += RegBytes;
12216 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12217 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12218 }
12219
12220 // The last store may be partial. Do a truncating store. On big-endian
12221 // machines this requires an extending load from the stack slot to ensure
12222 // that the bits are in the right place.
12223 EVT LoadMemVT =
12224 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12225
12226 // Load from the stack slot.
12227 SDValue Load = DAG.getExtLoad(
12228 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12229 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12230
12231 Stores.push_back(DAG.getTruncStore(
12232 Load.getValue(1), dl, Load, Ptr,
12233 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12234 ST->getBaseAlign(), ST->getMemOperand()->getFlags(), ST->getAAInfo()));
12235 // The order of the stores doesn't matter - say it with a TokenFactor.
12236 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12237 return Result;
12238 }
12239
12240 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12241 "Unaligned store of unknown type.");
12242 // Get the half-size VT
12243 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12244 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12245 unsigned IncrementSize = NumBits / 8;
12246
12247 // Divide the stored value in two parts.
12248 SDValue ShiftAmount =
12249 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12250 SDValue Lo = Val;
12251 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12252 // fold and not use the upper bits. A smaller constant may be easier to
12253 // materialize.
12254 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12255 Lo = DAG.getNode(
12256 ISD::AND, dl, VT, Lo,
12257 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12258 VT));
12259 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12260
12261 // Store the two parts
12262 SDValue Store1, Store2;
12263 Store1 = DAG.getTruncStore(Chain, dl,
12264 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
12265 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
12266 ST->getMemOperand()->getFlags());
12267
12268 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12269 Store2 = DAG.getTruncStore(
12270 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12271 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12272 ST->getMemOperand()->getFlags(), ST->getAAInfo());
12273
12274 SDValue Result =
12275 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12276 return Result;
12277}
12278
12279SDValue
12281 const SDLoc &DL, EVT DataVT,
12282 SelectionDAG &DAG,
12283 bool IsCompressedMemory) const {
12285 EVT AddrVT = Addr.getValueType();
12286 EVT MaskVT = Mask.getValueType();
12287 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12288 "Incompatible types of Data and Mask");
12289 if (IsCompressedMemory) {
12290 // Incrementing the pointer according to number of '1's in the mask.
12291 if (DataVT.isScalableVector()) {
12292 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12293 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12294 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12295 } else {
12296 EVT MaskIntVT =
12297 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12298 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12299 if (MaskIntVT.getSizeInBits() < 32) {
12300 MaskInIntReg =
12301 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12302 MaskIntVT = MVT::i32;
12303 }
12304 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12305 }
12306 // Scale is an element size in bytes.
12307 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12308 AddrVT);
12309 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12310 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12311 } else
12312 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12313
12314 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12315}
12316
12318 EVT VecVT, const SDLoc &dl,
12319 ElementCount SubEC) {
12320 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12321 "Cannot index a scalable vector within a fixed-width vector");
12322
12323 unsigned NElts = VecVT.getVectorMinNumElements();
12324 unsigned NumSubElts = SubEC.getKnownMinValue();
12325 EVT IdxVT = Idx.getValueType();
12326
12327 if (VecVT.isScalableVector() && !SubEC.isScalable()) {
12328 // If this is a constant index and we know the value plus the number of the
12329 // elements in the subvector minus one is less than the minimum number of
12330 // elements then it's safe to return Idx.
12331 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
12332 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
12333 return Idx;
12334 SDValue VS =
12335 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
12336 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
12337 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
12338 DAG.getConstant(NumSubElts, dl, IdxVT));
12339 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
12340 }
12341 if (isPowerOf2_32(NElts) && NumSubElts == 1) {
12343 return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
12344 DAG.getConstant(Imm, dl, IdxVT));
12345 }
12346 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
12347 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
12348 DAG.getConstant(MaxIndex, dl, IdxVT));
12349}
12350
12351SDValue
12353 EVT VecVT, SDValue Index,
12354 const SDNodeFlags PtrArithFlags) const {
12356 DAG, VecPtr, VecVT,
12358 Index, PtrArithFlags);
12359}
12360
12361SDValue
12363 EVT VecVT, EVT SubVecVT, SDValue Index,
12364 const SDNodeFlags PtrArithFlags) const {
12365 SDLoc dl(Index);
12366 // Make sure the index type is big enough to compute in.
12367 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12368
12369 EVT EltVT = VecVT.getVectorElementType();
12370
12371 // Calculate the element offset and add it to the pointer.
12372 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12373 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12374 "Converting bits to bytes lost precision");
12375 assert(SubVecVT.getVectorElementType() == EltVT &&
12376 "Sub-vector must be a vector with matching element type");
12377 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12378 SubVecVT.getVectorElementCount());
12379
12380 EVT IdxVT = Index.getValueType();
12381 if (SubVecVT.isScalableVector())
12382 Index =
12383 DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12384 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
12385
12386 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12387 DAG.getConstant(EltSize, dl, IdxVT));
12388 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12389}
12390
12391//===----------------------------------------------------------------------===//
12392// Implementation of Emulated TLS Model
12393//===----------------------------------------------------------------------===//
12394
12396 SelectionDAG &DAG) const {
12397 // Access to address of TLS varialbe xyz is lowered to a function call:
12398 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12399 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12400 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12401 SDLoc dl(GA);
12402
12403 ArgListTy Args;
12404 const GlobalValue *GV =
12406 SmallString<32> NameString("__emutls_v.");
12407 NameString += GV->getName();
12408 StringRef EmuTlsVarName(NameString);
12409 const GlobalVariable *EmuTlsVar =
12410 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12411 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12412 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12413
12414 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12415
12417 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12418 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12419 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12420
12421 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12422 // At last for X86 targets, maybe good for other targets too?
12424 MFI.setAdjustsStack(true); // Is this only for X86 target?
12425 MFI.setHasCalls(true);
12426
12427 assert((GA->getOffset() == 0) &&
12428 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12429 return CallResult.first;
12430}
12431
12433 SelectionDAG &DAG) const {
12434 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12435 if (!isCtlzFast())
12436 return SDValue();
12437 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12438 SDLoc dl(Op);
12439 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12440 EVT VT = Op.getOperand(0).getValueType();
12441 SDValue Zext = Op.getOperand(0);
12442 if (VT.bitsLT(MVT::i32)) {
12443 VT = MVT::i32;
12444 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12445 }
12446 unsigned Log2b = Log2_32(VT.getSizeInBits());
12447 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12448 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12449 DAG.getConstant(Log2b, dl, MVT::i32));
12450 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12451 }
12452 return SDValue();
12453}
12454
12456 SDValue Op0 = Node->getOperand(0);
12457 SDValue Op1 = Node->getOperand(1);
12458 EVT VT = Op0.getValueType();
12459 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12460 unsigned Opcode = Node->getOpcode();
12461 SDLoc DL(Node);
12462
12463 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12464 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12465 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12466 DAG.SignBitIsZero(Op1))
12467 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12468
12469 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12470 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12472 Op0 = DAG.getFreeze(Op0);
12473 SDValue Zero = DAG.getConstant(0, DL, VT);
12474 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12475 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12476 }
12477
12478 // umin(x,y) -> sub(x,usubsat(x,y))
12479 // TODO: Missing freeze(Op0)?
12480 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12482 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12483 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12484 }
12485
12486 // umax(x,y) -> add(x,usubsat(y,x))
12487 // TODO: Missing freeze(Op0)?
12488 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12490 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12491 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12492 }
12493
12494 // FIXME: Should really try to split the vector in case it's legal on a
12495 // subvector.
12497 return DAG.UnrollVectorOp(Node);
12498
12499 // Attempt to find an existing SETCC node that we can reuse.
12500 // TODO: Do we need a generic doesSETCCNodeExist?
12501 // TODO: Missing freeze(Op0)/freeze(Op1)?
12502 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12503 ISD::CondCode PrefCommuteCC,
12504 ISD::CondCode AltCommuteCC) {
12505 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12506 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12507 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12508 {Op0, Op1, DAG.getCondCode(CC)})) {
12509 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12510 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12511 }
12512 }
12513 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12514 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12515 {Op0, Op1, DAG.getCondCode(CC)})) {
12516 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12517 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12518 }
12519 }
12520 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12521 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12522 };
12523
12524 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12525 // -> Y = (A < B) ? B : A
12526 // -> Y = (A >= B) ? A : B
12527 // -> Y = (A <= B) ? B : A
12528 switch (Opcode) {
12529 case ISD::SMAX:
12530 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12531 case ISD::SMIN:
12532 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12533 case ISD::UMAX:
12534 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12535 case ISD::UMIN:
12536 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12537 }
12538
12539 llvm_unreachable("How did we get here?");
12540}
12541
12543 unsigned Opcode = Node->getOpcode();
12544 SDValue LHS = Node->getOperand(0);
12545 SDValue RHS = Node->getOperand(1);
12546 EVT VT = LHS.getValueType();
12547 SDLoc dl(Node);
12548
12549 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12550 assert(VT.isInteger() && "Expected operands to be integers");
12551
12552 // usub.sat(a, b) -> umax(a, b) - b
12553 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12554 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12555 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12556 }
12557
12558 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12559 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12560 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12562 LHS = DAG.getFreeze(LHS);
12563 SDValue Zero = DAG.getConstant(0, dl, VT);
12564 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12565 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12566 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12567 Subtrahend =
12568 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12569 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12570 }
12571
12572 // uadd.sat(a, b) -> umin(a, ~b) + b
12573 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12574 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12575 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12576 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12577 }
12578
12579 unsigned OverflowOp;
12580 switch (Opcode) {
12581 case ISD::SADDSAT:
12582 OverflowOp = ISD::SADDO;
12583 break;
12584 case ISD::UADDSAT:
12585 OverflowOp = ISD::UADDO;
12586 break;
12587 case ISD::SSUBSAT:
12588 OverflowOp = ISD::SSUBO;
12589 break;
12590 case ISD::USUBSAT:
12591 OverflowOp = ISD::USUBO;
12592 break;
12593 default:
12594 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12595 "addition or subtraction node.");
12596 }
12597
12598 // FIXME: Should really try to split the vector in case it's legal on a
12599 // subvector.
12601 return DAG.UnrollVectorOp(Node);
12602
12603 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12604 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12605 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12606 SDValue SumDiff = Result.getValue(0);
12607 SDValue Overflow = Result.getValue(1);
12608 SDValue Zero = DAG.getConstant(0, dl, VT);
12609 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12610
12611 if (Opcode == ISD::UADDSAT) {
12613 // (LHS + RHS) | OverflowMask
12614 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12615 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12616 }
12617 // Overflow ? 0xffff.... : (LHS + RHS)
12618 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12619 }
12620
12621 if (Opcode == ISD::USUBSAT) {
12623 // (LHS - RHS) & ~OverflowMask
12624 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12625 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12626 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12627 }
12628 // Overflow ? 0 : (LHS - RHS)
12629 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12630 }
12631
12632 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12633 "Expected signed saturating add/sub opcode");
12634
12635 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12636 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12637
12638 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12639 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12640
12641 // If either of the operand signs are known, then they are guaranteed to
12642 // only saturate in one direction. If non-negative they will saturate
12643 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12644 //
12645 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12646 // sign of 'y' has to be flipped.
12647
12648 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12649 bool RHSIsNonNegative =
12650 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12651 if (LHSIsNonNegative || RHSIsNonNegative) {
12652 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12653 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12654 }
12655
12656 bool LHSIsNegative = KnownLHS.isNegative();
12657 bool RHSIsNegative =
12658 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12659 if (LHSIsNegative || RHSIsNegative) {
12660 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12661 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
12662 }
12663
12664 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
12665 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12666 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
12667 DAG.getConstant(BitWidth - 1, dl, VT));
12668 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
12669 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
12670}
12671
12673 unsigned Opcode = Node->getOpcode();
12674 SDValue LHS = Node->getOperand(0);
12675 SDValue RHS = Node->getOperand(1);
12676 EVT VT = LHS.getValueType();
12677 EVT ResVT = Node->getValueType(0);
12678 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12679 SDLoc dl(Node);
12680
12681 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
12682 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
12683 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
12684 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
12685
12686 // We can't perform arithmetic on i1 values. Extending them would
12687 // probably result in worse codegen, so let's just use two selects instead.
12688 // Some targets are also just better off using selects rather than subtraction
12689 // because one of the conditions can be merged with one of the selects.
12690 // And finally, if we don't know the contents of high bits of a boolean value
12691 // we can't perform any arithmetic either.
12693 BoolVT.getScalarSizeInBits() == 1 ||
12695 SDValue SelectZeroOrOne =
12696 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
12697 DAG.getConstant(0, dl, ResVT));
12698 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
12699 SelectZeroOrOne);
12700 }
12701
12703 std::swap(IsGT, IsLT);
12704 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
12705 ResVT);
12706}
12707
12709 unsigned Opcode = Node->getOpcode();
12710 bool IsSigned = Opcode == ISD::SSHLSAT;
12711 SDValue LHS = Node->getOperand(0);
12712 SDValue RHS = Node->getOperand(1);
12713 EVT VT = LHS.getValueType();
12714 SDLoc dl(Node);
12715
12716 assert((Node->getOpcode() == ISD::SSHLSAT ||
12717 Node->getOpcode() == ISD::USHLSAT) &&
12718 "Expected a SHLSAT opcode");
12719 assert(VT.isInteger() && "Expected operands to be integers");
12720
12722 return DAG.UnrollVectorOp(Node);
12723
12724 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
12725
12726 unsigned BW = VT.getScalarSizeInBits();
12727 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12728 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
12729 SDValue Orig =
12730 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
12731
12732 SDValue SatVal;
12733 if (IsSigned) {
12734 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
12735 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
12736 SDValue Cond =
12737 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
12738 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
12739 } else {
12740 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
12741 }
12742 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
12743 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
12744}
12745
12747 bool Signed, SDValue &Lo, SDValue &Hi,
12748 SDValue LHS, SDValue RHS,
12749 SDValue HiLHS, SDValue HiRHS) const {
12750 EVT VT = LHS.getValueType();
12751 assert(RHS.getValueType() == VT && "Mismatching operand types");
12752
12753 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
12754 assert((!Signed || !HiLHS) &&
12755 "Signed flag should only be set when HiLHS and RiRHS are null");
12756
12757 // We'll expand the multiplication by brute force because we have no other
12758 // options. This is a trivially-generalized version of the code from
12759 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
12760 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
12761 // sign bits while calculating the Hi half.
12762 unsigned Bits = VT.getScalarSizeInBits();
12763 unsigned HalfBits = Bits / 2;
12764 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
12765 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
12766 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
12767
12768 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
12769 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
12770
12771 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
12772 // This is always an unsigned shift.
12773 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
12774
12775 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
12776 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
12777 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
12778
12779 SDValue U =
12780 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
12781 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
12782 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
12783
12784 SDValue V =
12785 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
12786 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
12787
12788 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
12789 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
12790
12791 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
12792 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
12793
12794 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
12795 // the products to Hi.
12796 if (HiLHS) {
12797 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
12798 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
12799 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
12800 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
12801 }
12802}
12803
12805 bool Signed, const SDValue LHS,
12806 const SDValue RHS, SDValue &Lo,
12807 SDValue &Hi) const {
12808 EVT VT = LHS.getValueType();
12809 assert(RHS.getValueType() == VT && "Mismatching operand types");
12810 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12811 // We can fall back to a libcall with an illegal type for the MUL if we
12812 // have a libcall big enough.
12813 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
12814 if (WideVT == MVT::i16)
12815 LC = RTLIB::MUL_I16;
12816 else if (WideVT == MVT::i32)
12817 LC = RTLIB::MUL_I32;
12818 else if (WideVT == MVT::i64)
12819 LC = RTLIB::MUL_I64;
12820 else if (WideVT == MVT::i128)
12821 LC = RTLIB::MUL_I128;
12822
12823 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
12824 if (LibcallImpl == RTLIB::Unsupported) {
12825 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
12826 return;
12827 }
12828
12829 SDValue HiLHS, HiRHS;
12830 if (Signed) {
12831 // The high part is obtained by SRA'ing all but one of the bits of low
12832 // part.
12833 unsigned LoSize = VT.getFixedSizeInBits();
12834 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
12835 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
12836 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
12837 } else {
12838 HiLHS = DAG.getConstant(0, dl, VT);
12839 HiRHS = DAG.getConstant(0, dl, VT);
12840 }
12841
12842 // Attempt a libcall.
12843 SDValue Ret;
12845 CallOptions.setIsSigned(Signed);
12846 CallOptions.setIsPostTypeLegalization(true);
12848 // Halves of WideVT are packed into registers in different order
12849 // depending on platform endianness. This is usually handled by
12850 // the C calling convention, but we can't defer to it in
12851 // the legalizer.
12852 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
12853 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12854 } else {
12855 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
12856 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12857 }
12859 "Ret value is a collection of constituent nodes holding result.");
12860 if (DAG.getDataLayout().isLittleEndian()) {
12861 // Same as above.
12862 Lo = Ret.getOperand(0);
12863 Hi = Ret.getOperand(1);
12864 } else {
12865 Lo = Ret.getOperand(1);
12866 Hi = Ret.getOperand(0);
12867 }
12868}
12869
12870SDValue
12872 assert((Node->getOpcode() == ISD::SMULFIX ||
12873 Node->getOpcode() == ISD::UMULFIX ||
12874 Node->getOpcode() == ISD::SMULFIXSAT ||
12875 Node->getOpcode() == ISD::UMULFIXSAT) &&
12876 "Expected a fixed point multiplication opcode");
12877
12878 SDLoc dl(Node);
12879 SDValue LHS = Node->getOperand(0);
12880 SDValue RHS = Node->getOperand(1);
12881 EVT VT = LHS.getValueType();
12882 unsigned Scale = Node->getConstantOperandVal(2);
12883 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
12884 Node->getOpcode() == ISD::UMULFIXSAT);
12885 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
12886 Node->getOpcode() == ISD::SMULFIXSAT);
12887 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12888 unsigned VTSize = VT.getScalarSizeInBits();
12889
12890 if (!Scale) {
12891 // [us]mul.fix(a, b, 0) -> mul(a, b)
12892 if (!Saturating) {
12894 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
12895 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
12896 SDValue Result =
12897 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12898 SDValue Product = Result.getValue(0);
12899 SDValue Overflow = Result.getValue(1);
12900 SDValue Zero = DAG.getConstant(0, dl, VT);
12901
12902 APInt MinVal = APInt::getSignedMinValue(VTSize);
12903 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
12904 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12905 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12906 // Xor the inputs, if resulting sign bit is 0 the product will be
12907 // positive, else negative.
12908 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
12909 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
12910 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
12911 return DAG.getSelect(dl, VT, Overflow, Result, Product);
12912 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
12913 SDValue Result =
12914 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12915 SDValue Product = Result.getValue(0);
12916 SDValue Overflow = Result.getValue(1);
12917
12918 APInt MaxVal = APInt::getMaxValue(VTSize);
12919 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12920 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
12921 }
12922 }
12923
12924 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
12925 "Expected scale to be less than the number of bits if signed or at "
12926 "most the number of bits if unsigned.");
12927 assert(LHS.getValueType() == RHS.getValueType() &&
12928 "Expected both operands to be the same type");
12929
12930 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
12931 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
12932 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
12933 SDValue Val, ISD::CondCode CC) {
12934 if (VT.isVector())
12935 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
12936 Sat, Val);
12937 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
12938 };
12939
12940 // Get the upper and lower bits of the result.
12941 SDValue Lo, Hi;
12942 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
12943 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
12944 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12945 if (isOperationLegalOrCustom(LoHiOp, VT)) {
12946 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
12947 Lo = Result.getValue(0);
12948 Hi = Result.getValue(1);
12949 } else if (isOperationLegalOrCustom(HiOp, VT)) {
12950 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
12951 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
12952 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
12953 // Try for a multiplication using a wider type.
12954 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
12955 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
12956 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
12957 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
12958 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
12959 SDValue Shifted =
12960 DAG.getNode(ISD::SRA, dl, WideVT, Res,
12961 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
12962 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
12963 } else if (VT.isVector()) {
12964 return SDValue();
12965 } else {
12966 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
12967 }
12968
12969 if (Scale == VTSize)
12970 // Result is just the top half since we'd be shifting by the width of the
12971 // operand. Overflow impossible so this works for both UMULFIX and
12972 // UMULFIXSAT.
12973 return Hi;
12974
12975 // The result will need to be shifted right by the scale since both operands
12976 // are scaled. The result is given to us in 2 halves, so we only want part of
12977 // both in the result.
12978 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
12979 DAG.getShiftAmountConstant(Scale, VT, dl));
12980 if (!Saturating)
12981 return Result;
12982
12983 if (!Signed) {
12984 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
12985 // widened multiplication) aren't all zeroes.
12986
12987 // Saturate to max if ((Hi >> Scale) != 0),
12988 // which is the same as if (Hi > ((1 << Scale) - 1))
12989 APInt MaxVal = APInt::getMaxValue(VTSize);
12990 SDValue LowMask =
12991 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
12992 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
12993 Result, ISD::SETUGT);
12994 }
12995
12996 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
12997 // widened multiplication) aren't all ones or all zeroes.
12998
12999 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
13000 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
13001
13002 if (Scale == 0) {
13003 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
13004 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
13005 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
13006 // Saturated to SatMin if wide product is negative, and SatMax if wide
13007 // product is positive ...
13008 SDValue Zero = DAG.getConstant(0, dl, VT);
13009 SDValue ResultIfOverflow =
13010 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
13011 // ... but only if we overflowed.
13012 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
13013 }
13014
13015 // We handled Scale==0 above so all the bits to examine is in Hi.
13016
13017 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
13018 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
13019 SDValue LowMask =
13020 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
13021 // Saturate to min if (Hi >> (Scale - 1)) < -1),
13022 // which is the same as if (HI < (-1 << (Scale - 1))
13023 SDValue HighMask = DAG.getConstant(
13024 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
13025 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
13026 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
13027 return Result;
13028}
13029
13030SDValue
13032 SDValue LHS, SDValue RHS,
13033 unsigned Scale, SelectionDAG &DAG) const {
13034 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
13035 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
13036 "Expected a fixed point division opcode");
13037
13038 EVT VT = LHS.getValueType();
13039 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
13040 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
13041 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13042
13043 // If there is enough room in the type to upscale the LHS or downscale the
13044 // RHS before the division, we can perform it in this type without having to
13045 // resize. For signed operations, the LHS headroom is the number of
13046 // redundant sign bits, and for unsigned ones it is the number of zeroes.
13047 // The headroom for the RHS is the number of trailing zeroes.
13048 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
13050 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
13051
13052 // For signed saturating operations, we need to be able to detect true integer
13053 // division overflow; that is, when you have MIN / -EPS. However, this
13054 // is undefined behavior and if we emit divisions that could take such
13055 // values it may cause undesired behavior (arithmetic exceptions on x86, for
13056 // example).
13057 // Avoid this by requiring an extra bit so that we never get this case.
13058 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13059 // signed saturating division, we need to emit a whopping 32-bit division.
13060 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13061 return SDValue();
13062
13063 unsigned LHSShift = std::min(LHSLead, Scale);
13064 unsigned RHSShift = Scale - LHSShift;
13065
13066 // At this point, we know that if we shift the LHS up by LHSShift and the
13067 // RHS down by RHSShift, we can emit a regular division with a final scaling
13068 // factor of Scale.
13069
13070 if (LHSShift)
13071 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13072 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13073 if (RHSShift)
13074 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13075 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13076
13077 SDValue Quot;
13078 if (Signed) {
13079 // For signed operations, if the resulting quotient is negative and the
13080 // remainder is nonzero, subtract 1 from the quotient to round towards
13081 // negative infinity.
13082 SDValue Rem;
13083 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13084 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13085 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13086 if (isTypeLegal(VT) &&
13088 Quot = DAG.getNode(ISD::SDIVREM, dl,
13089 DAG.getVTList(VT, VT),
13090 LHS, RHS);
13091 Rem = Quot.getValue(1);
13092 Quot = Quot.getValue(0);
13093 } else {
13094 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13095 LHS, RHS);
13096 Rem = DAG.getNode(ISD::SREM, dl, VT,
13097 LHS, RHS);
13098 }
13099 SDValue Zero = DAG.getConstant(0, dl, VT);
13100 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13101 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13102 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13103 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13104 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13105 DAG.getConstant(1, dl, VT));
13106 Quot = DAG.getSelect(dl, VT,
13107 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13108 Sub1, Quot);
13109 } else
13110 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13111 LHS, RHS);
13112
13113 return Quot;
13114}
13115
13117 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13118 SDLoc dl(Node);
13119 SDValue LHS = Node->getOperand(0);
13120 SDValue RHS = Node->getOperand(1);
13121 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13122
13123 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13124 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13125 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13126 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13127 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13128 { LHS, RHS, CarryIn });
13129 Result = SDValue(NodeCarry.getNode(), 0);
13130 Overflow = SDValue(NodeCarry.getNode(), 1);
13131 return;
13132 }
13133
13134 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13135 LHS.getValueType(), LHS, RHS);
13136
13137 EVT ResultType = Node->getValueType(1);
13138 EVT SetCCType = getSetCCResultType(
13139 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13140 SDValue SetCC;
13141 if (IsAdd && isOneConstant(RHS)) {
13142 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13143 // the live range of X. We assume comparing with 0 is cheap.
13144 // The general case (X + C) < C is not necessarily beneficial. Although we
13145 // reduce the live range of X, we may introduce the materialization of
13146 // constant C.
13147 SetCC =
13148 DAG.getSetCC(dl, SetCCType, Result,
13149 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13150 } else if (IsAdd && isAllOnesConstant(RHS)) {
13151 // Special case: uaddo X, -1 overflows if X != 0.
13152 SetCC =
13153 DAG.getSetCC(dl, SetCCType, LHS,
13154 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13155 } else {
13156 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
13157 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13158 }
13159 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13160}
13161
13163 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13164 SDLoc dl(Node);
13165 SDValue LHS = Node->getOperand(0);
13166 SDValue RHS = Node->getOperand(1);
13167 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13168
13169 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13170 LHS.getValueType(), LHS, RHS);
13171
13172 EVT ResultType = Node->getValueType(1);
13173 EVT OType = getSetCCResultType(
13174 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13175
13176 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13177 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13178 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13179 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13180 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13181 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13182 return;
13183 }
13184
13185 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13186
13187 if (IsAdd) {
13188 // For an addition, the result should be less than one of the operands (LHS)
13189 // if and only if the other operand (RHS) is negative, otherwise there will
13190 // be overflow.
13191 SDValue ResultLowerThanLHS =
13192 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13193 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13194 Overflow = DAG.getBoolExtOrTrunc(
13195 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13196 ResultType, ResultType);
13197 } else {
13198 // For subtraction, overflow occurs when the signed comparison of operands
13199 // doesn't match the sign of the result.
13200 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13201 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13202 Overflow = DAG.getBoolExtOrTrunc(
13203 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13204 ResultType, ResultType);
13205 }
13206}
13207
13209 SDValue &Overflow, SelectionDAG &DAG) const {
13210 SDLoc dl(Node);
13211 EVT VT = Node->getValueType(0);
13212 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13213 SDValue LHS = Node->getOperand(0);
13214 SDValue RHS = Node->getOperand(1);
13215 bool isSigned = Node->getOpcode() == ISD::SMULO;
13216
13217 // For power-of-two multiplications we can use a simpler shift expansion.
13218 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13219 const APInt &C = RHSC->getAPIntValue();
13220 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13221 if (C.isPowerOf2()) {
13222 // smulo(x, signed_min) is same as umulo(x, signed_min).
13223 bool UseArithShift = isSigned && !C.isMinSignedValue();
13224 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13225 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13226 Overflow = DAG.getSetCC(dl, SetCCVT,
13227 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13228 dl, VT, Result, ShiftAmt),
13229 LHS, ISD::SETNE);
13230 return true;
13231 }
13232 }
13233
13234 SDValue BottomHalf;
13235 SDValue TopHalf;
13236 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13237
13238 static const unsigned Ops[2][3] =
13241 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13242 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13243 RHS);
13244 TopHalf = BottomHalf.getValue(1);
13245 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13246 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13247 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13248 } else if (isTypeLegal(WideVT)) {
13249 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13250 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13251 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13252 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13253 SDValue ShiftAmt =
13254 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13255 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13256 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13257 } else {
13258 if (VT.isVector())
13259 return false;
13260
13261 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13262 }
13263
13264 Result = BottomHalf;
13265 if (isSigned) {
13266 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13267 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13268 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13269 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13270 } else {
13271 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13272 DAG.getConstant(0, dl, VT), ISD::SETNE);
13273 }
13274
13275 // Truncate the result if SetCC returns a larger type than needed.
13276 EVT RType = Node->getValueType(1);
13277 if (RType.bitsLT(Overflow.getValueType()))
13278 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13279
13280 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13281 "Unexpected result type for S/UMULO legalization");
13282 return true;
13283}
13284
13286 SDLoc dl(Node);
13287 EVT VT = Node->getValueType(0);
13288 SDValue LHS = Node->getOperand(0);
13289 SDValue RHS = Node->getOperand(1);
13290 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13291
13292 // Use MUL_LOHI if legal/custom for the original type.
13293 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13294 if (isOperationLegalOrCustom(LoHiOp, VT))
13295 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13296
13297 // Use a wide multiply if available.
13298 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13299 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13300 unsigned BW = VT.getScalarSizeInBits();
13301 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13302 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13303 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13304 DAG.getNode(ISD::SRL, dl, WideVT,
13305 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13306 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13307 }
13308
13309 // Let fixed-length vectors be scalarised by the caller.
13310 // Expand everything else with a wide multiply.
13311 if (!VT.isFixedLengthVector()) {
13312 SDValue Lo, Hi;
13313 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13314 return Hi;
13315 }
13316
13317 return SDValue();
13318}
13319
13321 SDLoc dl(Node);
13322 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13323 SDValue Op = Node->getOperand(0);
13324 SDNodeFlags Flags = Node->getFlags();
13325 EVT VT = Op.getValueType();
13326
13327 // Try to use a shuffle reduction for power of two vectors.
13328 if (VT.isPow2VectorType()) {
13329 // See if the reduction opcode is safe to use with widened types.
13330 bool WidenSrc = false;
13331 switch (Node->getOpcode()) {
13334 case ISD::VECREDUCE_ADD:
13335 case ISD::VECREDUCE_MUL:
13336 case ISD::VECREDUCE_AND:
13337 case ISD::VECREDUCE_OR:
13338 case ISD::VECREDUCE_XOR:
13343 WidenSrc = VT.isFixedLengthVector();
13344 break;
13345 }
13346
13348 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13349 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13350 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13351 // Attempt to widen the source vectors to a legal op.
13352 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13353 if (WideVT.isVector() &&
13354 WideVT.getScalarType() == HalfVT.getScalarType() &&
13355 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13356 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13357 SDValue Lo, Hi;
13358 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13359 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13360 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13361 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13362 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13363 VT = HalfVT;
13364 continue;
13365 }
13366 }
13367 break;
13368 }
13369
13370 SDValue Lo, Hi;
13371 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13372 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13373 VT = HalfVT;
13374
13375 // Stop if splitting is enough to make the reduction legal.
13376 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13377 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13378 Flags);
13379 }
13380 }
13381
13382 if (VT.isScalableVector())
13384 "Expanding reductions for scalable vectors is undefined.");
13385
13386 EVT EltVT = VT.getVectorElementType();
13387 unsigned NumElts = VT.getVectorNumElements();
13388
13390 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13391
13392 SDValue Res = Ops[0];
13393 for (unsigned i = 1; i < NumElts; i++)
13394 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13395
13396 // Result type may be wider than element type.
13397 if (EltVT != Node->getValueType(0))
13398 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13399 return Res;
13400}
13401
13403 SDLoc dl(Node);
13404 SDValue AccOp = Node->getOperand(0);
13405 SDValue VecOp = Node->getOperand(1);
13406 SDNodeFlags Flags = Node->getFlags();
13407
13408 EVT VT = VecOp.getValueType();
13409 EVT EltVT = VT.getVectorElementType();
13410
13411 if (VT.isScalableVector())
13413 "Expanding reductions for scalable vectors is undefined.");
13414
13415 unsigned NumElts = VT.getVectorNumElements();
13416
13418 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13419
13420 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13421
13422 SDValue Res = AccOp;
13423 for (unsigned i = 0; i < NumElts; i++)
13424 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13425
13426 return Res;
13427}
13428
13430 SelectionDAG &DAG) const {
13431 EVT VT = Node->getValueType(0);
13432 SDLoc dl(Node);
13433 bool isSigned = Node->getOpcode() == ISD::SREM;
13434 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13435 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13436 SDValue Dividend = Node->getOperand(0);
13437 SDValue Divisor = Node->getOperand(1);
13438 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13439 SDVTList VTs = DAG.getVTList(VT, VT);
13440 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13441 return true;
13442 }
13443 if (isOperationLegalOrCustom(DivOpc, VT)) {
13444 // X % Y -> X-X/Y*Y
13445 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13446 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13447 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13448 return true;
13449 }
13450 return false;
13451}
13452
13454 SelectionDAG &DAG) const {
13455 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13456 SDLoc dl(SDValue(Node, 0));
13457 SDValue Src = Node->getOperand(0);
13458
13459 // DstVT is the result type, while SatVT is the size to which we saturate
13460 EVT SrcVT = Src.getValueType();
13461 EVT DstVT = Node->getValueType(0);
13462
13463 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13464 unsigned SatWidth = SatVT.getScalarSizeInBits();
13465 unsigned DstWidth = DstVT.getScalarSizeInBits();
13466 assert(SatWidth <= DstWidth &&
13467 "Expected saturation width smaller than result width");
13468
13469 // Determine minimum and maximum integer values and their corresponding
13470 // floating-point values.
13471 APInt MinInt, MaxInt;
13472 if (IsSigned) {
13473 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13474 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13475 } else {
13476 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13477 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13478 }
13479
13480 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13481 // libcall emission cannot handle this. Large result types will fail.
13482 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13483 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13484 SrcVT = Src.getValueType();
13485 }
13486
13487 const fltSemantics &Sem = SrcVT.getFltSemantics();
13488 APFloat MinFloat(Sem);
13489 APFloat MaxFloat(Sem);
13490
13491 APFloat::opStatus MinStatus =
13492 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13493 APFloat::opStatus MaxStatus =
13494 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13495 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13496 !(MaxStatus & APFloat::opStatus::opInexact);
13497
13498 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13499 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13500
13501 // If the integer bounds are exactly representable as floats and min/max are
13502 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13503 // of comparisons and selects.
13504 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13505 bool MayPropagateNaN) {
13506 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13507 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13508 if (!MinMaxLegal)
13509 return SDValue();
13510
13511 SDValue Clamped = Src;
13512
13513 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13514 // then the result is MinFloat.
13515 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13516 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13517 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13518 // Convert clamped value to integer.
13519 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13520 dl, DstVT, Clamped);
13521
13522 // If !MayPropagateNan and the conversion is unsigned case we're done,
13523 // because we mapped NaN to MinFloat, which will cast to zero.
13524 if (!MayPropagateNaN && !IsSigned)
13525 return FpToInt;
13526
13527 // Otherwise, select 0 if Src is NaN.
13528 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13529 EVT SetCCVT =
13530 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13531 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13532 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13533 };
13534 if (AreExactFloatBounds) {
13535 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13536 /*MayPropagateNaN=*/false))
13537 return Res;
13538 // These may propagate NaN for sNaN operands.
13539 if (SDValue Res =
13540 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13541 return Res;
13542 // These always propagate NaN.
13543 if (SDValue Res =
13544 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13545 return Res;
13546 }
13547
13548 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13549 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13550
13551 // Result of direct conversion. The assumption here is that the operation is
13552 // non-trapping and it's fine to apply it to an out-of-range value if we
13553 // select it away later.
13554 SDValue FpToInt =
13555 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13556
13557 SDValue Select = FpToInt;
13558
13559 EVT SetCCVT =
13560 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13561
13562 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13563 // MinInt if Src is NaN.
13564 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13565 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13566 // If Src OGT MaxFloat, select MaxInt.
13567 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13568 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13569
13570 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13571 // is already zero.
13572 if (!IsSigned)
13573 return Select;
13574
13575 // Otherwise, select 0 if Src is NaN.
13576 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13577 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13578 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13579}
13580
13582 const SDLoc &dl,
13583 SelectionDAG &DAG) const {
13584 EVT OperandVT = Op.getValueType();
13585 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13586 return Op;
13587 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13588 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13589 // can induce double-rounding which may alter the results. We can
13590 // correct for this using a trick explained in: Boldo, Sylvie, and
13591 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13592 // World Congress. 2005.
13593 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13594 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13595
13596 // We can keep the narrow value as-is if narrowing was exact (no
13597 // rounding error), the wide value was NaN (the narrow value is also
13598 // NaN and should be preserved) or if we rounded to the odd value.
13599 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13600 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13601 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13602 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13603 EVT ResultIntVTCCVT = getSetCCResultType(
13604 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13605 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13606 // The result is already odd so we don't need to do anything.
13607 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13608
13609 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13610 Op.getValueType());
13611 // We keep results which are exact, odd or NaN.
13612 SDValue KeepNarrow =
13613 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13614 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13615 // We morally performed a round-down if AbsNarrow is smaller than
13616 // AbsWide.
13617 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13618 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13619 SDValue NarrowIsRd =
13620 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13621 // If the narrow value is odd or exact, pick it.
13622 // Otherwise, narrow is even and corresponds to either the rounded-up
13623 // or rounded-down value. If narrow is the rounded-down value, we want
13624 // the rounded-up value as it will be odd.
13625 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13626 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13627 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13628 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13629}
13630
13632 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13633 SDValue Op = Node->getOperand(0);
13634 EVT VT = Node->getValueType(0);
13635 SDLoc dl(Node);
13636 if (VT.getScalarType() == MVT::bf16) {
13637 if (Node->getConstantOperandVal(1) == 1) {
13638 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13639 }
13640 EVT OperandVT = Op.getValueType();
13641 SDValue IsNaN = DAG.getSetCC(
13642 dl,
13643 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
13644 Op, Op, ISD::SETUO);
13645
13646 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13647 // can induce double-rounding which may alter the results. We can
13648 // correct for this using a trick explained in: Boldo, Sylvie, and
13649 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13650 // World Congress. 2005.
13651 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
13652 EVT I32 = F32.changeTypeToInteger();
13653 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
13654 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
13655
13656 // Conversions should set NaN's quiet bit. This also prevents NaNs from
13657 // turning into infinities.
13658 SDValue NaN =
13659 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
13660
13661 // Factor in the contribution of the low 16 bits.
13662 SDValue One = DAG.getConstant(1, dl, I32);
13663 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
13664 DAG.getShiftAmountConstant(16, I32, dl));
13665 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
13666 SDValue RoundingBias =
13667 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
13668 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
13669
13670 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
13671 // 0x80000000.
13672 Op = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
13673
13674 // Now that we have rounded, shift the bits into position.
13675 Op = DAG.getNode(ISD::SRL, dl, I32, Op,
13676 DAG.getShiftAmountConstant(16, I32, dl));
13677 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
13678 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
13679 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13680 }
13681 return SDValue();
13682}
13683
13685 SelectionDAG &DAG) const {
13686 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
13687 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
13688 "Unexpected opcode!");
13689 assert((Node->getValueType(0).isScalableVector() ||
13690 !isa<ConstantSDNode>(Node->getOperand(2))) &&
13691 "Fixed length vector types with constant offsets expected to use "
13692 "SHUFFLE_VECTOR!");
13693
13694 EVT VT = Node->getValueType(0);
13695 SDValue V1 = Node->getOperand(0);
13696 SDValue V2 = Node->getOperand(1);
13697 SDValue Offset = Node->getOperand(2);
13698 SDLoc DL(Node);
13699
13700 // Expand through memory thusly:
13701 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
13702 // Store V1, Ptr
13703 // Store V2, Ptr + sizeof(V1)
13704 // if (VECTOR_SPLICE_LEFT)
13705 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
13706 // else
13707 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
13708 // Res = Load Ptr
13709
13710 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
13711
13713 VT.getVectorElementCount() * 2);
13714 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
13715 EVT PtrVT = StackPtr.getValueType();
13716 auto &MF = DAG.getMachineFunction();
13717 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13718 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
13719
13720 // Store the lo part of CONCAT_VECTORS(V1, V2)
13721 SDValue StoreV1 =
13722 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
13723 // Store the hi part of CONCAT_VECTORS(V1, V2)
13724 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
13725 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
13726 SDValue StoreV2 =
13727 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
13728
13729 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
13730 SDValue EltByteSize =
13731 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
13732 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
13733 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
13734
13735 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
13736
13737 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
13738 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
13739 else
13740 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
13741
13742 // Load the spliced result
13743 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
13745}
13746
13748 SelectionDAG &DAG) const {
13749 SDLoc DL(Node);
13750 SDValue Vec = Node->getOperand(0);
13751 SDValue Mask = Node->getOperand(1);
13752 SDValue Passthru = Node->getOperand(2);
13753
13754 EVT VecVT = Vec.getValueType();
13755 EVT ScalarVT = VecVT.getScalarType();
13756 EVT MaskVT = Mask.getValueType();
13757 EVT MaskScalarVT = MaskVT.getScalarType();
13758
13759 // Needs to be handled by targets that have scalable vector types.
13760 if (VecVT.isScalableVector())
13761 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
13762
13763 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
13764 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
13765 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13766 MachinePointerInfo PtrInfo =
13768
13769 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
13770 SDValue Chain = DAG.getEntryNode();
13771 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
13772
13773 bool HasPassthru = !Passthru.isUndef();
13774
13775 // If we have a passthru vector, store it on the stack, overwrite the matching
13776 // positions and then re-write the last element that was potentially
13777 // overwritten even though mask[i] = false.
13778 if (HasPassthru)
13779 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
13780
13781 SDValue LastWriteVal;
13782 APInt PassthruSplatVal;
13783 bool IsSplatPassthru =
13784 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal);
13785
13786 if (IsSplatPassthru) {
13787 // As we do not know which position we wrote to last, we cannot simply
13788 // access that index from the passthru vector. So we first check if passthru
13789 // is a splat vector, to use any element ...
13790 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
13791 } else if (HasPassthru) {
13792 // ... if it is not a splat vector, we need to get the passthru value at
13793 // position = popcount(mask) and re-load it from the stack before it is
13794 // overwritten in the loop below.
13795 EVT PopcountVT = ScalarVT.changeTypeToInteger();
13796 SDValue Popcount = DAG.getNode(
13798 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
13799 Popcount = DAG.getNode(
13801 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
13802 Popcount);
13803 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
13804 SDValue LastElmtPtr =
13805 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
13806 LastWriteVal = DAG.getLoad(
13807 ScalarVT, DL, Chain, LastElmtPtr,
13809 Chain = LastWriteVal.getValue(1);
13810 }
13811
13812 unsigned NumElms = VecVT.getVectorNumElements();
13813 for (unsigned I = 0; I < NumElms; I++) {
13814 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
13815 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
13816 Chain = DAG.getStore(
13817 Chain, DL, ValI, OutPtr,
13819
13820 // Get the mask value and add it to the current output position. This
13821 // either increments by 1 if MaskI is true or adds 0 otherwise.
13822 // Freeze in case we have poison/undef mask entries.
13823 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
13824 MaskI = DAG.getFreeze(MaskI);
13825 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
13826 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
13827 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
13828
13829 if (HasPassthru && I == NumElms - 1) {
13830 SDValue EndOfVector =
13831 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
13832 SDValue AllLanesSelected =
13833 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
13834 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
13835 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
13836
13837 // Re-write the last ValI if all lanes were selected. Otherwise,
13838 // overwrite the last write it with the passthru value.
13839 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
13840 LastWriteVal, SDNodeFlags::Unpredictable);
13841 Chain = DAG.getStore(
13842 Chain, DL, LastWriteVal, OutPtr,
13844 }
13845 }
13846
13847 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
13848}
13849
13851 SDLoc DL(Node);
13852 EVT VT = Node->getValueType(0);
13853 SDValue Op = Node->getOperand(0);
13854 ElementCount EC = Op.getValueType().getVectorElementCount();
13855
13856 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
13857 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
13858
13859 // No legal step vector: split mask in half and recombine results.
13860 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
13861 // (== LoNumElts when no active lane), allowing the SETNE comparison.
13862 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
13863 if (!StepVec) {
13864 EVT ResVT = Node->getValueType(0);
13865 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
13866 SDValue LoNumElts = DAG.getElementCount(
13867 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
13868 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
13869 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
13870 SDValue ResLoNotNumElts = DAG.getSetCC(
13871 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
13872 ResLo, LoNumElts, ISD::SETNE);
13873 // Per LangRef, ResVT must be wide enough to hold the total element count,
13874 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
13875 // the count is only required to fit unsigned.
13876 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
13878 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
13879 }
13880
13881 EVT StepVecVT = StepVec.getValueType();
13882 EVT StepVT = StepVecVT.getVectorElementType();
13883
13884 // Promote the scalar result type early to avoid redundant zexts.
13886 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
13887
13888 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
13889 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
13890 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
13891 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
13892 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
13894 StepVecVT.getVectorElementType(), Select);
13895 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
13896 DAG.getZExtOrTrunc(Max, DL, StepVT));
13897
13898 return DAG.getZExtOrTrunc(Sub, DL, VT);
13899}
13900
13902 SDLoc DL(N);
13903 SDValue Source = N->getOperand(0);
13904 SDValue Needle = N->getOperand(1);
13905 SDValue Mask = N->getOperand(2);
13906 EVT SourceVT = Source.getValueType();
13907 EVT NeedleVT = Needle.getValueType();
13908 EVT ResVT = N->getValueType(0);
13909 EVT CmpVT =
13910 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
13911
13912 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
13913
13914 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
13915 EVT NeedleEltVT = NeedleVT.getVectorElementType();
13916 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
13917 SDValue Splat;
13918 if (NeedleVT == SourceVT) {
13919 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
13920 Splat = DAG.getVectorShuffle(
13921 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
13923 } else {
13924 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
13925 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
13926 }
13927 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
13928 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
13929 }
13930
13931 EVT UseVT = ResVT;
13932 // If the result is immediately truncated, only extend to that type (to avoid
13933 // unnecessary sign/zero extends).
13934 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
13935 UseVT = N->user_begin()->getValueType(0);
13936
13937 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
13938 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
13939
13940 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
13941 if (UseVT != ResVT)
13942 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
13943 return Ret;
13944}
13945
13947 SelectionDAG &DAG) const {
13948 SDLoc DL(N);
13949 SDValue Acc = N->getOperand(0);
13950 SDValue MulLHS = N->getOperand(1);
13951 SDValue MulRHS = N->getOperand(2);
13952 EVT AccVT = Acc.getValueType();
13953 EVT MulOpVT = MulLHS.getValueType();
13954
13955 EVT ExtMulOpVT =
13957 MulOpVT.getVectorElementCount());
13958
13959 unsigned ExtOpcLHS, ExtOpcRHS;
13960 switch (N->getOpcode()) {
13961 default:
13962 llvm_unreachable("Unexpected opcode");
13964 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
13965 break;
13967 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
13968 break;
13970 ExtOpcLHS = ISD::SIGN_EXTEND;
13971 ExtOpcRHS = ISD::ZERO_EXTEND;
13972 break;
13974 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
13975 break;
13976 }
13977
13978 // A wide partial reduction is built from a ladder of narrower ones, a rung
13979 // at a time, each halving the element count and doubling the width.
13980 unsigned Opc = N->getOpcode();
13981 ElementCount MulEC = MulOpVT.getVectorElementCount();
13982 ElementCount AccEC = AccVT.getVectorElementCount();
13983 unsigned CountRatio =
13984 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
13985 unsigned WidthRatio =
13986 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
13987 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
13988 LLVMContext &Ctx = *DAG.getContext();
13989 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
13990
13991 // A pure reduction peels one rung and re-enters.
13992 if (llvm::isOneOrOneSplat(MulRHS)) {
13993 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
13994 return DAG.getNode(Opc, DL, AccVT, Acc,
13995 DAG.getNode(Opc, DL, RungVT,
13996 DAG.getConstant(0, DL, RungVT), MulLHS,
13997 MulRHS),
13998 DAG.getConstant(1, DL, RungVT));
13999 }
14000
14001 // A multiply widens the products by one rung, which legalizes back into a
14002 // widening multiply per half, and the ladder re-enters as a plain sum.
14003 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
14004 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
14005 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
14006 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
14007 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
14008
14009 // The halves meet at the narrowest rung, so the accumulator is added once.
14010 EVT MidVT = Lo.getValueType()
14011 .widenIntegerVectorElementType(Ctx)
14012 .getHalfNumVectorElementsVT(Ctx);
14014 return DAG.getNode(Opc, DL, AccVT,
14015 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
14016 SDValue Mid =
14017 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
14018 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
14019 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
14020 }
14021
14022 if (ExtMulOpVT != MulOpVT) {
14023 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
14024 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
14025 }
14026 SDValue Input = MulLHS;
14027 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
14028 if (!llvm::isOneOrOneSplatFP(MulRHS))
14029 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14030 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
14031 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14032 }
14033
14034 unsigned Stride = AccVT.getVectorMinNumElements();
14035 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
14036
14037 // Collect all of the subvectors
14038 std::deque<SDValue> Subvectors = {Acc};
14039 for (unsigned I = 0; I < ScaleFactor; I++)
14040 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
14041
14042 unsigned FlatNode =
14043 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
14044
14045 // Flatten the subvector tree
14046 while (Subvectors.size() > 1) {
14047 Subvectors.push_back(
14048 DAG.getNode(FlatNode, DL, AccVT, {Subvectors[0], Subvectors[1]}));
14049 Subvectors.pop_front();
14050 Subvectors.pop_front();
14051 }
14052
14053 assert(Subvectors.size() == 1 &&
14054 "There should only be one subvector after tree flattening");
14055
14056 return Subvectors[0];
14057}
14058
14059/// Given a store node \p StoreNode, return true if it is safe to fold that node
14060/// into \p FPNode, which expands to a library call with output pointers.
14062 SDNode *FPNode) {
14064 SmallVector<const SDNode *, 8> DeferredNodes;
14066
14067 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
14068 for (SDValue Op : StoreNode->ops())
14069 if (Op.getNode() != FPNode)
14070 Worklist.push_back(Op.getNode());
14071
14073 while (!Worklist.empty()) {
14074 const SDNode *Node = Worklist.pop_back_val();
14075 auto [_, Inserted] = Visited.insert(Node);
14076 if (!Inserted)
14077 continue;
14078
14079 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
14080 return false;
14081
14082 // Reached the FPNode (would result in a cycle).
14083 // OR Reached CALLSEQ_START (would result in nested call sequences).
14084 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
14085 return false;
14086
14087 if (Node->getOpcode() == ISD::CALLSEQ_END) {
14088 // Defer looking into call sequences (so we can check we're outside one).
14089 // We still need to look through these for the predecessor check.
14090 DeferredNodes.push_back(Node);
14091 continue;
14092 }
14093
14094 for (SDValue Op : Node->ops())
14095 Worklist.push_back(Op.getNode());
14096 }
14097
14098 // True if we're outside a call sequence and don't have the FPNode as a
14099 // predecessor. No cycles or nested call sequences possible.
14100 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
14101 MaxSteps);
14102}
14103
14105 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
14107 std::optional<unsigned> CallRetResNo) const {
14108 if (LC == RTLIB::UNKNOWN_LIBCALL)
14109 return false;
14110
14111 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
14112 if (LibcallImpl == RTLIB::Unsupported)
14113 return false;
14114
14115 LLVMContext &Ctx = *DAG.getContext();
14116 EVT VT = Node->getValueType(0);
14117 unsigned NumResults = Node->getNumValues();
14118
14119 // Find users of the node that store the results (and share input chains). The
14120 // destination pointers can be used instead of creating stack allocations.
14121 SDValue StoresInChain;
14122 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
14123 for (SDNode *User : Node->users()) {
14125 continue;
14126 auto *ST = cast<StoreSDNode>(User);
14127 SDValue StoreValue = ST->getValue();
14128 unsigned ResNo = StoreValue.getResNo();
14129 // Ensure the store corresponds to an output pointer.
14130 if (CallRetResNo == ResNo)
14131 continue;
14132 // Ensure the store to the default address space and not atomic or volatile.
14133 if (!ST->isSimple() || ST->getAddressSpace() != 0)
14134 continue;
14135 // Ensure all store chains are the same (so they don't alias).
14136 if (StoresInChain && ST->getChain() != StoresInChain)
14137 continue;
14138 // Ensure the store is properly aligned.
14139 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
14140 if (ST->getAlign() <
14141 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
14142 continue;
14143 // Avoid:
14144 // 1. Creating cyclic dependencies.
14145 // 2. Expanding the node to a call within a call sequence.
14147 continue;
14148 ResultStores[ResNo] = ST;
14149 StoresInChain = ST->getChain();
14150 }
14151
14152 ArgListTy Args;
14153
14154 // Pass the arguments.
14155 for (const SDValue &Op : Node->op_values()) {
14156 EVT ArgVT = Op.getValueType();
14157 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
14158 Args.emplace_back(Op, ArgTy);
14159 }
14160
14161 // Pass the output pointers.
14162 SmallVector<SDValue, 2> ResultPtrs(NumResults);
14164 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
14165 if (ResNo == CallRetResNo)
14166 continue;
14167 EVT ResVT = Node->getValueType(ResNo);
14168 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
14169 ResultPtrs[ResNo] = ResultPtr;
14170 Args.emplace_back(ResultPtr, PointerTy);
14171 }
14172
14173 SDLoc DL(Node);
14174
14176 // Pass the vector mask (if required).
14177 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
14178 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
14179 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14180 }
14181
14182 Type *RetType = CallRetResNo.has_value()
14183 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14184 : Type::getVoidTy(Ctx);
14185 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14186 SDValue Callee =
14187 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14189 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14190 getLibcallImplCallingConv(LibcallImpl), RetType, Callee, std::move(Args));
14191
14192 auto [Call, CallChain] = LowerCallTo(CLI);
14193
14194 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14195 if (ResNo == CallRetResNo) {
14196 Results.push_back(Call);
14197 continue;
14198 }
14199 MachinePointerInfo PtrInfo;
14200 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14201 ResultPtr, PtrInfo);
14202 SDValue OutChain = LoadResult.getValue(1);
14203
14204 if (StoreSDNode *ST = ResultStores[ResNo]) {
14205 // Replace store with the library call.
14206 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14207 PtrInfo = ST->getPointerInfo();
14208 } else {
14210 DAG.getMachineFunction(),
14211 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14212 }
14213
14214 Results.push_back(LoadResult);
14215 }
14216
14217 return true;
14218}
14219
14221 SDValue &LHS, SDValue &RHS,
14222 SDValue &CC, bool &NeedInvert,
14223 const SDLoc &dl, SDValue &Chain,
14224 bool IsSignaling) const {
14225 MVT OpVT = LHS.getSimpleValueType();
14226 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14227 NeedInvert = false;
14228 switch (getCondCodeAction(CCCode, OpVT)) {
14229 default:
14230 llvm_unreachable("Unknown condition code action!");
14232 // Nothing to do.
14233 break;
14236 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14237 std::swap(LHS, RHS);
14238 CC = DAG.getCondCode(InvCC);
14239 return true;
14240 }
14241 // Swapping operands didn't work. Try inverting the condition.
14242 bool NeedSwap = false;
14243 InvCC = getSetCCInverse(CCCode, OpVT);
14244 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14245 // If inverting the condition is not enough, try swapping operands
14246 // on top of it.
14247 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14248 NeedSwap = true;
14249 }
14250 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14251 CC = DAG.getCondCode(InvCC);
14252 NeedInvert = true;
14253 if (NeedSwap)
14254 std::swap(LHS, RHS);
14255 return true;
14256 }
14257
14258 // Special case: expand i1 comparisons using logical operations.
14259 if (OpVT == MVT::i1) {
14260 SDValue Ret;
14261 switch (CCCode) {
14262 default:
14263 llvm_unreachable("Unknown integer setcc!");
14264 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14265 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14266 MVT::i1);
14267 break;
14268 case ISD::SETNE: // X != Y --> (X ^ Y)
14269 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14270 break;
14271 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14272 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14273 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14274 DAG.getNOT(dl, LHS, MVT::i1));
14275 break;
14276 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14277 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14278 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14279 DAG.getNOT(dl, RHS, MVT::i1));
14280 break;
14281 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14282 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14283 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14284 DAG.getNOT(dl, LHS, MVT::i1));
14285 break;
14286 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14287 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14288 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14289 DAG.getNOT(dl, RHS, MVT::i1));
14290 break;
14291 }
14292
14293 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14294 RHS = SDValue();
14295 CC = SDValue();
14296 return true;
14297 }
14298
14300 unsigned Opc = 0;
14301 switch (CCCode) {
14302 default:
14303 llvm_unreachable("Don't know how to expand this condition!");
14304 case ISD::SETUO:
14305 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14306 CC1 = ISD::SETUNE;
14307 CC2 = ISD::SETUNE;
14308 Opc = ISD::OR;
14309 break;
14310 }
14312 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14313 NeedInvert = true;
14314 [[fallthrough]];
14315 case ISD::SETO:
14317 "If SETO is expanded, SETOEQ must be legal!");
14318 CC1 = ISD::SETOEQ;
14319 CC2 = ISD::SETOEQ;
14320 Opc = ISD::AND;
14321 break;
14322 case ISD::SETONE:
14323 case ISD::SETUEQ:
14324 // If the SETUO or SETO CC isn't legal, we might be able to use
14325 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14326 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14327 // the operands.
14328 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14329 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14330 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14331 CC1 = ISD::SETOGT;
14332 CC2 = ISD::SETOLT;
14333 Opc = ISD::OR;
14334 NeedInvert = ((unsigned)CCCode & 0x8U);
14335 break;
14336 }
14337 [[fallthrough]];
14338 case ISD::SETOEQ:
14339 case ISD::SETOGT:
14340 case ISD::SETOGE:
14341 case ISD::SETOLT:
14342 case ISD::SETOLE:
14343 case ISD::SETUNE:
14344 case ISD::SETUGT:
14345 case ISD::SETUGE:
14346 case ISD::SETULT:
14347 case ISD::SETULE:
14348 // If we are floating point, assign and break, otherwise fall through.
14349 if (!OpVT.isInteger()) {
14350 // We can use the 4th bit to tell if we are the unordered
14351 // or ordered version of the opcode.
14352 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14353 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14354 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14355 break;
14356 }
14357 // Fallthrough if we are unsigned integer.
14358 [[fallthrough]];
14359 case ISD::SETLE:
14360 case ISD::SETGT:
14361 case ISD::SETGE:
14362 case ISD::SETLT:
14363 case ISD::SETNE:
14364 case ISD::SETEQ:
14365 // If all combinations of inverting the condition and swapping operands
14366 // didn't work then we have no means to expand the condition.
14367 llvm_unreachable("Don't know how to expand this condition!");
14368 }
14369
14370 SDValue SetCC1, SetCC2;
14371 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14372 // If we aren't the ordered or unorder operation,
14373 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14374 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14375 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14376 } else {
14377 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14378 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14379 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14380 }
14381 if (Chain)
14382 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14383 SetCC2.getValue(1));
14384 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14385 RHS = SDValue();
14386 CC = SDValue();
14387 return true;
14388 }
14389 }
14390 return false;
14391}
14392
14394 SelectionDAG &DAG) const {
14395 EVT VT = Node->getValueType(0);
14396 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14397 // split into two equal parts.
14398 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14399 return SDValue();
14400
14401 // Restrict expansion to cases where both parts can be concatenated.
14402 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14403 if (LoVT != HiVT || !isTypeLegal(LoVT))
14404 return SDValue();
14405
14406 SDLoc DL(Node);
14407 unsigned Opcode = Node->getOpcode();
14408
14409 // Don't expand if the result is likely to be unrolled anyway.
14410 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14411 return SDValue();
14412
14413 SmallVector<SDValue, 4> LoOps, HiOps;
14414 for (const SDValue &V : Node->op_values()) {
14415 if (!V.getValueType().isVector()) {
14416 // Scalar operands pass through to both halves unchanged.
14417 LoOps.push_back(V);
14418 HiOps.push_back(V);
14419 continue;
14420 }
14421 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14422 LoOps.push_back(Lo);
14423 HiOps.push_back(Hi);
14424 }
14425
14426 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVT, LoOps, Node->getFlags());
14427 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVT, HiOps, Node->getFlags());
14428 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14429}
14430
14432 const SDLoc &DL,
14433 EVT InVecVT, SDValue EltNo,
14434 LoadSDNode *OriginalLoad,
14435 SelectionDAG &DAG) const {
14436 assert(OriginalLoad->isSimple());
14437
14438 EVT VecEltVT = InVecVT.getVectorElementType();
14439
14440 // If the vector element type is not a multiple of a byte then we are unable
14441 // to correctly compute an address to load only the extracted element as a
14442 // scalar.
14443 if (!VecEltVT.isByteSized())
14444 return SDValue();
14445
14446 ISD::LoadExtType ExtTy =
14447 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14448 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14449 return SDValue();
14450
14451 std::optional<unsigned> ByteOffset;
14452 Align Alignment = OriginalLoad->getAlign();
14454 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14455 int Elt = ConstEltNo->getZExtValue();
14456 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14457 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14458 Alignment = commonAlignment(Alignment, *ByteOffset);
14459 } else {
14460 // Discard the pointer info except the address space because the memory
14461 // operand can't represent this new access since the offset is variable.
14462 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14463 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14464 }
14465
14466 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14467 return SDValue();
14468
14469 unsigned IsFast = 0;
14470 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14471 OriginalLoad->getAddressSpace(), Alignment,
14472 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14473 !IsFast)
14474 return SDValue();
14475
14476 // The original DAG loaded the entire vector from memory, so arithmetic
14477 // within it must be inbounds.
14479 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
14480
14481 // We are replacing a vector load with a scalar load. The new load must have
14482 // identical memory op ordering to the original.
14483 SDValue Load;
14484 if (ResultVT.bitsGT(VecEltVT)) {
14485 // If the result type of vextract is wider than the load, then issue an
14486 // extending load instead.
14487 ISD::LoadExtType ExtType =
14488 isLoadLegal(ResultVT, VecEltVT, Alignment,
14489 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
14491 : ISD::EXTLOAD;
14492 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
14493 NewPtr, MPI, VecEltVT, Alignment,
14494 OriginalLoad->getMemOperand()->getFlags(),
14495 OriginalLoad->getAAInfo());
14496 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14497 } else {
14498 // The result type is narrower or the same width as the vector element
14499 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
14500 Alignment, OriginalLoad->getMemOperand()->getFlags(),
14501 OriginalLoad->getAAInfo());
14502 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14503 if (ResultVT.bitsLT(VecEltVT))
14504 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
14505 else
14506 Load = DAG.getBitcast(ResultVT, Load);
14507 }
14508
14509 return Load;
14510}
14511
14512// Set type id for call site info and metadata 'call_target'.
14513// We are filtering for:
14514// a) The call-graph-section use case that wants to know about indirect
14515// calls, or
14516// b) We want to annotate indirect calls.
14518 const CallBase *CB, MachineFunction &MF,
14519 MachineFunction::CallSiteInfo &CSInfo) const {
14520 if (CB && CB->isIndirectCall() &&
14523 CSInfo = MachineFunction::CallSiteInfo(*CB);
14524}
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
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
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.
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
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:869
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