LLVM 22.0.0git
InstCombineSimplifyDemanded.cpp
Go to the documentation of this file.
1//===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains logic for simplifying instructions based on information
10// about how they are used.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
21
22using namespace llvm;
23using namespace llvm::PatternMatch;
24
25#define DEBUG_TYPE "instcombine"
26
27static cl::opt<bool>
28 VerifyKnownBits("instcombine-verify-known-bits",
29 cl::desc("Verify that computeKnownBits() and "
30 "SimplifyDemandedBits() are consistent"),
31 cl::Hidden, cl::init(false));
32
34 "instcombine-simplify-vector-elts-depth",
36 "Depth limit when simplifying vector instructions and their operands"),
37 cl::Hidden, cl::init(10));
38
39/// Check to see if the specified operand of the specified instruction is a
40/// constant integer. If so, check to see if there are any bits set in the
41/// constant that are not demanded. If so, shrink the constant and return true.
42static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
43 const APInt &Demanded) {
44 assert(I && "No instruction?");
45 assert(OpNo < I->getNumOperands() && "Operand index too large");
46
47 // The operand must be a constant integer or splat integer.
48 Value *Op = I->getOperand(OpNo);
49 const APInt *C;
50 if (!match(Op, m_APInt(C)))
51 return false;
52
53 // If there are no bits set that aren't demanded, nothing to do.
54 if (C->isSubsetOf(Demanded))
55 return false;
56
57 // This instruction is producing bits that are not demanded. Shrink the RHS.
58 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
59
60 return true;
61}
62
63/// Returns the bitwidth of the given scalar or pointer type. For vector types,
64/// returns the element type's bitwidth.
65static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
66 if (unsigned BitWidth = Ty->getScalarSizeInBits())
67 return BitWidth;
68
69 return DL.getPointerTypeSizeInBits(Ty);
70}
71
72/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
73/// the instruction has any properties that allow us to simplify its operands.
75 KnownBits &Known) {
76 APInt DemandedMask(APInt::getAllOnes(Known.getBitWidth()));
77 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
78 SQ.getWithInstruction(&Inst));
79 if (!V) return false;
80 if (V == &Inst) return true;
81 replaceInstUsesWith(Inst, V);
82 return true;
83}
84
85/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
86/// the instruction has any properties that allow us to simplify its operands.
91
92/// This form of SimplifyDemandedBits simplifies the specified instruction
93/// operand if possible, updating it in place. It returns true if it made any
94/// change and false otherwise.
96 const APInt &DemandedMask,
97 KnownBits &Known,
98 const SimplifyQuery &Q,
99 unsigned Depth) {
100 Use &U = I->getOperandUse(OpNo);
101 Value *V = U.get();
102 if (isa<Constant>(V)) {
103 llvm::computeKnownBits(V, Known, Q, Depth);
104 return false;
105 }
106
107 Known.resetAll();
108 if (DemandedMask.isZero()) {
109 // Not demanding any bits from V.
110 replaceUse(U, UndefValue::get(V->getType()));
111 return true;
112 }
113
115 if (!VInst) {
116 llvm::computeKnownBits(V, Known, Q, Depth);
117 return false;
118 }
119
121 return false;
122
123 Value *NewVal;
124 if (VInst->hasOneUse()) {
125 // If the instruction has one use, we can directly simplify it.
126 NewVal = SimplifyDemandedUseBits(VInst, DemandedMask, Known, Q, Depth);
127 } else {
128 // If there are multiple uses of this instruction, then we can simplify
129 // VInst to some other value, but not modify the instruction.
130 NewVal =
131 SimplifyMultipleUseDemandedBits(VInst, DemandedMask, Known, Q, Depth);
132 }
133 if (!NewVal) return false;
134 if (Instruction* OpInst = dyn_cast<Instruction>(U))
135 salvageDebugInfo(*OpInst);
136
137 replaceUse(U, NewVal);
138 return true;
139}
140
141/// This function attempts to replace V with a simpler value based on the
142/// demanded bits. When this function is called, it is known that only the bits
143/// set in DemandedMask of the result of V are ever used downstream.
144/// Consequently, depending on the mask and V, it may be possible to replace V
145/// with a constant or one of its operands. In such cases, this function does
146/// the replacement and returns true. In all other cases, it returns false after
147/// analyzing the expression and setting KnownOne and known to be one in the
148/// expression. Known.Zero contains all the bits that are known to be zero in
149/// the expression. These are provided to potentially allow the caller (which
150/// might recursively be SimplifyDemandedBits itself) to simplify the
151/// expression.
152/// Known.One and Known.Zero always follow the invariant that:
153/// Known.One & Known.Zero == 0.
154/// That is, a bit can't be both 1 and 0. The bits in Known.One and Known.Zero
155/// are accurate even for bits not in DemandedMask. Note
156/// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
157/// be the same.
158///
159/// This returns null if it did not change anything and it permits no
160/// simplification. This returns V itself if it did some simplification of V's
161/// operands based on the information about what bits are demanded. This returns
162/// some other non-null value if it found out that V is equal to another value
163/// in the context where the specified bits are demanded, but not for all users.
165 const APInt &DemandedMask,
166 KnownBits &Known,
167 const SimplifyQuery &Q,
168 unsigned Depth) {
169 assert(I != nullptr && "Null pointer of Value???");
170 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
171 uint32_t BitWidth = DemandedMask.getBitWidth();
172 Type *VTy = I->getType();
173 assert(
174 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
175 Known.getBitWidth() == BitWidth &&
176 "Value *V, DemandedMask and Known must have same BitWidth");
177
178 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
179
180 // Update flags after simplifying an operand based on the fact that some high
181 // order bits are not demanded.
182 auto disableWrapFlagsBasedOnUnusedHighBits = [](Instruction *I,
183 unsigned NLZ) {
184 if (NLZ > 0) {
185 // Disable the nsw and nuw flags here: We can no longer guarantee that
186 // we won't wrap after simplification. Removing the nsw/nuw flags is
187 // legal here because the top bit is not demanded.
188 I->setHasNoSignedWrap(false);
189 I->setHasNoUnsignedWrap(false);
190 }
191 return I;
192 };
193
194 // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
195 // about the high bits of the operands.
196 auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
197 unsigned NLZ = DemandedMask.countl_zero();
198 // Right fill the mask of bits for the operands to demand the most
199 // significant bit and all those below it.
200 DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
201 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
202 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Q, Depth + 1) ||
203 ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
204 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1)) {
205 disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
206 return true;
207 }
208 return false;
209 };
210
211 switch (I->getOpcode()) {
212 default:
213 llvm::computeKnownBits(I, Known, Q, Depth);
214 break;
215 case Instruction::And: {
216 // If either the LHS or the RHS are Zero, the result is zero.
217 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
218 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown, Q,
219 Depth + 1))
220 return I;
221
222 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
223 Q, Depth);
224
225 // If the client is only demanding bits that we know, return the known
226 // constant.
227 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
228 return Constant::getIntegerValue(VTy, Known.One);
229
230 // If all of the demanded bits are known 1 on one side, return the other.
231 // These bits cannot contribute to the result of the 'and'.
232 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
233 return I->getOperand(0);
234 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
235 return I->getOperand(1);
236
237 // If the RHS is a constant, see if we can simplify it.
238 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
239 return I;
240
241 break;
242 }
243 case Instruction::Or: {
244 // If either the LHS or the RHS are One, the result is One.
245 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
246 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown, Q,
247 Depth + 1)) {
248 // Disjoint flag may not longer hold.
249 I->dropPoisonGeneratingFlags();
250 return I;
251 }
252
253 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
254 Q, Depth);
255
256 // If the client is only demanding bits that we know, return the known
257 // constant.
258 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
259 return Constant::getIntegerValue(VTy, Known.One);
260
261 // If all of the demanded bits are known zero on one side, return the other.
262 // These bits cannot contribute to the result of the 'or'.
263 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
264 return I->getOperand(0);
265 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
266 return I->getOperand(1);
267
268 // If the RHS is a constant, see if we can simplify it.
269 if (ShrinkDemandedConstant(I, 1, DemandedMask))
270 return I;
271
272 // Infer disjoint flag if no common bits are set.
273 if (!cast<PossiblyDisjointInst>(I)->isDisjoint()) {
274 WithCache<const Value *> LHSCache(I->getOperand(0), LHSKnown),
275 RHSCache(I->getOperand(1), RHSKnown);
276 if (haveNoCommonBitsSet(LHSCache, RHSCache, Q)) {
277 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
278 return I;
279 }
280 }
281
282 break;
283 }
284 case Instruction::Xor: {
285 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
286 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Q, Depth + 1))
287 return I;
288 Value *LHS, *RHS;
289 if (DemandedMask == 1 &&
290 match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) &&
291 match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) {
292 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
294 Builder.SetInsertPoint(I);
295 auto *Xor = Builder.CreateXor(LHS, RHS);
296 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
297 }
298
299 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
300 Q, Depth);
301
302 // If the client is only demanding bits that we know, return the known
303 // constant.
304 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
305 return Constant::getIntegerValue(VTy, Known.One);
306
307 // If all of the demanded bits are known zero on one side, return the other.
308 // These bits cannot contribute to the result of the 'xor'.
309 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
310 return I->getOperand(0);
311 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
312 return I->getOperand(1);
313
314 // If all of the demanded bits are known to be zero on one side or the
315 // other, turn this into an *inclusive* or.
316 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
317 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
318 Instruction *Or =
319 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1));
320 if (DemandedMask.isAllOnes())
321 cast<PossiblyDisjointInst>(Or)->setIsDisjoint(true);
322 Or->takeName(I);
323 return InsertNewInstWith(Or, I->getIterator());
324 }
325
326 // If all of the demanded bits on one side are known, and all of the set
327 // bits on that side are also known to be set on the other side, turn this
328 // into an AND, as we know the bits will be cleared.
329 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
330 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
331 RHSKnown.One.isSubsetOf(LHSKnown.One)) {
333 ~RHSKnown.One & DemandedMask);
334 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
335 return InsertNewInstWith(And, I->getIterator());
336 }
337
338 // If the RHS is a constant, see if we can change it. Don't alter a -1
339 // constant because that's a canonical 'not' op, and that is better for
340 // combining, SCEV, and codegen.
341 const APInt *C;
342 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
343 if ((*C | ~DemandedMask).isAllOnes()) {
344 // Force bits to 1 to create a 'not' op.
345 I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
346 return I;
347 }
348 // If we can't turn this into a 'not', try to shrink the constant.
349 if (ShrinkDemandedConstant(I, 1, DemandedMask))
350 return I;
351 }
352
353 // If our LHS is an 'and' and if it has one use, and if any of the bits we
354 // are flipping are known to be set, then the xor is just resetting those
355 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
356 // simplifying both of them.
357 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
358 ConstantInt *AndRHS, *XorRHS;
359 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
360 match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
361 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
362 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
363 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
364
365 Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue());
366 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
367 InsertNewInstWith(NewAnd, I->getIterator());
368
369 Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue());
370 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
371 return InsertNewInstWith(NewXor, I->getIterator());
372 }
373 }
374 break;
375 }
376 case Instruction::Select: {
377 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Q, Depth + 1) ||
378 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Q, Depth + 1))
379 return I;
380
381 // If the operands are constants, see if we can simplify them.
382 // This is similar to ShrinkDemandedConstant, but for a select we want to
383 // try to keep the selected constants the same as icmp value constants, if
384 // we can. This helps not break apart (or helps put back together)
385 // canonical patterns like min and max.
386 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
387 const APInt &DemandedMask) {
388 const APInt *SelC;
389 if (!match(I->getOperand(OpNo), m_APInt(SelC)))
390 return false;
391
392 // Get the constant out of the ICmp, if there is one.
393 // Only try this when exactly 1 operand is a constant (if both operands
394 // are constant, the icmp should eventually simplify). Otherwise, we may
395 // invert the transform that reduces set bits and infinite-loop.
396 Value *X;
397 const APInt *CmpC;
398 if (!match(I->getOperand(0), m_ICmp(m_Value(X), m_APInt(CmpC))) ||
399 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
400 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
401
402 // If the constant is already the same as the ICmp, leave it as-is.
403 if (*CmpC == *SelC)
404 return false;
405 // If the constants are not already the same, but can be with the demand
406 // mask, use the constant value from the ICmp.
407 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
408 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
409 return true;
410 }
411 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
412 };
413 if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
414 CanonicalizeSelectConstant(I, 2, DemandedMask))
415 return I;
416
417 // Only known if known in both the LHS and RHS.
418 adjustKnownBitsForSelectArm(LHSKnown, I->getOperand(0), I->getOperand(1),
419 /*Invert=*/false, Q, Depth);
420 adjustKnownBitsForSelectArm(RHSKnown, I->getOperand(0), I->getOperand(2),
421 /*Invert=*/true, Q, Depth);
422 Known = LHSKnown.intersectWith(RHSKnown);
423 break;
424 }
425 case Instruction::Trunc: {
426 // If we do not demand the high bits of a right-shifted and truncated value,
427 // then we may be able to truncate it before the shift.
428 Value *X;
429 const APInt *C;
430 if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
431 // The shift amount must be valid (not poison) in the narrow type, and
432 // it must not be greater than the high bits demanded of the result.
433 if (C->ult(VTy->getScalarSizeInBits()) &&
434 C->ule(DemandedMask.countl_zero())) {
435 // trunc (lshr X, C) --> lshr (trunc X), C
437 Builder.SetInsertPoint(I);
438 Value *Trunc = Builder.CreateTrunc(X, VTy);
439 return Builder.CreateLShr(Trunc, C->getZExtValue());
440 }
441 }
442 }
443 [[fallthrough]];
444 case Instruction::ZExt: {
445 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
446
447 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
448 KnownBits InputKnown(SrcBitWidth);
449 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Q,
450 Depth + 1)) {
451 // For zext nneg, we may have dropped the instruction which made the
452 // input non-negative.
453 I->dropPoisonGeneratingFlags();
454 return I;
455 }
456 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
457 if (I->getOpcode() == Instruction::ZExt && I->hasNonNeg() &&
458 !InputKnown.isNegative())
459 InputKnown.makeNonNegative();
460 Known = InputKnown.zextOrTrunc(BitWidth);
461
462 break;
463 }
464 case Instruction::SExt: {
465 // Compute the bits in the result that are not present in the input.
466 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
467
468 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
469
470 // If any of the sign extended bits are demanded, we know that the sign
471 // bit is demanded.
472 if (DemandedMask.getActiveBits() > SrcBitWidth)
473 InputDemandedBits.setBit(SrcBitWidth-1);
474
475 KnownBits InputKnown(SrcBitWidth);
476 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Q, Depth + 1))
477 return I;
478
479 // If the input sign bit is known zero, or if the NewBits are not demanded
480 // convert this into a zero extension.
481 if (InputKnown.isNonNegative() ||
482 DemandedMask.getActiveBits() <= SrcBitWidth) {
483 // Convert to ZExt cast.
484 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy);
485 NewCast->takeName(I);
486 return InsertNewInstWith(NewCast, I->getIterator());
487 }
488
489 // If the sign bit of the input is known set or clear, then we know the
490 // top bits of the result.
491 Known = InputKnown.sext(BitWidth);
492 break;
493 }
494 case Instruction::Add: {
495 if ((DemandedMask & 1) == 0) {
496 // If we do not need the low bit, try to convert bool math to logic:
497 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
498 Value *X, *Y;
500 m_OneUse(m_SExt(m_Value(Y))))) &&
501 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
502 // Truth table for inputs and output signbits:
503 // X:0 | X:1
504 // ----------
505 // Y:0 | 0 | 0 |
506 // Y:1 | -1 | 0 |
507 // ----------
509 Builder.SetInsertPoint(I);
510 Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
511 return Builder.CreateSExt(AndNot, VTy);
512 }
513
514 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
515 if (match(I, m_Add(m_SExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
516 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
517 (I->getOperand(0)->hasOneUse() || I->getOperand(1)->hasOneUse())) {
518
519 // Truth table for inputs and output signbits:
520 // X:0 | X:1
521 // -----------
522 // Y:0 | -1 | -1 |
523 // Y:1 | -1 | 0 |
524 // -----------
526 Builder.SetInsertPoint(I);
527 Value *Or = Builder.CreateOr(X, Y);
528 return Builder.CreateSExt(Or, VTy);
529 }
530 }
531
532 // Right fill the mask of bits for the operands to demand the most
533 // significant bit and all those below it.
534 unsigned NLZ = DemandedMask.countl_zero();
535 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
536 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
537 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1))
538 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
539
540 // If low order bits are not demanded and known to be zero in one operand,
541 // then we don't need to demand them from the other operand, since they
542 // can't cause overflow into any bits that are demanded in the result.
543 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
544 APInt DemandedFromLHS = DemandedFromOps;
545 DemandedFromLHS.clearLowBits(NTZ);
546 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
547 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Q, Depth + 1))
548 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
549
550 // If we are known to be adding zeros to every bit below
551 // the highest demanded bit, we just return the other side.
552 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
553 return I->getOperand(0);
554 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
555 return I->getOperand(1);
556
557 // (add X, C) --> (xor X, C) IFF C is equal to the top bit of the DemandMask
558 {
559 const APInt *C;
560 if (match(I->getOperand(1), m_APInt(C)) &&
561 C->isOneBitSet(DemandedMask.getActiveBits() - 1)) {
563 Builder.SetInsertPoint(I);
564 return Builder.CreateXor(I->getOperand(0), ConstantInt::get(VTy, *C));
565 }
566 }
567
568 // Otherwise just compute the known bits of the result.
569 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
570 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
571 Known = KnownBits::add(LHSKnown, RHSKnown, NSW, NUW);
572 break;
573 }
574 case Instruction::Sub: {
575 // Right fill the mask of bits for the operands to demand the most
576 // significant bit and all those below it.
577 unsigned NLZ = DemandedMask.countl_zero();
578 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
579 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
580 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1))
581 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
582
583 // If low order bits are not demanded and are known to be zero in RHS,
584 // then we don't need to demand them from LHS, since they can't cause a
585 // borrow from any bits that are demanded in the result.
586 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
587 APInt DemandedFromLHS = DemandedFromOps;
588 DemandedFromLHS.clearLowBits(NTZ);
589 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
590 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Q, Depth + 1))
591 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
592
593 // If we are known to be subtracting zeros from every bit below
594 // the highest demanded bit, we just return the other side.
595 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
596 return I->getOperand(0);
597 // We can't do this with the LHS for subtraction, unless we are only
598 // demanding the LSB.
599 if (DemandedFromOps.isOne() && DemandedFromOps.isSubsetOf(LHSKnown.Zero))
600 return I->getOperand(1);
601
602 // Canonicalize sub mask, X -> ~X
603 const APInt *LHSC;
604 if (match(I->getOperand(0), m_LowBitMask(LHSC)) &&
605 DemandedFromOps.isSubsetOf(*LHSC)) {
607 Builder.SetInsertPoint(I);
608 return Builder.CreateNot(I->getOperand(1));
609 }
610
611 // Otherwise just compute the known bits of the result.
612 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
613 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
614 Known = KnownBits::sub(LHSKnown, RHSKnown, NSW, NUW);
615 break;
616 }
617 case Instruction::Mul: {
618 APInt DemandedFromOps;
619 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
620 return I;
621
622 if (DemandedMask.isPowerOf2()) {
623 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
624 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
625 // odd (has LSB set), then the left-shifted low bit of X is the answer.
626 unsigned CTZ = DemandedMask.countr_zero();
627 const APInt *C;
628 if (match(I->getOperand(1), m_APInt(C)) && C->countr_zero() == CTZ) {
629 Constant *ShiftC = ConstantInt::get(VTy, CTZ);
630 Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
631 return InsertNewInstWith(Shl, I->getIterator());
632 }
633 }
634 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
635 // X * X is odd iff X is odd.
636 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
637 if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
638 Constant *One = ConstantInt::get(VTy, 1);
639 Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
640 return InsertNewInstWith(And1, I->getIterator());
641 }
642
643 llvm::computeKnownBits(I, Known, Q, Depth);
644 break;
645 }
646 case Instruction::Shl: {
647 const APInt *SA;
648 if (match(I->getOperand(1), m_APInt(SA))) {
649 const APInt *ShrAmt;
650 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
651 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
652 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
653 DemandedMask, Known))
654 return R;
655
656 // Do not simplify if shl is part of funnel-shift pattern
657 if (I->hasOneUse()) {
658 auto *Inst = dyn_cast<Instruction>(I->user_back());
659 if (Inst && Inst->getOpcode() == BinaryOperator::Or) {
660 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
661 auto [IID, FShiftArgs] = *Opt;
662 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
663 FShiftArgs[0] == FShiftArgs[1]) {
664 llvm::computeKnownBits(I, Known, Q, Depth);
665 break;
666 }
667 }
668 }
669 }
670
671 // We only want bits that already match the signbit then we don't
672 // need to shift.
673 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth - 1);
674 if (DemandedMask.countr_zero() >= ShiftAmt) {
675 if (I->hasNoSignedWrap()) {
676 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
677 unsigned SignBits =
678 ComputeNumSignBits(I->getOperand(0), Q.CxtI, Depth + 1);
679 if (SignBits > ShiftAmt && SignBits - ShiftAmt >= NumHiDemandedBits)
680 return I->getOperand(0);
681 }
682
683 // If we can pre-shift a right-shifted constant to the left without
684 // losing any high bits and we don't demand the low bits, then eliminate
685 // the left-shift:
686 // (C >> X) << LeftShiftAmtC --> (C << LeftShiftAmtC) >> X
687 Value *X;
688 Constant *C;
689 if (match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) {
690 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
691 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::Shl, C,
692 LeftShiftAmtC, DL);
693 if (ConstantFoldBinaryOpOperands(Instruction::LShr, NewC,
694 LeftShiftAmtC, DL) == C) {
695 Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X);
696 return InsertNewInstWith(Lshr, I->getIterator());
697 }
698 }
699 }
700
701 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
702
703 // If the shift is NUW/NSW, then it does demand the high bits.
705 if (IOp->hasNoSignedWrap())
706 DemandedMaskIn.setHighBits(ShiftAmt+1);
707 else if (IOp->hasNoUnsignedWrap())
708 DemandedMaskIn.setHighBits(ShiftAmt);
709
710 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1))
711 return I;
712
713 Known = KnownBits::shl(Known,
715 /* NUW */ IOp->hasNoUnsignedWrap(),
716 /* NSW */ IOp->hasNoSignedWrap());
717 } else {
718 // This is a variable shift, so we can't shift the demand mask by a known
719 // amount. But if we are not demanding high bits, then we are not
720 // demanding those bits from the pre-shifted operand either.
721 if (unsigned CTLZ = DemandedMask.countl_zero()) {
722 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
723 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Q, Depth + 1)) {
724 // We can't guarantee that nsw/nuw hold after simplifying the operand.
725 I->dropPoisonGeneratingFlags();
726 return I;
727 }
728 }
729 llvm::computeKnownBits(I, Known, Q, Depth);
730 }
731 break;
732 }
733 case Instruction::LShr: {
734 const APInt *SA;
735 if (match(I->getOperand(1), m_APInt(SA))) {
736 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
737
738 // Do not simplify if lshr is part of funnel-shift pattern
739 if (I->hasOneUse()) {
740 auto *Inst = dyn_cast<Instruction>(I->user_back());
741 if (Inst && Inst->getOpcode() == BinaryOperator::Or) {
742 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
743 auto [IID, FShiftArgs] = *Opt;
744 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
745 FShiftArgs[0] == FShiftArgs[1]) {
746 llvm::computeKnownBits(I, Known, Q, Depth);
747 break;
748 }
749 }
750 }
751 }
752
753 // If we are just demanding the shifted sign bit and below, then this can
754 // be treated as an ASHR in disguise.
755 if (DemandedMask.countl_zero() >= ShiftAmt) {
756 // If we only want bits that already match the signbit then we don't
757 // need to shift.
758 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
759 unsigned SignBits =
760 ComputeNumSignBits(I->getOperand(0), Q.CxtI, Depth + 1);
761 if (SignBits >= NumHiDemandedBits)
762 return I->getOperand(0);
763
764 // If we can pre-shift a left-shifted constant to the right without
765 // losing any low bits (we already know we don't demand the high bits),
766 // then eliminate the right-shift:
767 // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
768 Value *X;
769 Constant *C;
770 if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
771 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
772 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::LShr, C,
773 RightShiftAmtC, DL);
774 if (ConstantFoldBinaryOpOperands(Instruction::Shl, NewC,
775 RightShiftAmtC, DL) == C) {
776 Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
777 return InsertNewInstWith(Shl, I->getIterator());
778 }
779 }
780
781 const APInt *Factor;
782 if (match(I->getOperand(0),
783 m_OneUse(m_Mul(m_Value(X), m_APInt(Factor)))) &&
784 Factor->countr_zero() >= ShiftAmt) {
785 BinaryOperator *Mul = BinaryOperator::CreateMul(
786 X, ConstantInt::get(X->getType(), Factor->lshr(ShiftAmt)));
787 return InsertNewInstWith(Mul, I->getIterator());
788 }
789 }
790
791 // Unsigned shift right.
792 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
793 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1)) {
794 // exact flag may not longer hold.
795 I->dropPoisonGeneratingFlags();
796 return I;
797 }
798 Known >>= ShiftAmt;
799 if (ShiftAmt)
800 Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
801 } else {
802 llvm::computeKnownBits(I, Known, Q, Depth);
803 }
804 break;
805 }
806 case Instruction::AShr: {
807 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Q.CxtI, Depth + 1);
808
809 // If we only want bits that already match the signbit then we don't need
810 // to shift.
811 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
812 if (SignBits >= NumHiDemandedBits)
813 return I->getOperand(0);
814
815 // If this is an arithmetic shift right and only the low-bit is set, we can
816 // always convert this into a logical shr, even if the shift amount is
817 // variable. The low bit of the shift cannot be an input sign bit unless
818 // the shift amount is >= the size of the datatype, which is undefined.
819 if (DemandedMask.isOne()) {
820 // Perform the logical shift right.
821 Instruction *NewVal = BinaryOperator::CreateLShr(
822 I->getOperand(0), I->getOperand(1), I->getName());
823 return InsertNewInstWith(NewVal, I->getIterator());
824 }
825
826 const APInt *SA;
827 if (match(I->getOperand(1), m_APInt(SA))) {
828 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
829
830 // Signed shift right.
831 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
832 // If any of the bits being shifted in are demanded, then we should set
833 // the sign bit as demanded.
834 bool ShiftedInBitsDemanded = DemandedMask.countl_zero() < ShiftAmt;
835 if (ShiftedInBitsDemanded)
836 DemandedMaskIn.setSignBit();
837 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1)) {
838 // exact flag may not longer hold.
839 I->dropPoisonGeneratingFlags();
840 return I;
841 }
842
843 // If the input sign bit is known to be zero, or if none of the shifted in
844 // bits are demanded, turn this into an unsigned shift right.
845 if (Known.Zero[BitWidth - 1] || !ShiftedInBitsDemanded) {
846 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
847 I->getOperand(1));
848 LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
849 LShr->takeName(I);
850 return InsertNewInstWith(LShr, I->getIterator());
851 }
852
853 Known = KnownBits::ashr(
854 Known, KnownBits::makeConstant(APInt(BitWidth, ShiftAmt)),
855 ShiftAmt != 0, I->isExact());
856 } else {
857 llvm::computeKnownBits(I, Known, Q, Depth);
858 }
859 break;
860 }
861 case Instruction::UDiv: {
862 // UDiv doesn't demand low bits that are zero in the divisor.
863 const APInt *SA;
864 if (match(I->getOperand(1), m_APInt(SA))) {
865 // TODO: Take the demanded mask of the result into account.
866 unsigned RHSTrailingZeros = SA->countr_zero();
867 APInt DemandedMaskIn =
868 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
869 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Q, Depth + 1)) {
870 // We can't guarantee that "exact" is still true after changing the
871 // the dividend.
872 I->dropPoisonGeneratingFlags();
873 return I;
874 }
875
876 Known = KnownBits::udiv(LHSKnown, KnownBits::makeConstant(*SA),
877 cast<BinaryOperator>(I)->isExact());
878 } else {
879 llvm::computeKnownBits(I, Known, Q, Depth);
880 }
881 break;
882 }
883 case Instruction::SRem: {
884 const APInt *Rem;
885 if (match(I->getOperand(1), m_APInt(Rem)) && Rem->isPowerOf2()) {
886 if (DemandedMask.ult(*Rem)) // srem won't affect demanded bits
887 return I->getOperand(0);
888
889 APInt LowBits = *Rem - 1;
890 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
891 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Q, Depth + 1))
892 return I;
893 Known = KnownBits::srem(LHSKnown, KnownBits::makeConstant(*Rem));
894 break;
895 }
896
897 llvm::computeKnownBits(I, Known, Q, Depth);
898 break;
899 }
900 case Instruction::Call: {
901 bool KnownBitsComputed = false;
903 switch (II->getIntrinsicID()) {
904 case Intrinsic::abs: {
905 if (DemandedMask == 1)
906 return II->getArgOperand(0);
907 break;
908 }
909 case Intrinsic::ctpop: {
910 // Checking if the number of clear bits is odd (parity)? If the type has
911 // an even number of bits, that's the same as checking if the number of
912 // set bits is odd, so we can eliminate the 'not' op.
913 Value *X;
914 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
915 match(II->getArgOperand(0), m_Not(m_Value(X)))) {
917 II->getModule(), Intrinsic::ctpop, VTy);
918 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), I->getIterator());
919 }
920 break;
921 }
922 case Intrinsic::bswap: {
923 // If the only bits demanded come from one byte of the bswap result,
924 // just shift the input byte into position to eliminate the bswap.
925 unsigned NLZ = DemandedMask.countl_zero();
926 unsigned NTZ = DemandedMask.countr_zero();
927
928 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
929 // we need all the bits down to bit 8. Likewise, round NLZ. If we
930 // have 14 leading zeros, round to 8.
931 NLZ = alignDown(NLZ, 8);
932 NTZ = alignDown(NTZ, 8);
933 // If we need exactly one byte, we can do this transformation.
934 if (BitWidth - NLZ - NTZ == 8) {
935 // Replace this with either a left or right shift to get the byte into
936 // the right place.
937 Instruction *NewVal;
938 if (NLZ > NTZ)
939 NewVal = BinaryOperator::CreateLShr(
940 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
941 else
942 NewVal = BinaryOperator::CreateShl(
943 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
944 NewVal->takeName(I);
945 return InsertNewInstWith(NewVal, I->getIterator());
946 }
947 break;
948 }
949 case Intrinsic::ptrmask: {
950 unsigned MaskWidth = I->getOperand(1)->getType()->getScalarSizeInBits();
951 RHSKnown = KnownBits(MaskWidth);
952 // If either the LHS or the RHS are Zero, the result is zero.
953 if (SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Q, Depth + 1) ||
955 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth),
956 RHSKnown, Q, Depth + 1))
957 return I;
958
959 // TODO: Should be 1-extend
960 RHSKnown = RHSKnown.anyextOrTrunc(BitWidth);
961
962 Known = LHSKnown & RHSKnown;
963 KnownBitsComputed = true;
964
965 // If the client is only demanding bits we know to be zero, return
966 // `llvm.ptrmask(p, 0)`. We can't return `null` here due to pointer
967 // provenance, but making the mask zero will be easily optimizable in
968 // the backend.
969 if (DemandedMask.isSubsetOf(Known.Zero) &&
970 !match(I->getOperand(1), m_Zero()))
971 return replaceOperand(
972 *I, 1, Constant::getNullValue(I->getOperand(1)->getType()));
973
974 // Mask in demanded space does nothing.
975 // NOTE: We may have attributes associated with the return value of the
976 // llvm.ptrmask intrinsic that will be lost when we just return the
977 // operand. We should try to preserve them.
978 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
979 return I->getOperand(0);
980
981 // If the RHS is a constant, see if we can simplify it.
983 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth)))
984 return I;
985
986 // Combine:
987 // (ptrmask (getelementptr i8, ptr p, imm i), imm mask)
988 // -> (ptrmask (getelementptr i8, ptr p, imm (i & mask)), imm mask)
989 // where only the low bits known to be zero in the pointer are changed
990 Value *InnerPtr;
991 uint64_t GEPIndex;
992 uint64_t PtrMaskImmediate;
994 m_PtrAdd(m_Value(InnerPtr), m_ConstantInt(GEPIndex)),
995 m_ConstantInt(PtrMaskImmediate)))) {
996
997 LHSKnown = computeKnownBits(InnerPtr, I, Depth + 1);
998 if (!LHSKnown.isZero()) {
999 const unsigned trailingZeros = LHSKnown.countMinTrailingZeros();
1000 uint64_t PointerAlignBits = (uint64_t(1) << trailingZeros) - 1;
1001
1002 uint64_t HighBitsGEPIndex = GEPIndex & ~PointerAlignBits;
1003 uint64_t MaskedLowBitsGEPIndex =
1004 GEPIndex & PointerAlignBits & PtrMaskImmediate;
1005
1006 uint64_t MaskedGEPIndex = HighBitsGEPIndex | MaskedLowBitsGEPIndex;
1007
1008 if (MaskedGEPIndex != GEPIndex) {
1009 auto *GEP = cast<GEPOperator>(II->getArgOperand(0));
1010 Builder.SetInsertPoint(I);
1011 Type *GEPIndexType =
1012 DL.getIndexType(GEP->getPointerOperand()->getType());
1013 Value *MaskedGEP = Builder.CreateGEP(
1014 GEP->getSourceElementType(), InnerPtr,
1015 ConstantInt::get(GEPIndexType, MaskedGEPIndex),
1016 GEP->getName(), GEP->isInBounds());
1017
1018 replaceOperand(*I, 0, MaskedGEP);
1019 return I;
1020 }
1021 }
1022 }
1023
1024 break;
1025 }
1026
1027 case Intrinsic::fshr:
1028 case Intrinsic::fshl: {
1029 const APInt *SA;
1030 if (!match(I->getOperand(2), m_APInt(SA)))
1031 break;
1032
1033 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
1034 // defined, so no need to special-case zero shifts here.
1035 uint64_t ShiftAmt = SA->urem(BitWidth);
1036 if (II->getIntrinsicID() == Intrinsic::fshr)
1037 ShiftAmt = BitWidth - ShiftAmt;
1038
1039 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
1040 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
1041 if (I->getOperand(0) != I->getOperand(1)) {
1042 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Q,
1043 Depth + 1) ||
1044 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Q,
1045 Depth + 1)) {
1046 // Range attribute may no longer hold.
1047 I->dropPoisonGeneratingReturnAttributes();
1048 return I;
1049 }
1050 } else { // fshl is a rotate
1051 // Avoid converting rotate into funnel shift.
1052 // Only simplify if one operand is constant.
1053 LHSKnown = computeKnownBits(I->getOperand(0), I, Depth + 1);
1054 if (DemandedMaskLHS.isSubsetOf(LHSKnown.Zero | LHSKnown.One) &&
1055 !match(I->getOperand(0), m_SpecificInt(LHSKnown.One))) {
1056 replaceOperand(*I, 0, Constant::getIntegerValue(VTy, LHSKnown.One));
1057 return I;
1058 }
1059
1060 RHSKnown = computeKnownBits(I->getOperand(1), I, Depth + 1);
1061 if (DemandedMaskRHS.isSubsetOf(RHSKnown.Zero | RHSKnown.One) &&
1062 !match(I->getOperand(1), m_SpecificInt(RHSKnown.One))) {
1063 replaceOperand(*I, 1, Constant::getIntegerValue(VTy, RHSKnown.One));
1064 return I;
1065 }
1066 }
1067
1068 LHSKnown <<= ShiftAmt;
1069 RHSKnown >>= BitWidth - ShiftAmt;
1070 Known = LHSKnown.unionWith(RHSKnown);
1071 KnownBitsComputed = true;
1072 break;
1073 }
1074 case Intrinsic::umax: {
1075 // UMax(A, C) == A if ...
1076 // The lowest non-zero bit of DemandMask is higher than the highest
1077 // non-zero bit of C.
1078 const APInt *C;
1079 unsigned CTZ = DemandedMask.countr_zero();
1080 if (match(II->getArgOperand(1), m_APInt(C)) &&
1081 CTZ >= C->getActiveBits())
1082 return II->getArgOperand(0);
1083 break;
1084 }
1085 case Intrinsic::umin: {
1086 // UMin(A, C) == A if ...
1087 // The lowest non-zero bit of DemandMask is higher than the highest
1088 // non-one bit of C.
1089 // This comes from using DeMorgans on the above umax example.
1090 const APInt *C;
1091 unsigned CTZ = DemandedMask.countr_zero();
1092 if (match(II->getArgOperand(1), m_APInt(C)) &&
1093 CTZ >= C->getBitWidth() - C->countl_one())
1094 return II->getArgOperand(0);
1095 break;
1096 }
1097 default: {
1098 // Handle target specific intrinsics
1099 std::optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
1100 *II, DemandedMask, Known, KnownBitsComputed);
1101 if (V)
1102 return *V;
1103 break;
1104 }
1105 }
1106 }
1107
1108 if (!KnownBitsComputed)
1109 llvm::computeKnownBits(I, Known, Q, Depth);
1110 break;
1111 }
1112 }
1113
1114 if (I->getType()->isPointerTy()) {
1115 Align Alignment = I->getPointerAlignment(DL);
1116 Known.Zero.setLowBits(Log2(Alignment));
1117 }
1118
1119 // If the client is only demanding bits that we know, return the known
1120 // constant. We can't directly simplify pointers as a constant because of
1121 // pointer provenance.
1122 // TODO: We could return `(inttoptr const)` for pointers.
1123 if (!I->getType()->isPointerTy() &&
1124 DemandedMask.isSubsetOf(Known.Zero | Known.One))
1125 return Constant::getIntegerValue(VTy, Known.One);
1126
1127 if (VerifyKnownBits) {
1128 KnownBits ReferenceKnown = llvm::computeKnownBits(I, Q, Depth);
1129 if (Known != ReferenceKnown) {
1130 errs() << "Mismatched known bits for " << *I << " in "
1131 << I->getFunction()->getName() << "\n";
1132 errs() << "computeKnownBits(): " << ReferenceKnown << "\n";
1133 errs() << "SimplifyDemandedBits(): " << Known << "\n";
1134 std::abort();
1135 }
1136 }
1137
1138 return nullptr;
1139}
1140
1141/// Helper routine of SimplifyDemandedUseBits. It computes Known
1142/// bits. It also tries to handle simplifications that can be done based on
1143/// DemandedMask, but without modifying the Instruction.
1145 Instruction *I, const APInt &DemandedMask, KnownBits &Known,
1146 const SimplifyQuery &Q, unsigned Depth) {
1147 unsigned BitWidth = DemandedMask.getBitWidth();
1148 Type *ITy = I->getType();
1149
1150 KnownBits LHSKnown(BitWidth);
1151 KnownBits RHSKnown(BitWidth);
1152
1153 // Despite the fact that we can't simplify this instruction in all User's
1154 // context, we can at least compute the known bits, and we can
1155 // do simplifications that apply to *just* the one user if we know that
1156 // this instruction has a simpler value in that context.
1157 switch (I->getOpcode()) {
1158 case Instruction::And: {
1159 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1160 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1161 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1162 Q, Depth);
1164
1165 // If the client is only demanding bits that we know, return the known
1166 // constant.
1167 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1168 return Constant::getIntegerValue(ITy, Known.One);
1169
1170 // If all of the demanded bits are known 1 on one side, return the other.
1171 // These bits cannot contribute to the result of the 'and' in this context.
1172 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
1173 return I->getOperand(0);
1174 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
1175 return I->getOperand(1);
1176
1177 break;
1178 }
1179 case Instruction::Or: {
1180 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1181 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1182 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1183 Q, Depth);
1185
1186 // If the client is only demanding bits that we know, return the known
1187 // constant.
1188 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1189 return Constant::getIntegerValue(ITy, Known.One);
1190
1191 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1192 // only bits from X or Y are demanded.
1193 // If all of the demanded bits are known zero on one side, return the other.
1194 // These bits cannot contribute to the result of the 'or' in this context.
1195 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
1196 return I->getOperand(0);
1197 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1198 return I->getOperand(1);
1199
1200 break;
1201 }
1202 case Instruction::Xor: {
1203 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1204 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1205 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1206 Q, Depth);
1208
1209 // If the client is only demanding bits that we know, return the known
1210 // constant.
1211 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1212 return Constant::getIntegerValue(ITy, Known.One);
1213
1214 // We can simplify (X^Y) -> X or Y in the user's context if we know that
1215 // only bits from X or Y are demanded.
1216 // If all of the demanded bits are known zero on one side, return the other.
1217 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1218 return I->getOperand(0);
1219 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1220 return I->getOperand(1);
1221
1222 break;
1223 }
1224 case Instruction::Add: {
1225 unsigned NLZ = DemandedMask.countl_zero();
1226 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1227
1228 // If an operand adds zeros to every bit below the highest demanded bit,
1229 // that operand doesn't change the result. Return the other side.
1230 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1231 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1232 return I->getOperand(0);
1233
1234 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1235 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
1236 return I->getOperand(1);
1237
1238 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1239 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1240 Known = KnownBits::add(LHSKnown, RHSKnown, NSW, NUW);
1242 break;
1243 }
1244 case Instruction::Sub: {
1245 unsigned NLZ = DemandedMask.countl_zero();
1246 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1247
1248 // If an operand subtracts zeros from every bit below the highest demanded
1249 // bit, that operand doesn't change the result. Return the other side.
1250 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1251 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1252 return I->getOperand(0);
1253
1254 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1255 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1256 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1257 Known = KnownBits::sub(LHSKnown, RHSKnown, NSW, NUW);
1259 break;
1260 }
1261 case Instruction::AShr: {
1262 // Compute the Known bits to simplify things downstream.
1263 llvm::computeKnownBits(I, Known, Q, Depth);
1264
1265 // If this user is only demanding bits that we know, return the known
1266 // constant.
1267 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1268 return Constant::getIntegerValue(ITy, Known.One);
1269
1270 // If the right shift operand 0 is a result of a left shift by the same
1271 // amount, this is probably a zero/sign extension, which may be unnecessary,
1272 // if we do not demand any of the new sign bits. So, return the original
1273 // operand instead.
1274 const APInt *ShiftRC;
1275 const APInt *ShiftLC;
1276 Value *X;
1277 unsigned BitWidth = DemandedMask.getBitWidth();
1278 if (match(I,
1279 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1280 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1281 DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1282 BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1283 return X;
1284 }
1285
1286 break;
1287 }
1288 default:
1289 // Compute the Known bits to simplify things downstream.
1290 llvm::computeKnownBits(I, Known, Q, Depth);
1291
1292 // If this user is only demanding bits that we know, return the known
1293 // constant.
1294 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1295 return Constant::getIntegerValue(ITy, Known.One);
1296
1297 break;
1298 }
1299
1300 return nullptr;
1301}
1302
1303/// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1304/// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1305/// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1306/// of "C2-C1".
1307///
1308/// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1309/// ..., bn}, without considering the specific value X is holding.
1310/// This transformation is legal iff one of following conditions is hold:
1311/// 1) All the bit in S are 0, in this case E1 == E2.
1312/// 2) We don't care those bits in S, per the input DemandedMask.
1313/// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1314/// rest bits.
1315///
1316/// Currently we only test condition 2).
1317///
1318/// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1319/// not successful.
1321 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1322 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1323 if (!ShlOp1 || !ShrOp1)
1324 return nullptr; // No-op.
1325
1326 Value *VarX = Shr->getOperand(0);
1327 Type *Ty = VarX->getType();
1328 unsigned BitWidth = Ty->getScalarSizeInBits();
1329 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1330 return nullptr; // Undef.
1331
1332 unsigned ShlAmt = ShlOp1.getZExtValue();
1333 unsigned ShrAmt = ShrOp1.getZExtValue();
1334
1335 Known.One.clearAllBits();
1336 Known.Zero.setLowBits(ShlAmt - 1);
1337 Known.Zero &= DemandedMask;
1338
1339 APInt BitMask1(APInt::getAllOnes(BitWidth));
1340 APInt BitMask2(APInt::getAllOnes(BitWidth));
1341
1342 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1343 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1344 (BitMask1.ashr(ShrAmt) << ShlAmt);
1345
1346 if (ShrAmt <= ShlAmt) {
1347 BitMask2 <<= (ShlAmt - ShrAmt);
1348 } else {
1349 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1350 BitMask2.ashr(ShrAmt - ShlAmt);
1351 }
1352
1353 // Check if condition-2 (see the comment to this function) is satified.
1354 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1355 if (ShrAmt == ShlAmt)
1356 return VarX;
1357
1358 if (!Shr->hasOneUse())
1359 return nullptr;
1360
1361 BinaryOperator *New;
1362 if (ShrAmt < ShlAmt) {
1363 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1364 New = BinaryOperator::CreateShl(VarX, Amt);
1366 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1367 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1368 } else {
1369 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1370 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1371 BinaryOperator::CreateAShr(VarX, Amt);
1372 if (cast<BinaryOperator>(Shr)->isExact())
1373 New->setIsExact(true);
1374 }
1375
1376 return InsertNewInstWith(New, Shl->getIterator());
1377 }
1378
1379 return nullptr;
1380}
1381
1382/// The specified value produces a vector with any number of elements.
1383/// This method analyzes which elements of the operand are poison and
1384/// returns that information in PoisonElts.
1385///
1386/// DemandedElts contains the set of elements that are actually used by the
1387/// caller, and by default (AllowMultipleUsers equals false) the value is
1388/// simplified only if it has a single caller. If AllowMultipleUsers is set
1389/// to true, DemandedElts refers to the union of sets of elements that are
1390/// used by all callers.
1391///
1392/// If the information about demanded elements can be used to simplify the
1393/// operation, the operation is simplified, then the resultant value is
1394/// returned. This returns null if no change was made.
1396 APInt DemandedElts,
1397 APInt &PoisonElts,
1398 unsigned Depth,
1399 bool AllowMultipleUsers) {
1400 // Cannot analyze scalable type. The number of vector elements is not a
1401 // compile-time constant.
1402 if (isa<ScalableVectorType>(V->getType()))
1403 return nullptr;
1404
1405 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1406 APInt EltMask(APInt::getAllOnes(VWidth));
1407 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1408
1409 if (match(V, m_Poison())) {
1410 // If the entire vector is poison, just return this info.
1411 PoisonElts = EltMask;
1412 return nullptr;
1413 }
1414
1415 if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1416 PoisonElts = EltMask;
1417 return PoisonValue::get(V->getType());
1418 }
1419
1420 PoisonElts = 0;
1421
1422 if (auto *C = dyn_cast<Constant>(V)) {
1423 // Check if this is identity. If so, return 0 since we are not simplifying
1424 // anything.
1425 if (DemandedElts.isAllOnes())
1426 return nullptr;
1427
1428 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1431 for (unsigned i = 0; i != VWidth; ++i) {
1432 if (!DemandedElts[i]) { // If not demanded, set to poison.
1433 Elts.push_back(Poison);
1434 PoisonElts.setBit(i);
1435 continue;
1436 }
1437
1438 Constant *Elt = C->getAggregateElement(i);
1439 if (!Elt) return nullptr;
1440
1441 Elts.push_back(Elt);
1442 if (isa<PoisonValue>(Elt)) // Already poison.
1443 PoisonElts.setBit(i);
1444 }
1445
1446 // If we changed the constant, return it.
1447 Constant *NewCV = ConstantVector::get(Elts);
1448 return NewCV != C ? NewCV : nullptr;
1449 }
1450
1451 // Limit search depth.
1453 return nullptr;
1454
1455 if (!AllowMultipleUsers) {
1456 // If multiple users are using the root value, proceed with
1457 // simplification conservatively assuming that all elements
1458 // are needed.
1459 if (!V->hasOneUse()) {
1460 // Quit if we find multiple users of a non-root value though.
1461 // They'll be handled when it's their turn to be visited by
1462 // the main instcombine process.
1463 if (Depth != 0)
1464 // TODO: Just compute the PoisonElts information recursively.
1465 return nullptr;
1466
1467 // Conservatively assume that all elements are needed.
1468 DemandedElts = EltMask;
1469 }
1470 }
1471
1473 if (!I) return nullptr; // Only analyze instructions.
1474
1475 bool MadeChange = false;
1476 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1477 APInt Demanded, APInt &Undef) {
1478 auto *II = dyn_cast<IntrinsicInst>(Inst);
1479 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1480 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1481 replaceOperand(*Inst, OpNum, V);
1482 MadeChange = true;
1483 }
1484 };
1485
1486 APInt PoisonElts2(VWidth, 0);
1487 APInt PoisonElts3(VWidth, 0);
1488 switch (I->getOpcode()) {
1489 default: break;
1490
1491 case Instruction::GetElementPtr: {
1492 // The LangRef requires that struct geps have all constant indices. As
1493 // such, we can't convert any operand to partial undef.
1494 auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1495 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1496 I != E; I++)
1497 if (I.isStruct())
1498 return true;
1499 return false;
1500 };
1501 if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1502 break;
1503
1504 // Conservatively track the demanded elements back through any vector
1505 // operands we may have. We know there must be at least one, or we
1506 // wouldn't have a vector result to get here. Note that we intentionally
1507 // merge the undef bits here since gepping with either an poison base or
1508 // index results in poison.
1509 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1510 if (i == 0 ? match(I->getOperand(i), m_Undef())
1511 : match(I->getOperand(i), m_Poison())) {
1512 // If the entire vector is undefined, just return this info.
1513 PoisonElts = EltMask;
1514 return nullptr;
1515 }
1516 if (I->getOperand(i)->getType()->isVectorTy()) {
1517 APInt PoisonEltsOp(VWidth, 0);
1518 simplifyAndSetOp(I, i, DemandedElts, PoisonEltsOp);
1519 // gep(x, undef) is not undef, so skip considering idx ops here
1520 // Note that we could propagate poison, but we can't distinguish between
1521 // undef & poison bits ATM
1522 if (i == 0)
1523 PoisonElts |= PoisonEltsOp;
1524 }
1525 }
1526
1527 break;
1528 }
1529 case Instruction::InsertElement: {
1530 // If this is a variable index, we don't know which element it overwrites.
1531 // demand exactly the same input as we produce.
1532 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1533 if (!Idx) {
1534 // Note that we can't propagate undef elt info, because we don't know
1535 // which elt is getting updated.
1536 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts2);
1537 break;
1538 }
1539
1540 // The element inserted overwrites whatever was there, so the input demanded
1541 // set is simpler than the output set.
1542 unsigned IdxNo = Idx->getZExtValue();
1543 APInt PreInsertDemandedElts = DemandedElts;
1544 if (IdxNo < VWidth)
1545 PreInsertDemandedElts.clearBit(IdxNo);
1546
1547 // If we only demand the element that is being inserted and that element
1548 // was extracted from the same index in another vector with the same type,
1549 // replace this insert with that other vector.
1550 // Note: This is attempted before the call to simplifyAndSetOp because that
1551 // may change PoisonElts to a value that does not match with Vec.
1552 Value *Vec;
1553 if (PreInsertDemandedElts == 0 &&
1554 match(I->getOperand(1),
1555 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1556 Vec->getType() == I->getType()) {
1557 return Vec;
1558 }
1559
1560 simplifyAndSetOp(I, 0, PreInsertDemandedElts, PoisonElts);
1561
1562 // If this is inserting an element that isn't demanded, remove this
1563 // insertelement.
1564 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1565 Worklist.push(I);
1566 return I->getOperand(0);
1567 }
1568
1569 // The inserted element is defined.
1570 PoisonElts.clearBit(IdxNo);
1571 break;
1572 }
1573 case Instruction::ShuffleVector: {
1574 auto *Shuffle = cast<ShuffleVectorInst>(I);
1575 assert(Shuffle->getOperand(0)->getType() ==
1576 Shuffle->getOperand(1)->getType() &&
1577 "Expected shuffle operands to have same type");
1578 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1579 ->getNumElements();
1580 // Handle trivial case of a splat. Only check the first element of LHS
1581 // operand.
1582 if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1583 DemandedElts.isAllOnes()) {
1584 if (!isa<PoisonValue>(I->getOperand(1))) {
1585 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1586 MadeChange = true;
1587 }
1588 APInt LeftDemanded(OpWidth, 1);
1589 APInt LHSPoisonElts(OpWidth, 0);
1590 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1591 if (LHSPoisonElts[0])
1592 PoisonElts = EltMask;
1593 else
1594 PoisonElts.clearAllBits();
1595 break;
1596 }
1597
1598 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1599 for (unsigned i = 0; i < VWidth; i++) {
1600 if (DemandedElts[i]) {
1601 unsigned MaskVal = Shuffle->getMaskValue(i);
1602 if (MaskVal != -1u) {
1603 assert(MaskVal < OpWidth * 2 &&
1604 "shufflevector mask index out of range!");
1605 if (MaskVal < OpWidth)
1606 LeftDemanded.setBit(MaskVal);
1607 else
1608 RightDemanded.setBit(MaskVal - OpWidth);
1609 }
1610 }
1611 }
1612
1613 APInt LHSPoisonElts(OpWidth, 0);
1614 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1615
1616 APInt RHSPoisonElts(OpWidth, 0);
1617 simplifyAndSetOp(I, 1, RightDemanded, RHSPoisonElts);
1618
1619 // If this shuffle does not change the vector length and the elements
1620 // demanded by this shuffle are an identity mask, then this shuffle is
1621 // unnecessary.
1622 //
1623 // We are assuming canonical form for the mask, so the source vector is
1624 // operand 0 and operand 1 is not used.
1625 //
1626 // Note that if an element is demanded and this shuffle mask is undefined
1627 // for that element, then the shuffle is not considered an identity
1628 // operation. The shuffle prevents poison from the operand vector from
1629 // leaking to the result by replacing poison with an undefined value.
1630 if (VWidth == OpWidth) {
1631 bool IsIdentityShuffle = true;
1632 for (unsigned i = 0; i < VWidth; i++) {
1633 unsigned MaskVal = Shuffle->getMaskValue(i);
1634 if (DemandedElts[i] && i != MaskVal) {
1635 IsIdentityShuffle = false;
1636 break;
1637 }
1638 }
1639 if (IsIdentityShuffle)
1640 return Shuffle->getOperand(0);
1641 }
1642
1643 bool NewPoisonElts = false;
1644 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1645 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1646 bool LHSUniform = true;
1647 bool RHSUniform = true;
1648 for (unsigned i = 0; i < VWidth; i++) {
1649 unsigned MaskVal = Shuffle->getMaskValue(i);
1650 if (MaskVal == -1u) {
1651 PoisonElts.setBit(i);
1652 } else if (!DemandedElts[i]) {
1653 NewPoisonElts = true;
1654 PoisonElts.setBit(i);
1655 } else if (MaskVal < OpWidth) {
1656 if (LHSPoisonElts[MaskVal]) {
1657 NewPoisonElts = true;
1658 PoisonElts.setBit(i);
1659 } else {
1660 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1661 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1662 LHSUniform = LHSUniform && (MaskVal == i);
1663 }
1664 } else {
1665 if (RHSPoisonElts[MaskVal - OpWidth]) {
1666 NewPoisonElts = true;
1667 PoisonElts.setBit(i);
1668 } else {
1669 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1670 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1671 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1672 }
1673 }
1674 }
1675
1676 // Try to transform shuffle with constant vector and single element from
1677 // this constant vector to single insertelement instruction.
1678 // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1679 // insertelement V, C[ci], ci-n
1680 if (OpWidth ==
1681 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1682 Value *Op = nullptr;
1683 Constant *Value = nullptr;
1684 unsigned Idx = -1u;
1685
1686 // Find constant vector with the single element in shuffle (LHS or RHS).
1687 if (LHSIdx < OpWidth && RHSUniform) {
1688 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1689 Op = Shuffle->getOperand(1);
1690 Value = CV->getOperand(LHSValIdx);
1691 Idx = LHSIdx;
1692 }
1693 }
1694 if (RHSIdx < OpWidth && LHSUniform) {
1695 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1696 Op = Shuffle->getOperand(0);
1697 Value = CV->getOperand(RHSValIdx);
1698 Idx = RHSIdx;
1699 }
1700 }
1701 // Found constant vector with single element - convert to insertelement.
1702 if (Op && Value) {
1704 Op, Value, ConstantInt::get(Type::getInt64Ty(I->getContext()), Idx),
1705 Shuffle->getName());
1706 InsertNewInstWith(New, Shuffle->getIterator());
1707 return New;
1708 }
1709 }
1710 if (NewPoisonElts) {
1711 // Add additional discovered undefs.
1713 for (unsigned i = 0; i < VWidth; ++i) {
1714 if (PoisonElts[i])
1716 else
1717 Elts.push_back(Shuffle->getMaskValue(i));
1718 }
1719 Shuffle->setShuffleMask(Elts);
1720 MadeChange = true;
1721 }
1722 break;
1723 }
1724 case Instruction::Select: {
1725 // If this is a vector select, try to transform the select condition based
1726 // on the current demanded elements.
1728 if (Sel->getCondition()->getType()->isVectorTy()) {
1729 // TODO: We are not doing anything with PoisonElts based on this call.
1730 // It is overwritten below based on the other select operands. If an
1731 // element of the select condition is known undef, then we are free to
1732 // choose the output value from either arm of the select. If we know that
1733 // one of those values is undef, then the output can be undef.
1734 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1735 }
1736
1737 // Next, see if we can transform the arms of the select.
1738 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1739 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1740 for (unsigned i = 0; i < VWidth; i++) {
1741 Constant *CElt = CV->getAggregateElement(i);
1742
1743 // isNullValue() always returns false when called on a ConstantExpr.
1744 if (CElt->isNullValue())
1745 DemandedLHS.clearBit(i);
1746 else if (CElt->isOneValue())
1747 DemandedRHS.clearBit(i);
1748 }
1749 }
1750
1751 simplifyAndSetOp(I, 1, DemandedLHS, PoisonElts2);
1752 simplifyAndSetOp(I, 2, DemandedRHS, PoisonElts3);
1753
1754 // Output elements are undefined if the element from each arm is undefined.
1755 // TODO: This can be improved. See comment in select condition handling.
1756 PoisonElts = PoisonElts2 & PoisonElts3;
1757 break;
1758 }
1759 case Instruction::BitCast: {
1760 // Vector->vector casts only.
1761 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1762 if (!VTy) break;
1763 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1764 APInt InputDemandedElts(InVWidth, 0);
1765 PoisonElts2 = APInt(InVWidth, 0);
1766 unsigned Ratio;
1767
1768 if (VWidth == InVWidth) {
1769 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1770 // elements as are demanded of us.
1771 Ratio = 1;
1772 InputDemandedElts = DemandedElts;
1773 } else if ((VWidth % InVWidth) == 0) {
1774 // If the number of elements in the output is a multiple of the number of
1775 // elements in the input then an input element is live if any of the
1776 // corresponding output elements are live.
1777 Ratio = VWidth / InVWidth;
1778 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1779 if (DemandedElts[OutIdx])
1780 InputDemandedElts.setBit(OutIdx / Ratio);
1781 } else if ((InVWidth % VWidth) == 0) {
1782 // If the number of elements in the input is a multiple of the number of
1783 // elements in the output then an input element is live if the
1784 // corresponding output element is live.
1785 Ratio = InVWidth / VWidth;
1786 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1787 if (DemandedElts[InIdx / Ratio])
1788 InputDemandedElts.setBit(InIdx);
1789 } else {
1790 // Unsupported so far.
1791 break;
1792 }
1793
1794 simplifyAndSetOp(I, 0, InputDemandedElts, PoisonElts2);
1795
1796 if (VWidth == InVWidth) {
1797 PoisonElts = PoisonElts2;
1798 } else if ((VWidth % InVWidth) == 0) {
1799 // If the number of elements in the output is a multiple of the number of
1800 // elements in the input then an output element is undef if the
1801 // corresponding input element is undef.
1802 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1803 if (PoisonElts2[OutIdx / Ratio])
1804 PoisonElts.setBit(OutIdx);
1805 } else if ((InVWidth % VWidth) == 0) {
1806 // If the number of elements in the input is a multiple of the number of
1807 // elements in the output then an output element is undef if all of the
1808 // corresponding input elements are undef.
1809 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1810 APInt SubUndef = PoisonElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1811 if (SubUndef.popcount() == Ratio)
1812 PoisonElts.setBit(OutIdx);
1813 }
1814 } else {
1815 llvm_unreachable("Unimp");
1816 }
1817 break;
1818 }
1819 case Instruction::FPTrunc:
1820 case Instruction::FPExt:
1821 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1822 break;
1823
1824 case Instruction::Call: {
1826 if (!II) break;
1827 switch (II->getIntrinsicID()) {
1828 case Intrinsic::masked_gather: // fallthrough
1829 case Intrinsic::masked_load: {
1830 // Subtlety: If we load from a pointer, the pointer must be valid
1831 // regardless of whether the element is demanded. Doing otherwise risks
1832 // segfaults which didn't exist in the original program.
1833 APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1834 DemandedPassThrough(DemandedElts);
1835 if (auto *CMask = dyn_cast<Constant>(II->getOperand(2))) {
1836 for (unsigned i = 0; i < VWidth; i++) {
1837 if (Constant *CElt = CMask->getAggregateElement(i)) {
1838 if (CElt->isNullValue())
1839 DemandedPtrs.clearBit(i);
1840 else if (CElt->isAllOnesValue())
1841 DemandedPassThrough.clearBit(i);
1842 }
1843 }
1844 }
1845
1846 if (II->getIntrinsicID() == Intrinsic::masked_gather)
1847 simplifyAndSetOp(II, 0, DemandedPtrs, PoisonElts2);
1848 simplifyAndSetOp(II, 3, DemandedPassThrough, PoisonElts3);
1849
1850 // Output elements are undefined if the element from both sources are.
1851 // TODO: can strengthen via mask as well.
1852 PoisonElts = PoisonElts2 & PoisonElts3;
1853 break;
1854 }
1855 default: {
1856 // Handle target specific intrinsics
1857 std::optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1858 *II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
1859 simplifyAndSetOp);
1860 if (V)
1861 return *V;
1862 break;
1863 }
1864 } // switch on IntrinsicID
1865 break;
1866 } // case Call
1867 } // switch on Opcode
1868
1869 // TODO: We bail completely on integer div/rem and shifts because they have
1870 // UB/poison potential, but that should be refined.
1871 BinaryOperator *BO;
1872 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1873 Value *X = BO->getOperand(0);
1874 Value *Y = BO->getOperand(1);
1875
1876 // Look for an equivalent binop except that one operand has been shuffled.
1877 // If the demand for this binop only includes elements that are the same as
1878 // the other binop, then we may be able to replace this binop with a use of
1879 // the earlier one.
1880 //
1881 // Example:
1882 // %other_bo = bo (shuf X, {0}), Y
1883 // %this_extracted_bo = extelt (bo X, Y), 0
1884 // -->
1885 // %other_bo = bo (shuf X, {0}), Y
1886 // %this_extracted_bo = extelt %other_bo, 0
1887 //
1888 // TODO: Handle demand of an arbitrary single element or more than one
1889 // element instead of just element 0.
1890 // TODO: Unlike general demanded elements transforms, this should be safe
1891 // for any (div/rem/shift) opcode too.
1892 if (DemandedElts == 1 && !X->hasOneUse() && !Y->hasOneUse() &&
1893 BO->hasOneUse() ) {
1894
1895 auto findShufBO = [&](bool MatchShufAsOp0) -> User * {
1896 // Try to use shuffle-of-operand in place of an operand:
1897 // bo X, Y --> bo (shuf X), Y
1898 // bo X, Y --> bo X, (shuf Y)
1899
1900 Value *OtherOp = MatchShufAsOp0 ? Y : X;
1901 if (!OtherOp->hasUseList())
1902 return nullptr;
1903
1904 BinaryOperator::BinaryOps Opcode = BO->getOpcode();
1905 Value *ShufOp = MatchShufAsOp0 ? X : Y;
1906
1907 for (User *U : OtherOp->users()) {
1908 ArrayRef<int> Mask;
1909 auto Shuf = m_Shuffle(m_Specific(ShufOp), m_Value(), m_Mask(Mask));
1910 if (BO->isCommutative()
1911 ? match(U, m_c_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
1912 : MatchShufAsOp0
1913 ? match(U, m_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
1914 : match(U, m_BinOp(Opcode, m_Specific(OtherOp), Shuf)))
1915 if (match(Mask, m_ZeroMask()) && Mask[0] != PoisonMaskElem)
1916 if (DT.dominates(U, I))
1917 return U;
1918 }
1919 return nullptr;
1920 };
1921
1922 if (User *ShufBO = findShufBO(/* MatchShufAsOp0 */ true))
1923 return ShufBO;
1924 if (User *ShufBO = findShufBO(/* MatchShufAsOp0 */ false))
1925 return ShufBO;
1926 }
1927
1928 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1929 simplifyAndSetOp(I, 1, DemandedElts, PoisonElts2);
1930
1931 // Output elements are undefined if both are undefined. Consider things
1932 // like undef & 0. The result is known zero, not undef.
1933 PoisonElts &= PoisonElts2;
1934 }
1935
1936 // If we've proven all of the lanes poison, return a poison value.
1937 // TODO: Intersect w/demanded lanes
1938 if (PoisonElts.isAllOnes())
1939 return PoisonValue::get(I->getType());
1940
1941 return MadeChange ? I : nullptr;
1942}
1943
1944/// For floating-point classes that resolve to a single bit pattern, return that
1945/// value.
1947 if (Mask == fcNone)
1948 return PoisonValue::get(Ty);
1949
1950 if (Mask == fcPosZero)
1951 return Constant::getNullValue(Ty);
1952
1953 // TODO: Support aggregate types that are allowed by FPMathOperator.
1954 if (Ty->isAggregateType())
1955 return nullptr;
1956
1957 switch (Mask) {
1958 case fcNegZero:
1959 return ConstantFP::getZero(Ty, true);
1960 case fcPosInf:
1961 return ConstantFP::getInfinity(Ty);
1962 case fcNegInf:
1963 return ConstantFP::getInfinity(Ty, true);
1964 default:
1965 return nullptr;
1966 }
1967}
1968
1970 FPClassTest DemandedMask,
1971 KnownFPClass &Known,
1972 Instruction *CxtI,
1973 unsigned Depth) {
1974 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1975 Type *VTy = V->getType();
1976
1977 assert(Known == KnownFPClass() && "expected uninitialized state");
1978
1979 if (DemandedMask == fcNone)
1980 return isa<UndefValue>(V) ? nullptr : PoisonValue::get(VTy);
1981
1983 return nullptr;
1984
1986 if (!I) {
1987 // Handle constants and arguments
1988 Known = computeKnownFPClass(V, fcAllFlags, CxtI, Depth + 1);
1989 Value *FoldedToConst =
1990 getFPClassConstant(VTy, DemandedMask & Known.KnownFPClasses);
1991 return FoldedToConst == V ? nullptr : FoldedToConst;
1992 }
1993
1994 if (!I->hasOneUse())
1995 return nullptr;
1996
1997 if (auto *FPOp = dyn_cast<FPMathOperator>(I)) {
1998 if (FPOp->hasNoNaNs())
1999 DemandedMask &= ~fcNan;
2000 if (FPOp->hasNoInfs())
2001 DemandedMask &= ~fcInf;
2002 }
2003 switch (I->getOpcode()) {
2004 case Instruction::FNeg: {
2005 if (SimplifyDemandedFPClass(I, 0, llvm::fneg(DemandedMask), Known,
2006 Depth + 1))
2007 return I;
2008 Known.fneg();
2009 break;
2010 }
2011 case Instruction::Call: {
2012 CallInst *CI = cast<CallInst>(I);
2013 switch (CI->getIntrinsicID()) {
2014 case Intrinsic::fabs:
2015 if (SimplifyDemandedFPClass(I, 0, llvm::inverse_fabs(DemandedMask), Known,
2016 Depth + 1))
2017 return I;
2018 Known.fabs();
2019 break;
2020 case Intrinsic::arithmetic_fence:
2021 if (SimplifyDemandedFPClass(I, 0, DemandedMask, Known, Depth + 1))
2022 return I;
2023 break;
2024 case Intrinsic::copysign: {
2025 // Flip on more potentially demanded classes
2026 const FPClassTest DemandedMaskAnySign = llvm::unknown_sign(DemandedMask);
2027 if (SimplifyDemandedFPClass(I, 0, DemandedMaskAnySign, Known, Depth + 1))
2028 return I;
2029
2030 if ((DemandedMask & fcNegative) == DemandedMask) {
2031 // Roundabout way of replacing with fneg(fabs)
2032 I->setOperand(1, ConstantFP::get(VTy, -1.0));
2033 return I;
2034 }
2035
2036 if ((DemandedMask & fcPositive) == DemandedMask) {
2037 // Roundabout way of replacing with fabs
2038 I->setOperand(1, ConstantFP::getZero(VTy));
2039 return I;
2040 }
2041
2042 KnownFPClass KnownSign =
2043 computeKnownFPClass(I->getOperand(1), fcAllFlags, CxtI, Depth + 1);
2044 Known.copysign(KnownSign);
2045 break;
2046 }
2047 default:
2048 Known = computeKnownFPClass(I, ~DemandedMask, CxtI, Depth + 1);
2049 break;
2050 }
2051
2052 break;
2053 }
2054 case Instruction::Select: {
2055 KnownFPClass KnownLHS, KnownRHS;
2056 if (SimplifyDemandedFPClass(I, 2, DemandedMask, KnownRHS, Depth + 1) ||
2057 SimplifyDemandedFPClass(I, 1, DemandedMask, KnownLHS, Depth + 1))
2058 return I;
2059
2060 if (KnownLHS.isKnownNever(DemandedMask))
2061 return I->getOperand(2);
2062 if (KnownRHS.isKnownNever(DemandedMask))
2063 return I->getOperand(1);
2064
2065 // TODO: Recognize clamping patterns
2066 Known = KnownLHS | KnownRHS;
2067 break;
2068 }
2069 default:
2070 Known = computeKnownFPClass(I, ~DemandedMask, CxtI, Depth + 1);
2071 break;
2072 }
2073
2074 return getFPClassConstant(VTy, DemandedMask & Known.KnownFPClasses);
2075}
2076
2078 FPClassTest DemandedMask,
2079 KnownFPClass &Known,
2080 unsigned Depth) {
2081 Use &U = I->getOperandUse(OpNo);
2082 Value *NewVal =
2083 SimplifyDemandedUseFPClass(U.get(), DemandedMask, Known, I, Depth);
2084 if (!NewVal)
2085 return false;
2086 if (Instruction *OpInst = dyn_cast<Instruction>(U))
2087 salvageDebugInfo(*OpInst);
2088
2089 replaceUse(U, NewVal);
2090 return true;
2091}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Hexagon Common GEP
This file provides internal interfaces used to implement the InstCombine.
static cl::opt< unsigned > SimplifyDemandedVectorEltsDepthLimit("instcombine-simplify-vector-elts-depth", cl::desc("Depth limit when simplifying vector instructions and their operands"), cl::Hidden, cl::init(10))
static Constant * getFPClassConstant(Type *Ty, FPClassTest Mask)
For floating-point classes that resolve to a single bit pattern, return that value.
static cl::opt< bool > VerifyKnownBits("instcombine-verify-known-bits", cl::desc("Verify that computeKnownBits() and " "SimplifyDemandedBits() are consistent"), cl::Hidden, cl::init(false))
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
This file provides the interface for the instcombine pass implementation.
#define I(x, y, z)
Definition MD5.cpp:58
uint64_t IntrinsicInst * II
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:234
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1406
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:229
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1540
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1391
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1670
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1033
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1512
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:936
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1330
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:371
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:380
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1666
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1340
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1488
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1111
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1396
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1639
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1598
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1435
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:475
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:827
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:873
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1257
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:440
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:306
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:296
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1388
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:389
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:851
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1221
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
BinaryOps getOpcode() const
Definition InstrTypes.h:374
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:448
static LLVM_ABI Constant * getInfinity(Type *Ty, bool Negative=false)
static LLVM_ABI Constant * getZero(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:163
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:154
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:90
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
KnownFPClass computeKnownFPClass(Value *Val, FastMathFlags FMF, FPClassTest Interested=fcAllFlags, const Instruction *CtxI=nullptr, unsigned Depth=0) const
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
std::optional< std::pair< Intrinsic::ID, SmallVector< Value *, 3 > > > convertOrOfShiftsToFunnelShift(Instruction &Or)
Value * simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1, Instruction *Shl, const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known)
Helper routine of SimplifyDemandedUseBits.
Value * SimplifyDemandedUseBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Attempts to replace I with a simpler value based on the demanded bits.
bool SimplifyDemandedFPClass(Instruction *I, unsigned Op, FPClassTest DemandedMask, KnownFPClass &Known, unsigned Depth=0)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Value * SimplifyMultipleUseDemandedBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Helper routine of SimplifyDemandedUseBits.
Value * SimplifyDemandedUseFPClass(Value *V, FPClassTest DemandedMask, KnownFPClass &Known, Instruction *CxtI, unsigned Depth=0)
Attempts to replace V with a simpler value based on the demanded floating-point classes.
SimplifyQuery SQ
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
const DataLayout & DL
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
std::optional< Value * > targetSimplifyDemandedVectorEltsIntrinsic(IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
std::optional< Value * > targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)
BuilderTy & Builder
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
bool isShift() const
bool isIntDivRem() const
A wrapper class for inspecting calls to intrinsic functions.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:111
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:105
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
const Value * getCondition() const
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:298
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:231
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:232
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
iterator_range< user_iterator > users()
Definition Value.h:426
bool hasUseList() const
Check if this Value has a use-list.
Definition Value.h:344
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
Base class of all SIMD vector types.
This class represents zero extension of integer types.
self_iterator getIterator()
Definition ilist_node.h:134
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
class_match< PoisonValue > m_Poison()
Match an arbitrary poison constant.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1727
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:260
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1723
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:551
gep_type_iterator gep_type_end(const User *GEP)
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI FPClassTest fneg(FPClassTest Mask)
Return the test mask which returns true if the value's sign bit is flipped.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI FPClassTest inverse_fabs(FPClassTest Mask)
Return the test mask which returns true after fabs is applied to the value.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
LLVM_ABI FPClassTest unknown_sign(FPClassTest Mask)
Return the test mask which returns true if the value could have the same set of classes,...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
gep_type_iterator gep_type_begin(const User *GEP)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:208
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:294
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:179
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:101
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:117
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
void resetAll()
Resets the known state of all bits.
Definition KnownBits.h:74
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:314
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:304
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:173
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:340
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:189
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).
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:98
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:346
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).
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
void copysign(const KnownFPClass &Sign)
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
Matching combinators.
const Instruction * CxtI