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