LLVM 24.0.0git
GISelValueTracking.cpp
Go to the documentation of this file.
1//===- lib/CodeGen/GlobalISel/GISelValueTracking.cpp --------------*- C++
2//*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10/// Provides analysis for querying information about KnownBits during GISel
11/// passes.
12//
13//===----------------------------------------------------------------------===//
15#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/ScopeExit.h"
35#include "llvm/IR/FMF.h"
41
42#define DEBUG_TYPE "gisel-known-bits"
43
44using namespace llvm;
45using namespace MIPatternMatch;
46
48
50 "Analysis for ComputingKnownBits", false, true)
51
53 : MF(MF), MRI(MF.getRegInfo()), TL(*MF.getSubtarget().getTargetLowering()),
54 DL(MF.getFunction().getDataLayout()), MaxDepth(MaxDepth) {}
55
57 const MachineInstr *MI = MRI.getVRegDef(R);
58 switch (MI->getOpcode()) {
59 case TargetOpcode::COPY:
60 return computeKnownAlignment(MI->getOperand(1).getReg(), Depth);
61 case TargetOpcode::G_ASSERT_ALIGN: {
62 // TODO: Min with source
63 return Align(MI->getOperand(2).getImm());
64 }
65 case TargetOpcode::G_FRAME_INDEX: {
66 int FrameIdx = MI->getOperand(1).getIndex();
67 return MF.getFrameInfo().getObjectAlign(FrameIdx);
68 }
69 case TargetOpcode::G_INTRINSIC:
70 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
71 case TargetOpcode::G_INTRINSIC_CONVERGENT:
72 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS:
73 default:
74 return TL.computeKnownAlignForTargetInstr(*this, R, MRI, Depth + 1);
75 }
76}
77
79 const LLT Ty = MRI.getType(R);
80 // Since the number of lanes in a scalable vector is unknown at compile time,
81 // we track one bit which is implicitly broadcast to all lanes. This means
82 // that all lanes in a scalable vector are considered demanded.
83 APInt DemandedElts =
84 Ty.isFixedVector() ? APInt::getAllOnes(Ty.getNumElements()) : APInt(1, 1);
85 return getKnownBits(R, DemandedElts);
86}
87
89 const APInt &DemandedElts,
90 unsigned Depth) {
92 computeKnownBitsImpl(R, Known, DemandedElts, Depth);
93 return Known;
94}
95
97 LLT Ty = MRI.getType(R);
98 unsigned BitWidth = Ty.getScalarSizeInBits();
100}
101
103 LLT Ty = MRI.getType(R);
104 const APInt ScalarDemandedElts(1, 1);
105 APInt DemandedElts = Ty.isFixedVector()
106 ? APInt::getAllOnes(Ty.getNumElements())
107 : ScalarDemandedElts;
108 return isKnownNeverZero(R, DemandedElts, Depth);
109}
110
112 unsigned Depth) {
113 if (Depth >= getMaxDepth())
114 return false;
115
116 const APInt ScalarDemandedElts(1, 1);
117 MachineInstr &MI = *MRI.getVRegDef(R);
118
119 switch (MI.getOpcode()) {
120 default:
121 break;
122
123 case TargetOpcode::G_BUILD_VECTOR: {
124 for (const auto &[I, MO] : enumerate(drop_begin(MI.operands()))) {
125 if (!DemandedElts[I])
126 continue;
127 if (!isKnownNeverZero(MO.getReg(), ScalarDemandedElts, Depth + 1))
128 return false;
129 }
130 return true;
131 }
132
133 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
135 Register InVec = Extract.getVectorReg();
136 LLT VecTy = MRI.getType(InVec);
137 if (VecTy.isScalableVector())
138 break;
139 unsigned NumSrcElts = VecTy.getNumElements();
140 // An out-of-range constant index produces poison. Keep all lanes demanded,
141 // which is poison-safe and matches SelectionDAG's conservative behavior.
142 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
143 if (auto Idx = getIConstantVRegVal(Extract.getIndexReg(), MRI)) {
144 if (Idx->ult(NumSrcElts))
145 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, Idx->getZExtValue());
146 }
147 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
148 }
149
150 case TargetOpcode::G_SHUFFLE_VECTOR: {
152 LLT SrcTy = MRI.getType(Shuf.getSrc1Reg());
153 if (SrcTy.isScalableVector())
154 break;
155 APInt DemandedLHS, DemandedRHS;
156 if (!getShuffleDemandedElts(SrcTy.getNumElements(), Shuf.getMask(),
157 DemandedElts, DemandedLHS, DemandedRHS))
158 break;
159 if (!DemandedLHS.isZero() &&
160 !isKnownNeverZero(Shuf.getSrc1Reg(), DemandedLHS, Depth + 1))
161 return false;
162 if (!DemandedRHS.isZero() &&
163 !isKnownNeverZero(Shuf.getSrc2Reg(), DemandedRHS, Depth + 1))
164 return false;
165 return true;
166 }
167
168 case TargetOpcode::G_OR:
169 return isKnownNeverZero(MI.getOperand(1).getReg(), DemandedElts,
170 Depth + 1) ||
171 isKnownNeverZero(MI.getOperand(2).getReg(), DemandedElts, Depth + 1);
172
173 case TargetOpcode::G_SELECT:
174 return isKnownNeverZero(MI.getOperand(2).getReg(), DemandedElts,
175 Depth + 1) &&
176 isKnownNeverZero(MI.getOperand(3).getReg(), DemandedElts, Depth + 1);
177
178 case TargetOpcode::G_SHL: {
179 Register LHSReg = MI.getOperand(1).getReg();
180 if (MI.getFlag(MachineInstr::NoSWrap) || MI.getFlag(MachineInstr::NoUWrap))
181 return isKnownNeverZero(LHSReg, DemandedElts, Depth + 1);
182 KnownBits ValKnown = getKnownBits(LHSReg, DemandedElts, Depth + 1);
183 if (ValKnown.One[0])
184 return true;
185 APInt MaxCnt =
186 getKnownBits(MI.getOperand(2).getReg(), DemandedElts, Depth + 1)
187 .getMaxValue();
188 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
189 !ValKnown.One.shl(MaxCnt).isZero())
190 return true;
191 break;
192 }
193 }
194
195 // Pass through this frame's Depth (not Depth+1) because we have not recursed
196 // into a child MI here: the fallback queries KnownBits for the same R.
197 return getKnownBits(R, DemandedElts, Depth).isNonZero();
198}
199
203
207
208[[maybe_unused]] static void
209dumpResult(const MachineInstr &MI, const KnownBits &Known, unsigned Depth) {
210 dbgs() << "[" << Depth << "] Compute known bits: " << MI << "[" << Depth
211 << "] Computed for: " << MI << "[" << Depth << "] Known: 0x"
212 << toString(Known.Zero | Known.One, 16, false) << "\n"
213 << "[" << Depth << "] Zero: 0x" << toString(Known.Zero, 16, false)
214 << "\n"
215 << "[" << Depth << "] One: 0x" << toString(Known.One, 16, false)
216 << "\n";
217}
218
219/// Compute known bits for the intersection of \p Src0 and \p Src1
220void GISelValueTracking::computeKnownBitsMin(Register Src0, Register Src1,
222 const APInt &DemandedElts,
223 unsigned Depth) {
224 // Test src1 first, since we canonicalize simpler expressions to the RHS.
225 computeKnownBitsImpl(Src1, Known, DemandedElts, Depth);
226
227 // If we don't know any bits, early out.
228 if (Known.isUnknown())
229 return;
230
231 KnownBits Known2;
232 computeKnownBitsImpl(Src0, Known2, DemandedElts, Depth);
233
234 // Only known if known in both the LHS and RHS.
235 Known = Known.intersectWith(Known2);
236}
237
238// Bitfield extract is computed as (Src >> Offset) & Mask, where Mask is
239// created using Width. Use this function when the inputs are KnownBits
240// objects. TODO: Move this KnownBits.h if this is usable in more cases.
241static KnownBits extractBits(unsigned BitWidth, const KnownBits &SrcOpKnown,
242 const KnownBits &OffsetKnown,
243 const KnownBits &WidthKnown) {
244 KnownBits Mask(BitWidth);
245 Mask.Zero = APInt::getBitsSetFrom(
247 Mask.One = APInt::getLowBitsSet(
249 return KnownBits::lshr(SrcOpKnown, OffsetKnown) & Mask;
250}
251
253 const APInt &DemandedElts,
254 unsigned Depth) {
255 MachineInstr &MI = *MRI.getVRegDef(R);
256 unsigned Opcode = MI.getOpcode();
257 LLT DstTy = MRI.getType(R);
258
259 // Handle the case where this is called on a register that does not have a
260 // type constraint. For example, it may be post-ISel or this target might not
261 // preserve the type when early-selecting instructions.
262 if (!DstTy.isValid()) {
263 Known = KnownBits();
264 return;
265 }
266
267#ifndef NDEBUG
268 if (DstTy.isFixedVector()) {
269 assert(
270 DstTy.getNumElements() == DemandedElts.getBitWidth() &&
271 "DemandedElt width should equal the fixed vector number of elements");
272 } else {
273 assert(DemandedElts.getBitWidth() == 1 && DemandedElts == APInt(1, 1) &&
274 "DemandedElt width should be 1 for scalars or scalable vectors");
275 }
276#endif
277
278 unsigned BitWidth = DstTy.getScalarSizeInBits();
279 Known = KnownBits(BitWidth); // Don't know anything
280
281 // Depth may get bigger than max depth if it gets passed to a different
282 // GISelValueTracking object.
283 // This may happen when say a generic part uses a GISelValueTracking object
284 // with some max depth, but then we hit TL.computeKnownBitsForTargetInstr
285 // which creates a new GISelValueTracking object with a different and smaller
286 // depth. If we just check for equality, we would never exit if the depth
287 // that is passed down to the target specific GISelValueTracking object is
288 // already bigger than its max depth.
289 if (Depth >= getMaxDepth())
290 return;
291
292 if (!DemandedElts)
293 return; // No demanded elts, better to assume we don't know anything.
294
295 KnownBits Known2;
296
297 switch (Opcode) {
298 default:
299 TL.computeKnownBitsForTargetInstr(*this, R, Known, DemandedElts, MRI,
300 Depth);
301 break;
302 case TargetOpcode::G_BUILD_VECTOR: {
303 // Collect the known bits that are shared by every demanded vector element.
304 Known.Zero.setAllBits();
305 Known.One.setAllBits();
306 for (const auto &[I, MO] : enumerate(drop_begin(MI.operands()))) {
307 if (!DemandedElts[I])
308 continue;
309
310 computeKnownBitsImpl(MO.getReg(), Known2, APInt(1, 1), Depth + 1);
311
312 // Known bits are the values that are shared by every demanded element.
313 Known = Known.intersectWith(Known2);
314
315 // If we don't know any bits, early out.
316 if (Known.isUnknown())
317 break;
318 }
319 break;
320 }
321 case TargetOpcode::G_SPLAT_VECTOR: {
322 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, APInt(1, 1),
323 Depth + 1);
324 // Implicitly truncate the bits to match the official semantics of
325 // G_SPLAT_VECTOR.
326 Known = Known.trunc(BitWidth);
327 break;
328 }
329 case TargetOpcode::G_FREEZE: {
330 Register Src = MI.getOperand(1).getReg();
331 // freeze of undef/poison is an arbitrary noundef bit pattern, so the known
332 // bits of the source only carry over when it cannot be undef or poison.
333 if (isGuaranteedNotToBeUndefOrPoison(Src, MRI, Depth + 1))
334 computeKnownBitsImpl(Src, Known, DemandedElts, Depth + 1);
335 break;
336 }
337 case TargetOpcode::COPY:
338 case TargetOpcode::G_PHI:
339 case TargetOpcode::PHI: {
342 // Destination registers should not have subregisters at this
343 // point of the pipeline, otherwise the main live-range will be
344 // defined more than once, which is against SSA.
345 assert(MI.getOperand(0).getSubReg() == 0 && "Is this code in SSA?");
346 // PHI's operand are a mix of registers and basic blocks interleaved.
347 // We only care about the register ones.
348 for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
349 const MachineOperand &Src = MI.getOperand(Idx);
350 Register SrcReg = Src.getReg();
351 LLT SrcTy = MRI.getType(SrcReg);
352 // Look through trivial copies and phis but don't look through trivial
353 // copies or phis of the form `%1:(s32) = OP %0:gpr32`, known-bits
354 // analysis is currently unable to determine the bit width of a
355 // register class.
356 //
357 // We can't use NoSubRegister by name as it's defined by each target but
358 // it's always defined to be 0 by tablegen.
359 if (SrcReg.isVirtual() && Src.getSubReg() == 0 /*NoSubRegister*/ &&
360 SrcTy.isValid()) {
361 APInt NowDemandedElts;
362 if (!SrcTy.isFixedVector()) {
363 NowDemandedElts = APInt(1, 1);
364 } else if (DstTy.isFixedVector() &&
365 SrcTy.getNumElements() == DstTy.getNumElements()) {
366 NowDemandedElts = DemandedElts;
367 } else {
368 NowDemandedElts = APInt::getAllOnes(SrcTy.getNumElements());
369 }
370
371 // For COPYs we don't do anything, don't increase the depth.
372 computeKnownBitsImpl(SrcReg, Known2, NowDemandedElts,
373 Depth + (Opcode != TargetOpcode::COPY));
374 Known2 = Known2.anyextOrTrunc(BitWidth);
375 Known = Known.intersectWith(Known2);
376 // If we reach a point where we don't know anything
377 // just stop looking through the operands.
378 if (Known.isUnknown())
379 break;
380 } else {
381 // We know nothing.
383 break;
384 }
385 }
386 break;
387 }
388 case TargetOpcode::G_STEP_VECTOR: {
389 APInt Step = MI.getOperand(1).getCImm()->getValue();
390
391 if (Step.isPowerOf2())
392 Known.Zero.setLowBits(Step.logBase2());
393
395 break;
396
397 const APInt MinNumElts =
400 bool Overflow;
401 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
403 .umul_ov(MinNumElts, Overflow);
404 if (Overflow)
405 break;
406 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
407 if (Overflow)
408 break;
409 Known.Zero.setHighBits(MaxValue.countl_zero());
410 break;
411 }
412 case TargetOpcode::G_VSCALE: {
414 const APInt &Multiplier = MI.getOperand(1).getCImm()->getValue();
416 break;
417 }
418 case TargetOpcode::G_CONSTANT: {
419 Known = KnownBits::makeConstant(MI.getOperand(1).getCImm()->getValue());
420 break;
421 }
422 case TargetOpcode::G_FRAME_INDEX: {
423 int FrameIdx = MI.getOperand(1).getIndex();
424 TL.computeKnownBitsForStackObjectPointer(
425 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
426 break;
427 }
428 case TargetOpcode::G_SUB: {
429 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
430 Depth + 1);
431 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
432 Depth + 1);
434 MI.getFlag(MachineInstr::NoUWrap));
435 break;
436 }
437 case TargetOpcode::G_XOR: {
438 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
439 Depth + 1);
440 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
441 Depth + 1);
442
443 Known ^= Known2;
444 break;
445 }
446 case TargetOpcode::G_PTR_ADD: {
447 if (DstTy.isVector())
448 break;
449 // G_PTR_ADD is like G_ADD. FIXME: Is this true for all targets?
450 LLT Ty = MRI.getType(MI.getOperand(1).getReg());
451 if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
452 break;
453 [[fallthrough]];
454 }
455 case TargetOpcode::G_ADD: {
456 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
457 Depth + 1);
458 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
459 Depth + 1);
460 Known = KnownBits::add(Known, Known2);
461 break;
462 }
463 case TargetOpcode::G_AND: {
464 // If either the LHS or the RHS are Zero, the result is zero.
465 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
466 Depth + 1);
467 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
468 Depth + 1);
469
470 Known &= Known2;
471 break;
472 }
473 case TargetOpcode::G_OR: {
474 // If either the LHS or the RHS are Zero, the result is zero.
475 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
476 Depth + 1);
477 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
478 Depth + 1);
479
480 Known |= Known2;
481 break;
482 }
483 case TargetOpcode::G_MUL: {
484 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
485 Depth + 1);
486 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
487 Depth + 1);
488 Known = KnownBits::mul(Known, Known2);
489 break;
490 }
491 case TargetOpcode::G_UMULH: {
492 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
493 Depth + 1);
494 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
495 Depth + 1);
496 Known = KnownBits::mulhu(Known, Known2);
497 break;
498 }
499 case TargetOpcode::G_SMULH: {
500 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
501 Depth + 1);
502 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
503 Depth + 1);
504 Known = KnownBits::mulhs(Known, Known2);
505 break;
506 }
507 case TargetOpcode::G_CLMUL: {
508 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
509 Depth + 1);
510 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
511 Depth + 1);
512 Known = KnownBits::clmul(Known, Known2);
513 break;
514 }
515 case TargetOpcode::G_UAVGFLOOR: {
516 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
517 Depth + 1);
518 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
519 Depth + 1);
521 break;
522 }
523 case TargetOpcode::G_UAVGCEIL: {
524 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
525 Depth + 1);
526 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
527 Depth + 1);
529 break;
530 }
531 case TargetOpcode::G_SAVGFLOOR: {
532 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
533 Depth + 1);
534 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
535 Depth + 1);
537 break;
538 }
539 case TargetOpcode::G_SAVGCEIL: {
540 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
541 Depth + 1);
542 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
543 Depth + 1);
545 break;
546 }
547 case TargetOpcode::G_ABDU: {
548 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
549 Depth + 1);
550 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
551 Depth + 1);
552 Known = KnownBits::abdu(Known, Known2);
553 break;
554 }
555 case TargetOpcode::G_ABDS: {
556 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
557 Depth + 1);
558 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
559 Depth + 1);
560 Known = KnownBits::abds(Known, Known2);
561
562 unsigned SignBits1 =
563 computeNumSignBits(MI.getOperand(2).getReg(), DemandedElts, Depth + 1);
564 if (SignBits1 == 1) {
565 break;
566 }
567 unsigned SignBits0 =
568 computeNumSignBits(MI.getOperand(1).getReg(), DemandedElts, Depth + 1);
569
570 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
571 break;
572 }
573 case TargetOpcode::G_SADDSAT: {
574 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
575 Depth + 1);
576 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
577 Depth + 1);
579 break;
580 }
581 case TargetOpcode::G_UADDSAT: {
582 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
583 Depth + 1);
584 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
585 Depth + 1);
587 break;
588 }
589 case TargetOpcode::G_SSUBSAT: {
590 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
591 Depth + 1);
592 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
593 Depth + 1);
595 break;
596 }
597 case TargetOpcode::G_USUBSAT: {
598 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
599 Depth + 1);
600 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
601 Depth + 1);
603 break;
604 }
605 case TargetOpcode::G_UDIV: {
606 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
607 Depth + 1);
608 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
609 Depth + 1);
610 Known = KnownBits::udiv(Known, Known2,
612 break;
613 }
614 case TargetOpcode::G_SDIV: {
615 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
616 Depth + 1);
617 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
618 Depth + 1);
619 Known = KnownBits::sdiv(Known, Known2,
621 break;
622 }
623 case TargetOpcode::G_UREM: {
624 KnownBits LHSKnown(Known.getBitWidth());
625 KnownBits RHSKnown(Known.getBitWidth());
626
627 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
628 Depth + 1);
629 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
630 Depth + 1);
631
632 Known = KnownBits::urem(LHSKnown, RHSKnown);
633 break;
634 }
635 case TargetOpcode::G_SREM: {
636 KnownBits LHSKnown(Known.getBitWidth());
637 KnownBits RHSKnown(Known.getBitWidth());
638
639 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
640 Depth + 1);
641 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
642 Depth + 1);
643
644 Known = KnownBits::srem(LHSKnown, RHSKnown);
645 break;
646 }
647 case TargetOpcode::G_SELECT: {
648 computeKnownBitsMin(MI.getOperand(2).getReg(), MI.getOperand(3).getReg(),
649 Known, DemandedElts, Depth + 1);
650 break;
651 }
652 case TargetOpcode::G_SMIN: {
653 // TODO: Handle clamp pattern with number of sign bits
654 KnownBits KnownRHS;
655 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
656 Depth + 1);
657 computeKnownBitsImpl(MI.getOperand(2).getReg(), KnownRHS, DemandedElts,
658 Depth + 1);
659 Known = KnownBits::smin(Known, KnownRHS);
660 break;
661 }
662 case TargetOpcode::G_SMAX: {
663 // TODO: Handle clamp pattern with number of sign bits
664 KnownBits KnownRHS;
665 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
666 Depth + 1);
667 computeKnownBitsImpl(MI.getOperand(2).getReg(), KnownRHS, DemandedElts,
668 Depth + 1);
669 Known = KnownBits::smax(Known, KnownRHS);
670 break;
671 }
672 case TargetOpcode::G_UMIN: {
673 KnownBits KnownRHS;
674 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
675 Depth + 1);
676 computeKnownBitsImpl(MI.getOperand(2).getReg(), KnownRHS, DemandedElts,
677 Depth + 1);
678 Known = KnownBits::umin(Known, KnownRHS);
679 break;
680 }
681 case TargetOpcode::G_UMAX: {
682 KnownBits KnownRHS;
683 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
684 Depth + 1);
685 computeKnownBitsImpl(MI.getOperand(2).getReg(), KnownRHS, DemandedElts,
686 Depth + 1);
687 Known = KnownBits::umax(Known, KnownRHS);
688 break;
689 }
690 case TargetOpcode::G_FCMP:
691 case TargetOpcode::G_ICMP: {
692 if (DstTy.isVector())
693 break;
694 if (TL.getBooleanContents(DstTy.isVector(),
695 Opcode == TargetOpcode::G_FCMP) ==
697 BitWidth > 1)
698 Known.Zero.setBitsFrom(1);
699 break;
700 }
701 case TargetOpcode::G_SEXT: {
702 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
703 Depth + 1);
704 // If the sign bit is known to be zero or one, then sext will extend
705 // it to the top bits, else it will just zext.
706 Known = Known.sext(BitWidth);
707 break;
708 }
709 case TargetOpcode::G_ASSERT_SEXT:
710 case TargetOpcode::G_SEXT_INREG: {
711 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
712 Depth + 1);
713 Known = Known.sextInReg(MI.getOperand(2).getImm());
714 break;
715 }
716 case TargetOpcode::G_ANYEXT: {
717 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
718 Depth + 1);
719 Known = Known.anyext(BitWidth);
720 break;
721 }
722 case TargetOpcode::G_LOAD: {
723 const MachineMemOperand *MMO = *MI.memoperands_begin();
724 KnownBits KnownRange(MMO->getMemoryType().getScalarSizeInBits());
725 if (const MDNode *Ranges = MMO->getRanges())
726 computeKnownBitsFromRangeMetadata(*Ranges, KnownRange);
727 Known = KnownRange.anyext(Known.getBitWidth());
728 break;
729 }
730 case TargetOpcode::G_SEXTLOAD:
731 case TargetOpcode::G_ZEXTLOAD: {
732 if (DstTy.isVector())
733 break;
734 const MachineMemOperand *MMO = *MI.memoperands_begin();
735 KnownBits KnownRange(MMO->getMemoryType().getScalarSizeInBits());
736 if (const MDNode *Ranges = MMO->getRanges())
737 computeKnownBitsFromRangeMetadata(*Ranges, KnownRange);
738 Known = Opcode == TargetOpcode::G_SEXTLOAD
739 ? KnownRange.sext(Known.getBitWidth())
740 : KnownRange.zext(Known.getBitWidth());
741 break;
742 }
743 case TargetOpcode::G_ASHR: {
744 KnownBits LHSKnown, RHSKnown;
745 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
746 Depth + 1);
747 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
748 Depth + 1);
749 Known = KnownBits::ashr(LHSKnown, RHSKnown);
750 break;
751 }
752 case TargetOpcode::G_LSHR: {
753 KnownBits LHSKnown, RHSKnown;
754 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
755 Depth + 1);
756 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
757 Depth + 1);
758 Known = KnownBits::lshr(LHSKnown, RHSKnown);
759 break;
760 }
761 case TargetOpcode::G_SHL: {
762 KnownBits LHSKnown, RHSKnown;
763 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
764 Depth + 1);
765 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
766 Depth + 1);
767 Known = KnownBits::shl(LHSKnown, RHSKnown);
768 break;
769 }
770 case TargetOpcode::G_ROTL:
771 case TargetOpcode::G_ROTR: {
772 auto MaybeAmtOp =
773 isConstantOrConstantSplatVector(MI.getOperand(2).getReg(), MRI);
774 if (!MaybeAmtOp)
775 break;
776
777 Register SrcReg = MI.getOperand(1).getReg();
778 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
779
780 unsigned Amt = MaybeAmtOp->urem(BitWidth);
781
782 // Canonicalize to ROTR.
783 if (Opcode == TargetOpcode::G_ROTL)
784 Amt = BitWidth - Amt;
785
786 Known.Zero = Known.Zero.rotr(Amt);
787 Known.One = Known.One.rotr(Amt);
788 break;
789 }
790 case TargetOpcode::G_FSHL:
791 case TargetOpcode::G_FSHR: {
792 auto MaybeAmtOp =
793 isConstantOrConstantSplatVector(MI.getOperand(3).getReg(), MRI);
794 if (!MaybeAmtOp)
795 break;
796
797 const APInt Amt = *MaybeAmtOp;
798 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
799 Depth + 1);
800 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
801 Depth + 1);
802 Known = Opcode == TargetOpcode::G_FSHL
803 ? KnownBits::fshl(Known, Known2, Amt)
804 : KnownBits::fshr(Known, Known2, Amt);
805 break;
806 }
807 case TargetOpcode::G_INTTOPTR:
808 case TargetOpcode::G_PTRTOINT:
809 if (DstTy.isVector())
810 break;
811 // Fall through and handle them the same as zext/trunc.
812 [[fallthrough]];
813 case TargetOpcode::G_ZEXT:
814 case TargetOpcode::G_TRUNC: {
815 Register SrcReg = MI.getOperand(1).getReg();
816 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
817 Known = Known.zextOrTrunc(BitWidth);
818 break;
819 }
820 case TargetOpcode::G_TRUNC_SSAT_S: {
821 Register SrcReg = MI.getOperand(1).getReg();
822 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
823 Known = Known.truncSSat(BitWidth);
824 break;
825 }
826 case TargetOpcode::G_TRUNC_SSAT_U: {
827 Register SrcReg = MI.getOperand(1).getReg();
828 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
829 Known = Known.truncSSatU(BitWidth);
830 break;
831 }
832 case TargetOpcode::G_TRUNC_USAT_U: {
833 Register SrcReg = MI.getOperand(1).getReg();
834 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
835 Known = Known.truncUSat(BitWidth);
836 break;
837 }
838 case TargetOpcode::G_ASSERT_ZEXT: {
839 Register SrcReg = MI.getOperand(1).getReg();
840 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
841
842 unsigned SrcBitWidth = MI.getOperand(2).getImm();
843 assert(SrcBitWidth && "SrcBitWidth can't be zero");
844 APInt InMask = APInt::getLowBitsSet(BitWidth, SrcBitWidth);
845 Known.Zero |= (~InMask);
846 Known.One &= (~Known.Zero);
847 break;
848 }
849 case TargetOpcode::G_ASSERT_ALIGN: {
850 int64_t LogOfAlign = Log2_64(MI.getOperand(2).getImm());
851
852 // TODO: Should use maximum with source
853 // If a node is guaranteed to be aligned, set low zero bits accordingly as
854 // well as clearing one bits.
855 Known.Zero.setLowBits(LogOfAlign);
856 Known.One.clearLowBits(LogOfAlign);
857 break;
858 }
859 case TargetOpcode::G_MERGE_VALUES: {
860 unsigned NumOps = MI.getNumOperands();
861 unsigned OpSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
862
863 for (unsigned I = 0; I != NumOps - 1; ++I) {
864 KnownBits SrcOpKnown;
865 computeKnownBitsImpl(MI.getOperand(I + 1).getReg(), SrcOpKnown,
866 DemandedElts, Depth + 1);
867 Known.insertBits(SrcOpKnown, I * OpSize);
868 }
869 break;
870 }
871 case TargetOpcode::G_UNMERGE_VALUES: {
872 unsigned NumOps = MI.getNumOperands();
873 Register SrcReg = MI.getOperand(NumOps - 1).getReg();
874 LLT SrcTy = MRI.getType(SrcReg);
875
876 if (SrcTy.isVector() && SrcTy.getScalarType() != DstTy.getScalarType())
877 return; // TODO: Handle vector->subelement unmerges
878
879 // Figure out the result operand index
880 unsigned DstIdx = MI.findRegisterDefOperandIdx(R, nullptr);
881
882 APInt SubDemandedElts = DemandedElts;
883 if (SrcTy.isVector()) {
884 unsigned DstLanes = DstTy.isVector() ? DstTy.getNumElements() : 1;
885 SubDemandedElts =
886 DemandedElts.zext(SrcTy.getNumElements()).shl(DstIdx * DstLanes);
887 }
888
889 KnownBits SrcOpKnown;
890 computeKnownBitsImpl(SrcReg, SrcOpKnown, SubDemandedElts, Depth + 1);
891
892 if (SrcTy.isVector())
893 Known = std::move(SrcOpKnown);
894 else
895 Known = SrcOpKnown.extractBits(BitWidth, BitWidth * DstIdx);
896 break;
897 }
898 case TargetOpcode::G_BSWAP: {
899 Register SrcReg = MI.getOperand(1).getReg();
900 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
901 Known = Known.byteSwap();
902 break;
903 }
904 case TargetOpcode::G_BITREVERSE: {
905 Register SrcReg = MI.getOperand(1).getReg();
906 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
907 Known = Known.reverseBits();
908 break;
909 }
910 case TargetOpcode::G_CTPOP: {
911 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
912 Depth + 1);
913 // We can bound the space the count needs. Also, bits known to be zero
914 // can't contribute to the population.
915 unsigned BitsPossiblySet = Known2.countMaxPopulation();
916 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
917 Known.Zero.setBitsFrom(LowBits);
918 // TODO: we could bound Known.One using the lower bound on the number of
919 // bits which might be set provided by popcnt KnownOne2.
920 break;
921 }
922 case TargetOpcode::G_UBFX: {
923 KnownBits SrcOpKnown, OffsetKnown, WidthKnown;
924 computeKnownBitsImpl(MI.getOperand(1).getReg(), SrcOpKnown, DemandedElts,
925 Depth + 1);
926 computeKnownBitsImpl(MI.getOperand(2).getReg(), OffsetKnown, DemandedElts,
927 Depth + 1);
928 computeKnownBitsImpl(MI.getOperand(3).getReg(), WidthKnown, DemandedElts,
929 Depth + 1);
930 Known = extractBits(BitWidth, SrcOpKnown, OffsetKnown, WidthKnown);
931 break;
932 }
933 case TargetOpcode::G_SBFX: {
934 KnownBits SrcOpKnown, OffsetKnown, WidthKnown;
935 computeKnownBitsImpl(MI.getOperand(1).getReg(), SrcOpKnown, DemandedElts,
936 Depth + 1);
937 computeKnownBitsImpl(MI.getOperand(2).getReg(), OffsetKnown, DemandedElts,
938 Depth + 1);
939 computeKnownBitsImpl(MI.getOperand(3).getReg(), WidthKnown, DemandedElts,
940 Depth + 1);
941 OffsetKnown = OffsetKnown.sext(BitWidth);
942 WidthKnown = WidthKnown.sext(BitWidth);
943 Known = extractBits(BitWidth, SrcOpKnown, OffsetKnown, WidthKnown);
944 // Sign extend the extracted value using shift left and arithmetic shift
945 // right.
947 KnownBits ShiftKnown = KnownBits::sub(ExtKnown, WidthKnown);
948 Known = KnownBits::ashr(KnownBits::shl(Known, ShiftKnown), ShiftKnown);
949 break;
950 }
951 case TargetOpcode::G_UADDO:
952 case TargetOpcode::G_UADDE:
953 case TargetOpcode::G_SADDO:
954 case TargetOpcode::G_SADDE: {
955 if (MI.getOperand(1).getReg() == R) {
956 // If we know the result of a compare has the top bits zero, use this
957 // info.
958 if (TL.getBooleanContents(DstTy.isVector(), false) ==
960 BitWidth > 1)
961 Known.Zero.setBitsFrom(1);
962 break;
963 }
964
965 assert(MI.getOperand(0).getReg() == R &&
966 "We only compute knownbits for the sum here.");
967 // With [US]ADDE, a carry bit may be added in.
968 KnownBits Carry(1);
969 if (Opcode == TargetOpcode::G_UADDE || Opcode == TargetOpcode::G_SADDE) {
970 computeKnownBitsImpl(MI.getOperand(4).getReg(), Carry, DemandedElts,
971 Depth + 1);
972 // Carry has bit width 1
973 Carry = Carry.trunc(1);
974 } else {
975 Carry.setAllZero();
976 }
977
978 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
979 Depth + 1);
980 computeKnownBitsImpl(MI.getOperand(3).getReg(), Known2, DemandedElts,
981 Depth + 1);
982 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
983 break;
984 }
985 case TargetOpcode::G_USUBO:
986 case TargetOpcode::G_USUBE:
987 case TargetOpcode::G_SSUBO:
988 case TargetOpcode::G_SSUBE:
989 case TargetOpcode::G_UMULO:
990 case TargetOpcode::G_SMULO: {
991 if (MI.getOperand(1).getReg() == R) {
992 // If we know the result of a compare has the top bits zero, use this
993 // info.
994 if (TL.getBooleanContents(DstTy.isVector(), false) ==
996 BitWidth > 1)
997 Known.Zero.setBitsFrom(1);
998 }
999 break;
1000 }
1001 case TargetOpcode::G_CTTZ:
1002 case TargetOpcode::G_CTTZ_ZERO_POISON: {
1003 KnownBits SrcOpKnown;
1004 computeKnownBitsImpl(MI.getOperand(1).getReg(), SrcOpKnown, DemandedElts,
1005 Depth + 1);
1006 // If we have a known 1, its position is our upper bound
1007 unsigned PossibleTZ = SrcOpKnown.countMaxTrailingZeros();
1008 unsigned LowBits = llvm::bit_width(PossibleTZ);
1009 Known.Zero.setBitsFrom(LowBits);
1010 break;
1011 }
1012 case TargetOpcode::G_CTLZ:
1013 case TargetOpcode::G_CTLZ_ZERO_POISON: {
1014 KnownBits SrcOpKnown;
1015 computeKnownBitsImpl(MI.getOperand(1).getReg(), SrcOpKnown, DemandedElts,
1016 Depth + 1);
1017 // If we have a known 1, its position is our upper bound.
1018 unsigned PossibleLZ = SrcOpKnown.countMaxLeadingZeros();
1019 unsigned LowBits = llvm::bit_width(PossibleLZ);
1020 Known.Zero.setBitsFrom(LowBits);
1021 break;
1022 }
1023 case TargetOpcode::G_CTLS: {
1024 Register Reg = MI.getOperand(1).getReg();
1025 unsigned MinRedundantSignBits = computeNumSignBits(Reg, Depth + 1) - 1;
1026
1027 unsigned MaxUpperRedundantSignBits = MRI.getType(Reg).getScalarSizeInBits();
1028
1029 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
1030 APInt(BitWidth, MaxUpperRedundantSignBits));
1031
1032 Known = Range.toKnownBits();
1033 break;
1034 }
1035 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
1037 Register InVec = Extract.getVectorReg();
1038 Register EltNo = Extract.getIndexReg();
1039
1040 auto ConstEltNo = getIConstantVRegVal(EltNo, MRI);
1041
1042 LLT VecVT = MRI.getType(InVec);
1043 // computeKnownBits not yet implemented for scalable vectors.
1044 if (VecVT.isScalableVector())
1045 break;
1046
1047 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
1048 const unsigned NumSrcElts = VecVT.getNumElements();
1049 // A return type different from the vector's element type may lead to
1050 // issues with pattern selection. Bail out to avoid that.
1051 if (BitWidth > EltBitWidth)
1052 break;
1053
1054 Known.Zero.setAllBits();
1055 Known.One.setAllBits();
1056
1057 // If we know the element index, just demand that vector element, else for
1058 // an unknown element index, ignore DemandedElts and demand them all.
1059 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
1060 if (ConstEltNo && ConstEltNo->ult(NumSrcElts))
1061 DemandedSrcElts =
1062 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
1063
1064 computeKnownBitsImpl(InVec, Known, DemandedSrcElts, Depth + 1);
1065 break;
1066 }
1067 case TargetOpcode::G_INSERT_VECTOR_ELT: {
1069 Register InVec = Insert.getVectorReg();
1070 Register InVal = Insert.getElementReg();
1071 Register EltNo = Insert.getIndexReg();
1072 LLT VecVT = MRI.getType(InVec);
1073
1074 if (VecVT.isScalableVector())
1075 break;
1076
1077 auto ConstEltNo = getIConstantVRegVal(EltNo, MRI);
1078 unsigned NumElts = VecVT.getNumElements();
1079
1080 bool DemandedVal = true;
1081 APInt DemandedVecElts = DemandedElts;
1082 if (ConstEltNo && ConstEltNo->ult(NumElts)) {
1083 unsigned EltIdx = ConstEltNo->getZExtValue();
1084 DemandedVal = !!DemandedElts[EltIdx];
1085 DemandedVecElts.clearBit(EltIdx);
1086 }
1087 Known.setAllConflict();
1088 if (DemandedVal) {
1089 computeKnownBitsImpl(InVal, Known2, APInt(1, 1), Depth + 1);
1090 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
1091 }
1092 if (!!DemandedVecElts) {
1093 computeKnownBitsImpl(InVec, Known2, DemandedVecElts, Depth + 1);
1094 Known = Known.intersectWith(Known2);
1095 }
1096 break;
1097 }
1098 case TargetOpcode::G_INSERT_SUBVECTOR: {
1100 Register Src = Insert.getBigVec();
1101 Register Sub = Insert.getSubVec();
1102 uint64_t Idx = Insert.getIndexImm();
1103 LLT SrcTy = MRI.getType(Src);
1104 LLT SubTy = MRI.getType(Sub);
1105 APInt DemandedSubElts;
1106 APInt DemandedSrcElts;
1107
1108 if (SrcTy.isScalableVector()) {
1109 DemandedSubElts = SubTy.isScalableVector()
1110 ? APInt(1, 1)
1112 DemandedSrcElts = APInt(1, 1);
1113 } else {
1114 unsigned NumSubElts = SubTy.getNumElements();
1115 DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1116 DemandedSrcElts = DemandedElts;
1117 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
1118 }
1119
1120 Known.setAllConflict();
1121 if (!!DemandedSubElts) {
1122 computeKnownBitsImpl(Sub, Known2, DemandedSubElts, Depth + 1);
1123 Known = Known.intersectWith(Known2);
1124 if (Known.isUnknown())
1125 break;
1126 }
1127
1128 if (!!DemandedSrcElts) {
1129 computeKnownBitsImpl(Src, Known2, DemandedSrcElts, Depth + 1);
1130 Known = Known.intersectWith(Known2);
1131 }
1132
1133 break;
1134 }
1135 case TargetOpcode::G_EXTRACT_SUBVECTOR: {
1136 Register SrcReg = MI.getOperand(1).getReg();
1137 LLT SrcTy = MRI.getType(SrcReg);
1138 APInt DemandedSrcElts;
1139 if (SrcTy.isScalableVector()) {
1140 DemandedSrcElts = APInt(1, 1);
1141 } else {
1142 uint64_t Idx = MI.getOperand(2).getImm();
1143 unsigned NumSrcElts = SrcTy.getNumElements();
1144 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1145 }
1146 computeKnownBitsImpl(SrcReg, Known, DemandedSrcElts, Depth + 1);
1147 break;
1148 }
1149 case TargetOpcode::G_SHUFFLE_VECTOR: {
1150 APInt DemandedLHS, DemandedRHS;
1151 // Collect the known bits that are shared by every vector element referenced
1152 // by the shuffle.
1153 unsigned NumElts = MRI.getType(MI.getOperand(1).getReg()).getNumElements();
1154 if (!getShuffleDemandedElts(NumElts, MI.getOperand(3).getShuffleMask(),
1155 DemandedElts, DemandedLHS, DemandedRHS))
1156 break;
1157
1158 // Known bits are the values that are shared by every demanded element.
1159 Known.Zero.setAllBits();
1160 Known.One.setAllBits();
1161 if (!!DemandedLHS) {
1162 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedLHS,
1163 Depth + 1);
1164 Known = Known.intersectWith(Known2);
1165 }
1166 // If we don't know any bits, early out.
1167 if (Known.isUnknown())
1168 break;
1169 if (!!DemandedRHS) {
1170 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedRHS,
1171 Depth + 1);
1172 Known = Known.intersectWith(Known2);
1173 }
1174 break;
1175 }
1176 case TargetOpcode::G_CONCAT_VECTORS: {
1177 if (MRI.getType(MI.getOperand(0).getReg()).isScalableVector())
1178 break;
1179 // Split DemandedElts and test each of the demanded subvectors.
1180 Known.Zero.setAllBits();
1181 Known.One.setAllBits();
1182 unsigned NumSubVectorElts =
1183 MRI.getType(MI.getOperand(1).getReg()).getNumElements();
1184
1185 for (const auto &[I, MO] : enumerate(drop_begin(MI.operands()))) {
1186 APInt DemandedSub =
1187 DemandedElts.extractBits(NumSubVectorElts, I * NumSubVectorElts);
1188 if (!!DemandedSub) {
1189 computeKnownBitsImpl(MO.getReg(), Known2, DemandedSub, Depth + 1);
1190
1191 Known = Known.intersectWith(Known2);
1192 }
1193 // If we don't know any bits, early out.
1194 if (Known.isUnknown())
1195 break;
1196 }
1197 break;
1198 }
1199 case TargetOpcode::G_VECTOR_COMPRESS: {
1200 // Each result lane is either a lane of the source vector or the passthru,
1201 // so the known bits are those shared by both.
1202 Register Vec = MI.getOperand(1).getReg();
1203 Register PassThru = MI.getOperand(3).getReg();
1204 computeKnownBitsImpl(PassThru, Known, DemandedElts, Depth + 1);
1205 // If we don't know any bits, early out.
1206 if (Known.isUnknown())
1207 break;
1208 // Compression can move any source lane to any result position, so all
1209 // source lanes are demanded.
1210 APInt DemandedSrcElts = APInt::getAllOnes(DemandedElts.getBitWidth());
1211 computeKnownBitsImpl(Vec, Known2, DemandedSrcElts, Depth + 1);
1212 Known = Known.intersectWith(Known2);
1213 break;
1214 }
1215 case TargetOpcode::G_ABS: {
1216 Register SrcReg = MI.getOperand(1).getReg();
1217 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
1218 Known = Known.abs();
1219 Known.Zero.setHighBits(computeNumSignBits(SrcReg, DemandedElts, Depth + 1) -
1220 1);
1221 break;
1222 }
1223 }
1224
1226}
1227
1228void GISelValueTracking::computeKnownFPClass(Register R, KnownFPClass &Known,
1229 FPClassTest InterestedClasses,
1230 unsigned Depth) {
1231 LLT Ty = MRI.getType(R);
1232 APInt DemandedElts =
1233 Ty.isFixedVector() ? APInt::getAllOnes(Ty.getNumElements()) : APInt(1, 1);
1234 computeKnownFPClass(R, DemandedElts, InterestedClasses, Known, Depth);
1235}
1236
1237/// Return true if this value is known to be the fractional part x - floor(x),
1238/// which lies in [0, 1). This implies the value cannot introduce overflow in a
1239/// fmul when the other operand is known finite.
1241 using namespace MIPatternMatch;
1242 Register SubX;
1243 return mi_match(R, MRI, m_GFSub(m_Reg(SubX), m_GFFloor(m_DeferredReg(SubX))));
1244}
1245
1246void GISelValueTracking::computeKnownFPClassForFPTrunc(
1247 const MachineInstr &MI, const APInt &DemandedElts,
1248 FPClassTest InterestedClasses, KnownFPClass &Known, unsigned Depth) {
1249 if ((InterestedClasses & (KnownFPClass::OrderedLessThanZeroMask | fcNan)) ==
1250 fcNone)
1251 return;
1252
1253 Register Val = MI.getOperand(1).getReg();
1254 KnownFPClass KnownSrc;
1255 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1256 Depth + 1);
1257 Known = KnownFPClass::fptrunc(KnownSrc);
1258}
1259
1260void GISelValueTracking::computeKnownFPClass(Register R,
1261 const APInt &DemandedElts,
1262 FPClassTest InterestedClasses,
1264 unsigned Depth) {
1265 assert(Known.isUnknown() && "should not be called with known information");
1266
1267 if (!DemandedElts) {
1268 // No demanded elts, better to assume we don't know anything.
1269 Known.resetAll();
1270 return;
1271 }
1272
1273 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1274
1275 MachineInstr &MI = *MRI.getVRegDef(R);
1276 unsigned Opcode = MI.getOpcode();
1277 LLT DstTy = MRI.getType(R);
1278
1279 if (!DstTy.isValid()) {
1280 Known.resetAll();
1281 return;
1282 }
1283
1284 if (auto Cst = GFConstant::getConstant(R, MRI)) {
1285 switch (Cst->getKind()) {
1287 auto APF = Cst->getScalarValue();
1288 Known.setKnownFPClasses(APF.classify());
1289 Known.setSignBit(APF.isNegative());
1290 break;
1291 }
1293 Known.setKnownFPClasses(fcNone);
1294 bool SignBitAllZero = true;
1295 bool SignBitAllOne = true;
1296
1297 for (auto C : *Cst) {
1298 Known.setKnownFPClasses(Known.getKnownFPClasses() | C.classify());
1299 if (C.isNegative())
1300 SignBitAllZero = false;
1301 else
1302 SignBitAllOne = false;
1303 }
1304
1305 if (SignBitAllOne != SignBitAllZero)
1306 Known.setSignBit(SignBitAllOne);
1307
1308 break;
1309 }
1311 Known.resetAll();
1312 break;
1313 }
1314 }
1315
1316 return;
1317 }
1318
1319 FPClassTest KnownNotFromFlags = fcNone;
1321 KnownNotFromFlags |= fcNan;
1323 KnownNotFromFlags |= fcInf;
1324
1325 // We no longer need to find out about these bits from inputs if we can
1326 // assume this from flags/attributes.
1327 InterestedClasses &= ~KnownNotFromFlags;
1328
1329 llvm::scope_exit ClearClassesFromFlags(
1330 [=, &Known] { Known.knownNot(KnownNotFromFlags); });
1331
1332 // All recursive calls that increase depth must come after this.
1334 return;
1335
1336 const MachineFunction *MF = MI.getMF();
1337
1338 switch (Opcode) {
1339 default:
1340 TL.computeKnownFPClassForTargetInstr(*this, R, Known, DemandedElts, MRI,
1341 Depth);
1342 break;
1343 case TargetOpcode::G_FNEG: {
1344 Register Val = MI.getOperand(1).getReg();
1345 computeKnownFPClass(Val, DemandedElts, InterestedClasses, Known, Depth + 1);
1346 Known.fneg();
1347 break;
1348 }
1349 case TargetOpcode::G_SELECT: {
1350 GSelect &SelMI = cast<GSelect>(MI);
1351 Register Cond = SelMI.getCondReg();
1352 Register LHS = SelMI.getTrueReg();
1353 Register RHS = SelMI.getFalseReg();
1354
1355 FPClassTest FilterLHS = fcAllFlags;
1356 FPClassTest FilterRHS = fcAllFlags;
1357
1358 Register TestedValue;
1359 FPClassTest MaskIfTrue = fcAllFlags;
1360 FPClassTest MaskIfFalse = fcAllFlags;
1361 FPClassTest ClassVal = fcNone;
1362
1363 CmpInst::Predicate Pred;
1364 Register CmpLHS, CmpRHS;
1365 if (mi_match(Cond, MRI,
1366 m_GFCmp(m_Pred(Pred), m_Reg(CmpLHS), m_Reg(CmpRHS)))) {
1367 // If the select filters out a value based on the class, it no longer
1368 // participates in the class of the result
1369
1370 // TODO: In some degenerate cases we can infer something if we try again
1371 // without looking through sign operations.
1372 bool LookThroughFAbsFNeg = CmpLHS != LHS && CmpLHS != RHS;
1373 std::tie(TestedValue, MaskIfTrue, MaskIfFalse) =
1374 fcmpImpliesClass(Pred, *MF, CmpLHS, CmpRHS, LookThroughFAbsFNeg);
1375 } else if (mi_match(
1376 Cond, MRI,
1377 m_GIsFPClass(m_Reg(TestedValue), m_FPClassTest(ClassVal)))) {
1378 FPClassTest TestedMask = ClassVal;
1379 MaskIfTrue = TestedMask;
1380 MaskIfFalse = ~TestedMask;
1381 }
1382
1383 if (TestedValue == LHS) {
1384 // match !isnan(x) ? x : y
1385 FilterLHS = MaskIfTrue;
1386 } else if (TestedValue == RHS) { // && IsExactClass
1387 // match !isnan(x) ? y : x
1388 FilterRHS = MaskIfFalse;
1389 }
1390
1391 KnownFPClass Known2;
1392 computeKnownFPClass(LHS, DemandedElts, InterestedClasses & FilterLHS, Known,
1393 Depth + 1);
1394 Known.setKnownFPClasses(Known.getKnownFPClasses() & FilterLHS);
1395
1396 computeKnownFPClass(RHS, DemandedElts, InterestedClasses & FilterRHS,
1397 Known2, Depth + 1);
1398 Known2.setKnownFPClasses(Known2.getKnownFPClasses() & FilterRHS);
1399
1400 Known |= Known2;
1401 break;
1402 }
1403 case TargetOpcode::G_FCOPYSIGN: {
1404 Register Magnitude = MI.getOperand(1).getReg();
1405 Register Sign = MI.getOperand(2).getReg();
1406
1407 KnownFPClass KnownSign;
1408
1409 computeKnownFPClass(Magnitude, DemandedElts, InterestedClasses, Known,
1410 Depth + 1);
1411 computeKnownFPClass(Sign, DemandedElts, InterestedClasses, KnownSign,
1412 Depth + 1);
1413 Known.copysign(KnownSign);
1414 break;
1415 }
1416 case TargetOpcode::G_FMA:
1417 case TargetOpcode::G_STRICT_FMA:
1418 case TargetOpcode::G_FMAD: {
1419 if ((InterestedClasses & fcNegative) == fcNone)
1420 break;
1421
1422 Register A = MI.getOperand(1).getReg();
1423 Register B = MI.getOperand(2).getReg();
1424 Register C = MI.getOperand(3).getReg();
1425
1426 DenormalMode Mode =
1427 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1428
1429 if (A == B && isGuaranteedNotToBeUndef(A, MRI, Depth + 1)) {
1430 // x * x + y
1431 KnownFPClass KnownSrc, KnownAddend;
1432 computeKnownFPClass(C, DemandedElts, InterestedClasses, KnownAddend,
1433 Depth + 1);
1434 computeKnownFPClass(A, DemandedElts, InterestedClasses, KnownSrc,
1435 Depth + 1);
1436 if (KnownNotFromFlags) {
1437 KnownSrc.knownNot(KnownNotFromFlags);
1438 KnownAddend.knownNot(KnownNotFromFlags);
1439 }
1440 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
1441 } else {
1442 KnownFPClass KnownSrc[3];
1443 computeKnownFPClass(A, DemandedElts, InterestedClasses, KnownSrc[0],
1444 Depth + 1);
1445 if (KnownSrc[0].isUnknown())
1446 break;
1447 computeKnownFPClass(B, DemandedElts, InterestedClasses, KnownSrc[1],
1448 Depth + 1);
1449 if (KnownSrc[1].isUnknown())
1450 break;
1451 computeKnownFPClass(C, DemandedElts, InterestedClasses, KnownSrc[2],
1452 Depth + 1);
1453 if (KnownSrc[2].isUnknown())
1454 break;
1455 if (KnownNotFromFlags) {
1456 KnownSrc[0].knownNot(KnownNotFromFlags);
1457 KnownSrc[1].knownNot(KnownNotFromFlags);
1458 KnownSrc[2].knownNot(KnownNotFromFlags);
1459 }
1460 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
1461 }
1462 break;
1463 }
1464 case TargetOpcode::G_FSQRT:
1465 case TargetOpcode::G_STRICT_FSQRT: {
1466 KnownFPClass KnownSrc;
1467 FPClassTest InterestedSrcs = InterestedClasses;
1468 if (InterestedClasses & fcNan)
1469 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
1470
1471 Register Val = MI.getOperand(1).getReg();
1472 computeKnownFPClass(Val, DemandedElts, InterestedSrcs, KnownSrc, Depth + 1);
1473
1474 DenormalMode Mode =
1475 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1476 Known = KnownFPClass::sqrt(KnownSrc, Mode);
1477 if (MI.getFlag(MachineInstr::MIFlag::FmNsz))
1478 Known.knownNot(fcNegZero);
1479 break;
1480 }
1481 case TargetOpcode::G_FABS: {
1482 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
1483 Register Val = MI.getOperand(1).getReg();
1484 // If we only care about the sign bit we don't need to inspect the
1485 // operand.
1486 computeKnownFPClass(Val, DemandedElts, InterestedClasses, Known,
1487 Depth + 1);
1488 }
1489 Known.fabs();
1490 break;
1491 }
1492 case TargetOpcode::G_FATAN2: {
1493 FPClassTest InterestedY = InterestedClasses;
1494 FPClassTest InterestedX = InterestedClasses;
1495
1496 // We can rule out negative values if y cannot have a negative value.
1497 if ((InterestedClasses & fcNegFinite) != fcNone)
1498 InterestedY |= fcNegative;
1499
1500 // We can rule out positive values if y cannot have a positive value.
1501 if ((InterestedClasses & fcPosFinite) != fcNone)
1502 InterestedY |= fcPositive | fcNegSubnormal;
1503
1504 // We can rule out zero and subnormal if x cannot have a positive value.
1505 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
1506 InterestedX |= fcPositive | fcNegSubnormal;
1507
1508 Register Y = MI.getOperand(1).getReg();
1509 Register X = MI.getOperand(2).getReg();
1510 KnownFPClass KnownY, KnownX;
1511 computeKnownFPClass(Y, DemandedElts, InterestedY, KnownY, Depth + 1);
1512 computeKnownFPClass(X, DemandedElts, InterestedX, KnownX, Depth + 1);
1513 DenormalMode Mode =
1514 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1515 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
1516 break;
1517 }
1518 case TargetOpcode::G_FSINH: {
1519 Register Val = MI.getOperand(1).getReg();
1520 KnownFPClass KnownSrc;
1521 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1522 Depth + 1);
1523 Known = KnownFPClass::sinh(KnownSrc);
1524 break;
1525 }
1526 case TargetOpcode::G_FCOSH: {
1527 Register Val = MI.getOperand(1).getReg();
1528 KnownFPClass KnownSrc;
1529 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1530 Depth + 1);
1531 Known = KnownFPClass::cosh(KnownSrc);
1532 break;
1533 }
1534 case TargetOpcode::G_FTANH: {
1535 Register Val = MI.getOperand(1).getReg();
1536 KnownFPClass KnownSrc;
1537 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1538 Depth + 1);
1539 Known = KnownFPClass::tanh(KnownSrc);
1540 break;
1541 }
1542 case TargetOpcode::G_FASIN: {
1543 Register Val = MI.getOperand(1).getReg();
1544 KnownFPClass KnownSrc;
1545 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1546 Depth + 1);
1547 Known = KnownFPClass::asin(KnownSrc);
1548 break;
1549 }
1550 case TargetOpcode::G_FACOS: {
1551 Register Val = MI.getOperand(1).getReg();
1552 KnownFPClass KnownSrc;
1553 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1554 Depth + 1);
1555 Known = KnownFPClass::acos(KnownSrc);
1556 break;
1557 }
1558 case TargetOpcode::G_FATAN: {
1559 Register Val = MI.getOperand(1).getReg();
1560 KnownFPClass KnownSrc;
1561 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1562 Depth + 1);
1563 Known = KnownFPClass::atan(KnownSrc);
1564 break;
1565 }
1566 case TargetOpcode::G_FTAN: {
1567 Register Val = MI.getOperand(1).getReg();
1568 KnownFPClass KnownSrc;
1569 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1570 Depth + 1);
1571 Known = KnownFPClass::tan(KnownSrc);
1572 break;
1573 }
1574 case TargetOpcode::G_FSIN:
1575 case TargetOpcode::G_FCOS: {
1576 // Return NaN on infinite inputs.
1577 Register Val = MI.getOperand(1).getReg();
1578 KnownFPClass KnownSrc;
1579 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1580 Depth + 1);
1581 Known = Opcode == TargetOpcode::G_FCOS ? KnownFPClass::cos(KnownSrc)
1582 : KnownFPClass::sin(KnownSrc);
1583 break;
1584 }
1585 case TargetOpcode::G_FSINCOS: {
1586 // Operand layout: (sin_dst, cos_dst, src)
1587 Register Src = MI.getOperand(2).getReg();
1588 KnownFPClass KnownSrc;
1589 computeKnownFPClass(Src, DemandedElts, InterestedClasses, KnownSrc,
1590 Depth + 1);
1591 if (R == MI.getOperand(0).getReg())
1592 Known = KnownFPClass::sin(KnownSrc);
1593 else
1594 Known = KnownFPClass::cos(KnownSrc);
1595 break;
1596 }
1597 case TargetOpcode::G_FMAXNUM:
1598 case TargetOpcode::G_FMINNUM:
1599 case TargetOpcode::G_FMINNUM_IEEE:
1600 case TargetOpcode::G_FMAXIMUM:
1601 case TargetOpcode::G_FMINIMUM:
1602 case TargetOpcode::G_FMAXNUM_IEEE:
1603 case TargetOpcode::G_FMAXIMUMNUM:
1604 case TargetOpcode::G_FMINIMUMNUM: {
1605 Register LHS = MI.getOperand(1).getReg();
1606 Register RHS = MI.getOperand(2).getReg();
1607 KnownFPClass KnownLHS, KnownRHS;
1608
1609 computeKnownFPClass(LHS, DemandedElts, InterestedClasses, KnownLHS,
1610 Depth + 1);
1611 computeKnownFPClass(RHS, DemandedElts, InterestedClasses, KnownRHS,
1612 Depth + 1);
1613
1615 switch (Opcode) {
1616 case TargetOpcode::G_FMINIMUM:
1618 break;
1619 case TargetOpcode::G_FMAXIMUM:
1621 break;
1622 case TargetOpcode::G_FMINIMUMNUM:
1624 break;
1625 case TargetOpcode::G_FMAXIMUMNUM:
1627 break;
1628 case TargetOpcode::G_FMINNUM:
1629 case TargetOpcode::G_FMINNUM_IEEE:
1631 break;
1632 case TargetOpcode::G_FMAXNUM:
1633 case TargetOpcode::G_FMAXNUM_IEEE:
1635 break;
1636 default:
1637 llvm_unreachable("unhandled min/max opcode");
1638 }
1639
1640 DenormalMode Mode =
1641 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1642 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, Kind, Mode);
1643 break;
1644 }
1645 case TargetOpcode::G_FCANONICALIZE: {
1646 Register Val = MI.getOperand(1).getReg();
1647 KnownFPClass KnownSrc;
1648 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1649 Depth + 1);
1650
1651 LLT Ty = MRI.getType(Val).getScalarType();
1652 const fltSemantics &FPType = getFltSemanticForLLT(Ty);
1653 DenormalMode DenormMode = MF->getDenormalMode(FPType);
1654 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
1655 break;
1656 }
1657 case TargetOpcode::G_VECREDUCE_FMAX:
1658 case TargetOpcode::G_VECREDUCE_FMIN:
1659 case TargetOpcode::G_VECREDUCE_FMAXIMUM:
1660 case TargetOpcode::G_VECREDUCE_FMINIMUM:
1661 case TargetOpcode::G_VECREDUCE_FMAXIMUMNUM:
1662 case TargetOpcode::G_VECREDUCE_FMINIMUMNUM: {
1663 Register Val = MI.getOperand(1).getReg();
1664 // reduce min/max will choose an element from one of the vector elements,
1665 // so we can infer and class information that is common to all elements.
1666
1667 Known =
1668 computeKnownFPClass(Val, MI.getFlags(), InterestedClasses, Depth + 1);
1669 // Can only propagate sign if output is never NaN.
1670 if (!Known.isKnownNeverNaN())
1671 Known.setSignBit(std::nullopt);
1672 break;
1673 }
1674 case TargetOpcode::G_FFLOOR:
1675 case TargetOpcode::G_FCEIL:
1676 case TargetOpcode::G_FRINT:
1677 case TargetOpcode::G_FNEARBYINT:
1678 case TargetOpcode::G_INTRINSIC_ROUND:
1679 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
1680 case TargetOpcode::G_INTRINSIC_TRUNC: {
1681 Register Val = MI.getOperand(1).getReg();
1682 KnownFPClass KnownSrc;
1683 FPClassTest InterestedSrcs = InterestedClasses;
1684 if (InterestedSrcs & fcPosFinite)
1685 InterestedSrcs |= fcPosFinite;
1686 if (InterestedSrcs & fcNegFinite)
1687 InterestedSrcs |= fcNegFinite;
1688 computeKnownFPClass(Val, DemandedElts, InterestedSrcs, KnownSrc, Depth + 1);
1689
1690 // TODO: handle multi unit FPTypes once LLT FPInfo lands
1691 bool IsTrunc = Opcode == TargetOpcode::G_INTRINSIC_TRUNC;
1692 Known = KnownFPClass::roundToIntegral(KnownSrc, IsTrunc,
1693 /*IsMultiUnitFPType=*/false);
1694 break;
1695 }
1696 case TargetOpcode::G_FEXP:
1697 case TargetOpcode::G_FEXP2:
1698 case TargetOpcode::G_FEXP10: {
1699 Register Val = MI.getOperand(1).getReg();
1700 KnownFPClass KnownSrc;
1701 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1702 Depth + 1);
1703 Known = KnownFPClass::exp(KnownSrc);
1704 break;
1705 }
1706 case TargetOpcode::G_FLOG:
1707 case TargetOpcode::G_FLOG2:
1708 case TargetOpcode::G_FLOG10: {
1709 FPClassTest InterestedSrcs = fcNone;
1710
1711 // log(negative) produces NaN.
1712 if ((InterestedClasses & fcNan) != fcNone)
1713 InterestedSrcs |= fcNan | fcNegative;
1714
1715 // log(logical-zero) produces negative infinity.
1716 if ((InterestedClasses & fcNegInf) != fcNone)
1717 InterestedSrcs |= fcZero | fcSubnormal;
1718
1719 // log(x) < -0.0 if x < +1.0
1720 if ((InterestedClasses & fcNegNormal) != fcNone)
1721 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
1722
1723 // log(x) >= +0.0 if x >= +1.0
1724 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
1725 InterestedSrcs |= fcPosNormal;
1726
1727 // log(x) is positive infinity iff x is positive infinity.
1728 if ((InterestedClasses & fcPosInf) != fcNone)
1729 InterestedSrcs |= fcPosInf;
1730
1731 Register Val = MI.getOperand(1).getReg();
1732 KnownFPClass KnownSrc;
1733 if (InterestedSrcs != fcNone)
1734 computeKnownFPClass(Val, DemandedElts, InterestedSrcs, KnownSrc,
1735 Depth + 1);
1736
1737 LLT Ty = MRI.getType(Val).getScalarType();
1738 const fltSemantics &FltSem = getFltSemanticForLLT(Ty);
1739 DenormalMode Mode = MF->getDenormalMode(FltSem);
1740 Known = KnownFPClass::log(KnownSrc, Mode);
1741 break;
1742 }
1743 case TargetOpcode::G_FPOW: {
1744 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
1745 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
1746 if (!WantNaN && !WantNegative)
1747 break;
1748
1749 FPClassTest InterestedLHS = fcNone;
1750 FPClassTest InterestedRHS = fcNone;
1751 if (WantNaN) {
1752 // pow may return NaN if one of the arguments is NaN. NaN may be produced
1753 // from a non-zero-finite-negative base and a non-integer exponent.
1754 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
1755 InterestedRHS |= fcNan;
1756 }
1757 if (WantNegative) {
1758 // A negative value is returned when a negative base is raised to an odd
1759 // integer power. Only normal values can be odd integers.
1760 InterestedLHS |= fcNegative;
1761 InterestedRHS |= fcNormal;
1762 }
1763
1764 KnownFPClass KnownLHS;
1765 computeKnownFPClass(MI.getOperand(1).getReg(), DemandedElts, InterestedLHS,
1766 KnownLHS, Depth + 1);
1767
1768 // If the LHS is unknown, then querying the RHS is only useful for rare edge
1769 // cases.
1770 if (KnownLHS.isUnknown())
1771 break;
1772
1773 KnownFPClass KnownRHS;
1774 computeKnownFPClass(MI.getOperand(2).getReg(), DemandedElts, InterestedRHS,
1775 KnownRHS, Depth + 1);
1776 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
1777 break;
1778 }
1779 case TargetOpcode::G_FPOWI: {
1780 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
1781 break;
1782
1783 Register Exp = MI.getOperand(2).getReg();
1784 LLT ExpTy = MRI.getType(Exp);
1785 KnownBits ExponentKnownBits = getKnownBits(
1786 Exp, ExpTy.isVector() ? DemandedElts : APInt(1, 1), Depth + 1);
1787
1788 FPClassTest InterestedSrcs = fcNone;
1789 if (InterestedClasses & fcNan)
1790 InterestedSrcs |= fcNan;
1791 if (!ExponentKnownBits.isZero()) {
1792 if (InterestedClasses & fcInf)
1793 InterestedSrcs |= fcFinite | fcInf;
1794 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
1795 InterestedSrcs |= fcNegative;
1796 }
1797
1798 KnownFPClass KnownSrc;
1799 if (InterestedSrcs != fcNone) {
1800 Register Val = MI.getOperand(1).getReg();
1801 computeKnownFPClass(Val, DemandedElts, InterestedSrcs, KnownSrc,
1802 Depth + 1);
1803 }
1804
1805 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
1806 break;
1807 }
1808 case TargetOpcode::G_FLDEXP:
1809 case TargetOpcode::G_STRICT_FLDEXP: {
1810 Register Val = MI.getOperand(1).getReg();
1811 KnownFPClass KnownSrc;
1812 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1813 Depth + 1);
1814
1815 // Can refine inf/zero handling based on the exponent operand.
1816 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
1817 KnownBits ExpBits;
1818 if ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone) {
1819 Register ExpReg = MI.getOperand(2).getReg();
1820 LLT ExpTy = MRI.getType(ExpReg);
1821 ExpBits = getKnownBits(
1822 ExpReg, ExpTy.isVector() ? DemandedElts : APInt(1, 1), Depth + 1);
1823 }
1824
1825 LLT ScalarTy = DstTy.getScalarType();
1826 const fltSemantics &Flt = getFltSemanticForLLT(ScalarTy);
1827 DenormalMode Mode = MF->getDenormalMode(Flt);
1828 Known = KnownFPClass::ldexp(KnownSrc, ExpBits, Flt, Mode);
1829 break;
1830 }
1831 case TargetOpcode::G_FADD:
1832 case TargetOpcode::G_STRICT_FADD:
1833 case TargetOpcode::G_FSUB:
1834 case TargetOpcode::G_STRICT_FSUB: {
1835 Register LHS = MI.getOperand(1).getReg();
1836 Register RHS = MI.getOperand(2).getReg();
1837 bool IsAdd = (Opcode == TargetOpcode::G_FADD ||
1838 Opcode == TargetOpcode::G_STRICT_FADD);
1839 bool WantNegative =
1840 IsAdd &&
1841 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
1842 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
1843 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
1844
1845 if (!WantNaN && !WantNegative && !WantNegZero) {
1846 break;
1847 }
1848
1849 DenormalMode Mode =
1850 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1851
1852 FPClassTest InterestedSrcs = InterestedClasses;
1853 if (WantNegative)
1854 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
1855 if (InterestedClasses & fcNan)
1856 InterestedSrcs |= fcInf;
1857
1858 // Special case fadd x, x (canonical form of fmul x, 2).
1859 if (IsAdd && LHS == RHS && isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1)) {
1860 KnownFPClass KnownSelf;
1861 computeKnownFPClass(LHS, DemandedElts, InterestedSrcs, KnownSelf,
1862 Depth + 1);
1863 Known = KnownFPClass::fadd_self(KnownSelf, Mode);
1864 break;
1865 }
1866
1867 KnownFPClass KnownLHS, KnownRHS;
1868 computeKnownFPClass(RHS, DemandedElts, InterestedSrcs, KnownRHS, Depth + 1);
1869
1870 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
1871 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
1872 WantNegZero || !IsAdd) {
1873 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
1874 // there's no point.
1875 computeKnownFPClass(LHS, DemandedElts, InterestedSrcs, KnownLHS,
1876 Depth + 1);
1877 }
1878
1879 if (IsAdd)
1880 Known = KnownFPClass::fadd(KnownLHS, KnownRHS, Mode);
1881 else
1882 Known = KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
1883 break;
1884 }
1885 case TargetOpcode::G_FMUL:
1886 case TargetOpcode::G_STRICT_FMUL: {
1887 Register LHS = MI.getOperand(1).getReg();
1888 Register RHS = MI.getOperand(2).getReg();
1889 DenormalMode Mode =
1890 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1891
1892 // X * X is always non-negative or a NaN (use square() for precision).
1893 if (LHS == RHS && isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1)) {
1894 KnownFPClass KnownSrc;
1895 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Depth + 1);
1896 Known = KnownFPClass::square(KnownSrc, Mode);
1897 } else {
1898 // If RHS is a scalar constant, use the more precise APFloat overload.
1899 auto RHSCst = GFConstant::getConstant(RHS, MRI);
1900 if (RHSCst && RHSCst->getKind() == GFConstant::GFConstantKind::Scalar) {
1901 KnownFPClass KnownLHS;
1902 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Depth + 1);
1903 Known = KnownFPClass::fmul(KnownLHS, RHSCst->getScalarValue(), Mode);
1904 } else {
1905 KnownFPClass KnownLHS, KnownRHS;
1906 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Depth + 1);
1907 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Depth + 1);
1908 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
1909
1910 // If one operand is known |x| <= 1 and the other is finite, the
1911 // product cannot overflow to infinity.
1912 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS, MRI))
1913 Known.knownNot(fcInf);
1914 else if (KnownRHS.isKnownNever(fcInf) &&
1916 Known.knownNot(fcInf);
1917 }
1918 }
1919 break;
1920 }
1921 case TargetOpcode::G_FDIV: {
1922 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
1923
1924 Register LHS = MI.getOperand(1).getReg();
1925 Register RHS = MI.getOperand(2).getReg();
1926
1927 DenormalMode Mode =
1928 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1929
1930 if (LHS == RHS && isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1)) {
1931 // X / X is always exactly 1.0 or a NaN.
1932 Known.setKnownFPClasses(fcPosNormal | fcNan);
1933
1934 if (!WantNan)
1935 break;
1936
1937 KnownFPClass KnownSrc;
1938 computeKnownFPClass(LHS, DemandedElts,
1939 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc,
1940 Depth + 1);
1941 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
1942 break;
1943 }
1944
1945 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
1946 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
1947 if (!WantNan && !WantNegative && !WantPositive)
1948 break;
1949
1950 KnownFPClass KnownLHS, KnownRHS;
1951 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Depth + 1);
1952
1953 bool KnowSomethingUseful =
1954 KnownRHS.isKnownNeverNaN() ||
1957
1958 if (KnowSomethingUseful)
1959 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Depth + 1);
1960
1961 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
1962 break;
1963 }
1964 case TargetOpcode::G_FREM: {
1965 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
1966
1967 Register LHS = MI.getOperand(1).getReg();
1968 Register RHS = MI.getOperand(2).getReg();
1969
1970 Known.knownNot(fcInf);
1971
1972 DenormalMode Mode =
1973 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1974
1975 if (LHS == RHS && isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1)) {
1976 // X % X is always exactly [+-]0.0 or a NaN.
1977 Known.setKnownFPClasses(fcZero | fcNan);
1978
1979 if (!WantNan)
1980 break;
1981
1982 KnownFPClass KnownSrc;
1983 computeKnownFPClass(LHS, DemandedElts,
1984 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc,
1985 Depth + 1);
1986 Known = KnownFPClass::frem_self(KnownSrc, Mode);
1987 break;
1988 }
1989
1990 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
1991 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
1992 if (!WantNan && !WantNegative && !WantPositive)
1993 break;
1994
1995 KnownFPClass KnownLHS, KnownRHS;
1996 computeKnownFPClass(RHS, DemandedElts, fcNan | fcInf | fcZero | fcNegative,
1997 KnownRHS, Depth + 1);
1998
1999 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
2000 KnownRHS.isKnownNever(fcNegative) ||
2001 KnownRHS.isKnownNever(fcPositive);
2002
2003 if (KnowSomethingUseful || WantPositive)
2004 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Depth + 1);
2005
2006 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
2007
2008 break;
2009 }
2010 case TargetOpcode::G_FFREXP: {
2011 // Only handle the mantissa output (operand 0); the exponent is an integer.
2012 if (R != MI.getOperand(0).getReg())
2013 break;
2014 Register Src = MI.getOperand(2).getReg();
2015 KnownFPClass KnownSrc;
2016 computeKnownFPClass(Src, DemandedElts, InterestedClasses, KnownSrc,
2017 Depth + 1);
2018 DenormalMode Mode =
2019 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
2020 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
2021 break;
2022 }
2023 case TargetOpcode::G_FPEXT: {
2024 Register Src = MI.getOperand(1).getReg();
2025 KnownFPClass KnownSrc;
2026 computeKnownFPClass(Src, DemandedElts, InterestedClasses, KnownSrc,
2027 Depth + 1);
2028
2029 LLT DstScalarTy = DstTy.getScalarType();
2030 const fltSemantics &DstSem = getFltSemanticForLLT(DstScalarTy);
2031 LLT SrcTy = MRI.getType(Src).getScalarType();
2032 const fltSemantics &SrcSem = getFltSemanticForLLT(SrcTy);
2033
2034 Known = KnownFPClass::fpext(KnownSrc, DstSem, SrcSem);
2035 break;
2036 }
2037 case TargetOpcode::G_FPTRUNC:
2038 case TargetOpcode::G_INTRINSIC_FPTRUNC_ROUND: {
2039 computeKnownFPClassForFPTrunc(MI, DemandedElts, InterestedClasses, Known,
2040 Depth);
2041 break;
2042 }
2043 case TargetOpcode::G_SITOFP:
2044 case TargetOpcode::G_UITOFP: {
2045 // Cannot produce nan
2046 Known.knownNot(fcNan);
2047
2048 // Integers cannot be subnormal
2049 Known.knownNot(fcSubnormal);
2050
2051 // sitofp and uitofp turn into +0.0 for zero.
2052 Known.knownNot(fcNegZero);
2053
2054 // UIToFP is always non-negative regardless of known bits.
2055 if (Opcode == TargetOpcode::G_UITOFP)
2056 Known.signBitMustBeZero();
2057
2058 // Only compute known bits if we can learn something useful from them.
2059 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
2060 break;
2061
2062 Register Val = MI.getOperand(1).getReg();
2063 LLT Ty = MRI.getType(Val);
2064 KnownBits IntKnown = getKnownBits(
2065 Val, Ty.isVector() ? DemandedElts : APInt(1, 1), Depth + 1);
2066
2067 // If the integer is non-zero, the result cannot be +0.0.
2068 if (IntKnown.isNonZero())
2069 Known.knownNot(fcPosZero);
2070
2071 if (Opcode == TargetOpcode::G_SITOFP) {
2072 // If the signed integer is known non-negative, the result is
2073 // non-negative. If the signed integer is known negative, the result is
2074 // negative.
2075 if (IntKnown.isNonNegative())
2076 Known.signBitMustBeZero();
2077 else if (IntKnown.isNegative())
2078 Known.signBitMustBeOne();
2079 }
2080
2081 if (InterestedClasses & fcInf) {
2082 LLT FPTy = DstTy.getScalarType();
2083 const fltSemantics &FltSem = getFltSemanticForLLT(FPTy);
2084
2085 // Compute the effective integer width after removing known-zero leading
2086 // bits, to check if the result can overflow to infinity.
2087 int IntSize = IntKnown.getBitWidth();
2088 if (Opcode == TargetOpcode::G_UITOFP)
2089 IntSize -= IntKnown.countMinLeadingZeros();
2090 else
2091 IntSize -= IntKnown.countMinSignBits();
2092
2093 // If the exponent of the largest finite FP value can hold the largest
2094 // integer, the result of the cast must be finite.
2095 if (ilogb(APFloat::getLargest(FltSem)) >= IntSize)
2096 Known.knownNot(fcInf);
2097 }
2098
2099 break;
2100 }
2101 // case TargetOpcode::G_MERGE_VALUES:
2102 case TargetOpcode::G_BUILD_VECTOR:
2103 case TargetOpcode::G_CONCAT_VECTORS: {
2104 GMergeLikeInstr &Merge = cast<GMergeLikeInstr>(MI);
2105
2106 if (!DstTy.isFixedVector())
2107 break;
2108
2109 bool First = true;
2110 for (unsigned Idx = 0; Idx < Merge.getNumSources(); ++Idx) {
2111 // We know the index we are inserting to, so clear it from Vec check.
2112 bool NeedsElt = DemandedElts[Idx];
2113
2114 // Do we demand the inserted element?
2115 if (NeedsElt) {
2116 Register Src = Merge.getSourceReg(Idx);
2117 if (First) {
2118 computeKnownFPClass(Src, Known, InterestedClasses, Depth + 1);
2119 First = false;
2120 } else {
2121 KnownFPClass Known2;
2122 computeKnownFPClass(Src, Known2, InterestedClasses, Depth + 1);
2123 Known |= Known2;
2124 }
2125
2126 // If we don't know any bits, early out.
2127 if (Known.isUnknown())
2128 break;
2129 }
2130 }
2131
2132 break;
2133 }
2134 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
2135 // Look through extract element. If the index is non-constant or
2136 // out-of-range demand all elements, otherwise just the extracted
2137 // element.
2138 GExtractVectorElement &Extract = cast<GExtractVectorElement>(MI);
2139 Register Vec = Extract.getVectorReg();
2140 Register Idx = Extract.getIndexReg();
2141
2142 auto CIdx = getIConstantVRegVal(Idx, MRI);
2143
2144 LLT VecTy = MRI.getType(Vec);
2145
2146 if (VecTy.isFixedVector()) {
2147 unsigned NumElts = VecTy.getNumElements();
2148 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2149 if (CIdx && CIdx->ult(NumElts))
2150 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2151 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
2152 Depth + 1);
2153 }
2154
2155 break;
2156 }
2157 case TargetOpcode::G_INSERT_VECTOR_ELT: {
2158 GInsertVectorElement &Insert = cast<GInsertVectorElement>(MI);
2159 Register Vec = Insert.getVectorReg();
2160 Register Elt = Insert.getElementReg();
2161 Register Idx = Insert.getIndexReg();
2162
2163 LLT VecTy = MRI.getType(Vec);
2164
2165 if (VecTy.isScalableVector())
2166 return;
2167
2168 auto CIdx = getIConstantVRegVal(Idx, MRI);
2169
2170 unsigned NumElts = DemandedElts.getBitWidth();
2171 APInt DemandedVecElts = DemandedElts;
2172 bool NeedsElt = true;
2173 // If we know the index we are inserting to, clear it from Vec check.
2174 if (CIdx && CIdx->ult(NumElts)) {
2175 DemandedVecElts.clearBit(CIdx->getZExtValue());
2176 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2177 }
2178
2179 // Do we demand the inserted element?
2180 if (NeedsElt) {
2181 computeKnownFPClass(Elt, Known, InterestedClasses, Depth + 1);
2182 // If we don't know any bits, early out.
2183 if (Known.isUnknown())
2184 break;
2185 } else {
2186 Known.setKnownFPClasses(fcNone);
2187 }
2188
2189 // Do we need anymore elements from Vec?
2190 if (!DemandedVecElts.isZero()) {
2191 KnownFPClass Known2;
2192 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2,
2193 Depth + 1);
2194 Known |= Known2;
2195 }
2196
2197 break;
2198 }
2199 case TargetOpcode::G_SHUFFLE_VECTOR: {
2200 // For undef elements, we don't know anything about the common state of
2201 // the shuffle result.
2202 GShuffleVector &Shuf = cast<GShuffleVector>(MI);
2203 APInt DemandedLHS, DemandedRHS;
2204 if (DstTy.isScalableVector()) {
2205 assert(DemandedElts == APInt(1, 1));
2206 DemandedLHS = DemandedRHS = DemandedElts;
2207 } else {
2208 unsigned NumElts = MRI.getType(Shuf.getSrc1Reg()).getNumElements();
2209 if (!llvm::getShuffleDemandedElts(NumElts, Shuf.getMask(), DemandedElts,
2210 DemandedLHS, DemandedRHS)) {
2211 Known.resetAll();
2212 return;
2213 }
2214 }
2215
2216 if (!!DemandedLHS) {
2217 Register LHS = Shuf.getSrc1Reg();
2218 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known,
2219 Depth + 1);
2220
2221 // If we don't know any bits, early out.
2222 if (Known.isUnknown())
2223 break;
2224 } else {
2225 Known.setKnownFPClasses(fcNone);
2226 }
2227
2228 if (!!DemandedRHS) {
2229 KnownFPClass Known2;
2230 Register RHS = Shuf.getSrc2Reg();
2231 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2,
2232 Depth + 1);
2233 Known |= Known2;
2234 }
2235 break;
2236 }
2237 case TargetOpcode::G_PHI: {
2238 // Cap PHI recursion below the global limit to avoid spending the entire
2239 // budget chasing loop back-edges (matches ValueTracking's
2240 // PhiRecursionLimit).
2242 break;
2243 // PHI's operands are a mix of registers and basic blocks interleaved.
2244 // We only care about the register ones.
2245 bool First = true;
2246 for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
2247 const MachineOperand &Src = MI.getOperand(Idx);
2248 Register SrcReg = Src.getReg();
2249 if (First) {
2250 computeKnownFPClass(SrcReg, DemandedElts, InterestedClasses, Known,
2251 Depth + 1);
2252 First = false;
2253 } else {
2254 KnownFPClass Known2;
2255 computeKnownFPClass(SrcReg, DemandedElts, InterestedClasses, Known2,
2256 Depth + 1);
2257 Known = Known.intersectWith(Known2);
2258 }
2259 if (Known.isUnknown())
2260 break;
2261 }
2262 break;
2263 }
2264 case TargetOpcode::G_FREEZE: {
2265 Register Src = MI.getOperand(1).getReg();
2266 if (isGuaranteedNotToBeUndefOrPoison(Src, MRI, Depth + 1)) {
2267 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known,
2268 Depth + 1);
2269 }
2270 break;
2271 }
2272 case TargetOpcode::COPY: {
2273 Register Src = MI.getOperand(1).getReg();
2274
2275 if (!Src.isVirtual())
2276 return;
2277
2278 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Depth + 1);
2279 break;
2280 }
2281 }
2282}
2283
2285GISelValueTracking::computeKnownFPClass(Register R, const APInt &DemandedElts,
2286 FPClassTest InterestedClasses,
2287 unsigned Depth) {
2288 KnownFPClass KnownClasses;
2289 computeKnownFPClass(R, DemandedElts, InterestedClasses, KnownClasses, Depth);
2290 return KnownClasses;
2291}
2292
2293KnownFPClass GISelValueTracking::computeKnownFPClass(
2294 Register R, FPClassTest InterestedClasses, unsigned Depth) {
2296 computeKnownFPClass(R, Known, InterestedClasses, Depth);
2297 return Known;
2298}
2299
2300KnownFPClass GISelValueTracking::computeKnownFPClass(
2301 Register R, const APInt &DemandedElts, uint32_t Flags,
2302 FPClassTest InterestedClasses, unsigned Depth) {
2304 InterestedClasses &= ~fcNan;
2306 InterestedClasses &= ~fcInf;
2307
2308 KnownFPClass Result =
2309 computeKnownFPClass(R, DemandedElts, InterestedClasses, Depth);
2310
2312 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
2314 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
2315 return Result;
2316}
2317
2318KnownFPClass GISelValueTracking::computeKnownFPClass(
2319 Register R, uint32_t Flags, FPClassTest InterestedClasses, unsigned Depth) {
2320 LLT Ty = MRI.getType(R);
2321 APInt DemandedElts =
2322 Ty.isFixedVector() ? APInt::getAllOnes(Ty.getNumElements()) : APInt(1, 1);
2323 return computeKnownFPClass(R, DemandedElts, Flags, InterestedClasses, Depth);
2324}
2325
2327 const MachineInstr *DefMI = MRI.getVRegDef(Val);
2328 if (!DefMI)
2329 return false;
2330
2331 if (DefMI->getFlag(MachineInstr::FmNoNans))
2332 return true;
2333
2334 // IEEE 754 arithmetic operations always quiet signaling NaNs. Short-circuit
2335 // the value-tracking analysis for the SNaN-only case: if the defining op is
2336 // known to quiet sNaN, the output can never be an sNaN.
2337 if (SNaN) {
2338 switch (DefMI->getOpcode()) {
2339 default:
2340 break;
2341 case TargetOpcode::G_FADD:
2342 case TargetOpcode::G_STRICT_FADD:
2343 case TargetOpcode::G_FSUB:
2344 case TargetOpcode::G_STRICT_FSUB:
2345 case TargetOpcode::G_FMUL:
2346 case TargetOpcode::G_STRICT_FMUL:
2347 case TargetOpcode::G_FDIV:
2348 case TargetOpcode::G_FREM:
2349 case TargetOpcode::G_FMA:
2350 case TargetOpcode::G_STRICT_FMA:
2351 case TargetOpcode::G_FMAD:
2352 case TargetOpcode::G_FSQRT:
2353 case TargetOpcode::G_STRICT_FSQRT:
2354 // Note: G_FABS and G_FNEG are bit-manipulation ops that preserve sNaN
2355 // exactly (LLVM LangRef: "never change anything except possibly the sign
2356 // bit"). They must NOT be listed here.
2357 case TargetOpcode::G_FSIN:
2358 case TargetOpcode::G_FCOS:
2359 case TargetOpcode::G_FSINCOS:
2360 case TargetOpcode::G_FTAN:
2361 case TargetOpcode::G_FASIN:
2362 case TargetOpcode::G_FACOS:
2363 case TargetOpcode::G_FATAN:
2364 case TargetOpcode::G_FATAN2:
2365 case TargetOpcode::G_FSINH:
2366 case TargetOpcode::G_FCOSH:
2367 case TargetOpcode::G_FTANH:
2368 case TargetOpcode::G_FEXP:
2369 case TargetOpcode::G_FEXP2:
2370 case TargetOpcode::G_FEXP10:
2371 case TargetOpcode::G_FLOG:
2372 case TargetOpcode::G_FLOG2:
2373 case TargetOpcode::G_FLOG10:
2374 case TargetOpcode::G_FPOW:
2375 case TargetOpcode::G_FPOWI:
2376 case TargetOpcode::G_FLDEXP:
2377 case TargetOpcode::G_STRICT_FLDEXP:
2378 case TargetOpcode::G_FFREXP:
2379 case TargetOpcode::G_INTRINSIC_TRUNC:
2380 case TargetOpcode::G_INTRINSIC_ROUND:
2381 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
2382 case TargetOpcode::G_FFLOOR:
2383 case TargetOpcode::G_FCEIL:
2384 case TargetOpcode::G_FRINT:
2385 case TargetOpcode::G_FNEARBYINT:
2386 case TargetOpcode::G_FPEXT:
2387 case TargetOpcode::G_FPTRUNC:
2388 case TargetOpcode::G_FCANONICALIZE:
2389 case TargetOpcode::G_FMINNUM:
2390 case TargetOpcode::G_FMAXNUM:
2391 case TargetOpcode::G_FMINNUM_IEEE:
2392 case TargetOpcode::G_FMAXNUM_IEEE:
2393 case TargetOpcode::G_FMINIMUM:
2394 case TargetOpcode::G_FMAXIMUM:
2395 case TargetOpcode::G_FMINIMUMNUM:
2396 case TargetOpcode::G_FMAXIMUMNUM:
2397 return true;
2398 }
2399 }
2400
2401 KnownFPClass FPClass = computeKnownFPClass(Val, SNaN ? fcSNan : fcNan);
2402
2403 if (SNaN)
2404 return FPClass.isKnownNever(fcSNan);
2405
2406 return FPClass.isKnownNeverNaN();
2407}
2408
2410 KnownFPClass Known = computeKnownFPClass(Val, fcZero | fcSubnormal, Depth);
2411 LLT Ty = MRI.getType(Val).getScalarType();
2412 return Known.isKnownNeverLogicalZero(
2413 MF.getDenormalMode(getFltSemanticForLLT(Ty)));
2414}
2415
2416/// Compute number of sign bits for the intersection of \p Src0 and \p Src1
2417unsigned GISelValueTracking::computeNumSignBitsMin(Register Src0, Register Src1,
2418 const APInt &DemandedElts,
2419 unsigned Depth) {
2420 // Test src1 first, since we canonicalize simpler expressions to the RHS.
2421 unsigned Src1SignBits = computeNumSignBits(Src1, DemandedElts, Depth);
2422 if (Src1SignBits == 1)
2423 return 1;
2424 return std::min(computeNumSignBits(Src0, DemandedElts, Depth), Src1SignBits);
2425}
2426
2427/// Compute the known number of sign bits with attached range metadata in the
2428/// memory operand. If this is an extending load, accounts for the behavior of
2429/// the high bits.
2431 unsigned TyBits) {
2432 const MDNode *Ranges = Ld->getRanges();
2433 if (!Ranges)
2434 return 1;
2435
2437 if (TyBits > CR.getBitWidth()) {
2438 switch (Ld->getOpcode()) {
2439 case TargetOpcode::G_SEXTLOAD:
2440 CR = CR.signExtend(TyBits);
2441 break;
2442 case TargetOpcode::G_ZEXTLOAD:
2443 CR = CR.zeroExtend(TyBits);
2444 break;
2445 default:
2446 break;
2447 }
2448 }
2449
2450 return std::min(CR.getSignedMin().getNumSignBits(),
2452}
2453
2455 const APInt &DemandedElts,
2456 unsigned Depth) {
2457 MachineInstr &MI = *MRI.getVRegDef(R);
2458 unsigned Opcode = MI.getOpcode();
2459
2460 if (Opcode == TargetOpcode::G_CONSTANT)
2461 return MI.getOperand(1).getCImm()->getValue().getNumSignBits();
2462
2463 if (Depth == getMaxDepth())
2464 return 1;
2465
2466 if (!DemandedElts)
2467 return 1; // No demanded elts, better to assume we don't know anything.
2468
2469 LLT DstTy = MRI.getType(R);
2470 const unsigned TyBits = DstTy.getScalarSizeInBits();
2471
2472 // Handle the case where this is called on a register that does not have a
2473 // type constraint. This is unlikely to occur except by looking through copies
2474 // but it is possible for the initial register being queried to be in this
2475 // state.
2476 if (!DstTy.isValid())
2477 return 1;
2478
2479 unsigned FirstAnswer = 1;
2480 switch (Opcode) {
2481 case TargetOpcode::COPY: {
2482 MachineOperand &Src = MI.getOperand(1);
2483 if (Src.getReg().isVirtual() && Src.getSubReg() == 0 &&
2484 MRI.getType(Src.getReg()).isValid()) {
2485 // Don't increment Depth for this one since we didn't do any work.
2486 return computeNumSignBits(Src.getReg(), DemandedElts, Depth);
2487 }
2488
2489 return 1;
2490 }
2491 case TargetOpcode::G_FREEZE: {
2492 Register Src = MI.getOperand(1).getReg();
2493 if (isGuaranteedNotToBeUndefOrPoison(Src, MRI, Depth + 1))
2494 return computeNumSignBits(Src, DemandedElts, Depth + 1);
2495 break;
2496 }
2497 case TargetOpcode::G_SEXT: {
2498 Register Src = MI.getOperand(1).getReg();
2499 LLT SrcTy = MRI.getType(Src);
2500 unsigned Tmp = TyBits - SrcTy.getScalarSizeInBits();
2501 return computeNumSignBits(Src, DemandedElts, Depth + 1) + Tmp;
2502 }
2503 case TargetOpcode::G_ASSERT_SEXT:
2504 case TargetOpcode::G_SEXT_INREG: {
2505 // Max of the input and what this extends.
2506 Register Src = MI.getOperand(1).getReg();
2507 unsigned SrcBits = MI.getOperand(2).getImm();
2508 unsigned InRegBits = TyBits - SrcBits + 1;
2509 return std::max(computeNumSignBits(Src, DemandedElts, Depth + 1),
2510 InRegBits);
2511 }
2512 case TargetOpcode::G_LOAD: {
2513 GLoad *Ld = cast<GLoad>(&MI);
2514 if (DemandedElts != 1 || !getDataLayout().isLittleEndian())
2515 break;
2516
2517 return computeNumSignBitsFromRangeMetadata(Ld, TyBits);
2518 }
2519 case TargetOpcode::G_SEXTLOAD: {
2521
2522 // FIXME: We need an in-memory type representation.
2523 if (DstTy.isVector())
2524 return 1;
2525
2526 unsigned NumBits = computeNumSignBitsFromRangeMetadata(Ld, TyBits);
2527 if (NumBits != 1)
2528 return NumBits;
2529
2530 // e.g. i16->i32 = '17' bits known.
2531 const MachineMemOperand *MMO = *MI.memoperands_begin();
2532 return TyBits - MMO->getSizeInBits().getValue() + 1;
2533 }
2534 case TargetOpcode::G_ZEXTLOAD: {
2536
2537 // FIXME: We need an in-memory type representation.
2538 if (DstTy.isVector())
2539 return 1;
2540
2541 unsigned NumBits = computeNumSignBitsFromRangeMetadata(Ld, TyBits);
2542 if (NumBits != 1)
2543 return NumBits;
2544
2545 // e.g. i16->i32 = '16' bits known.
2546 const MachineMemOperand *MMO = *MI.memoperands_begin();
2547 return TyBits - MMO->getSizeInBits().getValue();
2548 }
2549 case TargetOpcode::G_AND:
2550 case TargetOpcode::G_OR:
2551 case TargetOpcode::G_XOR: {
2552 Register Src1 = MI.getOperand(1).getReg();
2553 unsigned Src1NumSignBits =
2554 computeNumSignBits(Src1, DemandedElts, Depth + 1);
2555 if (Src1NumSignBits != 1) {
2556 Register Src2 = MI.getOperand(2).getReg();
2557 unsigned Src2NumSignBits =
2558 computeNumSignBits(Src2, DemandedElts, Depth + 1);
2559 FirstAnswer = std::min(Src1NumSignBits, Src2NumSignBits);
2560 }
2561 break;
2562 }
2563 case TargetOpcode::G_ASHR: {
2564 Register Src1 = MI.getOperand(1).getReg();
2565 Register Src2 = MI.getOperand(2).getReg();
2566 FirstAnswer = computeNumSignBits(Src1, DemandedElts, Depth + 1);
2567 if (auto C = getValidMinimumShiftAmount(Src2, DemandedElts, Depth + 1))
2568 FirstAnswer = std::min<uint64_t>(FirstAnswer + *C, TyBits);
2569 break;
2570 }
2571 case TargetOpcode::G_SHL: {
2572 Register Src1 = MI.getOperand(1).getReg();
2573 Register Src2 = MI.getOperand(2).getReg();
2574 if (std::optional<ConstantRange> ShAmtRange =
2575 getValidShiftAmountRange(Src2, DemandedElts, Depth + 1)) {
2576 uint64_t MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
2577 uint64_t MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
2578
2579 MachineInstr &ExtMI = *MRI.getVRegDef(Src1);
2580 unsigned ExtOpc = ExtMI.getOpcode();
2581
2582 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
2583 // shifted out, then we can compute the number of sign bits for the
2584 // operand being extended. A future improvement could be to pass along the
2585 // "shifted left by" information in the recursive calls to
2586 // ComputeKnownSignBits. Allowing us to handle this more generically.
2587 if (ExtOpc == TargetOpcode::G_SEXT || ExtOpc == TargetOpcode::G_ZEXT ||
2588 ExtOpc == TargetOpcode::G_ANYEXT) {
2589 LLT ExtTy = MRI.getType(Src1);
2590 Register Extendee = ExtMI.getOperand(1).getReg();
2591 LLT ExtendeeTy = MRI.getType(Extendee);
2592 uint64_t SizeDiff =
2593 ExtTy.getScalarSizeInBits() - ExtendeeTy.getScalarSizeInBits();
2594
2595 if (SizeDiff <= MinShAmt) {
2596 unsigned Tmp =
2597 SizeDiff + computeNumSignBits(Extendee, DemandedElts, Depth + 1);
2598 if (MaxShAmt < Tmp)
2599 return Tmp - MaxShAmt;
2600 }
2601 }
2602 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
2603 unsigned Tmp = computeNumSignBits(Src1, DemandedElts, Depth + 1);
2604 if (MaxShAmt < Tmp)
2605 return Tmp - MaxShAmt;
2606 }
2607 break;
2608 }
2609 case TargetOpcode::G_ROTL:
2610 case TargetOpcode::G_ROTR: {
2611 Register SrcReg = MI.getOperand(1).getReg();
2612 unsigned Tmp = computeNumSignBits(SrcReg, DemandedElts, Depth + 1);
2613 auto MaybeAmt =
2614 isConstantOrConstantSplatVector(MI.getOperand(2).getReg(), MRI);
2615 FirstAnswer =
2616 SignBitsOps::rot(Tmp, TyBits, MaybeAmt, Opcode == TargetOpcode::G_ROTR);
2617 break;
2618 }
2619 case TargetOpcode::G_SAVGFLOOR:
2620 case TargetOpcode::G_SAVGCEIL: {
2621 Register Src1 = MI.getOperand(1).getReg();
2622 Register Src2 = MI.getOperand(2).getReg();
2623 FirstAnswer = computeNumSignBitsMin(Src1, Src2, DemandedElts, Depth + 1);
2624 break;
2625 }
2626 case TargetOpcode::G_SREM: {
2627 // The sign bit is the LHS's sign bit, except when the result of the
2628 // remainder is zero. The magnitude of the result should be less than or
2629 // equal to the magnitude of the LHS. Therefore, the result should have
2630 // at least as many sign bits as the left hand side.
2631 Register Src = MI.getOperand(1).getReg();
2632 return computeNumSignBits(Src, DemandedElts, Depth + 1);
2633 }
2634 case TargetOpcode::G_TRUNC: {
2635 Register Src = MI.getOperand(1).getReg();
2636 LLT SrcTy = MRI.getType(Src);
2637
2638 // Check if the sign bits of source go down as far as the truncated value.
2639 unsigned NumSrcBits = SrcTy.getScalarSizeInBits();
2640 unsigned NumSrcSignBits = computeNumSignBits(Src, DemandedElts, Depth + 1);
2641 if (NumSrcSignBits > (NumSrcBits - TyBits))
2642 return NumSrcSignBits - (NumSrcBits - TyBits);
2643 break;
2644 }
2645 case TargetOpcode::G_SELECT: {
2646 return computeNumSignBitsMin(MI.getOperand(2).getReg(),
2647 MI.getOperand(3).getReg(), DemandedElts,
2648 Depth + 1);
2649 }
2650 case TargetOpcode::G_SMIN:
2651 case TargetOpcode::G_SMAX:
2652 case TargetOpcode::G_UMIN:
2653 case TargetOpcode::G_UMAX:
2654 // TODO: Handle clamp pattern with number of sign bits for SMIN/SMAX.
2655 return computeNumSignBitsMin(MI.getOperand(1).getReg(),
2656 MI.getOperand(2).getReg(), DemandedElts,
2657 Depth + 1);
2658 case TargetOpcode::G_SADDO:
2659 case TargetOpcode::G_SADDE:
2660 case TargetOpcode::G_UADDO:
2661 case TargetOpcode::G_UADDE:
2662 case TargetOpcode::G_SSUBO:
2663 case TargetOpcode::G_SSUBE:
2664 case TargetOpcode::G_USUBO:
2665 case TargetOpcode::G_USUBE:
2666 case TargetOpcode::G_SMULO:
2667 case TargetOpcode::G_UMULO: {
2668 // If compares returns 0/-1, all bits are sign bits.
2669 // We know that we have an integer-based boolean since these operations
2670 // are only available for integer.
2671 if (MI.getOperand(1).getReg() == R) {
2672 if (TL.getBooleanContents(DstTy.isVector(), false) ==
2674 return TyBits;
2675 }
2676
2677 break;
2678 }
2679 case TargetOpcode::G_SUB: {
2680 Register Src2 = MI.getOperand(2).getReg();
2681 unsigned Src2NumSignBits =
2682 computeNumSignBits(Src2, DemandedElts, Depth + 1);
2683 if (Src2NumSignBits == 1)
2684 return 1; // Early out.
2685
2686 // Handle NEG.
2687 Register Src1 = MI.getOperand(1).getReg();
2688 KnownBits Known1 = getKnownBits(Src1, DemandedElts, Depth);
2689 if (Known1.isZero()) {
2690 KnownBits Known2 = getKnownBits(Src2, DemandedElts, Depth);
2691 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2692 // sign bits set.
2693 if ((Known2.Zero | 1).isAllOnes())
2694 return TyBits;
2695
2696 // If the input is known to be positive (the sign bit is known clear),
2697 // the output of the NEG has, at worst, the same number of sign bits as
2698 // the input.
2699 if (Known2.isNonNegative()) {
2700 FirstAnswer = Src2NumSignBits;
2701 break;
2702 }
2703
2704 // Otherwise, we treat this like a SUB.
2705 }
2706
2707 unsigned Src1NumSignBits =
2708 computeNumSignBits(Src1, DemandedElts, Depth + 1);
2709 if (Src1NumSignBits == 1)
2710 return 1; // Early Out.
2711
2712 // Sub can have at most one carry bit. Thus we know that the output
2713 // is, at worst, one more bit than the inputs.
2714 FirstAnswer = std::min(Src1NumSignBits, Src2NumSignBits) - 1;
2715 break;
2716 }
2717 case TargetOpcode::G_ADD: {
2718 Register Src2 = MI.getOperand(2).getReg();
2719 unsigned Src2NumSignBits =
2720 computeNumSignBits(Src2, DemandedElts, Depth + 1);
2721 if (Src2NumSignBits <= 2)
2722 return 1; // Early out.
2723
2724 Register Src1 = MI.getOperand(1).getReg();
2725 unsigned Src1NumSignBits =
2726 computeNumSignBits(Src1, DemandedElts, Depth + 1);
2727 if (Src1NumSignBits == 1)
2728 return 1; // Early Out.
2729
2730 // Special case decrementing a value (ADD X, -1):
2731 KnownBits Known2 = getKnownBits(Src2, DemandedElts, Depth);
2732 if (Known2.isAllOnes()) {
2733 KnownBits Known1 = getKnownBits(Src1, DemandedElts, Depth);
2734 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2735 // sign bits set.
2736 if ((Known1.Zero | 1).isAllOnes())
2737 return TyBits;
2738
2739 // If we are subtracting one from a positive number, there is no carry
2740 // out of the result.
2741 if (Known1.isNonNegative()) {
2742 FirstAnswer = Src1NumSignBits;
2743 break;
2744 }
2745
2746 // Otherwise, we treat this like an ADD.
2747 }
2748
2749 // Add can have at most one carry bit. Thus we know that the output
2750 // is, at worst, one more bit than the inputs.
2751 FirstAnswer = std::min(Src1NumSignBits, Src2NumSignBits) - 1;
2752 break;
2753 }
2754 case TargetOpcode::G_FCMP:
2755 case TargetOpcode::G_ICMP: {
2756 bool IsFP = Opcode == TargetOpcode::G_FCMP;
2757 if (TyBits == 1)
2758 break;
2759 auto BC = TL.getBooleanContents(DstTy.isVector(), IsFP);
2761 return TyBits; // All bits are sign bits.
2763 return TyBits - 1; // Every always-zero bit is a sign bit.
2764 break;
2765 }
2766 case TargetOpcode::G_UNMERGE_VALUES: {
2767 unsigned NumOps = MI.getNumOperands();
2768 Register SrcReg = MI.getOperand(NumOps - 1).getReg();
2769 LLT SrcTy = MRI.getType(SrcReg);
2770
2771 if ((SrcTy.isVector() && SrcTy.getScalarType() != DstTy.getScalarType()) ||
2772 (SrcTy.isScalar() && DstTy.isVector()))
2773 break;
2774
2775 // Figure out the result operand index
2776 unsigned DstIdx = MI.findRegisterDefOperandIdx(R, nullptr);
2777
2778 APInt SubDemandedElts = DemandedElts;
2779 unsigned DstLanes = DstTy.isVector() ? DstTy.getNumElements() : 1;
2780 if (SrcTy.isVector()) {
2781 SubDemandedElts =
2782 DemandedElts.zext(SrcTy.getNumElements()).shl(DstIdx * DstLanes);
2783 }
2784
2785 unsigned SrcOpKnown =
2786 computeNumSignBits(SrcReg, SubDemandedElts, Depth + 1);
2787 if (SrcTy.isVector()) {
2788 FirstAnswer = SrcOpKnown;
2789 } else if (SrcOpKnown >= (MI.getNumOperands() - DstIdx - 2) * TyBits) {
2790 FirstAnswer = SrcOpKnown >= (MI.getNumOperands() - DstIdx - 1) * TyBits
2791 ? TyBits
2792 : SrcOpKnown % TyBits;
2793 }
2794 break;
2795 }
2796 case TargetOpcode::G_BUILD_VECTOR: {
2797 // Collect the known bits that are shared by every demanded vector element.
2798 FirstAnswer = TyBits;
2799 APInt SingleDemandedElt(1, 1);
2800 for (const auto &[I, MO] : enumerate(drop_begin(MI.operands()))) {
2801 if (!DemandedElts[I])
2802 continue;
2803
2804 unsigned Tmp2 =
2805 computeNumSignBits(MO.getReg(), SingleDemandedElt, Depth + 1);
2806 FirstAnswer = std::min(FirstAnswer, Tmp2);
2807
2808 // If we don't know any bits, early out.
2809 if (FirstAnswer == 1)
2810 break;
2811 }
2812 break;
2813 }
2814 case TargetOpcode::G_CONCAT_VECTORS: {
2815 if (MRI.getType(MI.getOperand(0).getReg()).isScalableVector())
2816 break;
2817 FirstAnswer = TyBits;
2818 // Determine the minimum number of sign bits across all demanded
2819 // elts of the input vectors. Early out if the result is already 1.
2820 unsigned NumSubVectorElts =
2821 MRI.getType(MI.getOperand(1).getReg()).getNumElements();
2822 for (const auto &[I, MO] : enumerate(drop_begin(MI.operands()))) {
2823 APInt DemandedSub =
2824 DemandedElts.extractBits(NumSubVectorElts, I * NumSubVectorElts);
2825 if (!DemandedSub)
2826 continue;
2827 unsigned Tmp2 = computeNumSignBits(MO.getReg(), DemandedSub, Depth + 1);
2828
2829 FirstAnswer = std::min(FirstAnswer, Tmp2);
2830
2831 // If we don't know any bits, early out.
2832 if (FirstAnswer == 1)
2833 break;
2834 }
2835 break;
2836 }
2837 case TargetOpcode::G_VECTOR_COMPRESS: {
2838 // Each result lane is either a lane of the source vector or the passthru,
2839 // so the number of sign bits is the minimum of the two.
2840 Register Vec = MI.getOperand(1).getReg();
2841 Register PassThru = MI.getOperand(3).getReg();
2842 unsigned Tmp = computeNumSignBits(PassThru, DemandedElts, Depth + 1);
2843 // If passthru contributes nothing, fall back to the KnownBits refinement.
2844 if (Tmp == 1)
2845 break;
2846 // Compression can move any source lane to any result position, so all
2847 // source lanes are demanded.
2848 APInt DemandedSrcElts = APInt::getAllOnes(DemandedElts.getBitWidth());
2849 unsigned Tmp2 = computeNumSignBits(Vec, DemandedSrcElts, Depth + 1);
2850 FirstAnswer = std::min(Tmp, Tmp2);
2851 break;
2852 }
2853 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
2855 Register InVec = Extract.getVectorReg();
2856 Register EltNo = Extract.getIndexReg();
2857 LLT VecVT = MRI.getType(InVec);
2858 if (VecVT.isScalableVector())
2859 return computeNumSignBits(InVec, APInt(1, 1), Depth + 1);
2860 unsigned NumSrcElts = VecVT.getNumElements();
2861 std::optional<APInt> ConstEltNo = getIConstantVRegVal(EltNo, MRI);
2862 APInt DemandedSrcElts =
2863 ConstEltNo && ConstEltNo->ult(NumSrcElts)
2864 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
2865 : APInt::getAllOnes(NumSrcElts);
2866 return computeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
2867 }
2868 case TargetOpcode::G_EXTRACT_SUBVECTOR: {
2869 // Offset the demanded elts by the subvector index.
2870 Register SrcReg = MI.getOperand(1).getReg();
2871 LLT SrcTy = MRI.getType(SrcReg);
2872 APInt DemandedSrcElts;
2873 if (SrcTy.isScalableVector()) {
2874 DemandedSrcElts = APInt(1, 1);
2875 } else {
2876 uint64_t Idx = MI.getOperand(2).getImm();
2877 unsigned NumSrcElts = SrcTy.getNumElements();
2878 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2879 }
2880 return computeNumSignBits(SrcReg, DemandedSrcElts, Depth + 1);
2881 }
2882 case TargetOpcode::G_SHUFFLE_VECTOR: {
2883 // Collect the minimum number of sign bits that are shared by every vector
2884 // element referenced by the shuffle.
2885 APInt DemandedLHS, DemandedRHS;
2886 Register Src1 = MI.getOperand(1).getReg();
2887 unsigned NumElts = MRI.getType(Src1).getNumElements();
2888 if (!getShuffleDemandedElts(NumElts, MI.getOperand(3).getShuffleMask(),
2889 DemandedElts, DemandedLHS, DemandedRHS))
2890 return 1;
2891
2892 if (!!DemandedLHS)
2893 FirstAnswer = computeNumSignBits(Src1, DemandedLHS, Depth + 1);
2894 // If we don't know anything, early out and try computeKnownBits fall-back.
2895 if (FirstAnswer == 1)
2896 break;
2897 if (!!DemandedRHS) {
2898 unsigned Tmp2 =
2899 computeNumSignBits(MI.getOperand(2).getReg(), DemandedRHS, Depth + 1);
2900 FirstAnswer = std::min(FirstAnswer, Tmp2);
2901 }
2902 break;
2903 }
2904 case TargetOpcode::G_SPLAT_VECTOR: {
2905 // Check if the sign bits of source go down as far as the truncated value.
2906 Register Src = MI.getOperand(1).getReg();
2907 unsigned NumSrcSignBits = computeNumSignBits(Src, APInt(1, 1), Depth + 1);
2908 unsigned NumSrcBits = MRI.getType(Src).getSizeInBits();
2909 if (NumSrcSignBits > (NumSrcBits - TyBits))
2910 return NumSrcSignBits - (NumSrcBits - TyBits);
2911 break;
2912 }
2913 case TargetOpcode::G_INTRINSIC:
2914 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
2915 case TargetOpcode::G_INTRINSIC_CONVERGENT:
2916 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS:
2917 default: {
2918 unsigned NumBits =
2919 TL.computeNumSignBitsForTargetInstr(*this, R, DemandedElts, MRI, Depth);
2920 if (NumBits > 1)
2921 FirstAnswer = std::max(FirstAnswer, NumBits);
2922 break;
2923 }
2924 }
2925
2926 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2927 // use this information.
2928 KnownBits Known = getKnownBits(R, DemandedElts, Depth);
2929 return std::max(FirstAnswer, Known.countMinSignBits());
2930}
2931
2933 LLT Ty = MRI.getType(R);
2934 APInt DemandedElts =
2935 Ty.isFixedVector() ? APInt::getAllOnes(Ty.getNumElements()) : APInt(1, 1);
2936 return computeNumSignBits(R, DemandedElts, Depth);
2937}
2938
2940 Register R, const APInt &DemandedElts, unsigned Depth) {
2941 // Shifting more than the bitwidth is not valid.
2942 MachineInstr &MI = *MRI.getVRegDef(R);
2943 unsigned Opcode = MI.getOpcode();
2944
2945 LLT Ty = MRI.getType(R);
2946 unsigned BitWidth = Ty.getScalarSizeInBits();
2947
2948 if (Opcode == TargetOpcode::G_CONSTANT) {
2949 const APInt &ShAmt = MI.getOperand(1).getCImm()->getValue();
2950 if (ShAmt.uge(BitWidth))
2951 return std::nullopt;
2952 return ConstantRange(ShAmt);
2953 }
2954
2955 if (Opcode == TargetOpcode::G_BUILD_VECTOR) {
2956 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
2957 for (unsigned I = 0, E = MI.getNumOperands() - 1; I != E; ++I) {
2958 if (!DemandedElts[I])
2959 continue;
2960 MachineInstr *Op = MRI.getVRegDef(MI.getOperand(I + 1).getReg());
2961 if (Op->getOpcode() != TargetOpcode::G_CONSTANT) {
2962 MinAmt = MaxAmt = nullptr;
2963 break;
2964 }
2965
2966 const APInt &ShAmt = Op->getOperand(1).getCImm()->getValue();
2967 if (ShAmt.uge(BitWidth))
2968 return std::nullopt;
2969 if (!MinAmt || MinAmt->ugt(ShAmt))
2970 MinAmt = &ShAmt;
2971 if (!MaxAmt || MaxAmt->ult(ShAmt))
2972 MaxAmt = &ShAmt;
2973 }
2974 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
2975 "Failed to find matching min/max shift amounts");
2976 if (MinAmt && MaxAmt)
2977 return ConstantRange(*MinAmt, *MaxAmt + 1);
2978 }
2979
2980 // Use computeKnownBits to find a hidden constant/knownbits (usually type
2981 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
2982 KnownBits KnownAmt = getKnownBits(R, DemandedElts, Depth);
2983 if (KnownAmt.getMaxValue().ult(BitWidth))
2984 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
2985
2986 return std::nullopt;
2987}
2988
2990 Register R, const APInt &DemandedElts, unsigned Depth) {
2991 if (std::optional<ConstantRange> AmtRange =
2992 getValidShiftAmountRange(R, DemandedElts, Depth))
2993 return AmtRange->getUnsignedMin().getZExtValue();
2994 return std::nullopt;
2995}
2996
3002
3007
3009 if (!Info) {
3010 unsigned MaxDepth =
3012 Info = std::make_unique<GISelValueTracking>(MF, MaxDepth);
3013 }
3014 return *Info;
3015}
3016
3017AnalysisKey GISelValueTrackingAnalysis::Key;
3018
3022 unsigned MaxDepth =
3024 return Result(MF, MaxDepth);
3025}
3026
3027static PreservedAnalyses
3030 bool PrintFPClass) {
3031 auto &VTA = MFAM.getResult<GISelValueTrackingAnalysis>(MF);
3032 const auto &MRI = MF.getRegInfo();
3033 OS << "name: ";
3034 MF.getFunction().printAsOperand(OS, /*PrintType=*/false);
3035 OS << '\n';
3036
3037 for (MachineBasicBlock &BB : MF) {
3038 for (MachineInstr &MI : BB) {
3039 for (MachineOperand &MO : MI.defs()) {
3040 if (!MO.isReg() || MO.getReg().isPhysical())
3041 continue;
3042 Register Reg = MO.getReg();
3043 if (!MRI.getType(Reg).isValid())
3044 continue;
3045 if (PrintFPClass) {
3046 KnownFPClass FPKnown = VTA.computeKnownFPClass(Reg);
3047 OS << " " << MO << " FPClasses:" << FPKnown.getKnownFPClasses()
3048 << " SignBitKnown:";
3049 if (FPKnown.getSignBit())
3050 OS << (*FPKnown.getSignBit() ? '1' : '0');
3051 else
3052 OS << '?';
3053 OS << '\n';
3054 } else {
3055 KnownBits Known = VTA.getKnownBits(Reg);
3056 unsigned SignedBits = VTA.computeNumSignBits(Reg);
3057 bool IsKnownNeverZero = VTA.isKnownNeverZero(Reg);
3058 OS << " " << MO << " KnownBits:" << Known
3059 << " SignBits:" << SignedBits
3060 << " IsKnownNeverZero:" << IsKnownNeverZero << '\n';
3061 }
3062 };
3063 }
3064 }
3065 return PreservedAnalyses::all();
3066}
3067
3073
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
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< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Utilities for dealing with flags related to floating point properties and mode controls.
static void dumpResult(const MachineInstr &MI, const KnownBits &Known, unsigned Depth)
static PreservedAnalyses printGISelValueTracking(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM, raw_ostream &OS, bool PrintFPClass)
static unsigned computeNumSignBitsFromRangeMetadata(const GAnyLoad *Ld, unsigned TyBits)
Compute the known number of sign bits with attached range metadata in the memory operand.
Provides analysis for querying information about KnownBits during GISel passes.
#define DEBUG_TYPE
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
static bool isAbsoluteValueULEOne(const Value *V)
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Value * RHS
Value * LHS
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
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 ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
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 shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
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
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
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
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
This class represents a range of values.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
Represents any generic load, including sign/zero extending variants.
Represents an extract vector element.
static LLVM_ABI std::optional< GFConstant > getConstant(Register Const, const MachineRegisterInfo &MRI)
Definition Utils.cpp:2038
To use KnownBitsInfo analysis in a pass, KnownBitsInfo &Info = getAnalysis<GISelValueTrackingInfoAnal...
GISelValueTracking & get(MachineFunction &MF)
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
KnownBits getKnownBits(Register R)
Align computeKnownAlignment(Register R, unsigned Depth=0)
std::optional< ConstantRange > getValidShiftAmountRange(Register R, const APInt &DemandedElts, unsigned Depth)
If a G_SHL/G_ASHR/G_LSHR node with shift operand R has shift amounts that are all less than the eleme...
bool maskedValueIsZero(Register Val, const APInt &Mask)
std::optional< uint64_t > getValidMinimumShiftAmount(Register R, const APInt &DemandedElts, unsigned Depth=0)
If a G_SHL/G_ASHR/G_LSHR node with shift operand R has shift amounts that are all less than the eleme...
const DataLayout & getDataLayout() const
unsigned computeNumSignBits(Register R, const APInt &DemandedElts, unsigned Depth=0)
const MachineFunction & getMachineFunction() const
bool isKnownNeverNaN(Register Val, bool SNaN=false)
Returns true if Val can be assumed to never be a NaN.
bool isKnownNeverLogicalZero(Register Val, unsigned Depth=0)
Returns true if Val can be assumed to never be a zero, accounting for denormal flushing of the contai...
void computeKnownBitsImpl(Register R, KnownBits &Known, const APInt &DemandedElts, unsigned Depth=0)
bool isKnownNeverZero(Register R, unsigned Depth=0)
Return true if the value defined by R is provably never zero.
Represents a insert subvector.
Represents an insert vector element.
Represents a G_LOAD.
Represents a G_SEXTLOAD.
Register getCondReg() const
Register getFalseReg() const
Register getTrueReg() const
Represents a G_SHUFFLE_VECTOR.
ArrayRef< int > getMask() const
Represents a G_ZEXTLOAD.
constexpr bool isScalableVector() const
Returns true if the LLT is a scalable vector.
constexpr unsigned getScalarSizeInBits() const
LLT getScalarType() const
constexpr bool isValid() const
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
constexpr ElementCount getElementCount() const
constexpr bool isFixedVector() const
Returns true if the LLT is a fixed vector.
TypeSize getValue() const
Metadata node.
Definition Metadata.h:1092
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
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
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
LLT getMemoryType() const
Return the memory type of the memory reference.
const MDNode * getRanges() const
Return the range tag for the memory reference.
LocationSize getSizeInBits() const
Return the size in bits of the memory reference.
MachineOperand class - Representation of each machine instruction operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
operand_type_match m_Reg()
UnaryOp_match< SrcTy, TargetOpcode::G_FFLOOR > m_GFFloor(const SrcTy &Src)
operand_type_match m_Pred()
bind_ty< FPClassTest > m_FPClassTest(FPClassTest &T)
deferred_ty< Register > m_DeferredReg(Register &R)
Similar to m_SpecificReg/Type, but the specific value to match originated from an earlier sub-pattern...
BinaryOp_match< LHS, RHS, TargetOpcode::G_FSUB, false > m_GFSub(const LHS &L, const RHS &R)
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
ClassifyOp_match< LHS, Test, TargetOpcode::G_IS_FPCLASS > m_GIsFPClass(const LHS &L, const Test &T)
Matches the register and immediate used in a fpclass test G_IS_FPCLASS val, 96.
CompareOp_match< Pred, LHS, RHS, TargetOpcode::G_FCMP > m_GFCmp(const Pred &P, const LHS &L, const RHS &R)
LLVM_ABI unsigned rot(unsigned SrcSignBits, unsigned BitWidth, std::optional< APInt > RotAmt, bool IsRotateRight)
Compute the number of sign bits after rotating a value.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI std::optional< APInt > isConstantOrConstantSplatVector(Register Def, const MachineRegisterInfo &MRI)
Determines if Def defines a constant integer or a splat vector of constant integers.
Definition Utils.cpp:1517
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
LLVM_ABI std::optional< APInt > getIConstantVRegVal(Register VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT, return the corresponding value.
Definition Utils.cpp:297
@ Known
Known to have no common set bits.
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
LLVM_ABI const llvm::fltSemantics & getFltSemanticForLLT(LLT Ty)
Get the appropriate floating point arithmetic semantic based on the bit size of the given scalar LLT.
scope_exit(Callable) -> scope_exit< Callable >
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
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...
constexpr unsigned MaxAnalysisRecursionDepth
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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...
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Sub
Subtraction of integers.
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static uint32_t extractBits(uint64_t Val, uint32_t Hi, uint32_t Lo)
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
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 mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
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
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
static LLVM_ABI KnownBits abdu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for abdu(LHS, RHS).
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits avgFloorU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorU.
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:184
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:200
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 fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits abds(KnownBits LHS, KnownBits RHS)
Compute known bits for abds(LHS, RHS).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static LLVM_ABI KnownBits avgFloorS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorS.
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits computeForAddCarry(const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry)
Compute known bits resulting from adding LHS, RHS and a 1-bit Carry.
Definition KnownBits.cpp:54
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
static LLVM_ABI KnownBits avgCeilU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilU.
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
bool isAllOnes() const
Returns true if value is all one bits.
Definition KnownBits.h:81
static LLVM_ABI KnownBits avgCeilS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilS.
void setKnownFPClasses(FPClassTest Classes)
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass frem(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for atan2.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass cosh(const KnownFPClass &Src)
Report known values for cosh.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
static LLVM_ABI KnownFPClass asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
std::optional< bool > getSignBit() const
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem x, x.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass pow(const KnownFPClass &LHS, const KnownFPClass &RHS)
Propagate known class for pow.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.