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/ValueTracking.h"
16 #include "llvm/IR/IntrinsicInst.h"
17 #include "llvm/IR/IntrinsicsAMDGPU.h"
18 #include "llvm/IR/IntrinsicsX86.h"
19 #include "llvm/IR/PatternMatch.h"
20 #include "llvm/Support/KnownBits.h"
21 
22 using namespace llvm;
23 using namespace llvm::PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 namespace {
28 
29 struct AMDGPUImageDMaskIntrinsic {
30   unsigned Intr;
31 };
32 
33 #define GET_AMDGPUImageDMaskIntrinsicTable_IMPL
34 #include "InstCombineTables.inc"
35 
36 } // end anonymous namespace
37 
38 /// Check to see if the specified operand of the specified instruction is a
39 /// constant integer. If so, check to see if there are any bits set in the
40 /// constant that are not demanded. If so, shrink the constant and return true.
41 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
42                                    const APInt &Demanded) {
43   assert(I && "No instruction?");
44   assert(OpNo < I->getNumOperands() && "Operand index too large");
45 
46   // The operand must be a constant integer or splat integer.
47   Value *Op = I->getOperand(OpNo);
48   const APInt *C;
49   if (!match(Op, m_APInt(C)))
50     return false;
51 
52   // If there are no bits set that aren't demanded, nothing to do.
53   if (C->isSubsetOf(Demanded))
54     return false;
55 
56   // This instruction is producing bits that are not demanded. Shrink the RHS.
57   I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
58 
59   return true;
60 }
61 
62 
63 
64 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
65 /// the instruction has any properties that allow us to simplify its operands.
66 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
67   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
68   KnownBits Known(BitWidth);
69   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
70 
71   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
72                                      0, &Inst);
73   if (!V) return false;
74   if (V == &Inst) return true;
75   replaceInstUsesWith(Inst, V);
76   return true;
77 }
78 
79 /// This form of SimplifyDemandedBits simplifies the specified instruction
80 /// operand if possible, updating it in place. It returns true if it made any
81 /// change and false otherwise.
82 bool InstCombiner::SimplifyDemandedBits(Instruction *I, unsigned OpNo,
83                                         const APInt &DemandedMask,
84                                         KnownBits &Known,
85                                         unsigned Depth) {
86   Use &U = I->getOperandUse(OpNo);
87   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known,
88                                           Depth, I);
89   if (!NewVal) return false;
90   if (Instruction* OpInst = dyn_cast<Instruction>(U))
91     salvageDebugInfoOrMarkUndef(*OpInst);
92 
93   replaceUse(U, NewVal);
94   return true;
95 }
96 
97 
98 /// This function attempts to replace V with a simpler value based on the
99 /// demanded bits. When this function is called, it is known that only the bits
100 /// set in DemandedMask of the result of V are ever used downstream.
101 /// Consequently, depending on the mask and V, it may be possible to replace V
102 /// with a constant or one of its operands. In such cases, this function does
103 /// the replacement and returns true. In all other cases, it returns false after
104 /// analyzing the expression and setting KnownOne and known to be one in the
105 /// expression. Known.Zero contains all the bits that are known to be zero in
106 /// the expression. These are provided to potentially allow the caller (which
107 /// might recursively be SimplifyDemandedBits itself) to simplify the
108 /// expression.
109 /// Known.One and Known.Zero always follow the invariant that:
110 ///   Known.One & Known.Zero == 0.
111 /// That is, a bit can't be both 1 and 0. Note that the bits in Known.One and
112 /// Known.Zero may only be accurate for those bits set in DemandedMask. Note
113 /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
114 /// be the same.
115 ///
116 /// This returns null if it did not change anything and it permits no
117 /// simplification.  This returns V itself if it did some simplification of V's
118 /// operands based on the information about what bits are demanded. This returns
119 /// some other non-null value if it found out that V is equal to another value
120 /// in the context where the specified bits are demanded, but not for all users.
121 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
122                                              KnownBits &Known, unsigned Depth,
123                                              Instruction *CxtI) {
124   assert(V != nullptr && "Null pointer of Value???");
125   assert(Depth <= 6 && "Limit Search Depth");
126   uint32_t BitWidth = DemandedMask.getBitWidth();
127   Type *VTy = V->getType();
128   assert(
129       (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
130       Known.getBitWidth() == BitWidth &&
131       "Value *V, DemandedMask and Known must have same BitWidth");
132 
133   if (isa<Constant>(V)) {
134     computeKnownBits(V, Known, Depth, CxtI);
135     return nullptr;
136   }
137 
138   Known.resetAll();
139   if (DemandedMask.isNullValue())     // Not demanding any bits from V.
140     return UndefValue::get(VTy);
141 
142   if (Depth == 6)        // Limit search depth.
143     return nullptr;
144 
145   Instruction *I = dyn_cast<Instruction>(V);
146   if (!I) {
147     computeKnownBits(V, Known, Depth, CxtI);
148     return nullptr;        // Only analyze instructions.
149   }
150 
151   // If there are multiple uses of this value and we aren't at the root, then
152   // we can't do any simplifications of the operands, because DemandedMask
153   // only reflects the bits demanded by *one* of the users.
154   if (Depth != 0 && !I->hasOneUse())
155     return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI);
156 
157   KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
158 
159   // If this is the root being simplified, allow it to have multiple uses,
160   // just set the DemandedMask to all bits so that we can try to simplify the
161   // operands.  This allows visitTruncInst (for example) to simplify the
162   // operand of a trunc without duplicating all the logic below.
163   if (Depth == 0 && !V->hasOneUse())
164     DemandedMask.setAllBits();
165 
166   switch (I->getOpcode()) {
167   default:
168     computeKnownBits(I, Known, Depth, CxtI);
169     break;
170   case Instruction::And: {
171     // If either the LHS or the RHS are Zero, the result is zero.
172     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
173         SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
174                              Depth + 1))
175       return I;
176     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
177     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
178 
179     // Output known-0 are known to be clear if zero in either the LHS | RHS.
180     APInt IKnownZero = RHSKnown.Zero | LHSKnown.Zero;
181     // Output known-1 bits are only known if set in both the LHS & RHS.
182     APInt IKnownOne = RHSKnown.One & LHSKnown.One;
183 
184     // If the client is only demanding bits that we know, return the known
185     // constant.
186     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
187       return Constant::getIntegerValue(VTy, IKnownOne);
188 
189     // If all of the demanded bits are known 1 on one side, return the other.
190     // These bits cannot contribute to the result of the 'and'.
191     if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
192       return I->getOperand(0);
193     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
194       return I->getOperand(1);
195 
196     // If the RHS is a constant, see if we can simplify it.
197     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
198       return I;
199 
200     Known.Zero = std::move(IKnownZero);
201     Known.One  = std::move(IKnownOne);
202     break;
203   }
204   case Instruction::Or: {
205     // If either the LHS or the RHS are One, the result is One.
206     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
207         SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
208                              Depth + 1))
209       return I;
210     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
211     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
212 
213     // Output known-0 bits are only known if clear in both the LHS & RHS.
214     APInt IKnownZero = RHSKnown.Zero & LHSKnown.Zero;
215     // Output known-1 are known. to be set if s.et in either the LHS | RHS.
216     APInt IKnownOne = RHSKnown.One | LHSKnown.One;
217 
218     // If the client is only demanding bits that we know, return the known
219     // constant.
220     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
221       return Constant::getIntegerValue(VTy, IKnownOne);
222 
223     // If all of the demanded bits are known zero on one side, return the other.
224     // These bits cannot contribute to the result of the 'or'.
225     if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
226       return I->getOperand(0);
227     if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
228       return I->getOperand(1);
229 
230     // If the RHS is a constant, see if we can simplify it.
231     if (ShrinkDemandedConstant(I, 1, DemandedMask))
232       return I;
233 
234     Known.Zero = std::move(IKnownZero);
235     Known.One  = std::move(IKnownOne);
236     break;
237   }
238   case Instruction::Xor: {
239     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
240         SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1))
241       return I;
242     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
243     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
244 
245     // Output known-0 bits are known if clear or set in both the LHS & RHS.
246     APInt IKnownZero = (RHSKnown.Zero & LHSKnown.Zero) |
247                        (RHSKnown.One & LHSKnown.One);
248     // Output known-1 are known to be set if set in only one of the LHS, RHS.
249     APInt IKnownOne =  (RHSKnown.Zero & LHSKnown.One) |
250                        (RHSKnown.One & LHSKnown.Zero);
251 
252     // If the client is only demanding bits that we know, return the known
253     // constant.
254     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
255       return Constant::getIntegerValue(VTy, IKnownOne);
256 
257     // If all of the demanded bits are known zero on one side, return the other.
258     // These bits cannot contribute to the result of the 'xor'.
259     if (DemandedMask.isSubsetOf(RHSKnown.Zero))
260       return I->getOperand(0);
261     if (DemandedMask.isSubsetOf(LHSKnown.Zero))
262       return I->getOperand(1);
263 
264     // If all of the demanded bits are known to be zero on one side or the
265     // other, turn this into an *inclusive* or.
266     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
267     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
268       Instruction *Or =
269         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
270                                  I->getName());
271       return InsertNewInstWith(Or, *I);
272     }
273 
274     // If all of the demanded bits on one side are known, and all of the set
275     // bits on that side are also known to be set on the other side, turn this
276     // into an AND, as we know the bits will be cleared.
277     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
278     if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
279         RHSKnown.One.isSubsetOf(LHSKnown.One)) {
280       Constant *AndC = Constant::getIntegerValue(VTy,
281                                                  ~RHSKnown.One & DemandedMask);
282       Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
283       return InsertNewInstWith(And, *I);
284     }
285 
286     // If the RHS is a constant, see if we can simplify it.
287     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
288     if (ShrinkDemandedConstant(I, 1, DemandedMask))
289       return I;
290 
291     // If our LHS is an 'and' and if it has one use, and if any of the bits we
292     // are flipping are known to be set, then the xor is just resetting those
293     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
294     // simplifying both of them.
295     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
296       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
297           isa<ConstantInt>(I->getOperand(1)) &&
298           isa<ConstantInt>(LHSInst->getOperand(1)) &&
299           (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
300         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
301         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
302         APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
303 
304         Constant *AndC =
305           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
306         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
307         InsertNewInstWith(NewAnd, *I);
308 
309         Constant *XorC =
310           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
311         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
312         return InsertNewInstWith(NewXor, *I);
313       }
314 
315     // Output known-0 bits are known if clear or set in both the LHS & RHS.
316     Known.Zero = std::move(IKnownZero);
317     // Output known-1 are known to be set if set in only one of the LHS, RHS.
318     Known.One  = std::move(IKnownOne);
319     break;
320   }
321   case Instruction::Select: {
322     Value *LHS, *RHS;
323     SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
324     if (SPF == SPF_UMAX) {
325       // UMax(A, C) == A if ...
326       // The lowest non-zero bit of DemandMask is higher than the highest
327       // non-zero bit of C.
328       const APInt *C;
329       unsigned CTZ = DemandedMask.countTrailingZeros();
330       if (match(RHS, m_APInt(C)) && CTZ >= C->getActiveBits())
331         return LHS;
332     } else if (SPF == SPF_UMIN) {
333       // UMin(A, C) == A if ...
334       // The lowest non-zero bit of DemandMask is higher than the highest
335       // non-one bit of C.
336       // This comes from using DeMorgans on the above umax example.
337       const APInt *C;
338       unsigned CTZ = DemandedMask.countTrailingZeros();
339       if (match(RHS, m_APInt(C)) &&
340           CTZ >= C->getBitWidth() - C->countLeadingOnes())
341         return LHS;
342     }
343 
344     // If this is a select as part of any other min/max pattern, don't simplify
345     // any further in case we break the structure.
346     if (SPF != SPF_UNKNOWN)
347       return nullptr;
348 
349     if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) ||
350         SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1))
351       return I;
352     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
353     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
354 
355     // If the operands are constants, see if we can simplify them.
356     // This is similar to ShrinkDemandedConstant, but for a select we want to
357     // try to keep the selected constants the same as icmp value constants, if
358     // we can. This helps not break apart (or helps put back together)
359     // canonical patterns like min and max.
360     auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
361                                          APInt DemandedMask) {
362       const APInt *SelC;
363       if (!match(I->getOperand(OpNo), m_APInt(SelC)))
364         return false;
365 
366       // Get the constant out of the ICmp, if there is one.
367       const APInt *CmpC;
368       ICmpInst::Predicate Pred;
369       if (!match(I->getOperand(0), m_c_ICmp(Pred, m_APInt(CmpC), m_Value())) ||
370           CmpC->getBitWidth() != SelC->getBitWidth())
371         return ShrinkDemandedConstant(I, OpNo, DemandedMask);
372 
373       // If the constant is already the same as the ICmp, leave it as-is.
374       if (*CmpC == *SelC)
375         return false;
376       // If the constants are not already the same, but can be with the demand
377       // mask, use the constant value from the ICmp.
378       if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
379         I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
380         return true;
381       }
382       return ShrinkDemandedConstant(I, OpNo, DemandedMask);
383     };
384     if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
385         CanonicalizeSelectConstant(I, 2, DemandedMask))
386       return I;
387 
388     // Only known if known in both the LHS and RHS.
389     Known.One = RHSKnown.One & LHSKnown.One;
390     Known.Zero = RHSKnown.Zero & LHSKnown.Zero;
391     break;
392   }
393   case Instruction::ZExt:
394   case Instruction::Trunc: {
395     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
396 
397     APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
398     KnownBits InputKnown(SrcBitWidth);
399     if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1))
400       return I;
401     assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
402     Known = InputKnown.zextOrTrunc(BitWidth);
403     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
404     break;
405   }
406   case Instruction::BitCast:
407     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
408       return nullptr;  // vector->int or fp->int?
409 
410     if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
411       if (VectorType *SrcVTy =
412             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
413         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
414           // Don't touch a bitcast between vectors of different element counts.
415           return nullptr;
416       } else
417         // Don't touch a scalar-to-vector bitcast.
418         return nullptr;
419     } else if (I->getOperand(0)->getType()->isVectorTy())
420       // Don't touch a vector-to-scalar bitcast.
421       return nullptr;
422 
423     if (SimplifyDemandedBits(I, 0, DemandedMask, Known, Depth + 1))
424       return I;
425     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
426     break;
427   case Instruction::SExt: {
428     // Compute the bits in the result that are not present in the input.
429     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
430 
431     APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
432 
433     // If any of the sign extended bits are demanded, we know that the sign
434     // bit is demanded.
435     if (DemandedMask.getActiveBits() > SrcBitWidth)
436       InputDemandedBits.setBit(SrcBitWidth-1);
437 
438     KnownBits InputKnown(SrcBitWidth);
439     if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1))
440       return I;
441 
442     // If the input sign bit is known zero, or if the NewBits are not demanded
443     // convert this into a zero extension.
444     if (InputKnown.isNonNegative() ||
445         DemandedMask.getActiveBits() <= SrcBitWidth) {
446       // Convert to ZExt cast.
447       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
448       return InsertNewInstWith(NewCast, *I);
449      }
450 
451     // If the sign bit of the input is known set or clear, then we know the
452     // top bits of the result.
453     Known = InputKnown.sext(BitWidth);
454     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
455     break;
456   }
457   case Instruction::Add:
458     if ((DemandedMask & 1) == 0) {
459       // If we do not need the low bit, try to convert bool math to logic:
460       // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
461       Value *X, *Y;
462       if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))),
463                            m_OneUse(m_SExt(m_Value(Y))))) &&
464           X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
465         // Truth table for inputs and output signbits:
466         //       X:0 | X:1
467         //      ----------
468         // Y:0  |  0 | 0 |
469         // Y:1  | -1 | 0 |
470         //      ----------
471         IRBuilderBase::InsertPointGuard Guard(Builder);
472         Builder.SetInsertPoint(I);
473         Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
474         return Builder.CreateSExt(AndNot, VTy);
475       }
476 
477       // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
478       // TODO: Relax the one-use checks because we are removing an instruction?
479       if (match(I, m_Add(m_OneUse(m_SExt(m_Value(X))),
480                          m_OneUse(m_SExt(m_Value(Y))))) &&
481           X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
482         // Truth table for inputs and output signbits:
483         //       X:0 | X:1
484         //      -----------
485         // Y:0  | -1 | -1 |
486         // Y:1  | -1 |  0 |
487         //      -----------
488         IRBuilderBase::InsertPointGuard Guard(Builder);
489         Builder.SetInsertPoint(I);
490         Value *Or = Builder.CreateOr(X, Y);
491         return Builder.CreateSExt(Or, VTy);
492       }
493     }
494     LLVM_FALLTHROUGH;
495   case Instruction::Sub: {
496     /// If the high-bits of an ADD/SUB are not demanded, then we do not care
497     /// about the high bits of the operands.
498     unsigned NLZ = DemandedMask.countLeadingZeros();
499     // Right fill the mask of bits for this ADD/SUB to demand the most
500     // significant bit and all those below it.
501     APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
502     if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
503         SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) ||
504         ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
505         SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) {
506       if (NLZ > 0) {
507         // Disable the nsw and nuw flags here: We can no longer guarantee that
508         // we won't wrap after simplification. Removing the nsw/nuw flags is
509         // legal here because the top bit is not demanded.
510         BinaryOperator &BinOP = *cast<BinaryOperator>(I);
511         BinOP.setHasNoSignedWrap(false);
512         BinOP.setHasNoUnsignedWrap(false);
513       }
514       return I;
515     }
516 
517     // If we are known to be adding/subtracting zeros to every bit below
518     // the highest demanded bit, we just return the other side.
519     if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
520       return I->getOperand(0);
521     // We can't do this with the LHS for subtraction, unless we are only
522     // demanding the LSB.
523     if ((I->getOpcode() == Instruction::Add ||
524          DemandedFromOps.isOneValue()) &&
525         DemandedFromOps.isSubsetOf(LHSKnown.Zero))
526       return I->getOperand(1);
527 
528     // Otherwise just compute the known bits of the result.
529     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
530     Known = KnownBits::computeForAddSub(I->getOpcode() == Instruction::Add,
531                                         NSW, LHSKnown, RHSKnown);
532     break;
533   }
534   case Instruction::Shl: {
535     const APInt *SA;
536     if (match(I->getOperand(1), m_APInt(SA))) {
537       const APInt *ShrAmt;
538       if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
539         if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
540           if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
541                                                     DemandedMask, Known))
542             return R;
543 
544       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
545       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
546 
547       // If the shift is NUW/NSW, then it does demand the high bits.
548       ShlOperator *IOp = cast<ShlOperator>(I);
549       if (IOp->hasNoSignedWrap())
550         DemandedMaskIn.setHighBits(ShiftAmt+1);
551       else if (IOp->hasNoUnsignedWrap())
552         DemandedMaskIn.setHighBits(ShiftAmt);
553 
554       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
555         return I;
556       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
557 
558       bool SignBitZero = Known.Zero.isSignBitSet();
559       bool SignBitOne = Known.One.isSignBitSet();
560       Known.Zero <<= ShiftAmt;
561       Known.One  <<= ShiftAmt;
562       // low bits known zero.
563       if (ShiftAmt)
564         Known.Zero.setLowBits(ShiftAmt);
565 
566       // If this shift has "nsw" keyword, then the result is either a poison
567       // value or has the same sign bit as the first operand.
568       if (IOp->hasNoSignedWrap()) {
569         if (SignBitZero)
570           Known.Zero.setSignBit();
571         else if (SignBitOne)
572           Known.One.setSignBit();
573         if (Known.hasConflict())
574           return UndefValue::get(I->getType());
575       }
576     } else {
577       computeKnownBits(I, Known, Depth, CxtI);
578     }
579     break;
580   }
581   case Instruction::LShr: {
582     const APInt *SA;
583     if (match(I->getOperand(1), m_APInt(SA))) {
584       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
585 
586       // Unsigned shift right.
587       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
588 
589       // If the shift is exact, then it does demand the low bits (and knows that
590       // they are zero).
591       if (cast<LShrOperator>(I)->isExact())
592         DemandedMaskIn.setLowBits(ShiftAmt);
593 
594       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
595         return I;
596       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
597       Known.Zero.lshrInPlace(ShiftAmt);
598       Known.One.lshrInPlace(ShiftAmt);
599       if (ShiftAmt)
600         Known.Zero.setHighBits(ShiftAmt);  // high bits known zero.
601     } else {
602       computeKnownBits(I, Known, Depth, CxtI);
603     }
604     break;
605   }
606   case Instruction::AShr: {
607     // If this is an arithmetic shift right and only the low-bit is set, we can
608     // always convert this into a logical shr, even if the shift amount is
609     // variable.  The low bit of the shift cannot be an input sign bit unless
610     // the shift amount is >= the size of the datatype, which is undefined.
611     if (DemandedMask.isOneValue()) {
612       // Perform the logical shift right.
613       Instruction *NewVal = BinaryOperator::CreateLShr(
614                         I->getOperand(0), I->getOperand(1), I->getName());
615       return InsertNewInstWith(NewVal, *I);
616     }
617 
618     // If the sign bit is the only bit demanded by this ashr, then there is no
619     // need to do it, the shift doesn't change the high bit.
620     if (DemandedMask.isSignMask())
621       return I->getOperand(0);
622 
623     const APInt *SA;
624     if (match(I->getOperand(1), m_APInt(SA))) {
625       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
626 
627       // Signed shift right.
628       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
629       // If any of the high bits are demanded, we should set the sign bit as
630       // demanded.
631       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
632         DemandedMaskIn.setSignBit();
633 
634       // If the shift is exact, then it does demand the low bits (and knows that
635       // they are zero).
636       if (cast<AShrOperator>(I)->isExact())
637         DemandedMaskIn.setLowBits(ShiftAmt);
638 
639       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
640         return I;
641 
642       unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
643 
644       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
645       // Compute the new bits that are at the top now plus sign bits.
646       APInt HighBits(APInt::getHighBitsSet(
647           BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
648       Known.Zero.lshrInPlace(ShiftAmt);
649       Known.One.lshrInPlace(ShiftAmt);
650 
651       // If the input sign bit is known to be zero, or if none of the top bits
652       // are demanded, turn this into an unsigned shift right.
653       assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
654       if (Known.Zero[BitWidth-ShiftAmt-1] ||
655           !DemandedMask.intersects(HighBits)) {
656         BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
657                                                           I->getOperand(1));
658         LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
659         return InsertNewInstWith(LShr, *I);
660       } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
661         Known.One |= HighBits;
662       }
663     } else {
664       computeKnownBits(I, Known, Depth, CxtI);
665     }
666     break;
667   }
668   case Instruction::UDiv: {
669     // UDiv doesn't demand low bits that are zero in the divisor.
670     const APInt *SA;
671     if (match(I->getOperand(1), m_APInt(SA))) {
672       // If the shift is exact, then it does demand the low bits.
673       if (cast<UDivOperator>(I)->isExact())
674         break;
675 
676       // FIXME: Take the demanded mask of the result into account.
677       unsigned RHSTrailingZeros = SA->countTrailingZeros();
678       APInt DemandedMaskIn =
679           APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
680       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1))
681         return I;
682 
683       // Propagate zero bits from the input.
684       Known.Zero.setHighBits(std::min(
685           BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros));
686     } else {
687       computeKnownBits(I, Known, Depth, CxtI);
688     }
689     break;
690   }
691   case Instruction::SRem:
692     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
693       // X % -1 demands all the bits because we don't want to introduce
694       // INT_MIN % -1 (== undef) by accident.
695       if (Rem->isMinusOne())
696         break;
697       APInt RA = Rem->getValue().abs();
698       if (RA.isPowerOf2()) {
699         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
700           return I->getOperand(0);
701 
702         APInt LowBits = RA - 1;
703         APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
704         if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1))
705           return I;
706 
707         // The low bits of LHS are unchanged by the srem.
708         Known.Zero = LHSKnown.Zero & LowBits;
709         Known.One = LHSKnown.One & LowBits;
710 
711         // If LHS is non-negative or has all low bits zero, then the upper bits
712         // are all zero.
713         if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
714           Known.Zero |= ~LowBits;
715 
716         // If LHS is negative and not all low bits are zero, then the upper bits
717         // are all one.
718         if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
719           Known.One |= ~LowBits;
720 
721         assert(!Known.hasConflict() && "Bits known to be one AND zero?");
722         break;
723       }
724     }
725 
726     // The sign bit is the LHS's sign bit, except when the result of the
727     // remainder is zero.
728     if (DemandedMask.isSignBitSet()) {
729       computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
730       // If it's known zero, our sign bit is also zero.
731       if (LHSKnown.isNonNegative())
732         Known.makeNonNegative();
733     }
734     break;
735   case Instruction::URem: {
736     KnownBits Known2(BitWidth);
737     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
738     if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) ||
739         SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1))
740       return I;
741 
742     unsigned Leaders = Known2.countMinLeadingZeros();
743     Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
744     break;
745   }
746   case Instruction::Call: {
747     bool KnownBitsComputed = false;
748     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
749       switch (II->getIntrinsicID()) {
750       default: break;
751       case Intrinsic::bswap: {
752         // If the only bits demanded come from one byte of the bswap result,
753         // just shift the input byte into position to eliminate the bswap.
754         unsigned NLZ = DemandedMask.countLeadingZeros();
755         unsigned NTZ = DemandedMask.countTrailingZeros();
756 
757         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
758         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
759         // have 14 leading zeros, round to 8.
760         NLZ &= ~7;
761         NTZ &= ~7;
762         // If we need exactly one byte, we can do this transformation.
763         if (BitWidth-NLZ-NTZ == 8) {
764           unsigned ResultBit = NTZ;
765           unsigned InputBit = BitWidth-NTZ-8;
766 
767           // Replace this with either a left or right shift to get the byte into
768           // the right place.
769           Instruction *NewVal;
770           if (InputBit > ResultBit)
771             NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
772                     ConstantInt::get(I->getType(), InputBit-ResultBit));
773           else
774             NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
775                     ConstantInt::get(I->getType(), ResultBit-InputBit));
776           NewVal->takeName(I);
777           return InsertNewInstWith(NewVal, *I);
778         }
779         break;
780       }
781       case Intrinsic::fshr:
782       case Intrinsic::fshl: {
783         const APInt *SA;
784         if (!match(I->getOperand(2), m_APInt(SA)))
785           break;
786 
787         // Normalize to funnel shift left. APInt shifts of BitWidth are well-
788         // defined, so no need to special-case zero shifts here.
789         uint64_t ShiftAmt = SA->urem(BitWidth);
790         if (II->getIntrinsicID() == Intrinsic::fshr)
791           ShiftAmt = BitWidth - ShiftAmt;
792 
793         APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
794         APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
795         if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) ||
796             SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
797           return I;
798 
799         Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
800                      RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
801         Known.One = LHSKnown.One.shl(ShiftAmt) |
802                     RHSKnown.One.lshr(BitWidth - ShiftAmt);
803         KnownBitsComputed = true;
804         break;
805       }
806       case Intrinsic::x86_mmx_pmovmskb:
807       case Intrinsic::x86_sse_movmsk_ps:
808       case Intrinsic::x86_sse2_movmsk_pd:
809       case Intrinsic::x86_sse2_pmovmskb_128:
810       case Intrinsic::x86_avx_movmsk_ps_256:
811       case Intrinsic::x86_avx_movmsk_pd_256:
812       case Intrinsic::x86_avx2_pmovmskb: {
813         // MOVMSK copies the vector elements' sign bits to the low bits
814         // and zeros the high bits.
815         unsigned ArgWidth;
816         if (II->getIntrinsicID() == Intrinsic::x86_mmx_pmovmskb) {
817           ArgWidth = 8; // Arg is x86_mmx, but treated as <8 x i8>.
818         } else {
819           auto Arg = II->getArgOperand(0);
820           auto ArgType = cast<VectorType>(Arg->getType());
821           ArgWidth = ArgType->getNumElements();
822         }
823 
824         // If we don't need any of low bits then return zero,
825         // we know that DemandedMask is non-zero already.
826         APInt DemandedElts = DemandedMask.zextOrTrunc(ArgWidth);
827         if (DemandedElts.isNullValue())
828           return ConstantInt::getNullValue(VTy);
829 
830         // We know that the upper bits are set to zero.
831         Known.Zero.setBitsFrom(ArgWidth);
832         KnownBitsComputed = true;
833         break;
834       }
835       case Intrinsic::x86_sse42_crc32_64_64:
836         Known.Zero.setBitsFrom(32);
837         KnownBitsComputed = true;
838         break;
839       }
840     }
841 
842     if (!KnownBitsComputed)
843       computeKnownBits(V, Known, Depth, CxtI);
844     break;
845   }
846   }
847 
848   // If the client is only demanding bits that we know, return the known
849   // constant.
850   if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
851     return Constant::getIntegerValue(VTy, Known.One);
852   return nullptr;
853 }
854 
855 /// Helper routine of SimplifyDemandedUseBits. It computes Known
856 /// bits. It also tries to handle simplifications that can be done based on
857 /// DemandedMask, but without modifying the Instruction.
858 Value *InstCombiner::SimplifyMultipleUseDemandedBits(Instruction *I,
859                                                      const APInt &DemandedMask,
860                                                      KnownBits &Known,
861                                                      unsigned Depth,
862                                                      Instruction *CxtI) {
863   unsigned BitWidth = DemandedMask.getBitWidth();
864   Type *ITy = I->getType();
865 
866   KnownBits LHSKnown(BitWidth);
867   KnownBits RHSKnown(BitWidth);
868 
869   // Despite the fact that we can't simplify this instruction in all User's
870   // context, we can at least compute the known bits, and we can
871   // do simplifications that apply to *just* the one user if we know that
872   // this instruction has a simpler value in that context.
873   switch (I->getOpcode()) {
874   case Instruction::And: {
875     // If either the LHS or the RHS are Zero, the result is zero.
876     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
877     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
878                      CxtI);
879 
880     // Output known-0 are known to be clear if zero in either the LHS | RHS.
881     APInt IKnownZero = RHSKnown.Zero | LHSKnown.Zero;
882     // Output known-1 bits are only known if set in both the LHS & RHS.
883     APInt IKnownOne = RHSKnown.One & LHSKnown.One;
884 
885     // If the client is only demanding bits that we know, return the known
886     // constant.
887     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
888       return Constant::getIntegerValue(ITy, IKnownOne);
889 
890     // If all of the demanded bits are known 1 on one side, return the other.
891     // These bits cannot contribute to the result of the 'and' in this
892     // context.
893     if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
894       return I->getOperand(0);
895     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
896       return I->getOperand(1);
897 
898     Known.Zero = std::move(IKnownZero);
899     Known.One  = std::move(IKnownOne);
900     break;
901   }
902   case Instruction::Or: {
903     // We can simplify (X|Y) -> X or Y in the user's context if we know that
904     // only bits from X or Y are demanded.
905 
906     // If either the LHS or the RHS are One, the result is One.
907     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
908     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
909                      CxtI);
910 
911     // Output known-0 bits are only known if clear in both the LHS & RHS.
912     APInt IKnownZero = RHSKnown.Zero & LHSKnown.Zero;
913     // Output known-1 are known to be set if set in either the LHS | RHS.
914     APInt IKnownOne = RHSKnown.One | LHSKnown.One;
915 
916     // If the client is only demanding bits that we know, return the known
917     // constant.
918     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
919       return Constant::getIntegerValue(ITy, IKnownOne);
920 
921     // If all of the demanded bits are known zero on one side, return the
922     // other.  These bits cannot contribute to the result of the 'or' in this
923     // context.
924     if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
925       return I->getOperand(0);
926     if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
927       return I->getOperand(1);
928 
929     Known.Zero = std::move(IKnownZero);
930     Known.One  = std::move(IKnownOne);
931     break;
932   }
933   case Instruction::Xor: {
934     // We can simplify (X^Y) -> X or Y in the user's context if we know that
935     // only bits from X or Y are demanded.
936 
937     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
938     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
939                      CxtI);
940 
941     // Output known-0 bits are known if clear or set in both the LHS & RHS.
942     APInt IKnownZero = (RHSKnown.Zero & LHSKnown.Zero) |
943                        (RHSKnown.One & LHSKnown.One);
944     // Output known-1 are known to be set if set in only one of the LHS, RHS.
945     APInt IKnownOne =  (RHSKnown.Zero & LHSKnown.One) |
946                        (RHSKnown.One & LHSKnown.Zero);
947 
948     // If the client is only demanding bits that we know, return the known
949     // constant.
950     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
951       return Constant::getIntegerValue(ITy, IKnownOne);
952 
953     // If all of the demanded bits are known zero on one side, return the
954     // other.
955     if (DemandedMask.isSubsetOf(RHSKnown.Zero))
956       return I->getOperand(0);
957     if (DemandedMask.isSubsetOf(LHSKnown.Zero))
958       return I->getOperand(1);
959 
960     // Output known-0 bits are known if clear or set in both the LHS & RHS.
961     Known.Zero = std::move(IKnownZero);
962     // Output known-1 are known to be set if set in only one of the LHS, RHS.
963     Known.One  = std::move(IKnownOne);
964     break;
965   }
966   default:
967     // Compute the Known bits to simplify things downstream.
968     computeKnownBits(I, Known, Depth, CxtI);
969 
970     // If this user is only demanding bits that we know, return the known
971     // constant.
972     if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
973       return Constant::getIntegerValue(ITy, Known.One);
974 
975     break;
976   }
977 
978   return nullptr;
979 }
980 
981 
982 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
983 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
984 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
985 /// of "C2-C1".
986 ///
987 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
988 /// ..., bn}, without considering the specific value X is holding.
989 /// This transformation is legal iff one of following conditions is hold:
990 ///  1) All the bit in S are 0, in this case E1 == E2.
991 ///  2) We don't care those bits in S, per the input DemandedMask.
992 ///  3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
993 ///     rest bits.
994 ///
995 /// Currently we only test condition 2).
996 ///
997 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
998 /// not successful.
999 Value *
1000 InstCombiner::simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1,
1001                                          Instruction *Shl, const APInt &ShlOp1,
1002                                          const APInt &DemandedMask,
1003                                          KnownBits &Known) {
1004   if (!ShlOp1 || !ShrOp1)
1005     return nullptr; // No-op.
1006 
1007   Value *VarX = Shr->getOperand(0);
1008   Type *Ty = VarX->getType();
1009   unsigned BitWidth = Ty->getScalarSizeInBits();
1010   if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1011     return nullptr; // Undef.
1012 
1013   unsigned ShlAmt = ShlOp1.getZExtValue();
1014   unsigned ShrAmt = ShrOp1.getZExtValue();
1015 
1016   Known.One.clearAllBits();
1017   Known.Zero.setLowBits(ShlAmt - 1);
1018   Known.Zero &= DemandedMask;
1019 
1020   APInt BitMask1(APInt::getAllOnesValue(BitWidth));
1021   APInt BitMask2(APInt::getAllOnesValue(BitWidth));
1022 
1023   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1024   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1025                       (BitMask1.ashr(ShrAmt) << ShlAmt);
1026 
1027   if (ShrAmt <= ShlAmt) {
1028     BitMask2 <<= (ShlAmt - ShrAmt);
1029   } else {
1030     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1031                         BitMask2.ashr(ShrAmt - ShlAmt);
1032   }
1033 
1034   // Check if condition-2 (see the comment to this function) is satified.
1035   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1036     if (ShrAmt == ShlAmt)
1037       return VarX;
1038 
1039     if (!Shr->hasOneUse())
1040       return nullptr;
1041 
1042     BinaryOperator *New;
1043     if (ShrAmt < ShlAmt) {
1044       Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1045       New = BinaryOperator::CreateShl(VarX, Amt);
1046       BinaryOperator *Orig = cast<BinaryOperator>(Shl);
1047       New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1048       New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1049     } else {
1050       Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1051       New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1052                      BinaryOperator::CreateAShr(VarX, Amt);
1053       if (cast<BinaryOperator>(Shr)->isExact())
1054         New->setIsExact(true);
1055     }
1056 
1057     return InsertNewInstWith(New, *Shl);
1058   }
1059 
1060   return nullptr;
1061 }
1062 
1063 /// Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics.
1064 ///
1065 /// Note: This only supports non-TFE/LWE image intrinsic calls; those have
1066 ///       struct returns.
1067 Value *InstCombiner::simplifyAMDGCNMemoryIntrinsicDemanded(IntrinsicInst *II,
1068                                                            APInt DemandedElts,
1069                                                            int DMaskIdx) {
1070 
1071   // FIXME: Allow v3i16/v3f16 in buffer intrinsics when the types are fully supported.
1072   if (DMaskIdx < 0 &&
1073       II->getType()->getScalarSizeInBits() != 32 &&
1074       DemandedElts.getActiveBits() == 3)
1075     return nullptr;
1076 
1077   unsigned VWidth = II->getType()->getVectorNumElements();
1078   if (VWidth == 1)
1079     return nullptr;
1080 
1081   IRBuilderBase::InsertPointGuard Guard(Builder);
1082   Builder.SetInsertPoint(II);
1083 
1084   // Assume the arguments are unchanged and later override them, if needed.
1085   SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end());
1086 
1087   if (DMaskIdx < 0) {
1088     // Buffer case.
1089 
1090     const unsigned ActiveBits = DemandedElts.getActiveBits();
1091     const unsigned UnusedComponentsAtFront = DemandedElts.countTrailingZeros();
1092 
1093     // Start assuming the prefix of elements is demanded, but possibly clear
1094     // some other bits if there are trailing zeros (unused components at front)
1095     // and update offset.
1096     DemandedElts = (1 << ActiveBits) - 1;
1097 
1098     if (UnusedComponentsAtFront > 0) {
1099       static const unsigned InvalidOffsetIdx = 0xf;
1100 
1101       unsigned OffsetIdx;
1102       switch (II->getIntrinsicID()) {
1103       case Intrinsic::amdgcn_raw_buffer_load:
1104         OffsetIdx = 1;
1105         break;
1106       case Intrinsic::amdgcn_s_buffer_load:
1107         // If resulting type is vec3, there is no point in trimming the
1108         // load with updated offset, as the vec3 would most likely be widened to
1109         // vec4 anyway during lowering.
1110         if (ActiveBits == 4 && UnusedComponentsAtFront == 1)
1111           OffsetIdx = InvalidOffsetIdx;
1112         else
1113           OffsetIdx = 1;
1114         break;
1115       case Intrinsic::amdgcn_struct_buffer_load:
1116         OffsetIdx = 2;
1117         break;
1118       default:
1119         // TODO: handle tbuffer* intrinsics.
1120         OffsetIdx = InvalidOffsetIdx;
1121         break;
1122       }
1123 
1124       if (OffsetIdx != InvalidOffsetIdx) {
1125         // Clear demanded bits and update the offset.
1126         DemandedElts &= ~((1 << UnusedComponentsAtFront) - 1);
1127         auto *Offset = II->getArgOperand(OffsetIdx);
1128         unsigned SingleComponentSizeInBits =
1129             getDataLayout().getTypeSizeInBits(II->getType()->getScalarType());
1130         unsigned OffsetAdd =
1131             UnusedComponentsAtFront * SingleComponentSizeInBits / 8;
1132         auto *OffsetAddVal = ConstantInt::get(Offset->getType(), OffsetAdd);
1133         Args[OffsetIdx] = Builder.CreateAdd(Offset, OffsetAddVal);
1134       }
1135     }
1136   } else {
1137     // Image case.
1138 
1139     ConstantInt *DMask = cast<ConstantInt>(II->getArgOperand(DMaskIdx));
1140     unsigned DMaskVal = DMask->getZExtValue() & 0xf;
1141 
1142     // Mask off values that are undefined because the dmask doesn't cover them
1143     DemandedElts &= (1 << countPopulation(DMaskVal)) - 1;
1144 
1145     unsigned NewDMaskVal = 0;
1146     unsigned OrigLoadIdx = 0;
1147     for (unsigned SrcIdx = 0; SrcIdx < 4; ++SrcIdx) {
1148       const unsigned Bit = 1 << SrcIdx;
1149       if (!!(DMaskVal & Bit)) {
1150         if (!!DemandedElts[OrigLoadIdx])
1151           NewDMaskVal |= Bit;
1152         OrigLoadIdx++;
1153       }
1154     }
1155 
1156     if (DMaskVal != NewDMaskVal)
1157       Args[DMaskIdx] = ConstantInt::get(DMask->getType(), NewDMaskVal);
1158   }
1159 
1160   unsigned NewNumElts = DemandedElts.countPopulation();
1161   if (!NewNumElts)
1162     return UndefValue::get(II->getType());
1163 
1164   if (NewNumElts >= VWidth && DemandedElts.isMask()) {
1165     if (DMaskIdx >= 0)
1166       II->setArgOperand(DMaskIdx, Args[DMaskIdx]);
1167     return nullptr;
1168   }
1169 
1170   // Determine the overload types of the original intrinsic.
1171   auto IID = II->getIntrinsicID();
1172   SmallVector<Intrinsic::IITDescriptor, 16> Table;
1173   getIntrinsicInfoTableEntries(IID, Table);
1174   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1175 
1176   // Validate function argument and return types, extracting overloaded types
1177   // along the way.
1178   FunctionType *FTy = II->getCalledFunction()->getFunctionType();
1179   SmallVector<Type *, 6> OverloadTys;
1180   Intrinsic::matchIntrinsicSignature(FTy, TableRef, OverloadTys);
1181 
1182   Module *M = II->getParent()->getParent()->getParent();
1183   Type *EltTy = II->getType()->getVectorElementType();
1184   Type *NewTy = (NewNumElts == 1) ? EltTy : VectorType::get(EltTy, NewNumElts);
1185 
1186   OverloadTys[0] = NewTy;
1187   Function *NewIntrin = Intrinsic::getDeclaration(M, IID, OverloadTys);
1188 
1189   CallInst *NewCall = Builder.CreateCall(NewIntrin, Args);
1190   NewCall->takeName(II);
1191   NewCall->copyMetadata(*II);
1192 
1193   if (NewNumElts == 1) {
1194     return Builder.CreateInsertElement(UndefValue::get(II->getType()), NewCall,
1195                                        DemandedElts.countTrailingZeros());
1196   }
1197 
1198   SmallVector<uint32_t, 8> EltMask;
1199   unsigned NewLoadIdx = 0;
1200   for (unsigned OrigLoadIdx = 0; OrigLoadIdx < VWidth; ++OrigLoadIdx) {
1201     if (!!DemandedElts[OrigLoadIdx])
1202       EltMask.push_back(NewLoadIdx++);
1203     else
1204       EltMask.push_back(NewNumElts);
1205   }
1206 
1207   Value *Shuffle =
1208       Builder.CreateShuffleVector(NewCall, UndefValue::get(NewTy), EltMask);
1209 
1210   return Shuffle;
1211 }
1212 
1213 /// The specified value produces a vector with any number of elements.
1214 /// This method analyzes which elements of the operand are undef and returns
1215 /// that information in UndefElts.
1216 ///
1217 /// DemandedElts contains the set of elements that are actually used by the
1218 /// caller, and by default (AllowMultipleUsers equals false) the value is
1219 /// simplified only if it has a single caller. If AllowMultipleUsers is set
1220 /// to true, DemandedElts refers to the union of sets of elements that are
1221 /// used by all callers.
1222 ///
1223 /// If the information about demanded elements can be used to simplify the
1224 /// operation, the operation is simplified, then the resultant value is
1225 /// returned.  This returns null if no change was made.
1226 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1227                                                 APInt &UndefElts,
1228                                                 unsigned Depth,
1229                                                 bool AllowMultipleUsers) {
1230   unsigned VWidth = V->getType()->getVectorNumElements();
1231   APInt EltMask(APInt::getAllOnesValue(VWidth));
1232   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1233 
1234   if (isa<UndefValue>(V)) {
1235     // If the entire vector is undefined, just return this info.
1236     UndefElts = EltMask;
1237     return nullptr;
1238   }
1239 
1240   if (DemandedElts.isNullValue()) { // If nothing is demanded, provide undef.
1241     UndefElts = EltMask;
1242     return UndefValue::get(V->getType());
1243   }
1244 
1245   UndefElts = 0;
1246 
1247   if (auto *C = dyn_cast<Constant>(V)) {
1248     // Check if this is identity. If so, return 0 since we are not simplifying
1249     // anything.
1250     if (DemandedElts.isAllOnesValue())
1251       return nullptr;
1252 
1253     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1254     Constant *Undef = UndefValue::get(EltTy);
1255     SmallVector<Constant*, 16> Elts;
1256     for (unsigned i = 0; i != VWidth; ++i) {
1257       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1258         Elts.push_back(Undef);
1259         UndefElts.setBit(i);
1260         continue;
1261       }
1262 
1263       Constant *Elt = C->getAggregateElement(i);
1264       if (!Elt) return nullptr;
1265 
1266       if (isa<UndefValue>(Elt)) {   // Already undef.
1267         Elts.push_back(Undef);
1268         UndefElts.setBit(i);
1269       } else {                               // Otherwise, defined.
1270         Elts.push_back(Elt);
1271       }
1272     }
1273 
1274     // If we changed the constant, return it.
1275     Constant *NewCV = ConstantVector::get(Elts);
1276     return NewCV != C ? NewCV : nullptr;
1277   }
1278 
1279   // Limit search depth.
1280   if (Depth == 10)
1281     return nullptr;
1282 
1283   if (!AllowMultipleUsers) {
1284     // If multiple users are using the root value, proceed with
1285     // simplification conservatively assuming that all elements
1286     // are needed.
1287     if (!V->hasOneUse()) {
1288       // Quit if we find multiple users of a non-root value though.
1289       // They'll be handled when it's their turn to be visited by
1290       // the main instcombine process.
1291       if (Depth != 0)
1292         // TODO: Just compute the UndefElts information recursively.
1293         return nullptr;
1294 
1295       // Conservatively assume that all elements are needed.
1296       DemandedElts = EltMask;
1297     }
1298   }
1299 
1300   Instruction *I = dyn_cast<Instruction>(V);
1301   if (!I) return nullptr;        // Only analyze instructions.
1302 
1303   bool MadeChange = false;
1304   auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1305                               APInt Demanded, APInt &Undef) {
1306     auto *II = dyn_cast<IntrinsicInst>(Inst);
1307     Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1308     if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1309       replaceOperand(*Inst, OpNum, V);
1310       MadeChange = true;
1311     }
1312   };
1313 
1314   APInt UndefElts2(VWidth, 0);
1315   APInt UndefElts3(VWidth, 0);
1316   switch (I->getOpcode()) {
1317   default: break;
1318 
1319   case Instruction::GetElementPtr: {
1320     // The LangRef requires that struct geps have all constant indices.  As
1321     // such, we can't convert any operand to partial undef.
1322     auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1323       for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1324            I != E; I++)
1325         if (I.isStruct())
1326           return true;;
1327       return false;
1328     };
1329     if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1330       break;
1331 
1332     // Conservatively track the demanded elements back through any vector
1333     // operands we may have.  We know there must be at least one, or we
1334     // wouldn't have a vector result to get here. Note that we intentionally
1335     // merge the undef bits here since gepping with either an undef base or
1336     // index results in undef.
1337     for (unsigned i = 0; i < I->getNumOperands(); i++) {
1338       if (isa<UndefValue>(I->getOperand(i))) {
1339         // If the entire vector is undefined, just return this info.
1340         UndefElts = EltMask;
1341         return nullptr;
1342       }
1343       if (I->getOperand(i)->getType()->isVectorTy()) {
1344         APInt UndefEltsOp(VWidth, 0);
1345         simplifyAndSetOp(I, i, DemandedElts, UndefEltsOp);
1346         UndefElts |= UndefEltsOp;
1347       }
1348     }
1349 
1350     break;
1351   }
1352   case Instruction::InsertElement: {
1353     // If this is a variable index, we don't know which element it overwrites.
1354     // demand exactly the same input as we produce.
1355     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1356     if (!Idx) {
1357       // Note that we can't propagate undef elt info, because we don't know
1358       // which elt is getting updated.
1359       simplifyAndSetOp(I, 0, DemandedElts, UndefElts2);
1360       break;
1361     }
1362 
1363     // The element inserted overwrites whatever was there, so the input demanded
1364     // set is simpler than the output set.
1365     unsigned IdxNo = Idx->getZExtValue();
1366     APInt PreInsertDemandedElts = DemandedElts;
1367     if (IdxNo < VWidth)
1368       PreInsertDemandedElts.clearBit(IdxNo);
1369 
1370     simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts);
1371 
1372     // If this is inserting an element that isn't demanded, remove this
1373     // insertelement.
1374     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1375       Worklist.push(I);
1376       return I->getOperand(0);
1377     }
1378 
1379     // The inserted element is defined.
1380     UndefElts.clearBit(IdxNo);
1381     break;
1382   }
1383   case Instruction::ShuffleVector: {
1384     auto *Shuffle = cast<ShuffleVectorInst>(I);
1385     assert(Shuffle->getOperand(0)->getType() ==
1386            Shuffle->getOperand(1)->getType() &&
1387            "Expected shuffle operands to have same type");
1388     unsigned OpWidth =
1389         Shuffle->getOperand(0)->getType()->getVectorNumElements();
1390     // Handle trivial case of a splat. Only check the first element of LHS
1391     // operand.
1392     if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1393         DemandedElts.isAllOnesValue()) {
1394       if (!isa<UndefValue>(I->getOperand(1))) {
1395         I->setOperand(1, UndefValue::get(I->getOperand(1)->getType()));
1396         MadeChange = true;
1397       }
1398       APInt LeftDemanded(OpWidth, 1);
1399       APInt LHSUndefElts(OpWidth, 0);
1400       simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1401       if (LHSUndefElts[0])
1402         UndefElts = EltMask;
1403       else
1404         UndefElts.clearAllBits();
1405       break;
1406     }
1407 
1408     APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1409     for (unsigned i = 0; i < VWidth; i++) {
1410       if (DemandedElts[i]) {
1411         unsigned MaskVal = Shuffle->getMaskValue(i);
1412         if (MaskVal != -1u) {
1413           assert(MaskVal < OpWidth * 2 &&
1414                  "shufflevector mask index out of range!");
1415           if (MaskVal < OpWidth)
1416             LeftDemanded.setBit(MaskVal);
1417           else
1418             RightDemanded.setBit(MaskVal - OpWidth);
1419         }
1420       }
1421     }
1422 
1423     APInt LHSUndefElts(OpWidth, 0);
1424     simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1425 
1426     APInt RHSUndefElts(OpWidth, 0);
1427     simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts);
1428 
1429     // If this shuffle does not change the vector length and the elements
1430     // demanded by this shuffle are an identity mask, then this shuffle is
1431     // unnecessary.
1432     //
1433     // We are assuming canonical form for the mask, so the source vector is
1434     // operand 0 and operand 1 is not used.
1435     //
1436     // Note that if an element is demanded and this shuffle mask is undefined
1437     // for that element, then the shuffle is not considered an identity
1438     // operation. The shuffle prevents poison from the operand vector from
1439     // leaking to the result by replacing poison with an undefined value.
1440     if (VWidth == OpWidth) {
1441       bool IsIdentityShuffle = true;
1442       for (unsigned i = 0; i < VWidth; i++) {
1443         unsigned MaskVal = Shuffle->getMaskValue(i);
1444         if (DemandedElts[i] && i != MaskVal) {
1445           IsIdentityShuffle = false;
1446           break;
1447         }
1448       }
1449       if (IsIdentityShuffle)
1450         return Shuffle->getOperand(0);
1451     }
1452 
1453     bool NewUndefElts = false;
1454     unsigned LHSIdx = -1u, LHSValIdx = -1u;
1455     unsigned RHSIdx = -1u, RHSValIdx = -1u;
1456     bool LHSUniform = true;
1457     bool RHSUniform = true;
1458     for (unsigned i = 0; i < VWidth; i++) {
1459       unsigned MaskVal = Shuffle->getMaskValue(i);
1460       if (MaskVal == -1u) {
1461         UndefElts.setBit(i);
1462       } else if (!DemandedElts[i]) {
1463         NewUndefElts = true;
1464         UndefElts.setBit(i);
1465       } else if (MaskVal < OpWidth) {
1466         if (LHSUndefElts[MaskVal]) {
1467           NewUndefElts = true;
1468           UndefElts.setBit(i);
1469         } else {
1470           LHSIdx = LHSIdx == -1u ? i : OpWidth;
1471           LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1472           LHSUniform = LHSUniform && (MaskVal == i);
1473         }
1474       } else {
1475         if (RHSUndefElts[MaskVal - OpWidth]) {
1476           NewUndefElts = true;
1477           UndefElts.setBit(i);
1478         } else {
1479           RHSIdx = RHSIdx == -1u ? i : OpWidth;
1480           RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1481           RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1482         }
1483       }
1484     }
1485 
1486     // Try to transform shuffle with constant vector and single element from
1487     // this constant vector to single insertelement instruction.
1488     // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1489     // insertelement V, C[ci], ci-n
1490     if (OpWidth == Shuffle->getType()->getNumElements()) {
1491       Value *Op = nullptr;
1492       Constant *Value = nullptr;
1493       unsigned Idx = -1u;
1494 
1495       // Find constant vector with the single element in shuffle (LHS or RHS).
1496       if (LHSIdx < OpWidth && RHSUniform) {
1497         if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1498           Op = Shuffle->getOperand(1);
1499           Value = CV->getOperand(LHSValIdx);
1500           Idx = LHSIdx;
1501         }
1502       }
1503       if (RHSIdx < OpWidth && LHSUniform) {
1504         if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1505           Op = Shuffle->getOperand(0);
1506           Value = CV->getOperand(RHSValIdx);
1507           Idx = RHSIdx;
1508         }
1509       }
1510       // Found constant vector with single element - convert to insertelement.
1511       if (Op && Value) {
1512         Instruction *New = InsertElementInst::Create(
1513             Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx),
1514             Shuffle->getName());
1515         InsertNewInstWith(New, *Shuffle);
1516         return New;
1517       }
1518     }
1519     if (NewUndefElts) {
1520       // Add additional discovered undefs.
1521       SmallVector<int, 16> Elts;
1522       for (unsigned i = 0; i < VWidth; ++i) {
1523         if (UndefElts[i])
1524           Elts.push_back(UndefMaskElem);
1525         else
1526           Elts.push_back(Shuffle->getMaskValue(i));
1527       }
1528       Shuffle->setShuffleMask(Elts);
1529       MadeChange = true;
1530     }
1531     break;
1532   }
1533   case Instruction::Select: {
1534     // If this is a vector select, try to transform the select condition based
1535     // on the current demanded elements.
1536     SelectInst *Sel = cast<SelectInst>(I);
1537     if (Sel->getCondition()->getType()->isVectorTy()) {
1538       // TODO: We are not doing anything with UndefElts based on this call.
1539       // It is overwritten below based on the other select operands. If an
1540       // element of the select condition is known undef, then we are free to
1541       // choose the output value from either arm of the select. If we know that
1542       // one of those values is undef, then the output can be undef.
1543       simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1544     }
1545 
1546     // Next, see if we can transform the arms of the select.
1547     APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1548     if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1549       for (unsigned i = 0; i < VWidth; i++) {
1550         // isNullValue() always returns false when called on a ConstantExpr.
1551         // Skip constant expressions to avoid propagating incorrect information.
1552         Constant *CElt = CV->getAggregateElement(i);
1553         if (isa<ConstantExpr>(CElt))
1554           continue;
1555         // TODO: If a select condition element is undef, we can demand from
1556         // either side. If one side is known undef, choosing that side would
1557         // propagate undef.
1558         if (CElt->isNullValue())
1559           DemandedLHS.clearBit(i);
1560         else
1561           DemandedRHS.clearBit(i);
1562       }
1563     }
1564 
1565     simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2);
1566     simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3);
1567 
1568     // Output elements are undefined if the element from each arm is undefined.
1569     // TODO: This can be improved. See comment in select condition handling.
1570     UndefElts = UndefElts2 & UndefElts3;
1571     break;
1572   }
1573   case Instruction::BitCast: {
1574     // Vector->vector casts only.
1575     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1576     if (!VTy) break;
1577     unsigned InVWidth = VTy->getNumElements();
1578     APInt InputDemandedElts(InVWidth, 0);
1579     UndefElts2 = APInt(InVWidth, 0);
1580     unsigned Ratio;
1581 
1582     if (VWidth == InVWidth) {
1583       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1584       // elements as are demanded of us.
1585       Ratio = 1;
1586       InputDemandedElts = DemandedElts;
1587     } else if ((VWidth % InVWidth) == 0) {
1588       // If the number of elements in the output is a multiple of the number of
1589       // elements in the input then an input element is live if any of the
1590       // corresponding output elements are live.
1591       Ratio = VWidth / InVWidth;
1592       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1593         if (DemandedElts[OutIdx])
1594           InputDemandedElts.setBit(OutIdx / Ratio);
1595     } else if ((InVWidth % VWidth) == 0) {
1596       // If the number of elements in the input is a multiple of the number of
1597       // elements in the output then an input element is live if the
1598       // corresponding output element is live.
1599       Ratio = InVWidth / VWidth;
1600       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1601         if (DemandedElts[InIdx / Ratio])
1602           InputDemandedElts.setBit(InIdx);
1603     } else {
1604       // Unsupported so far.
1605       break;
1606     }
1607 
1608     simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2);
1609 
1610     if (VWidth == InVWidth) {
1611       UndefElts = UndefElts2;
1612     } else if ((VWidth % InVWidth) == 0) {
1613       // If the number of elements in the output is a multiple of the number of
1614       // elements in the input then an output element is undef if the
1615       // corresponding input element is undef.
1616       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1617         if (UndefElts2[OutIdx / Ratio])
1618           UndefElts.setBit(OutIdx);
1619     } else if ((InVWidth % VWidth) == 0) {
1620       // If the number of elements in the input is a multiple of the number of
1621       // elements in the output then an output element is undef if all of the
1622       // corresponding input elements are undef.
1623       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1624         APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1625         if (SubUndef.countPopulation() == Ratio)
1626           UndefElts.setBit(OutIdx);
1627       }
1628     } else {
1629       llvm_unreachable("Unimp");
1630     }
1631     break;
1632   }
1633   case Instruction::FPTrunc:
1634   case Instruction::FPExt:
1635     simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1636     break;
1637 
1638   case Instruction::Call: {
1639     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1640     if (!II) break;
1641     switch (II->getIntrinsicID()) {
1642     case Intrinsic::masked_gather: // fallthrough
1643     case Intrinsic::masked_load: {
1644       // Subtlety: If we load from a pointer, the pointer must be valid
1645       // regardless of whether the element is demanded.  Doing otherwise risks
1646       // segfaults which didn't exist in the original program.
1647       APInt DemandedPtrs(APInt::getAllOnesValue(VWidth)),
1648         DemandedPassThrough(DemandedElts);
1649       if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
1650         for (unsigned i = 0; i < VWidth; i++) {
1651           Constant *CElt = CV->getAggregateElement(i);
1652           if (CElt->isNullValue())
1653             DemandedPtrs.clearBit(i);
1654           else if (CElt->isAllOnesValue())
1655             DemandedPassThrough.clearBit(i);
1656         }
1657       if (II->getIntrinsicID() == Intrinsic::masked_gather)
1658         simplifyAndSetOp(II, 0, DemandedPtrs, UndefElts2);
1659       simplifyAndSetOp(II, 3, DemandedPassThrough, UndefElts3);
1660 
1661       // Output elements are undefined if the element from both sources are.
1662       // TODO: can strengthen via mask as well.
1663       UndefElts = UndefElts2 & UndefElts3;
1664       break;
1665     }
1666     case Intrinsic::x86_xop_vfrcz_ss:
1667     case Intrinsic::x86_xop_vfrcz_sd:
1668       // The instructions for these intrinsics are speced to zero upper bits not
1669       // pass them through like other scalar intrinsics. So we shouldn't just
1670       // use Arg0 if DemandedElts[0] is clear like we do for other intrinsics.
1671       // Instead we should return a zero vector.
1672       if (!DemandedElts[0]) {
1673         Worklist.push(II);
1674         return ConstantAggregateZero::get(II->getType());
1675       }
1676 
1677       // Only the lower element is used.
1678       DemandedElts = 1;
1679       simplifyAndSetOp(II, 0, DemandedElts, UndefElts);
1680 
1681       // Only the lower element is undefined. The high elements are zero.
1682       UndefElts = UndefElts[0];
1683       break;
1684 
1685     // Unary scalar-as-vector operations that work column-wise.
1686     case Intrinsic::x86_sse_rcp_ss:
1687     case Intrinsic::x86_sse_rsqrt_ss:
1688       simplifyAndSetOp(II, 0, DemandedElts, UndefElts);
1689 
1690       // If lowest element of a scalar op isn't used then use Arg0.
1691       if (!DemandedElts[0]) {
1692         Worklist.push(II);
1693         return II->getArgOperand(0);
1694       }
1695       // TODO: If only low elt lower SQRT to FSQRT (with rounding/exceptions
1696       // checks).
1697       break;
1698 
1699     // Binary scalar-as-vector operations that work column-wise. The high
1700     // elements come from operand 0. The low element is a function of both
1701     // operands.
1702     case Intrinsic::x86_sse_min_ss:
1703     case Intrinsic::x86_sse_max_ss:
1704     case Intrinsic::x86_sse_cmp_ss:
1705     case Intrinsic::x86_sse2_min_sd:
1706     case Intrinsic::x86_sse2_max_sd:
1707     case Intrinsic::x86_sse2_cmp_sd: {
1708       simplifyAndSetOp(II, 0, DemandedElts, UndefElts);
1709 
1710       // If lowest element of a scalar op isn't used then use Arg0.
1711       if (!DemandedElts[0]) {
1712         Worklist.push(II);
1713         return II->getArgOperand(0);
1714       }
1715 
1716       // Only lower element is used for operand 1.
1717       DemandedElts = 1;
1718       simplifyAndSetOp(II, 1, DemandedElts, UndefElts2);
1719 
1720       // Lower element is undefined if both lower elements are undefined.
1721       // Consider things like undef&0.  The result is known zero, not undef.
1722       if (!UndefElts2[0])
1723         UndefElts.clearBit(0);
1724 
1725       break;
1726     }
1727 
1728     // Binary scalar-as-vector operations that work column-wise. The high
1729     // elements come from operand 0 and the low element comes from operand 1.
1730     case Intrinsic::x86_sse41_round_ss:
1731     case Intrinsic::x86_sse41_round_sd: {
1732       // Don't use the low element of operand 0.
1733       APInt DemandedElts2 = DemandedElts;
1734       DemandedElts2.clearBit(0);
1735       simplifyAndSetOp(II, 0, DemandedElts2, UndefElts);
1736 
1737       // If lowest element of a scalar op isn't used then use Arg0.
1738       if (!DemandedElts[0]) {
1739         Worklist.push(II);
1740         return II->getArgOperand(0);
1741       }
1742 
1743       // Only lower element is used for operand 1.
1744       DemandedElts = 1;
1745       simplifyAndSetOp(II, 1, DemandedElts, UndefElts2);
1746 
1747       // Take the high undef elements from operand 0 and take the lower element
1748       // from operand 1.
1749       UndefElts.clearBit(0);
1750       UndefElts |= UndefElts2[0];
1751       break;
1752     }
1753 
1754     // Three input scalar-as-vector operations that work column-wise. The high
1755     // elements come from operand 0 and the low element is a function of all
1756     // three inputs.
1757     case Intrinsic::x86_avx512_mask_add_ss_round:
1758     case Intrinsic::x86_avx512_mask_div_ss_round:
1759     case Intrinsic::x86_avx512_mask_mul_ss_round:
1760     case Intrinsic::x86_avx512_mask_sub_ss_round:
1761     case Intrinsic::x86_avx512_mask_max_ss_round:
1762     case Intrinsic::x86_avx512_mask_min_ss_round:
1763     case Intrinsic::x86_avx512_mask_add_sd_round:
1764     case Intrinsic::x86_avx512_mask_div_sd_round:
1765     case Intrinsic::x86_avx512_mask_mul_sd_round:
1766     case Intrinsic::x86_avx512_mask_sub_sd_round:
1767     case Intrinsic::x86_avx512_mask_max_sd_round:
1768     case Intrinsic::x86_avx512_mask_min_sd_round:
1769       simplifyAndSetOp(II, 0, DemandedElts, UndefElts);
1770 
1771       // If lowest element of a scalar op isn't used then use Arg0.
1772       if (!DemandedElts[0]) {
1773         Worklist.push(II);
1774         return II->getArgOperand(0);
1775       }
1776 
1777       // Only lower element is used for operand 1 and 2.
1778       DemandedElts = 1;
1779       simplifyAndSetOp(II, 1, DemandedElts, UndefElts2);
1780       simplifyAndSetOp(II, 2, DemandedElts, UndefElts3);
1781 
1782       // Lower element is undefined if all three lower elements are undefined.
1783       // Consider things like undef&0.  The result is known zero, not undef.
1784       if (!UndefElts2[0] || !UndefElts3[0])
1785         UndefElts.clearBit(0);
1786 
1787       break;
1788 
1789     case Intrinsic::x86_sse2_packssdw_128:
1790     case Intrinsic::x86_sse2_packsswb_128:
1791     case Intrinsic::x86_sse2_packuswb_128:
1792     case Intrinsic::x86_sse41_packusdw:
1793     case Intrinsic::x86_avx2_packssdw:
1794     case Intrinsic::x86_avx2_packsswb:
1795     case Intrinsic::x86_avx2_packusdw:
1796     case Intrinsic::x86_avx2_packuswb:
1797     case Intrinsic::x86_avx512_packssdw_512:
1798     case Intrinsic::x86_avx512_packsswb_512:
1799     case Intrinsic::x86_avx512_packusdw_512:
1800     case Intrinsic::x86_avx512_packuswb_512: {
1801       auto *Ty0 = II->getArgOperand(0)->getType();
1802       unsigned InnerVWidth = Ty0->getVectorNumElements();
1803       assert(VWidth == (InnerVWidth * 2) && "Unexpected input size");
1804 
1805       unsigned NumLanes = Ty0->getPrimitiveSizeInBits() / 128;
1806       unsigned VWidthPerLane = VWidth / NumLanes;
1807       unsigned InnerVWidthPerLane = InnerVWidth / NumLanes;
1808 
1809       // Per lane, pack the elements of the first input and then the second.
1810       // e.g.
1811       // v8i16 PACK(v4i32 X, v4i32 Y) - (X[0..3],Y[0..3])
1812       // v32i8 PACK(v16i16 X, v16i16 Y) - (X[0..7],Y[0..7]),(X[8..15],Y[8..15])
1813       for (int OpNum = 0; OpNum != 2; ++OpNum) {
1814         APInt OpDemandedElts(InnerVWidth, 0);
1815         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1816           unsigned LaneIdx = Lane * VWidthPerLane;
1817           for (unsigned Elt = 0; Elt != InnerVWidthPerLane; ++Elt) {
1818             unsigned Idx = LaneIdx + Elt + InnerVWidthPerLane * OpNum;
1819             if (DemandedElts[Idx])
1820               OpDemandedElts.setBit((Lane * InnerVWidthPerLane) + Elt);
1821           }
1822         }
1823 
1824         // Demand elements from the operand.
1825         APInt OpUndefElts(InnerVWidth, 0);
1826         simplifyAndSetOp(II, OpNum, OpDemandedElts, OpUndefElts);
1827 
1828         // Pack the operand's UNDEF elements, one lane at a time.
1829         OpUndefElts = OpUndefElts.zext(VWidth);
1830         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1831           APInt LaneElts = OpUndefElts.lshr(InnerVWidthPerLane * Lane);
1832           LaneElts = LaneElts.getLoBits(InnerVWidthPerLane);
1833           LaneElts <<= InnerVWidthPerLane * (2 * Lane + OpNum);
1834           UndefElts |= LaneElts;
1835         }
1836       }
1837       break;
1838     }
1839 
1840     // PSHUFB
1841     case Intrinsic::x86_ssse3_pshuf_b_128:
1842     case Intrinsic::x86_avx2_pshuf_b:
1843     case Intrinsic::x86_avx512_pshuf_b_512:
1844     // PERMILVAR
1845     case Intrinsic::x86_avx_vpermilvar_ps:
1846     case Intrinsic::x86_avx_vpermilvar_ps_256:
1847     case Intrinsic::x86_avx512_vpermilvar_ps_512:
1848     case Intrinsic::x86_avx_vpermilvar_pd:
1849     case Intrinsic::x86_avx_vpermilvar_pd_256:
1850     case Intrinsic::x86_avx512_vpermilvar_pd_512:
1851     // PERMV
1852     case Intrinsic::x86_avx2_permd:
1853     case Intrinsic::x86_avx2_permps: {
1854       simplifyAndSetOp(II, 1, DemandedElts, UndefElts);
1855       break;
1856     }
1857 
1858     // SSE4A instructions leave the upper 64-bits of the 128-bit result
1859     // in an undefined state.
1860     case Intrinsic::x86_sse4a_extrq:
1861     case Intrinsic::x86_sse4a_extrqi:
1862     case Intrinsic::x86_sse4a_insertq:
1863     case Intrinsic::x86_sse4a_insertqi:
1864       UndefElts.setHighBits(VWidth / 2);
1865       break;
1866     case Intrinsic::amdgcn_buffer_load:
1867     case Intrinsic::amdgcn_buffer_load_format:
1868     case Intrinsic::amdgcn_raw_buffer_load:
1869     case Intrinsic::amdgcn_raw_buffer_load_format:
1870     case Intrinsic::amdgcn_raw_tbuffer_load:
1871     case Intrinsic::amdgcn_s_buffer_load:
1872     case Intrinsic::amdgcn_struct_buffer_load:
1873     case Intrinsic::amdgcn_struct_buffer_load_format:
1874     case Intrinsic::amdgcn_struct_tbuffer_load:
1875     case Intrinsic::amdgcn_tbuffer_load:
1876       return simplifyAMDGCNMemoryIntrinsicDemanded(II, DemandedElts);
1877     default: {
1878       if (getAMDGPUImageDMaskIntrinsic(II->getIntrinsicID()))
1879         return simplifyAMDGCNMemoryIntrinsicDemanded(II, DemandedElts, 0);
1880 
1881       break;
1882     }
1883     } // switch on IntrinsicID
1884     break;
1885   } // case Call
1886   } // switch on Opcode
1887 
1888   // TODO: We bail completely on integer div/rem and shifts because they have
1889   // UB/poison potential, but that should be refined.
1890   BinaryOperator *BO;
1891   if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1892     simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1893     simplifyAndSetOp(I, 1, DemandedElts, UndefElts2);
1894 
1895     // Any change to an instruction with potential poison must clear those flags
1896     // because we can not guarantee those constraints now. Other analysis may
1897     // determine that it is safe to re-apply the flags.
1898     if (MadeChange)
1899       BO->dropPoisonGeneratingFlags();
1900 
1901     // Output elements are undefined if both are undefined. Consider things
1902     // like undef & 0. The result is known zero, not undef.
1903     UndefElts &= UndefElts2;
1904   }
1905 
1906   // If we've proven all of the lanes undef, return an undef value.
1907   // TODO: Intersect w/demanded lanes
1908   if (UndefElts.isAllOnesValue())
1909     return UndefValue::get(I->getType());;
1910 
1911   return MadeChange ? I : nullptr;
1912 }
1913