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"
15 #include "llvm/Analysis/TargetTransformInfo.h"
16 #include "llvm/Analysis/ValueTracking.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Support/KnownBits.h"
20 #include "llvm/Transforms/InstCombine/InstCombiner.h"
21 
22 using namespace llvm;
23 using namespace llvm::PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 /// Check to see if the specified operand of the specified instruction is a
28 /// constant integer. If so, check to see if there are any bits set in the
29 /// constant that are not demanded. If so, shrink the constant and return true.
30 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
31                                    const APInt &Demanded) {
32   assert(I && "No instruction?");
33   assert(OpNo < I->getNumOperands() && "Operand index too large");
34 
35   // The operand must be a constant integer or splat integer.
36   Value *Op = I->getOperand(OpNo);
37   const APInt *C;
38   if (!match(Op, m_APInt(C)))
39     return false;
40 
41   // If there are no bits set that aren't demanded, nothing to do.
42   if (C->isSubsetOf(Demanded))
43     return false;
44 
45   // This instruction is producing bits that are not demanded. Shrink the RHS.
46   I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
47 
48   return true;
49 }
50 
51 
52 
53 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
54 /// the instruction has any properties that allow us to simplify its operands.
55 bool InstCombinerImpl::SimplifyDemandedInstructionBits(Instruction &Inst) {
56   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
57   KnownBits Known(BitWidth);
58   APInt DemandedMask(APInt::getAllOnes(BitWidth));
59 
60   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
61                                      0, &Inst);
62   if (!V) return false;
63   if (V == &Inst) return true;
64   replaceInstUsesWith(Inst, V);
65   return true;
66 }
67 
68 /// This form of SimplifyDemandedBits simplifies the specified instruction
69 /// operand if possible, updating it in place. It returns true if it made any
70 /// change and false otherwise.
71 bool InstCombinerImpl::SimplifyDemandedBits(Instruction *I, unsigned OpNo,
72                                             const APInt &DemandedMask,
73                                             KnownBits &Known, unsigned Depth) {
74   Use &U = I->getOperandUse(OpNo);
75   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known,
76                                           Depth, I);
77   if (!NewVal) return false;
78   if (Instruction* OpInst = dyn_cast<Instruction>(U))
79     salvageDebugInfo(*OpInst);
80 
81   replaceUse(U, NewVal);
82   return true;
83 }
84 
85 /// This function attempts to replace V with a simpler value based on the
86 /// demanded bits. When this function is called, it is known that only the bits
87 /// set in DemandedMask of the result of V are ever used downstream.
88 /// Consequently, depending on the mask and V, it may be possible to replace V
89 /// with a constant or one of its operands. In such cases, this function does
90 /// the replacement and returns true. In all other cases, it returns false after
91 /// analyzing the expression and setting KnownOne and known to be one in the
92 /// expression. Known.Zero contains all the bits that are known to be zero in
93 /// the expression. These are provided to potentially allow the caller (which
94 /// might recursively be SimplifyDemandedBits itself) to simplify the
95 /// expression.
96 /// Known.One and Known.Zero always follow the invariant that:
97 ///   Known.One & Known.Zero == 0.
98 /// That is, a bit can't be both 1 and 0. Note that the bits in Known.One and
99 /// Known.Zero may only be accurate for those bits set in DemandedMask. Note
100 /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
101 /// be the same.
102 ///
103 /// This returns null if it did not change anything and it permits no
104 /// simplification.  This returns V itself if it did some simplification of V's
105 /// operands based on the information about what bits are demanded. This returns
106 /// some other non-null value if it found out that V is equal to another value
107 /// in the context where the specified bits are demanded, but not for all users.
108 Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
109                                                  KnownBits &Known,
110                                                  unsigned Depth,
111                                                  Instruction *CxtI) {
112   assert(V != nullptr && "Null pointer of Value???");
113   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
114   uint32_t BitWidth = DemandedMask.getBitWidth();
115   Type *VTy = V->getType();
116   assert(
117       (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
118       Known.getBitWidth() == BitWidth &&
119       "Value *V, DemandedMask and Known must have same BitWidth");
120 
121   if (isa<Constant>(V)) {
122     computeKnownBits(V, Known, Depth, CxtI);
123     return nullptr;
124   }
125 
126   Known.resetAll();
127   if (DemandedMask.isZero()) // Not demanding any bits from V.
128     return UndefValue::get(VTy);
129 
130   if (Depth == MaxAnalysisRecursionDepth)
131     return nullptr;
132 
133   if (isa<ScalableVectorType>(VTy))
134     return nullptr;
135 
136   Instruction *I = dyn_cast<Instruction>(V);
137   if (!I) {
138     computeKnownBits(V, Known, Depth, CxtI);
139     return nullptr;        // Only analyze instructions.
140   }
141 
142   // If there are multiple uses of this value and we aren't at the root, then
143   // we can't do any simplifications of the operands, because DemandedMask
144   // only reflects the bits demanded by *one* of the users.
145   if (Depth != 0 && !I->hasOneUse())
146     return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI);
147 
148   KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
149 
150   // If this is the root being simplified, allow it to have multiple uses,
151   // just set the DemandedMask to all bits so that we can try to simplify the
152   // operands.  This allows visitTruncInst (for example) to simplify the
153   // operand of a trunc without duplicating all the logic below.
154   if (Depth == 0 && !V->hasOneUse())
155     DemandedMask.setAllBits();
156 
157   // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
158   // about the high bits of the operands.
159   auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
160     unsigned NLZ = DemandedMask.countLeadingZeros();
161     // Right fill the mask of bits for the operands to demand the most
162     // significant bit and all those below it.
163     DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
164     if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
165         SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) ||
166         ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
167         SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) {
168       if (NLZ > 0) {
169         // Disable the nsw and nuw flags here: We can no longer guarantee that
170         // we won't wrap after simplification. Removing the nsw/nuw flags is
171         // legal here because the top bit is not demanded.
172         I->setHasNoSignedWrap(false);
173         I->setHasNoUnsignedWrap(false);
174       }
175       return true;
176     }
177     return false;
178   };
179 
180   switch (I->getOpcode()) {
181   default:
182     computeKnownBits(I, Known, Depth, CxtI);
183     break;
184   case Instruction::And: {
185     // If either the LHS or the RHS are Zero, the result is zero.
186     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
187         SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
188                              Depth + 1))
189       return I;
190     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
191     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
192 
193     Known = LHSKnown & RHSKnown;
194 
195     // If the client is only demanding bits that we know, return the known
196     // constant.
197     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
198       return Constant::getIntegerValue(VTy, Known.One);
199 
200     // If all of the demanded bits are known 1 on one side, return the other.
201     // These bits cannot contribute to the result of the 'and'.
202     if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
203       return I->getOperand(0);
204     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
205       return I->getOperand(1);
206 
207     // If the RHS is a constant, see if we can simplify it.
208     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
209       return I;
210 
211     break;
212   }
213   case Instruction::Or: {
214     // If either the LHS or the RHS are One, the result is One.
215     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
216         SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
217                              Depth + 1))
218       return I;
219     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
220     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
221 
222     Known = LHSKnown | RHSKnown;
223 
224     // If the client is only demanding bits that we know, return the known
225     // constant.
226     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
227       return Constant::getIntegerValue(VTy, Known.One);
228 
229     // If all of the demanded bits are known zero on one side, return the other.
230     // These bits cannot contribute to the result of the 'or'.
231     if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
232       return I->getOperand(0);
233     if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
234       return I->getOperand(1);
235 
236     // If the RHS is a constant, see if we can simplify it.
237     if (ShrinkDemandedConstant(I, 1, DemandedMask))
238       return I;
239 
240     break;
241   }
242   case Instruction::Xor: {
243     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
244         SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1))
245       return I;
246     Value *LHS, *RHS;
247     if (DemandedMask == 1 &&
248         match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) &&
249         match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) {
250       // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
251       IRBuilderBase::InsertPointGuard Guard(Builder);
252       Builder.SetInsertPoint(I);
253       auto *Xor = Builder.CreateXor(LHS, RHS);
254       return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
255     }
256 
257     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
258     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
259 
260     Known = LHSKnown ^ RHSKnown;
261 
262     // If the client is only demanding bits that we know, return the known
263     // constant.
264     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
265       return Constant::getIntegerValue(VTy, Known.One);
266 
267     // If all of the demanded bits are known zero on one side, return the other.
268     // These bits cannot contribute to the result of the 'xor'.
269     if (DemandedMask.isSubsetOf(RHSKnown.Zero))
270       return I->getOperand(0);
271     if (DemandedMask.isSubsetOf(LHSKnown.Zero))
272       return I->getOperand(1);
273 
274     // If all of the demanded bits are known to be zero on one side or the
275     // other, turn this into an *inclusive* or.
276     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
277     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
278       Instruction *Or =
279         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
280                                  I->getName());
281       return InsertNewInstWith(Or, *I);
282     }
283 
284     // If all of the demanded bits on one side are known, and all of the set
285     // bits on that side are also known to be set on the other side, turn this
286     // into an AND, as we know the bits will be cleared.
287     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
288     if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
289         RHSKnown.One.isSubsetOf(LHSKnown.One)) {
290       Constant *AndC = Constant::getIntegerValue(VTy,
291                                                  ~RHSKnown.One & DemandedMask);
292       Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
293       return InsertNewInstWith(And, *I);
294     }
295 
296     // If the RHS is a constant, see if we can change it. Don't alter a -1
297     // constant because that's a canonical 'not' op, and that is better for
298     // combining, SCEV, and codegen.
299     const APInt *C;
300     if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
301       if ((*C | ~DemandedMask).isAllOnes()) {
302         // Force bits to 1 to create a 'not' op.
303         I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
304         return I;
305       }
306       // If we can't turn this into a 'not', try to shrink the constant.
307       if (ShrinkDemandedConstant(I, 1, DemandedMask))
308         return I;
309     }
310 
311     // If our LHS is an 'and' and if it has one use, and if any of the bits we
312     // are flipping are known to be set, then the xor is just resetting those
313     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
314     // simplifying both of them.
315     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
316       ConstantInt *AndRHS, *XorRHS;
317       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
318           match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
319           match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
320           (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
321         APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
322 
323         Constant *AndC =
324             ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
325         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
326         InsertNewInstWith(NewAnd, *I);
327 
328         Constant *XorC =
329             ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
330         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
331         return InsertNewInstWith(NewXor, *I);
332       }
333     }
334     break;
335   }
336   case Instruction::Select: {
337     Value *LHS, *RHS;
338     SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
339     if (SPF == SPF_UMAX) {
340       // UMax(A, C) == A if ...
341       // The lowest non-zero bit of DemandMask is higher than the highest
342       // non-zero bit of C.
343       const APInt *C;
344       unsigned CTZ = DemandedMask.countTrailingZeros();
345       if (match(RHS, m_APInt(C)) && CTZ >= C->getActiveBits())
346         return LHS;
347     } else if (SPF == SPF_UMIN) {
348       // UMin(A, C) == A if ...
349       // The lowest non-zero bit of DemandMask is higher than the highest
350       // non-one bit of C.
351       // This comes from using DeMorgans on the above umax example.
352       const APInt *C;
353       unsigned CTZ = DemandedMask.countTrailingZeros();
354       if (match(RHS, m_APInt(C)) &&
355           CTZ >= C->getBitWidth() - C->countLeadingOnes())
356         return LHS;
357     }
358 
359     // If this is a select as part of any other min/max pattern, don't simplify
360     // any further in case we break the structure.
361     if (SPF != SPF_UNKNOWN)
362       return nullptr;
363 
364     if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) ||
365         SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1))
366       return I;
367     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
368     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
369 
370     // If the operands are constants, see if we can simplify them.
371     // This is similar to ShrinkDemandedConstant, but for a select we want to
372     // try to keep the selected constants the same as icmp value constants, if
373     // we can. This helps not break apart (or helps put back together)
374     // canonical patterns like min and max.
375     auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
376                                          const APInt &DemandedMask) {
377       const APInt *SelC;
378       if (!match(I->getOperand(OpNo), m_APInt(SelC)))
379         return false;
380 
381       // Get the constant out of the ICmp, if there is one.
382       // Only try this when exactly 1 operand is a constant (if both operands
383       // are constant, the icmp should eventually simplify). Otherwise, we may
384       // invert the transform that reduces set bits and infinite-loop.
385       Value *X;
386       const APInt *CmpC;
387       ICmpInst::Predicate Pred;
388       if (!match(I->getOperand(0), m_ICmp(Pred, m_Value(X), m_APInt(CmpC))) ||
389           isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
390         return ShrinkDemandedConstant(I, OpNo, DemandedMask);
391 
392       // If the constant is already the same as the ICmp, leave it as-is.
393       if (*CmpC == *SelC)
394         return false;
395       // If the constants are not already the same, but can be with the demand
396       // mask, use the constant value from the ICmp.
397       if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
398         I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
399         return true;
400       }
401       return ShrinkDemandedConstant(I, OpNo, DemandedMask);
402     };
403     if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
404         CanonicalizeSelectConstant(I, 2, DemandedMask))
405       return I;
406 
407     // Only known if known in both the LHS and RHS.
408     Known = KnownBits::commonBits(LHSKnown, RHSKnown);
409     break;
410   }
411   case Instruction::Trunc: {
412     // If we do not demand the high bits of a right-shifted and truncated value,
413     // then we may be able to truncate it before the shift.
414     Value *X;
415     const APInt *C;
416     if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
417       // The shift amount must be valid (not poison) in the narrow type, and
418       // it must not be greater than the high bits demanded of the result.
419       if (C->ult(I->getType()->getScalarSizeInBits()) &&
420           C->ule(DemandedMask.countLeadingZeros())) {
421         // trunc (lshr X, C) --> lshr (trunc X), C
422         IRBuilderBase::InsertPointGuard Guard(Builder);
423         Builder.SetInsertPoint(I);
424         Value *Trunc = Builder.CreateTrunc(X, I->getType());
425         return Builder.CreateLShr(Trunc, C->getZExtValue());
426       }
427     }
428   }
429     LLVM_FALLTHROUGH;
430   case Instruction::ZExt: {
431     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
432 
433     APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
434     KnownBits InputKnown(SrcBitWidth);
435     if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1))
436       return I;
437     assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
438     Known = InputKnown.zextOrTrunc(BitWidth);
439     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
440     break;
441   }
442   case Instruction::BitCast:
443     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
444       return nullptr;  // vector->int or fp->int?
445 
446     if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
447       if (VectorType *SrcVTy =
448             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
449         if (cast<FixedVectorType>(DstVTy)->getNumElements() !=
450             cast<FixedVectorType>(SrcVTy)->getNumElements())
451           // Don't touch a bitcast between vectors of different element counts.
452           return nullptr;
453       } else
454         // Don't touch a scalar-to-vector bitcast.
455         return nullptr;
456     } else if (I->getOperand(0)->getType()->isVectorTy())
457       // Don't touch a vector-to-scalar bitcast.
458       return nullptr;
459 
460     if (SimplifyDemandedBits(I, 0, DemandedMask, Known, Depth + 1))
461       return I;
462     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
463     break;
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, 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, I->getName());
485       return InsertNewInstWith(NewCast, *I);
486      }
487 
488     // If the sign bit of the input is known set or clear, then we know the
489     // top bits of the result.
490     Known = InputKnown.sext(BitWidth);
491     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
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;
499       if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))),
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         //      ----------
508         IRBuilderBase::InsertPointGuard Guard(Builder);
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       // TODO: Relax the one-use checks because we are removing an instruction?
516       if (match(I, m_Add(m_OneUse(m_SExt(m_Value(X))),
517                          m_OneUse(m_SExt(m_Value(Y))))) &&
518           X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
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         //      -----------
525         IRBuilderBase::InsertPointGuard Guard(Builder);
526         Builder.SetInsertPoint(I);
527         Value *Or = Builder.CreateOr(X, Y);
528         return Builder.CreateSExt(Or, VTy);
529       }
530     }
531     LLVM_FALLTHROUGH;
532   case Instruction::Sub: {
533     APInt DemandedFromOps;
534     if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
535       return I;
536 
537     // If we are known to be adding/subtracting zeros to every bit below
538     // the highest demanded bit, we just return the other side.
539     if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
540       return I->getOperand(0);
541     // We can't do this with the LHS for subtraction, unless we are only
542     // demanding the LSB.
543     if ((I->getOpcode() == Instruction::Add || DemandedFromOps.isOne()) &&
544         DemandedFromOps.isSubsetOf(LHSKnown.Zero))
545       return I->getOperand(1);
546 
547     // Otherwise just compute the known bits of the result.
548     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
549     Known = KnownBits::computeForAddSub(I->getOpcode() == Instruction::Add,
550                                         NSW, LHSKnown, RHSKnown);
551     break;
552   }
553   case Instruction::Mul: {
554     APInt DemandedFromOps;
555     if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
556       return I;
557 
558     if (DemandedMask.isPowerOf2()) {
559       // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
560       // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
561       // odd (has LSB set), then the left-shifted low bit of X is the answer.
562       unsigned CTZ = DemandedMask.countTrailingZeros();
563       const APInt *C;
564       if (match(I->getOperand(1), m_APInt(C)) &&
565           C->countTrailingZeros() == CTZ) {
566         Constant *ShiftC = ConstantInt::get(I->getType(), CTZ);
567         Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
568         return InsertNewInstWith(Shl, *I);
569       }
570     }
571     // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
572     // X * X is odd iff X is odd.
573     // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
574     if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
575       Constant *One = ConstantInt::get(VTy, 1);
576       Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
577       return InsertNewInstWith(And1, *I);
578     }
579 
580     computeKnownBits(I, Known, Depth, CxtI);
581     break;
582   }
583   case Instruction::Shl: {
584     const APInt *SA;
585     if (match(I->getOperand(1), m_APInt(SA))) {
586       const APInt *ShrAmt;
587       if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
588         if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
589           if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
590                                                     DemandedMask, Known))
591             return R;
592 
593       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
594       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
595 
596       // If the shift is NUW/NSW, then it does demand the high bits.
597       ShlOperator *IOp = cast<ShlOperator>(I);
598       if (IOp->hasNoSignedWrap())
599         DemandedMaskIn.setHighBits(ShiftAmt+1);
600       else if (IOp->hasNoUnsignedWrap())
601         DemandedMaskIn.setHighBits(ShiftAmt);
602 
603       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
604         return I;
605       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
606 
607       bool SignBitZero = Known.Zero.isSignBitSet();
608       bool SignBitOne = Known.One.isSignBitSet();
609       Known.Zero <<= ShiftAmt;
610       Known.One  <<= ShiftAmt;
611       // low bits known zero.
612       if (ShiftAmt)
613         Known.Zero.setLowBits(ShiftAmt);
614 
615       // If this shift has "nsw" keyword, then the result is either a poison
616       // value or has the same sign bit as the first operand.
617       if (IOp->hasNoSignedWrap()) {
618         if (SignBitZero)
619           Known.Zero.setSignBit();
620         else if (SignBitOne)
621           Known.One.setSignBit();
622         if (Known.hasConflict())
623           return UndefValue::get(I->getType());
624       }
625     } else {
626       // This is a variable shift, so we can't shift the demand mask by a known
627       // amount. But if we are not demanding high bits, then we are not
628       // demanding those bits from the pre-shifted operand either.
629       if (unsigned CTLZ = DemandedMask.countLeadingZeros()) {
630         APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
631         if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Depth + 1)) {
632           // We can't guarantee that nsw/nuw hold after simplifying the operand.
633           I->dropPoisonGeneratingFlags();
634           return I;
635         }
636       }
637       computeKnownBits(I, Known, Depth, CxtI);
638     }
639     break;
640   }
641   case Instruction::LShr: {
642     const APInt *SA;
643     if (match(I->getOperand(1), m_APInt(SA))) {
644       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
645 
646       // Unsigned shift right.
647       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
648 
649       // If the shift is exact, then it does demand the low bits (and knows that
650       // they are zero).
651       if (cast<LShrOperator>(I)->isExact())
652         DemandedMaskIn.setLowBits(ShiftAmt);
653 
654       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
655         return I;
656       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
657       Known.Zero.lshrInPlace(ShiftAmt);
658       Known.One.lshrInPlace(ShiftAmt);
659       if (ShiftAmt)
660         Known.Zero.setHighBits(ShiftAmt);  // high bits known zero.
661     } else {
662       computeKnownBits(I, Known, Depth, CxtI);
663     }
664     break;
665   }
666   case Instruction::AShr: {
667     // If this is an arithmetic shift right and only the low-bit is set, we can
668     // always convert this into a logical shr, even if the shift amount is
669     // variable.  The low bit of the shift cannot be an input sign bit unless
670     // the shift amount is >= the size of the datatype, which is undefined.
671     if (DemandedMask.isOne()) {
672       // Perform the logical shift right.
673       Instruction *NewVal = BinaryOperator::CreateLShr(
674                         I->getOperand(0), I->getOperand(1), I->getName());
675       return InsertNewInstWith(NewVal, *I);
676     }
677 
678     // If the sign bit is the only bit demanded by this ashr, then there is no
679     // need to do it, the shift doesn't change the high bit.
680     if (DemandedMask.isSignMask())
681       return I->getOperand(0);
682 
683     const APInt *SA;
684     if (match(I->getOperand(1), m_APInt(SA))) {
685       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
686 
687       // Signed shift right.
688       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
689       // If any of the high bits are demanded, we should set the sign bit as
690       // demanded.
691       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
692         DemandedMaskIn.setSignBit();
693 
694       // If the shift is exact, then it does demand the low bits (and knows that
695       // they are zero).
696       if (cast<AShrOperator>(I)->isExact())
697         DemandedMaskIn.setLowBits(ShiftAmt);
698 
699       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
700         return I;
701 
702       unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
703 
704       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
705       // Compute the new bits that are at the top now plus sign bits.
706       APInt HighBits(APInt::getHighBitsSet(
707           BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
708       Known.Zero.lshrInPlace(ShiftAmt);
709       Known.One.lshrInPlace(ShiftAmt);
710 
711       // If the input sign bit is known to be zero, or if none of the top bits
712       // are demanded, turn this into an unsigned shift right.
713       assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
714       if (Known.Zero[BitWidth-ShiftAmt-1] ||
715           !DemandedMask.intersects(HighBits)) {
716         BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
717                                                           I->getOperand(1));
718         LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
719         return InsertNewInstWith(LShr, *I);
720       } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
721         Known.One |= HighBits;
722       }
723     } else {
724       computeKnownBits(I, Known, Depth, CxtI);
725     }
726     break;
727   }
728   case Instruction::UDiv: {
729     // UDiv doesn't demand low bits that are zero in the divisor.
730     const APInt *SA;
731     if (match(I->getOperand(1), m_APInt(SA))) {
732       // If the shift is exact, then it does demand the low bits.
733       if (cast<UDivOperator>(I)->isExact())
734         break;
735 
736       // FIXME: Take the demanded mask of the result into account.
737       unsigned RHSTrailingZeros = SA->countTrailingZeros();
738       APInt DemandedMaskIn =
739           APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
740       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1))
741         return I;
742 
743       // Propagate zero bits from the input.
744       Known.Zero.setHighBits(std::min(
745           BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros));
746     } else {
747       computeKnownBits(I, Known, Depth, CxtI);
748     }
749     break;
750   }
751   case Instruction::SRem: {
752     ConstantInt *Rem;
753     if (match(I->getOperand(1), m_ConstantInt(Rem))) {
754       // X % -1 demands all the bits because we don't want to introduce
755       // INT_MIN % -1 (== undef) by accident.
756       if (Rem->isMinusOne())
757         break;
758       APInt RA = Rem->getValue().abs();
759       if (RA.isPowerOf2()) {
760         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
761           return I->getOperand(0);
762 
763         APInt LowBits = RA - 1;
764         APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
765         if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1))
766           return I;
767 
768         // The low bits of LHS are unchanged by the srem.
769         Known.Zero = LHSKnown.Zero & LowBits;
770         Known.One = LHSKnown.One & LowBits;
771 
772         // If LHS is non-negative or has all low bits zero, then the upper bits
773         // are all zero.
774         if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
775           Known.Zero |= ~LowBits;
776 
777         // If LHS is negative and not all low bits are zero, then the upper bits
778         // are all one.
779         if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
780           Known.One |= ~LowBits;
781 
782         assert(!Known.hasConflict() && "Bits known to be one AND zero?");
783         break;
784       }
785     }
786 
787     // The sign bit is the LHS's sign bit, except when the result of the
788     // remainder is zero.
789     if (DemandedMask.isSignBitSet()) {
790       computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
791       // If it's known zero, our sign bit is also zero.
792       if (LHSKnown.isNonNegative())
793         Known.makeNonNegative();
794     }
795     break;
796   }
797   case Instruction::URem: {
798     KnownBits Known2(BitWidth);
799     APInt AllOnes = APInt::getAllOnes(BitWidth);
800     if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) ||
801         SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1))
802       return I;
803 
804     unsigned Leaders = Known2.countMinLeadingZeros();
805     Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
806     break;
807   }
808   case Instruction::Call: {
809     bool KnownBitsComputed = false;
810     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
811       switch (II->getIntrinsicID()) {
812       case Intrinsic::abs: {
813         if (DemandedMask == 1)
814           return II->getArgOperand(0);
815         break;
816       }
817       case Intrinsic::ctpop: {
818         // Checking if the number of clear bits is odd (parity)? If the type has
819         // an even number of bits, that's the same as checking if the number of
820         // set bits is odd, so we can eliminate the 'not' op.
821         Value *X;
822         if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
823             match(II->getArgOperand(0), m_Not(m_Value(X)))) {
824           Function *Ctpop = Intrinsic::getDeclaration(
825               II->getModule(), Intrinsic::ctpop, II->getType());
826           return InsertNewInstWith(CallInst::Create(Ctpop, {X}), *I);
827         }
828         break;
829       }
830       case Intrinsic::bswap: {
831         // If the only bits demanded come from one byte of the bswap result,
832         // just shift the input byte into position to eliminate the bswap.
833         unsigned NLZ = DemandedMask.countLeadingZeros();
834         unsigned NTZ = DemandedMask.countTrailingZeros();
835 
836         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
837         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
838         // have 14 leading zeros, round to 8.
839         NLZ = alignDown(NLZ, 8);
840         NTZ = alignDown(NTZ, 8);
841         // If we need exactly one byte, we can do this transformation.
842         if (BitWidth - NLZ - NTZ == 8) {
843           // Replace this with either a left or right shift to get the byte into
844           // the right place.
845           Instruction *NewVal;
846           if (NLZ > NTZ)
847             NewVal = BinaryOperator::CreateLShr(
848                 II->getArgOperand(0),
849                 ConstantInt::get(I->getType(), NLZ - NTZ));
850           else
851             NewVal = BinaryOperator::CreateShl(
852                 II->getArgOperand(0),
853                 ConstantInt::get(I->getType(), NTZ - NLZ));
854           NewVal->takeName(I);
855           return InsertNewInstWith(NewVal, *I);
856         }
857         break;
858       }
859       case Intrinsic::fshr:
860       case Intrinsic::fshl: {
861         const APInt *SA;
862         if (!match(I->getOperand(2), m_APInt(SA)))
863           break;
864 
865         // Normalize to funnel shift left. APInt shifts of BitWidth are well-
866         // defined, so no need to special-case zero shifts here.
867         uint64_t ShiftAmt = SA->urem(BitWidth);
868         if (II->getIntrinsicID() == Intrinsic::fshr)
869           ShiftAmt = BitWidth - ShiftAmt;
870 
871         APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
872         APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
873         if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) ||
874             SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
875           return I;
876 
877         Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
878                      RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
879         Known.One = LHSKnown.One.shl(ShiftAmt) |
880                     RHSKnown.One.lshr(BitWidth - ShiftAmt);
881         KnownBitsComputed = true;
882         break;
883       }
884       case Intrinsic::umax: {
885         // UMax(A, C) == A if ...
886         // The lowest non-zero bit of DemandMask is higher than the highest
887         // non-zero bit of C.
888         const APInt *C;
889         unsigned CTZ = DemandedMask.countTrailingZeros();
890         if (match(II->getArgOperand(1), m_APInt(C)) &&
891             CTZ >= C->getActiveBits())
892           return II->getArgOperand(0);
893         break;
894       }
895       case Intrinsic::umin: {
896         // UMin(A, C) == A if ...
897         // The lowest non-zero bit of DemandMask is higher than the highest
898         // non-one bit of C.
899         // This comes from using DeMorgans on the above umax example.
900         const APInt *C;
901         unsigned CTZ = DemandedMask.countTrailingZeros();
902         if (match(II->getArgOperand(1), m_APInt(C)) &&
903             CTZ >= C->getBitWidth() - C->countLeadingOnes())
904           return II->getArgOperand(0);
905         break;
906       }
907       default: {
908         // Handle target specific intrinsics
909         Optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
910             *II, DemandedMask, Known, KnownBitsComputed);
911         if (V.hasValue())
912           return V.getValue();
913         break;
914       }
915       }
916     }
917 
918     if (!KnownBitsComputed)
919       computeKnownBits(V, Known, Depth, CxtI);
920     break;
921   }
922   }
923 
924   // If the client is only demanding bits that we know, return the known
925   // constant.
926   if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
927     return Constant::getIntegerValue(VTy, Known.One);
928   return nullptr;
929 }
930 
931 /// Helper routine of SimplifyDemandedUseBits. It computes Known
932 /// bits. It also tries to handle simplifications that can be done based on
933 /// DemandedMask, but without modifying the Instruction.
934 Value *InstCombinerImpl::SimplifyMultipleUseDemandedBits(
935     Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth,
936     Instruction *CxtI) {
937   unsigned BitWidth = DemandedMask.getBitWidth();
938   Type *ITy = I->getType();
939 
940   KnownBits LHSKnown(BitWidth);
941   KnownBits RHSKnown(BitWidth);
942 
943   // Despite the fact that we can't simplify this instruction in all User's
944   // context, we can at least compute the known bits, and we can
945   // do simplifications that apply to *just* the one user if we know that
946   // this instruction has a simpler value in that context.
947   switch (I->getOpcode()) {
948   case Instruction::And: {
949     // If either the LHS or the RHS are Zero, the result is zero.
950     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
951     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
952                      CxtI);
953 
954     Known = LHSKnown & RHSKnown;
955 
956     // If the client is only demanding bits that we know, return the known
957     // constant.
958     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
959       return Constant::getIntegerValue(ITy, Known.One);
960 
961     // If all of the demanded bits are known 1 on one side, return the other.
962     // These bits cannot contribute to the result of the 'and' in this
963     // context.
964     if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
965       return I->getOperand(0);
966     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
967       return I->getOperand(1);
968 
969     break;
970   }
971   case Instruction::Or: {
972     // We can simplify (X|Y) -> X or Y in the user's context if we know that
973     // only bits from X or Y are demanded.
974 
975     // If either the LHS or the RHS are One, the result is One.
976     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
977     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
978                      CxtI);
979 
980     Known = LHSKnown | RHSKnown;
981 
982     // If the client is only demanding bits that we know, return the known
983     // constant.
984     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
985       return Constant::getIntegerValue(ITy, Known.One);
986 
987     // If all of the demanded bits are known zero on one side, return the
988     // other.  These bits cannot contribute to the result of the 'or' in this
989     // context.
990     if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
991       return I->getOperand(0);
992     if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
993       return I->getOperand(1);
994 
995     break;
996   }
997   case Instruction::Xor: {
998     // We can simplify (X^Y) -> X or Y in the user's context if we know that
999     // only bits from X or Y are demanded.
1000 
1001     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1002     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
1003                      CxtI);
1004 
1005     Known = LHSKnown ^ RHSKnown;
1006 
1007     // If the client is only demanding bits that we know, return the known
1008     // constant.
1009     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1010       return Constant::getIntegerValue(ITy, Known.One);
1011 
1012     // If all of the demanded bits are known zero on one side, return the
1013     // other.
1014     if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1015       return I->getOperand(0);
1016     if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1017       return I->getOperand(1);
1018 
1019     break;
1020   }
1021   case Instruction::AShr: {
1022     // Compute the Known bits to simplify things downstream.
1023     computeKnownBits(I, Known, Depth, CxtI);
1024 
1025     // If this user is only demanding bits that we know, return the known
1026     // constant.
1027     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1028       return Constant::getIntegerValue(ITy, Known.One);
1029 
1030     // If the right shift operand 0 is a result of a left shift by the same
1031     // amount, this is probably a zero/sign extension, which may be unnecessary,
1032     // if we do not demand any of the new sign bits. So, return the original
1033     // operand instead.
1034     const APInt *ShiftRC;
1035     const APInt *ShiftLC;
1036     Value *X;
1037     unsigned BitWidth = DemandedMask.getBitWidth();
1038     if (match(I,
1039               m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1040         ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1041         DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1042             BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1043       return X;
1044     }
1045 
1046     break;
1047   }
1048   default:
1049     // Compute the Known bits to simplify things downstream.
1050     computeKnownBits(I, Known, Depth, CxtI);
1051 
1052     // If this user is only demanding bits that we know, return the known
1053     // constant.
1054     if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1055       return Constant::getIntegerValue(ITy, Known.One);
1056 
1057     break;
1058   }
1059 
1060   return nullptr;
1061 }
1062 
1063 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1064 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1065 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1066 /// of "C2-C1".
1067 ///
1068 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1069 /// ..., bn}, without considering the specific value X is holding.
1070 /// This transformation is legal iff one of following conditions is hold:
1071 ///  1) All the bit in S are 0, in this case E1 == E2.
1072 ///  2) We don't care those bits in S, per the input DemandedMask.
1073 ///  3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1074 ///     rest bits.
1075 ///
1076 /// Currently we only test condition 2).
1077 ///
1078 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1079 /// not successful.
1080 Value *InstCombinerImpl::simplifyShrShlDemandedBits(
1081     Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1082     const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1083   if (!ShlOp1 || !ShrOp1)
1084     return nullptr; // No-op.
1085 
1086   Value *VarX = Shr->getOperand(0);
1087   Type *Ty = VarX->getType();
1088   unsigned BitWidth = Ty->getScalarSizeInBits();
1089   if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1090     return nullptr; // Undef.
1091 
1092   unsigned ShlAmt = ShlOp1.getZExtValue();
1093   unsigned ShrAmt = ShrOp1.getZExtValue();
1094 
1095   Known.One.clearAllBits();
1096   Known.Zero.setLowBits(ShlAmt - 1);
1097   Known.Zero &= DemandedMask;
1098 
1099   APInt BitMask1(APInt::getAllOnes(BitWidth));
1100   APInt BitMask2(APInt::getAllOnes(BitWidth));
1101 
1102   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1103   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1104                       (BitMask1.ashr(ShrAmt) << ShlAmt);
1105 
1106   if (ShrAmt <= ShlAmt) {
1107     BitMask2 <<= (ShlAmt - ShrAmt);
1108   } else {
1109     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1110                         BitMask2.ashr(ShrAmt - ShlAmt);
1111   }
1112 
1113   // Check if condition-2 (see the comment to this function) is satified.
1114   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1115     if (ShrAmt == ShlAmt)
1116       return VarX;
1117 
1118     if (!Shr->hasOneUse())
1119       return nullptr;
1120 
1121     BinaryOperator *New;
1122     if (ShrAmt < ShlAmt) {
1123       Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1124       New = BinaryOperator::CreateShl(VarX, Amt);
1125       BinaryOperator *Orig = cast<BinaryOperator>(Shl);
1126       New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1127       New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1128     } else {
1129       Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1130       New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1131                      BinaryOperator::CreateAShr(VarX, Amt);
1132       if (cast<BinaryOperator>(Shr)->isExact())
1133         New->setIsExact(true);
1134     }
1135 
1136     return InsertNewInstWith(New, *Shl);
1137   }
1138 
1139   return nullptr;
1140 }
1141 
1142 /// The specified value produces a vector with any number of elements.
1143 /// This method analyzes which elements of the operand are undef or poison and
1144 /// returns that information in UndefElts.
1145 ///
1146 /// DemandedElts contains the set of elements that are actually used by the
1147 /// caller, and by default (AllowMultipleUsers equals false) the value is
1148 /// simplified only if it has a single caller. If AllowMultipleUsers is set
1149 /// to true, DemandedElts refers to the union of sets of elements that are
1150 /// used by all callers.
1151 ///
1152 /// If the information about demanded elements can be used to simplify the
1153 /// operation, the operation is simplified, then the resultant value is
1154 /// returned.  This returns null if no change was made.
1155 Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V,
1156                                                     APInt DemandedElts,
1157                                                     APInt &UndefElts,
1158                                                     unsigned Depth,
1159                                                     bool AllowMultipleUsers) {
1160   // Cannot analyze scalable type. The number of vector elements is not a
1161   // compile-time constant.
1162   if (isa<ScalableVectorType>(V->getType()))
1163     return nullptr;
1164 
1165   unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1166   APInt EltMask(APInt::getAllOnes(VWidth));
1167   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1168 
1169   if (match(V, m_Undef())) {
1170     // If the entire vector is undef or poison, just return this info.
1171     UndefElts = EltMask;
1172     return nullptr;
1173   }
1174 
1175   if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1176     UndefElts = EltMask;
1177     return PoisonValue::get(V->getType());
1178   }
1179 
1180   UndefElts = 0;
1181 
1182   if (auto *C = dyn_cast<Constant>(V)) {
1183     // Check if this is identity. If so, return 0 since we are not simplifying
1184     // anything.
1185     if (DemandedElts.isAllOnes())
1186       return nullptr;
1187 
1188     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1189     Constant *Poison = PoisonValue::get(EltTy);
1190     SmallVector<Constant*, 16> Elts;
1191     for (unsigned i = 0; i != VWidth; ++i) {
1192       if (!DemandedElts[i]) {   // If not demanded, set to poison.
1193         Elts.push_back(Poison);
1194         UndefElts.setBit(i);
1195         continue;
1196       }
1197 
1198       Constant *Elt = C->getAggregateElement(i);
1199       if (!Elt) return nullptr;
1200 
1201       Elts.push_back(Elt);
1202       if (isa<UndefValue>(Elt))   // Already undef or poison.
1203         UndefElts.setBit(i);
1204     }
1205 
1206     // If we changed the constant, return it.
1207     Constant *NewCV = ConstantVector::get(Elts);
1208     return NewCV != C ? NewCV : nullptr;
1209   }
1210 
1211   // Limit search depth.
1212   if (Depth == 10)
1213     return nullptr;
1214 
1215   if (!AllowMultipleUsers) {
1216     // If multiple users are using the root value, proceed with
1217     // simplification conservatively assuming that all elements
1218     // are needed.
1219     if (!V->hasOneUse()) {
1220       // Quit if we find multiple users of a non-root value though.
1221       // They'll be handled when it's their turn to be visited by
1222       // the main instcombine process.
1223       if (Depth != 0)
1224         // TODO: Just compute the UndefElts information recursively.
1225         return nullptr;
1226 
1227       // Conservatively assume that all elements are needed.
1228       DemandedElts = EltMask;
1229     }
1230   }
1231 
1232   Instruction *I = dyn_cast<Instruction>(V);
1233   if (!I) return nullptr;        // Only analyze instructions.
1234 
1235   bool MadeChange = false;
1236   auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1237                               APInt Demanded, APInt &Undef) {
1238     auto *II = dyn_cast<IntrinsicInst>(Inst);
1239     Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1240     if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1241       replaceOperand(*Inst, OpNum, V);
1242       MadeChange = true;
1243     }
1244   };
1245 
1246   APInt UndefElts2(VWidth, 0);
1247   APInt UndefElts3(VWidth, 0);
1248   switch (I->getOpcode()) {
1249   default: break;
1250 
1251   case Instruction::GetElementPtr: {
1252     // The LangRef requires that struct geps have all constant indices.  As
1253     // such, we can't convert any operand to partial undef.
1254     auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1255       for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1256            I != E; I++)
1257         if (I.isStruct())
1258           return true;
1259       return false;
1260     };
1261     if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1262       break;
1263 
1264     // Conservatively track the demanded elements back through any vector
1265     // operands we may have.  We know there must be at least one, or we
1266     // wouldn't have a vector result to get here. Note that we intentionally
1267     // merge the undef bits here since gepping with either an poison base or
1268     // index results in poison.
1269     for (unsigned i = 0; i < I->getNumOperands(); i++) {
1270       if (i == 0 ? match(I->getOperand(i), m_Undef())
1271                  : match(I->getOperand(i), m_Poison())) {
1272         // If the entire vector is undefined, just return this info.
1273         UndefElts = EltMask;
1274         return nullptr;
1275       }
1276       if (I->getOperand(i)->getType()->isVectorTy()) {
1277         APInt UndefEltsOp(VWidth, 0);
1278         simplifyAndSetOp(I, i, DemandedElts, UndefEltsOp);
1279         // gep(x, undef) is not undef, so skip considering idx ops here
1280         // Note that we could propagate poison, but we can't distinguish between
1281         // undef & poison bits ATM
1282         if (i == 0)
1283           UndefElts |= UndefEltsOp;
1284       }
1285     }
1286 
1287     break;
1288   }
1289   case Instruction::InsertElement: {
1290     // If this is a variable index, we don't know which element it overwrites.
1291     // demand exactly the same input as we produce.
1292     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1293     if (!Idx) {
1294       // Note that we can't propagate undef elt info, because we don't know
1295       // which elt is getting updated.
1296       simplifyAndSetOp(I, 0, DemandedElts, UndefElts2);
1297       break;
1298     }
1299 
1300     // The element inserted overwrites whatever was there, so the input demanded
1301     // set is simpler than the output set.
1302     unsigned IdxNo = Idx->getZExtValue();
1303     APInt PreInsertDemandedElts = DemandedElts;
1304     if (IdxNo < VWidth)
1305       PreInsertDemandedElts.clearBit(IdxNo);
1306 
1307     // If we only demand the element that is being inserted and that element
1308     // was extracted from the same index in another vector with the same type,
1309     // replace this insert with that other vector.
1310     // Note: This is attempted before the call to simplifyAndSetOp because that
1311     //       may change UndefElts to a value that does not match with Vec.
1312     Value *Vec;
1313     if (PreInsertDemandedElts == 0 &&
1314         match(I->getOperand(1),
1315               m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1316         Vec->getType() == I->getType()) {
1317       return Vec;
1318     }
1319 
1320     simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts);
1321 
1322     // If this is inserting an element that isn't demanded, remove this
1323     // insertelement.
1324     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1325       Worklist.push(I);
1326       return I->getOperand(0);
1327     }
1328 
1329     // The inserted element is defined.
1330     UndefElts.clearBit(IdxNo);
1331     break;
1332   }
1333   case Instruction::ShuffleVector: {
1334     auto *Shuffle = cast<ShuffleVectorInst>(I);
1335     assert(Shuffle->getOperand(0)->getType() ==
1336            Shuffle->getOperand(1)->getType() &&
1337            "Expected shuffle operands to have same type");
1338     unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1339                            ->getNumElements();
1340     // Handle trivial case of a splat. Only check the first element of LHS
1341     // operand.
1342     if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1343         DemandedElts.isAllOnes()) {
1344       if (!match(I->getOperand(1), m_Undef())) {
1345         I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1346         MadeChange = true;
1347       }
1348       APInt LeftDemanded(OpWidth, 1);
1349       APInt LHSUndefElts(OpWidth, 0);
1350       simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1351       if (LHSUndefElts[0])
1352         UndefElts = EltMask;
1353       else
1354         UndefElts.clearAllBits();
1355       break;
1356     }
1357 
1358     APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1359     for (unsigned i = 0; i < VWidth; i++) {
1360       if (DemandedElts[i]) {
1361         unsigned MaskVal = Shuffle->getMaskValue(i);
1362         if (MaskVal != -1u) {
1363           assert(MaskVal < OpWidth * 2 &&
1364                  "shufflevector mask index out of range!");
1365           if (MaskVal < OpWidth)
1366             LeftDemanded.setBit(MaskVal);
1367           else
1368             RightDemanded.setBit(MaskVal - OpWidth);
1369         }
1370       }
1371     }
1372 
1373     APInt LHSUndefElts(OpWidth, 0);
1374     simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1375 
1376     APInt RHSUndefElts(OpWidth, 0);
1377     simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts);
1378 
1379     // If this shuffle does not change the vector length and the elements
1380     // demanded by this shuffle are an identity mask, then this shuffle is
1381     // unnecessary.
1382     //
1383     // We are assuming canonical form for the mask, so the source vector is
1384     // operand 0 and operand 1 is not used.
1385     //
1386     // Note that if an element is demanded and this shuffle mask is undefined
1387     // for that element, then the shuffle is not considered an identity
1388     // operation. The shuffle prevents poison from the operand vector from
1389     // leaking to the result by replacing poison with an undefined value.
1390     if (VWidth == OpWidth) {
1391       bool IsIdentityShuffle = true;
1392       for (unsigned i = 0; i < VWidth; i++) {
1393         unsigned MaskVal = Shuffle->getMaskValue(i);
1394         if (DemandedElts[i] && i != MaskVal) {
1395           IsIdentityShuffle = false;
1396           break;
1397         }
1398       }
1399       if (IsIdentityShuffle)
1400         return Shuffle->getOperand(0);
1401     }
1402 
1403     bool NewUndefElts = false;
1404     unsigned LHSIdx = -1u, LHSValIdx = -1u;
1405     unsigned RHSIdx = -1u, RHSValIdx = -1u;
1406     bool LHSUniform = true;
1407     bool RHSUniform = true;
1408     for (unsigned i = 0; i < VWidth; i++) {
1409       unsigned MaskVal = Shuffle->getMaskValue(i);
1410       if (MaskVal == -1u) {
1411         UndefElts.setBit(i);
1412       } else if (!DemandedElts[i]) {
1413         NewUndefElts = true;
1414         UndefElts.setBit(i);
1415       } else if (MaskVal < OpWidth) {
1416         if (LHSUndefElts[MaskVal]) {
1417           NewUndefElts = true;
1418           UndefElts.setBit(i);
1419         } else {
1420           LHSIdx = LHSIdx == -1u ? i : OpWidth;
1421           LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1422           LHSUniform = LHSUniform && (MaskVal == i);
1423         }
1424       } else {
1425         if (RHSUndefElts[MaskVal - OpWidth]) {
1426           NewUndefElts = true;
1427           UndefElts.setBit(i);
1428         } else {
1429           RHSIdx = RHSIdx == -1u ? i : OpWidth;
1430           RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1431           RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1432         }
1433       }
1434     }
1435 
1436     // Try to transform shuffle with constant vector and single element from
1437     // this constant vector to single insertelement instruction.
1438     // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1439     // insertelement V, C[ci], ci-n
1440     if (OpWidth ==
1441         cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1442       Value *Op = nullptr;
1443       Constant *Value = nullptr;
1444       unsigned Idx = -1u;
1445 
1446       // Find constant vector with the single element in shuffle (LHS or RHS).
1447       if (LHSIdx < OpWidth && RHSUniform) {
1448         if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1449           Op = Shuffle->getOperand(1);
1450           Value = CV->getOperand(LHSValIdx);
1451           Idx = LHSIdx;
1452         }
1453       }
1454       if (RHSIdx < OpWidth && LHSUniform) {
1455         if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1456           Op = Shuffle->getOperand(0);
1457           Value = CV->getOperand(RHSValIdx);
1458           Idx = RHSIdx;
1459         }
1460       }
1461       // Found constant vector with single element - convert to insertelement.
1462       if (Op && Value) {
1463         Instruction *New = InsertElementInst::Create(
1464             Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx),
1465             Shuffle->getName());
1466         InsertNewInstWith(New, *Shuffle);
1467         return New;
1468       }
1469     }
1470     if (NewUndefElts) {
1471       // Add additional discovered undefs.
1472       SmallVector<int, 16> Elts;
1473       for (unsigned i = 0; i < VWidth; ++i) {
1474         if (UndefElts[i])
1475           Elts.push_back(UndefMaskElem);
1476         else
1477           Elts.push_back(Shuffle->getMaskValue(i));
1478       }
1479       Shuffle->setShuffleMask(Elts);
1480       MadeChange = true;
1481     }
1482     break;
1483   }
1484   case Instruction::Select: {
1485     // If this is a vector select, try to transform the select condition based
1486     // on the current demanded elements.
1487     SelectInst *Sel = cast<SelectInst>(I);
1488     if (Sel->getCondition()->getType()->isVectorTy()) {
1489       // TODO: We are not doing anything with UndefElts based on this call.
1490       // It is overwritten below based on the other select operands. If an
1491       // element of the select condition is known undef, then we are free to
1492       // choose the output value from either arm of the select. If we know that
1493       // one of those values is undef, then the output can be undef.
1494       simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1495     }
1496 
1497     // Next, see if we can transform the arms of the select.
1498     APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1499     if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1500       for (unsigned i = 0; i < VWidth; i++) {
1501         // isNullValue() always returns false when called on a ConstantExpr.
1502         // Skip constant expressions to avoid propagating incorrect information.
1503         Constant *CElt = CV->getAggregateElement(i);
1504         if (isa<ConstantExpr>(CElt))
1505           continue;
1506         // TODO: If a select condition element is undef, we can demand from
1507         // either side. If one side is known undef, choosing that side would
1508         // propagate undef.
1509         if (CElt->isNullValue())
1510           DemandedLHS.clearBit(i);
1511         else
1512           DemandedRHS.clearBit(i);
1513       }
1514     }
1515 
1516     simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2);
1517     simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3);
1518 
1519     // Output elements are undefined if the element from each arm is undefined.
1520     // TODO: This can be improved. See comment in select condition handling.
1521     UndefElts = UndefElts2 & UndefElts3;
1522     break;
1523   }
1524   case Instruction::BitCast: {
1525     // Vector->vector casts only.
1526     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1527     if (!VTy) break;
1528     unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1529     APInt InputDemandedElts(InVWidth, 0);
1530     UndefElts2 = APInt(InVWidth, 0);
1531     unsigned Ratio;
1532 
1533     if (VWidth == InVWidth) {
1534       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1535       // elements as are demanded of us.
1536       Ratio = 1;
1537       InputDemandedElts = DemandedElts;
1538     } else if ((VWidth % InVWidth) == 0) {
1539       // If the number of elements in the output is a multiple of the number of
1540       // elements in the input then an input element is live if any of the
1541       // corresponding output elements are live.
1542       Ratio = VWidth / InVWidth;
1543       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1544         if (DemandedElts[OutIdx])
1545           InputDemandedElts.setBit(OutIdx / Ratio);
1546     } else if ((InVWidth % VWidth) == 0) {
1547       // If the number of elements in the input is a multiple of the number of
1548       // elements in the output then an input element is live if the
1549       // corresponding output element is live.
1550       Ratio = InVWidth / VWidth;
1551       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1552         if (DemandedElts[InIdx / Ratio])
1553           InputDemandedElts.setBit(InIdx);
1554     } else {
1555       // Unsupported so far.
1556       break;
1557     }
1558 
1559     simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2);
1560 
1561     if (VWidth == InVWidth) {
1562       UndefElts = UndefElts2;
1563     } else if ((VWidth % InVWidth) == 0) {
1564       // If the number of elements in the output is a multiple of the number of
1565       // elements in the input then an output element is undef if the
1566       // corresponding input element is undef.
1567       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1568         if (UndefElts2[OutIdx / Ratio])
1569           UndefElts.setBit(OutIdx);
1570     } else if ((InVWidth % VWidth) == 0) {
1571       // If the number of elements in the input is a multiple of the number of
1572       // elements in the output then an output element is undef if all of the
1573       // corresponding input elements are undef.
1574       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1575         APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1576         if (SubUndef.countPopulation() == Ratio)
1577           UndefElts.setBit(OutIdx);
1578       }
1579     } else {
1580       llvm_unreachable("Unimp");
1581     }
1582     break;
1583   }
1584   case Instruction::FPTrunc:
1585   case Instruction::FPExt:
1586     simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1587     break;
1588 
1589   case Instruction::Call: {
1590     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1591     if (!II) break;
1592     switch (II->getIntrinsicID()) {
1593     case Intrinsic::masked_gather: // fallthrough
1594     case Intrinsic::masked_load: {
1595       // Subtlety: If we load from a pointer, the pointer must be valid
1596       // regardless of whether the element is demanded.  Doing otherwise risks
1597       // segfaults which didn't exist in the original program.
1598       APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1599           DemandedPassThrough(DemandedElts);
1600       if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
1601         for (unsigned i = 0; i < VWidth; i++) {
1602           Constant *CElt = CV->getAggregateElement(i);
1603           if (CElt->isNullValue())
1604             DemandedPtrs.clearBit(i);
1605           else if (CElt->isAllOnesValue())
1606             DemandedPassThrough.clearBit(i);
1607         }
1608       if (II->getIntrinsicID() == Intrinsic::masked_gather)
1609         simplifyAndSetOp(II, 0, DemandedPtrs, UndefElts2);
1610       simplifyAndSetOp(II, 3, DemandedPassThrough, UndefElts3);
1611 
1612       // Output elements are undefined if the element from both sources are.
1613       // TODO: can strengthen via mask as well.
1614       UndefElts = UndefElts2 & UndefElts3;
1615       break;
1616     }
1617     default: {
1618       // Handle target specific intrinsics
1619       Optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1620           *II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
1621           simplifyAndSetOp);
1622       if (V.hasValue())
1623         return V.getValue();
1624       break;
1625     }
1626     } // switch on IntrinsicID
1627     break;
1628   } // case Call
1629   } // switch on Opcode
1630 
1631   // TODO: We bail completely on integer div/rem and shifts because they have
1632   // UB/poison potential, but that should be refined.
1633   BinaryOperator *BO;
1634   if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1635     simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1636     simplifyAndSetOp(I, 1, DemandedElts, UndefElts2);
1637 
1638     // Output elements are undefined if both are undefined. Consider things
1639     // like undef & 0. The result is known zero, not undef.
1640     UndefElts &= UndefElts2;
1641   }
1642 
1643   // If we've proven all of the lanes undef, return an undef value.
1644   // TODO: Intersect w/demanded lanes
1645   if (UndefElts.isAllOnes())
1646     return UndefValue::get(I->getType());;
1647 
1648   return MadeChange ? I : nullptr;
1649 }
1650