1 //===- InstCombineCasts.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 implements the visit functions for cast operations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/PatternMatch.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 using namespace llvm;
20 using namespace PatternMatch;
21 
22 #define DEBUG_TYPE "instcombine"
23 
24 /// Analyze 'Val', seeing if it is a simple linear expression.
25 /// If so, decompose it, returning some value X, such that Val is
26 /// X*Scale+Offset.
27 ///
28 static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
29                                         uint64_t &Offset) {
30   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
31     Offset = CI->getZExtValue();
32     Scale  = 0;
33     return ConstantInt::get(Val->getType(), 0);
34   }
35 
36   if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
37     // Cannot look past anything that might overflow.
38     OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
39     if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
40       Scale = 1;
41       Offset = 0;
42       return Val;
43     }
44 
45     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
46       if (I->getOpcode() == Instruction::Shl) {
47         // This is a value scaled by '1 << the shift amt'.
48         Scale = UINT64_C(1) << RHS->getZExtValue();
49         Offset = 0;
50         return I->getOperand(0);
51       }
52 
53       if (I->getOpcode() == Instruction::Mul) {
54         // This value is scaled by 'RHS'.
55         Scale = RHS->getZExtValue();
56         Offset = 0;
57         return I->getOperand(0);
58       }
59 
60       if (I->getOpcode() == Instruction::Add) {
61         // We have X+C.  Check to see if we really have (X*C2)+C1,
62         // where C1 is divisible by C2.
63         unsigned SubScale;
64         Value *SubVal =
65           decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
66         Offset += RHS->getZExtValue();
67         Scale = SubScale;
68         return SubVal;
69       }
70     }
71   }
72 
73   // Otherwise, we can't look past this.
74   Scale = 1;
75   Offset = 0;
76   return Val;
77 }
78 
79 /// If we find a cast of an allocation instruction, try to eliminate the cast by
80 /// moving the type information into the alloc.
81 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
82                                                    AllocaInst &AI) {
83   PointerType *PTy = cast<PointerType>(CI.getType());
84 
85   BuilderTy AllocaBuilder(*Builder);
86   AllocaBuilder.SetInsertPoint(&AI);
87 
88   // Get the type really allocated and the type casted to.
89   Type *AllocElTy = AI.getAllocatedType();
90   Type *CastElTy = PTy->getElementType();
91   if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
92 
93   unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy);
94   unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy);
95   if (CastElTyAlign < AllocElTyAlign) return nullptr;
96 
97   // If the allocation has multiple uses, only promote it if we are strictly
98   // increasing the alignment of the resultant allocation.  If we keep it the
99   // same, we open the door to infinite loops of various kinds.
100   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
101 
102   uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy);
103   uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy);
104   if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
105 
106   // If the allocation has multiple uses, only promote it if we're not
107   // shrinking the amount of memory being allocated.
108   uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy);
109   uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy);
110   if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
111 
112   // See if we can satisfy the modulus by pulling a scale out of the array
113   // size argument.
114   unsigned ArraySizeScale;
115   uint64_t ArrayOffset;
116   Value *NumElements = // See if the array size is a decomposable linear expr.
117     decomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
118 
119   // If we can now satisfy the modulus, by using a non-1 scale, we really can
120   // do the xform.
121   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
122       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return nullptr;
123 
124   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
125   Value *Amt = nullptr;
126   if (Scale == 1) {
127     Amt = NumElements;
128   } else {
129     Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
130     // Insert before the alloca, not before the cast.
131     Amt = AllocaBuilder.CreateMul(Amt, NumElements);
132   }
133 
134   if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
135     Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
136                                   Offset, true);
137     Amt = AllocaBuilder.CreateAdd(Amt, Off);
138   }
139 
140   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
141   New->setAlignment(AI.getAlignment());
142   New->takeName(&AI);
143   New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
144 
145   // If the allocation has multiple real uses, insert a cast and change all
146   // things that used it to use the new cast.  This will also hack on CI, but it
147   // will die soon.
148   if (!AI.hasOneUse()) {
149     // New is the allocation instruction, pointer typed. AI is the original
150     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
151     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
152     replaceInstUsesWith(AI, NewCast);
153   }
154   return replaceInstUsesWith(CI, New);
155 }
156 
157 /// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns
158 /// true for, actually insert the code to evaluate the expression.
159 Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
160                                              bool isSigned) {
161   if (Constant *C = dyn_cast<Constant>(V)) {
162     C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
163     // If we got a constantexpr back, try to simplify it with DL info.
164     if (Constant *FoldedC = ConstantFoldConstant(C, DL, &TLI))
165       C = FoldedC;
166     return C;
167   }
168 
169   // Otherwise, it must be an instruction.
170   Instruction *I = cast<Instruction>(V);
171   Instruction *Res = nullptr;
172   unsigned Opc = I->getOpcode();
173   switch (Opc) {
174   case Instruction::Add:
175   case Instruction::Sub:
176   case Instruction::Mul:
177   case Instruction::And:
178   case Instruction::Or:
179   case Instruction::Xor:
180   case Instruction::AShr:
181   case Instruction::LShr:
182   case Instruction::Shl:
183   case Instruction::UDiv:
184   case Instruction::URem: {
185     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
186     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
187     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
188     break;
189   }
190   case Instruction::Trunc:
191   case Instruction::ZExt:
192   case Instruction::SExt:
193     // If the source type of the cast is the type we're trying for then we can
194     // just return the source.  There's no need to insert it because it is not
195     // new.
196     if (I->getOperand(0)->getType() == Ty)
197       return I->getOperand(0);
198 
199     // Otherwise, must be the same type of cast, so just reinsert a new one.
200     // This also handles the case of zext(trunc(x)) -> zext(x).
201     Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
202                                       Opc == Instruction::SExt);
203     break;
204   case Instruction::Select: {
205     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
206     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
207     Res = SelectInst::Create(I->getOperand(0), True, False);
208     break;
209   }
210   case Instruction::PHI: {
211     PHINode *OPN = cast<PHINode>(I);
212     PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
213     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
214       Value *V =
215           EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
216       NPN->addIncoming(V, OPN->getIncomingBlock(i));
217     }
218     Res = NPN;
219     break;
220   }
221   default:
222     // TODO: Can handle more cases here.
223     llvm_unreachable("Unreachable!");
224   }
225 
226   Res->takeName(I);
227   return InsertNewInstWith(Res, *I);
228 }
229 
230 Instruction::CastOps InstCombiner::isEliminableCastPair(const CastInst *CI1,
231                                                         const CastInst *CI2) {
232   Type *SrcTy = CI1->getSrcTy();
233   Type *MidTy = CI1->getDestTy();
234   Type *DstTy = CI2->getDestTy();
235 
236   Instruction::CastOps firstOp = Instruction::CastOps(CI1->getOpcode());
237   Instruction::CastOps secondOp = Instruction::CastOps(CI2->getOpcode());
238   Type *SrcIntPtrTy =
239       SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
240   Type *MidIntPtrTy =
241       MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
242   Type *DstIntPtrTy =
243       DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
244   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
245                                                 DstTy, SrcIntPtrTy, MidIntPtrTy,
246                                                 DstIntPtrTy);
247 
248   // We don't want to form an inttoptr or ptrtoint that converts to an integer
249   // type that differs from the pointer size.
250   if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
251       (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
252     Res = 0;
253 
254   return Instruction::CastOps(Res);
255 }
256 
257 /// @brief Implement the transforms common to all CastInst visitors.
258 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
259   Value *Src = CI.getOperand(0);
260 
261   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
262   // eliminate it now.
263   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
264     if (Instruction::CastOps opc =
265             isEliminableCastPair(CSrc, &CI)) {
266       // The first cast (CSrc) is eliminable so we need to fix up or replace
267       // the second cast (CI). CSrc will then have a good chance of being dead.
268       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
269     }
270   }
271 
272   // If we are casting a select then fold the cast into the select
273   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
274     if (Instruction *NV = FoldOpIntoSelect(CI, SI))
275       return NV;
276 
277   // If we are casting a PHI then fold the cast into the PHI
278   if (isa<PHINode>(Src)) {
279     // We don't do this if this would create a PHI node with an illegal type if
280     // it is currently legal.
281     if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
282         ShouldChangeType(CI.getType(), Src->getType()))
283       if (Instruction *NV = FoldOpIntoPhi(CI))
284         return NV;
285   }
286 
287   return nullptr;
288 }
289 
290 /// Return true if we can evaluate the specified expression tree as type Ty
291 /// instead of its larger type, and arrive with the same value.
292 /// This is used by code that tries to eliminate truncates.
293 ///
294 /// Ty will always be a type smaller than V.  We should return true if trunc(V)
295 /// can be computed by computing V in the smaller type.  If V is an instruction,
296 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
297 /// makes sense if x and y can be efficiently truncated.
298 ///
299 /// This function works on both vectors and scalars.
300 ///
301 static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC,
302                                  Instruction *CxtI) {
303   // We can always evaluate constants in another type.
304   if (isa<Constant>(V))
305     return true;
306 
307   Instruction *I = dyn_cast<Instruction>(V);
308   if (!I) return false;
309 
310   Type *OrigTy = V->getType();
311 
312   // If this is an extension from the dest type, we can eliminate it, even if it
313   // has multiple uses.
314   if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
315       I->getOperand(0)->getType() == Ty)
316     return true;
317 
318   // We can't extend or shrink something that has multiple uses: doing so would
319   // require duplicating the instruction in general, which isn't profitable.
320   if (!I->hasOneUse()) return false;
321 
322   unsigned Opc = I->getOpcode();
323   switch (Opc) {
324   case Instruction::Add:
325   case Instruction::Sub:
326   case Instruction::Mul:
327   case Instruction::And:
328   case Instruction::Or:
329   case Instruction::Xor:
330     // These operators can all arbitrarily be extended or truncated.
331     return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
332            canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
333 
334   case Instruction::UDiv:
335   case Instruction::URem: {
336     // UDiv and URem can be truncated if all the truncated bits are zero.
337     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
338     uint32_t BitWidth = Ty->getScalarSizeInBits();
339     if (BitWidth < OrigBitWidth) {
340       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
341       if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
342           IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
343         return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
344                canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
345       }
346     }
347     break;
348   }
349   case Instruction::Shl:
350     // If we are truncating the result of this SHL, and if it's a shift of a
351     // constant amount, we can always perform a SHL in a smaller type.
352     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
353       uint32_t BitWidth = Ty->getScalarSizeInBits();
354       if (CI->getLimitedValue(BitWidth) < BitWidth)
355         return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
356     }
357     break;
358   case Instruction::LShr:
359     // If this is a truncate of a logical shr, we can truncate it to a smaller
360     // lshr iff we know that the bits we would otherwise be shifting in are
361     // already zeros.
362     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
363       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
364       uint32_t BitWidth = Ty->getScalarSizeInBits();
365       if (IC.MaskedValueIsZero(I->getOperand(0),
366             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth), 0, CxtI) &&
367           CI->getLimitedValue(BitWidth) < BitWidth) {
368         return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
369       }
370     }
371     break;
372   case Instruction::Trunc:
373     // trunc(trunc(x)) -> trunc(x)
374     return true;
375   case Instruction::ZExt:
376   case Instruction::SExt:
377     // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
378     // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
379     return true;
380   case Instruction::Select: {
381     SelectInst *SI = cast<SelectInst>(I);
382     return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
383            canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
384   }
385   case Instruction::PHI: {
386     // We can change a phi if we can change all operands.  Note that we never
387     // get into trouble with cyclic PHIs here because we only consider
388     // instructions with a single use.
389     PHINode *PN = cast<PHINode>(I);
390     for (Value *IncValue : PN->incoming_values())
391       if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI))
392         return false;
393     return true;
394   }
395   default:
396     // TODO: Can handle more cases here.
397     break;
398   }
399 
400   return false;
401 }
402 
403 /// Given a vector that is bitcast to an integer, optionally logically
404 /// right-shifted, and truncated, convert it to an extractelement.
405 /// Example (big endian):
406 ///   trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32
407 ///   --->
408 ///   extractelement <4 x i32> %X, 1
409 static Instruction *foldVecTruncToExtElt(TruncInst &Trunc, InstCombiner &IC,
410                                          const DataLayout &DL) {
411   Value *TruncOp = Trunc.getOperand(0);
412   Type *DestType = Trunc.getType();
413   if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType))
414     return nullptr;
415 
416   Value *VecInput = nullptr;
417   ConstantInt *ShiftVal = nullptr;
418   if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)),
419                                   m_LShr(m_BitCast(m_Value(VecInput)),
420                                          m_ConstantInt(ShiftVal)))) ||
421       !isa<VectorType>(VecInput->getType()))
422     return nullptr;
423 
424   VectorType *VecType = cast<VectorType>(VecInput->getType());
425   unsigned VecWidth = VecType->getPrimitiveSizeInBits();
426   unsigned DestWidth = DestType->getPrimitiveSizeInBits();
427   unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0;
428 
429   if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0))
430     return nullptr;
431 
432   // If the element type of the vector doesn't match the result type,
433   // bitcast it to a vector type that we can extract from.
434   unsigned NumVecElts = VecWidth / DestWidth;
435   if (VecType->getElementType() != DestType) {
436     VecType = VectorType::get(DestType, NumVecElts);
437     VecInput = IC.Builder->CreateBitCast(VecInput, VecType, "bc");
438   }
439 
440   unsigned Elt = ShiftAmount / DestWidth;
441   if (DL.isBigEndian())
442     Elt = NumVecElts - 1 - Elt;
443 
444   return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
445 }
446 
447 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
448   if (Instruction *Result = commonCastTransforms(CI))
449     return Result;
450 
451   // Test if the trunc is the user of a select which is part of a
452   // minimum or maximum operation. If so, don't do any more simplification.
453   // Even simplifying demanded bits can break the canonical form of a
454   // min/max.
455   Value *LHS, *RHS;
456   if (SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0)))
457     if (matchSelectPattern(SI, LHS, RHS).Flavor != SPF_UNKNOWN)
458       return nullptr;
459 
460   // See if we can simplify any instructions used by the input whose sole
461   // purpose is to compute bits we don't care about.
462   if (SimplifyDemandedInstructionBits(CI))
463     return &CI;
464 
465   Value *Src = CI.getOperand(0);
466   Type *DestTy = CI.getType(), *SrcTy = Src->getType();
467 
468   // Attempt to truncate the entire input expression tree to the destination
469   // type.   Only do this if the dest type is a simple type, don't convert the
470   // expression tree to something weird like i93 unless the source is also
471   // strange.
472   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
473       canEvaluateTruncated(Src, DestTy, *this, &CI)) {
474 
475     // If this cast is a truncate, evaluting in a different type always
476     // eliminates the cast, so it is always a win.
477     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
478           " to avoid cast: " << CI << '\n');
479     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
480     assert(Res->getType() == DestTy);
481     return replaceInstUsesWith(CI, Res);
482   }
483 
484   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
485   if (DestTy->getScalarSizeInBits() == 1) {
486     Constant *One = ConstantInt::get(SrcTy, 1);
487     Src = Builder->CreateAnd(Src, One);
488     Value *Zero = Constant::getNullValue(Src->getType());
489     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
490   }
491 
492   // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
493   Value *A = nullptr; ConstantInt *Cst = nullptr;
494   if (Src->hasOneUse() &&
495       match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
496     // We have three types to worry about here, the type of A, the source of
497     // the truncate (MidSize), and the destination of the truncate. We know that
498     // ASize < MidSize   and MidSize > ResultSize, but don't know the relation
499     // between ASize and ResultSize.
500     unsigned ASize = A->getType()->getPrimitiveSizeInBits();
501 
502     // If the shift amount is larger than the size of A, then the result is
503     // known to be zero because all the input bits got shifted out.
504     if (Cst->getZExtValue() >= ASize)
505       return replaceInstUsesWith(CI, Constant::getNullValue(DestTy));
506 
507     // Since we're doing an lshr and a zero extend, and know that the shift
508     // amount is smaller than ASize, it is always safe to do the shift in A's
509     // type, then zero extend or truncate to the result.
510     Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
511     Shift->takeName(Src);
512     return CastInst::CreateIntegerCast(Shift, DestTy, false);
513   }
514 
515   // Transform trunc(lshr (sext A), Cst) to ashr A, Cst to eliminate type
516   // conversion.
517   // It works because bits coming from sign extension have the same value as
518   // the sign bit of the original value; performing ashr instead of lshr
519   // generates bits of the same value as the sign bit.
520   if (Src->hasOneUse() &&
521       match(Src, m_LShr(m_SExt(m_Value(A)), m_ConstantInt(Cst))) &&
522       cast<Instruction>(Src)->getOperand(0)->hasOneUse()) {
523     const unsigned ASize = A->getType()->getPrimitiveSizeInBits();
524     // This optimization can be only performed when zero bits generated by
525     // the original lshr aren't pulled into the value after truncation, so we
526     // can only shift by values smaller than the size of destination type (in
527     // bits).
528     if (Cst->getValue().ult(ASize)) {
529       Value *Shift = Builder->CreateAShr(A, Cst->getZExtValue());
530       Shift->takeName(Src);
531       return CastInst::CreateIntegerCast(Shift, CI.getType(), true);
532     }
533   }
534 
535   if (Src->hasOneUse() && isa<IntegerType>(SrcTy) &&
536       ShouldChangeType(SrcTy, DestTy)) {
537 
538     // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the
539     // dest type is native.
540     if (match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
541       Value *NewTrunc = Builder->CreateTrunc(A, DestTy, A->getName() + ".tr");
542       return BinaryOperator::CreateAnd(NewTrunc,
543                                        ConstantExpr::getTrunc(Cst, DestTy));
544     }
545 
546     // Transform "trunc (shl X, cst)" -> "shl (trunc X), cst" so long as the
547     // dest type is native and cst < dest size.
548     if (match(Src, m_Shl(m_Value(A), m_ConstantInt(Cst))) &&
549         !match(A, m_Shr(m_Value(), m_Constant()))) {
550       // Skip shifts of shift by constants. It undoes a combine in
551       // FoldShiftByConstant and is the extend in reg pattern.
552       const unsigned DestSize = DestTy->getScalarSizeInBits();
553       if (Cst->getValue().ult(DestSize)) {
554         Value *NewTrunc = Builder->CreateTrunc(A, DestTy, A->getName() + ".tr");
555 
556         return BinaryOperator::Create(
557           Instruction::Shl, NewTrunc,
558           ConstantInt::get(DestTy, Cst->getValue().trunc(DestSize)));
559       }
560     }
561   }
562 
563   if (Instruction *I = foldVecTruncToExtElt(CI, *this, DL))
564     return I;
565 
566   return nullptr;
567 }
568 
569 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
570                                              bool DoTransform) {
571   // If we are just checking for a icmp eq of a single bit and zext'ing it
572   // to an integer, then shift the bit to the appropriate place and then
573   // cast to integer to avoid the comparison.
574   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
575     const APInt &Op1CV = Op1C->getValue();
576 
577     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
578     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
579     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
580         (ICI->getPredicate() == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
581       if (!DoTransform) return ICI;
582 
583       Value *In = ICI->getOperand(0);
584       Value *Sh = ConstantInt::get(In->getType(),
585                                    In->getType()->getScalarSizeInBits() - 1);
586       In = Builder->CreateLShr(In, Sh, In->getName() + ".lobit");
587       if (In->getType() != CI.getType())
588         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
589 
590       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
591         Constant *One = ConstantInt::get(In->getType(), 1);
592         In = Builder->CreateXor(In, One, In->getName() + ".not");
593       }
594 
595       return replaceInstUsesWith(CI, In);
596     }
597 
598     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
599     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
600     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
601     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
602     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
603     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
604     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
605     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
606     if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
607         // This only works for EQ and NE
608         ICI->isEquality()) {
609       // If Op1C some other power of two, convert:
610       uint32_t BitWidth = Op1C->getType()->getBitWidth();
611       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
612       computeKnownBits(ICI->getOperand(0), KnownZero, KnownOne, 0, &CI);
613 
614       APInt KnownZeroMask(~KnownZero);
615       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
616         if (!DoTransform) return ICI;
617 
618         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
619         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
620           // (X&4) == 2 --> false
621           // (X&4) != 2 --> true
622           Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
623                                            isNE);
624           Res = ConstantExpr::getZExt(Res, CI.getType());
625           return replaceInstUsesWith(CI, Res);
626         }
627 
628         uint32_t ShAmt = KnownZeroMask.logBase2();
629         Value *In = ICI->getOperand(0);
630         if (ShAmt) {
631           // Perform a logical shr by shiftamt.
632           // Insert the shift to put the result in the low bit.
633           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(), ShAmt),
634                                    In->getName() + ".lobit");
635         }
636 
637         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
638           Constant *One = ConstantInt::get(In->getType(), 1);
639           In = Builder->CreateXor(In, One);
640         }
641 
642         if (CI.getType() == In->getType())
643           return replaceInstUsesWith(CI, In);
644 
645         Value *IntCast = Builder->CreateIntCast(In, CI.getType(), false);
646         return replaceInstUsesWith(CI, IntCast);
647       }
648     }
649   }
650 
651   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
652   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
653   // may lead to additional simplifications.
654   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
655     if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
656       uint32_t BitWidth = ITy->getBitWidth();
657       Value *LHS = ICI->getOperand(0);
658       Value *RHS = ICI->getOperand(1);
659 
660       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
661       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
662       computeKnownBits(LHS, KnownZeroLHS, KnownOneLHS, 0, &CI);
663       computeKnownBits(RHS, KnownZeroRHS, KnownOneRHS, 0, &CI);
664 
665       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
666         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
667         APInt UnknownBit = ~KnownBits;
668         if (UnknownBit.countPopulation() == 1) {
669           if (!DoTransform) return ICI;
670 
671           Value *Result = Builder->CreateXor(LHS, RHS);
672 
673           // Mask off any bits that are set and won't be shifted away.
674           if (KnownOneLHS.uge(UnknownBit))
675             Result = Builder->CreateAnd(Result,
676                                         ConstantInt::get(ITy, UnknownBit));
677 
678           // Shift the bit we're testing down to the lsb.
679           Result = Builder->CreateLShr(
680                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
681 
682           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
683             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
684           Result->takeName(ICI);
685           return replaceInstUsesWith(CI, Result);
686         }
687       }
688     }
689   }
690 
691   return nullptr;
692 }
693 
694 /// Determine if the specified value can be computed in the specified wider type
695 /// and produce the same low bits. If not, return false.
696 ///
697 /// If this function returns true, it can also return a non-zero number of bits
698 /// (in BitsToClear) which indicates that the value it computes is correct for
699 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
700 /// out.  For example, to promote something like:
701 ///
702 ///   %B = trunc i64 %A to i32
703 ///   %C = lshr i32 %B, 8
704 ///   %E = zext i32 %C to i64
705 ///
706 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
707 /// set to 8 to indicate that the promoted value needs to have bits 24-31
708 /// cleared in addition to bits 32-63.  Since an 'and' will be generated to
709 /// clear the top bits anyway, doing this has no extra cost.
710 ///
711 /// This function works on both vectors and scalars.
712 static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
713                              InstCombiner &IC, Instruction *CxtI) {
714   BitsToClear = 0;
715   if (isa<Constant>(V))
716     return true;
717 
718   Instruction *I = dyn_cast<Instruction>(V);
719   if (!I) return false;
720 
721   // If the input is a truncate from the destination type, we can trivially
722   // eliminate it.
723   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
724     return true;
725 
726   // We can't extend or shrink something that has multiple uses: doing so would
727   // require duplicating the instruction in general, which isn't profitable.
728   if (!I->hasOneUse()) return false;
729 
730   unsigned Opc = I->getOpcode(), Tmp;
731   switch (Opc) {
732   case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
733   case Instruction::SExt:  // zext(sext(x)) -> sext(x).
734   case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
735     return true;
736   case Instruction::And:
737   case Instruction::Or:
738   case Instruction::Xor:
739   case Instruction::Add:
740   case Instruction::Sub:
741   case Instruction::Mul:
742     if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
743         !canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
744       return false;
745     // These can all be promoted if neither operand has 'bits to clear'.
746     if (BitsToClear == 0 && Tmp == 0)
747       return true;
748 
749     // If the operation is an AND/OR/XOR and the bits to clear are zero in the
750     // other side, BitsToClear is ok.
751     if (Tmp == 0 &&
752         (Opc == Instruction::And || Opc == Instruction::Or ||
753          Opc == Instruction::Xor)) {
754       // We use MaskedValueIsZero here for generality, but the case we care
755       // about the most is constant RHS.
756       unsigned VSize = V->getType()->getScalarSizeInBits();
757       if (IC.MaskedValueIsZero(I->getOperand(1),
758                                APInt::getHighBitsSet(VSize, BitsToClear),
759                                0, CxtI))
760         return true;
761     }
762 
763     // Otherwise, we don't know how to analyze this BitsToClear case yet.
764     return false;
765 
766   case Instruction::Shl:
767     // We can promote shl(x, cst) if we can promote x.  Since shl overwrites the
768     // upper bits we can reduce BitsToClear by the shift amount.
769     if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
770       if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
771         return false;
772       uint64_t ShiftAmt = Amt->getZExtValue();
773       BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
774       return true;
775     }
776     return false;
777   case Instruction::LShr:
778     // We can promote lshr(x, cst) if we can promote x.  This requires the
779     // ultimate 'and' to clear out the high zero bits we're clearing out though.
780     if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
781       if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
782         return false;
783       BitsToClear += Amt->getZExtValue();
784       if (BitsToClear > V->getType()->getScalarSizeInBits())
785         BitsToClear = V->getType()->getScalarSizeInBits();
786       return true;
787     }
788     // Cannot promote variable LSHR.
789     return false;
790   case Instruction::Select:
791     if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
792         !canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
793         // TODO: If important, we could handle the case when the BitsToClear are
794         // known zero in the disagreeing side.
795         Tmp != BitsToClear)
796       return false;
797     return true;
798 
799   case Instruction::PHI: {
800     // We can change a phi if we can change all operands.  Note that we never
801     // get into trouble with cyclic PHIs here because we only consider
802     // instructions with a single use.
803     PHINode *PN = cast<PHINode>(I);
804     if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
805       return false;
806     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
807       if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
808           // TODO: If important, we could handle the case when the BitsToClear
809           // are known zero in the disagreeing input.
810           Tmp != BitsToClear)
811         return false;
812     return true;
813   }
814   default:
815     // TODO: Can handle more cases here.
816     return false;
817   }
818 }
819 
820 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
821   // If this zero extend is only used by a truncate, let the truncate be
822   // eliminated before we try to optimize this zext.
823   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
824     return nullptr;
825 
826   // If one of the common conversion will work, do it.
827   if (Instruction *Result = commonCastTransforms(CI))
828     return Result;
829 
830   // See if we can simplify any instructions used by the input whose sole
831   // purpose is to compute bits we don't care about.
832   if (SimplifyDemandedInstructionBits(CI))
833     return &CI;
834 
835   Value *Src = CI.getOperand(0);
836   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
837 
838   // Attempt to extend the entire input expression tree to the destination
839   // type.   Only do this if the dest type is a simple type, don't convert the
840   // expression tree to something weird like i93 unless the source is also
841   // strange.
842   unsigned BitsToClear;
843   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
844       canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
845     assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
846            "Unreasonable BitsToClear");
847 
848     // Okay, we can transform this!  Insert the new expression now.
849     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
850           " to avoid zero extend: " << CI << '\n');
851     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
852     assert(Res->getType() == DestTy);
853 
854     uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
855     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
856 
857     // If the high bits are already filled with zeros, just replace this
858     // cast with the result.
859     if (MaskedValueIsZero(Res,
860                           APInt::getHighBitsSet(DestBitSize,
861                                                 DestBitSize-SrcBitsKept),
862                              0, &CI))
863       return replaceInstUsesWith(CI, Res);
864 
865     // We need to emit an AND to clear the high bits.
866     Constant *C = ConstantInt::get(Res->getType(),
867                                APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
868     return BinaryOperator::CreateAnd(Res, C);
869   }
870 
871   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
872   // types and if the sizes are just right we can convert this into a logical
873   // 'and' which will be much cheaper than the pair of casts.
874   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
875     // TODO: Subsume this into EvaluateInDifferentType.
876 
877     // Get the sizes of the types involved.  We know that the intermediate type
878     // will be smaller than A or C, but don't know the relation between A and C.
879     Value *A = CSrc->getOperand(0);
880     unsigned SrcSize = A->getType()->getScalarSizeInBits();
881     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
882     unsigned DstSize = CI.getType()->getScalarSizeInBits();
883     // If we're actually extending zero bits, then if
884     // SrcSize <  DstSize: zext(a & mask)
885     // SrcSize == DstSize: a & mask
886     // SrcSize  > DstSize: trunc(a) & mask
887     if (SrcSize < DstSize) {
888       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
889       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
890       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
891       return new ZExtInst(And, CI.getType());
892     }
893 
894     if (SrcSize == DstSize) {
895       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
896       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
897                                                            AndValue));
898     }
899     if (SrcSize > DstSize) {
900       Value *Trunc = Builder->CreateTrunc(A, CI.getType());
901       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
902       return BinaryOperator::CreateAnd(Trunc,
903                                        ConstantInt::get(Trunc->getType(),
904                                                         AndValue));
905     }
906   }
907 
908   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
909     return transformZExtICmp(ICI, CI);
910 
911   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
912   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
913     // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) if at least one
914     // of the (zext icmp) can be eliminated. If so, immediately perform the
915     // according elimination.
916     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
917     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
918     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
919         (transformZExtICmp(LHS, CI, false) ||
920          transformZExtICmp(RHS, CI, false))) {
921       // zext (or icmp, icmp) -> or (zext icmp), (zext icmp)
922       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
923       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
924       BinaryOperator *Or = BinaryOperator::Create(Instruction::Or, LCast, RCast);
925 
926       // Perform the elimination.
927       if (auto *LZExt = dyn_cast<ZExtInst>(LCast))
928         transformZExtICmp(LHS, *LZExt);
929       if (auto *RZExt = dyn_cast<ZExtInst>(RCast))
930         transformZExtICmp(RHS, *RZExt);
931 
932       return Or;
933     }
934   }
935 
936   // zext(trunc(X) & C) -> (X & zext(C)).
937   Constant *C;
938   Value *X;
939   if (SrcI &&
940       match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
941       X->getType() == CI.getType())
942     return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
943 
944   // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
945   Value *And;
946   if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
947       match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
948       X->getType() == CI.getType()) {
949     Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
950     return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
951   }
952 
953   return nullptr;
954 }
955 
956 /// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp.
957 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
958   Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
959   ICmpInst::Predicate Pred = ICI->getPredicate();
960 
961   // Don't bother if Op1 isn't of vector or integer type.
962   if (!Op1->getType()->isIntOrIntVectorTy())
963     return nullptr;
964 
965   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
966     // (x <s  0) ? -1 : 0 -> ashr x, 31        -> all ones if negative
967     // (x >s -1) ? -1 : 0 -> not (ashr x, 31)  -> all ones if positive
968     if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
969         (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
970 
971       Value *Sh = ConstantInt::get(Op0->getType(),
972                                    Op0->getType()->getScalarSizeInBits()-1);
973       Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
974       if (In->getType() != CI.getType())
975         In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
976 
977       if (Pred == ICmpInst::ICMP_SGT)
978         In = Builder->CreateNot(In, In->getName()+".not");
979       return replaceInstUsesWith(CI, In);
980     }
981   }
982 
983   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
984     // If we know that only one bit of the LHS of the icmp can be set and we
985     // have an equality comparison with zero or a power of 2, we can transform
986     // the icmp and sext into bitwise/integer operations.
987     if (ICI->hasOneUse() &&
988         ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
989       unsigned BitWidth = Op1C->getType()->getBitWidth();
990       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
991       computeKnownBits(Op0, KnownZero, KnownOne, 0, &CI);
992 
993       APInt KnownZeroMask(~KnownZero);
994       if (KnownZeroMask.isPowerOf2()) {
995         Value *In = ICI->getOperand(0);
996 
997         // If the icmp tests for a known zero bit we can constant fold it.
998         if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
999           Value *V = Pred == ICmpInst::ICMP_NE ?
1000                        ConstantInt::getAllOnesValue(CI.getType()) :
1001                        ConstantInt::getNullValue(CI.getType());
1002           return replaceInstUsesWith(CI, V);
1003         }
1004 
1005         if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
1006           // sext ((x & 2^n) == 0)   -> (x >> n) - 1
1007           // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
1008           unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
1009           // Perform a right shift to place the desired bit in the LSB.
1010           if (ShiftAmt)
1011             In = Builder->CreateLShr(In,
1012                                      ConstantInt::get(In->getType(), ShiftAmt));
1013 
1014           // At this point "In" is either 1 or 0. Subtract 1 to turn
1015           // {1, 0} -> {0, -1}.
1016           In = Builder->CreateAdd(In,
1017                                   ConstantInt::getAllOnesValue(In->getType()),
1018                                   "sext");
1019         } else {
1020           // sext ((x & 2^n) != 0)   -> (x << bitwidth-n) a>> bitwidth-1
1021           // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
1022           unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
1023           // Perform a left shift to place the desired bit in the MSB.
1024           if (ShiftAmt)
1025             In = Builder->CreateShl(In,
1026                                     ConstantInt::get(In->getType(), ShiftAmt));
1027 
1028           // Distribute the bit over the whole bit width.
1029           In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
1030                                                         BitWidth - 1), "sext");
1031         }
1032 
1033         if (CI.getType() == In->getType())
1034           return replaceInstUsesWith(CI, In);
1035         return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
1036       }
1037     }
1038   }
1039 
1040   return nullptr;
1041 }
1042 
1043 /// Return true if we can take the specified value and return it as type Ty
1044 /// without inserting any new casts and without changing the value of the common
1045 /// low bits.  This is used by code that tries to promote integer operations to
1046 /// a wider types will allow us to eliminate the extension.
1047 ///
1048 /// This function works on both vectors and scalars.
1049 ///
1050 static bool canEvaluateSExtd(Value *V, Type *Ty) {
1051   assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
1052          "Can't sign extend type to a smaller type");
1053   // If this is a constant, it can be trivially promoted.
1054   if (isa<Constant>(V))
1055     return true;
1056 
1057   Instruction *I = dyn_cast<Instruction>(V);
1058   if (!I) return false;
1059 
1060   // If this is a truncate from the dest type, we can trivially eliminate it.
1061   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
1062     return true;
1063 
1064   // We can't extend or shrink something that has multiple uses: doing so would
1065   // require duplicating the instruction in general, which isn't profitable.
1066   if (!I->hasOneUse()) return false;
1067 
1068   switch (I->getOpcode()) {
1069   case Instruction::SExt:  // sext(sext(x)) -> sext(x)
1070   case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
1071   case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1072     return true;
1073   case Instruction::And:
1074   case Instruction::Or:
1075   case Instruction::Xor:
1076   case Instruction::Add:
1077   case Instruction::Sub:
1078   case Instruction::Mul:
1079     // These operators can all arbitrarily be extended if their inputs can.
1080     return canEvaluateSExtd(I->getOperand(0), Ty) &&
1081            canEvaluateSExtd(I->getOperand(1), Ty);
1082 
1083   //case Instruction::Shl:   TODO
1084   //case Instruction::LShr:  TODO
1085 
1086   case Instruction::Select:
1087     return canEvaluateSExtd(I->getOperand(1), Ty) &&
1088            canEvaluateSExtd(I->getOperand(2), Ty);
1089 
1090   case Instruction::PHI: {
1091     // We can change a phi if we can change all operands.  Note that we never
1092     // get into trouble with cyclic PHIs here because we only consider
1093     // instructions with a single use.
1094     PHINode *PN = cast<PHINode>(I);
1095     for (Value *IncValue : PN->incoming_values())
1096       if (!canEvaluateSExtd(IncValue, Ty)) return false;
1097     return true;
1098   }
1099   default:
1100     // TODO: Can handle more cases here.
1101     break;
1102   }
1103 
1104   return false;
1105 }
1106 
1107 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
1108   // If this sign extend is only used by a truncate, let the truncate be
1109   // eliminated before we try to optimize this sext.
1110   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
1111     return nullptr;
1112 
1113   if (Instruction *I = commonCastTransforms(CI))
1114     return I;
1115 
1116   // See if we can simplify any instructions used by the input whose sole
1117   // purpose is to compute bits we don't care about.
1118   if (SimplifyDemandedInstructionBits(CI))
1119     return &CI;
1120 
1121   Value *Src = CI.getOperand(0);
1122   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1123 
1124   // If we know that the value being extended is positive, we can use a zext
1125   // instead.
1126   bool KnownZero, KnownOne;
1127   ComputeSignBit(Src, KnownZero, KnownOne, 0, &CI);
1128   if (KnownZero) {
1129     Value *ZExt = Builder->CreateZExt(Src, DestTy);
1130     return replaceInstUsesWith(CI, ZExt);
1131   }
1132 
1133   // Attempt to extend the entire input expression tree to the destination
1134   // type.   Only do this if the dest type is a simple type, don't convert the
1135   // expression tree to something weird like i93 unless the source is also
1136   // strange.
1137   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
1138       canEvaluateSExtd(Src, DestTy)) {
1139     // Okay, we can transform this!  Insert the new expression now.
1140     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1141           " to avoid sign extend: " << CI << '\n');
1142     Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1143     assert(Res->getType() == DestTy);
1144 
1145     uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1146     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1147 
1148     // If the high bits are already filled with sign bit, just replace this
1149     // cast with the result.
1150     if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
1151       return replaceInstUsesWith(CI, Res);
1152 
1153     // We need to emit a shl + ashr to do the sign extend.
1154     Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1155     return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1156                                       ShAmt);
1157   }
1158 
1159   // If this input is a trunc from our destination, then turn sext(trunc(x))
1160   // into shifts.
1161   if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1162     if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1163       uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1164       uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1165 
1166       // We need to emit a shl + ashr to do the sign extend.
1167       Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1168       Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1169       return BinaryOperator::CreateAShr(Res, ShAmt);
1170     }
1171 
1172   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1173     return transformSExtICmp(ICI, CI);
1174 
1175   // If the input is a shl/ashr pair of a same constant, then this is a sign
1176   // extension from a smaller value.  If we could trust arbitrary bitwidth
1177   // integers, we could turn this into a truncate to the smaller bit and then
1178   // use a sext for the whole extension.  Since we don't, look deeper and check
1179   // for a truncate.  If the source and dest are the same type, eliminate the
1180   // trunc and extend and just do shifts.  For example, turn:
1181   //   %a = trunc i32 %i to i8
1182   //   %b = shl i8 %a, 6
1183   //   %c = ashr i8 %b, 6
1184   //   %d = sext i8 %c to i32
1185   // into:
1186   //   %a = shl i32 %i, 30
1187   //   %d = ashr i32 %a, 30
1188   Value *A = nullptr;
1189   // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1190   ConstantInt *BA = nullptr, *CA = nullptr;
1191   if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1192                         m_ConstantInt(CA))) &&
1193       BA == CA && A->getType() == CI.getType()) {
1194     unsigned MidSize = Src->getType()->getScalarSizeInBits();
1195     unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1196     unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1197     Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1198     A = Builder->CreateShl(A, ShAmtV, CI.getName());
1199     return BinaryOperator::CreateAShr(A, ShAmtV);
1200   }
1201 
1202   return nullptr;
1203 }
1204 
1205 
1206 /// Return a Constant* for the specified floating-point constant if it fits
1207 /// in the specified FP type without changing its value.
1208 static Constant *fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1209   bool losesInfo;
1210   APFloat F = CFP->getValueAPF();
1211   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1212   if (!losesInfo)
1213     return ConstantFP::get(CFP->getContext(), F);
1214   return nullptr;
1215 }
1216 
1217 /// If this is a floating-point extension instruction, look
1218 /// through it until we get the source value.
1219 static Value *lookThroughFPExtensions(Value *V) {
1220   if (Instruction *I = dyn_cast<Instruction>(V))
1221     if (I->getOpcode() == Instruction::FPExt)
1222       return lookThroughFPExtensions(I->getOperand(0));
1223 
1224   // If this value is a constant, return the constant in the smallest FP type
1225   // that can accurately represent it.  This allows us to turn
1226   // (float)((double)X+2.0) into x+2.0f.
1227   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1228     if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1229       return V;  // No constant folding of this.
1230     // See if the value can be truncated to half and then reextended.
1231     if (Value *V = fitsInFPType(CFP, APFloat::IEEEhalf))
1232       return V;
1233     // See if the value can be truncated to float and then reextended.
1234     if (Value *V = fitsInFPType(CFP, APFloat::IEEEsingle))
1235       return V;
1236     if (CFP->getType()->isDoubleTy())
1237       return V;  // Won't shrink.
1238     if (Value *V = fitsInFPType(CFP, APFloat::IEEEdouble))
1239       return V;
1240     // Don't try to shrink to various long double types.
1241   }
1242 
1243   return V;
1244 }
1245 
1246 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1247   if (Instruction *I = commonCastTransforms(CI))
1248     return I;
1249   // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1250   // simplify this expression to avoid one or more of the trunc/extend
1251   // operations if we can do so without changing the numerical results.
1252   //
1253   // The exact manner in which the widths of the operands interact to limit
1254   // what we can and cannot do safely varies from operation to operation, and
1255   // is explained below in the various case statements.
1256   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1257   if (OpI && OpI->hasOneUse()) {
1258     Value *LHSOrig = lookThroughFPExtensions(OpI->getOperand(0));
1259     Value *RHSOrig = lookThroughFPExtensions(OpI->getOperand(1));
1260     unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1261     unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
1262     unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
1263     unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1264     unsigned DstWidth = CI.getType()->getFPMantissaWidth();
1265     switch (OpI->getOpcode()) {
1266       default: break;
1267       case Instruction::FAdd:
1268       case Instruction::FSub:
1269         // For addition and subtraction, the infinitely precise result can
1270         // essentially be arbitrarily wide; proving that double rounding
1271         // will not occur because the result of OpI is exact (as we will for
1272         // FMul, for example) is hopeless.  However, we *can* nonetheless
1273         // frequently know that double rounding cannot occur (or that it is
1274         // innocuous) by taking advantage of the specific structure of
1275         // infinitely-precise results that admit double rounding.
1276         //
1277         // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
1278         // to represent both sources, we can guarantee that the double
1279         // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1280         // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1281         // for proof of this fact).
1282         //
1283         // Note: Figueroa does not consider the case where DstFormat !=
1284         // SrcFormat.  It's possible (likely even!) that this analysis
1285         // could be tightened for those cases, but they are rare (the main
1286         // case of interest here is (float)((double)float + float)).
1287         if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1288           if (LHSOrig->getType() != CI.getType())
1289             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1290           if (RHSOrig->getType() != CI.getType())
1291             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1292           Instruction *RI =
1293             BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
1294           RI->copyFastMathFlags(OpI);
1295           return RI;
1296         }
1297         break;
1298       case Instruction::FMul:
1299         // For multiplication, the infinitely precise result has at most
1300         // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1301         // that such a value can be exactly represented, then no double
1302         // rounding can possibly occur; we can safely perform the operation
1303         // in the destination format if it can represent both sources.
1304         if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1305           if (LHSOrig->getType() != CI.getType())
1306             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1307           if (RHSOrig->getType() != CI.getType())
1308             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1309           Instruction *RI =
1310             BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
1311           RI->copyFastMathFlags(OpI);
1312           return RI;
1313         }
1314         break;
1315       case Instruction::FDiv:
1316         // For division, we use again use the bound from Figueroa's
1317         // dissertation.  I am entirely certain that this bound can be
1318         // tightened in the unbalanced operand case by an analysis based on
1319         // the diophantine rational approximation bound, but the well-known
1320         // condition used here is a good conservative first pass.
1321         // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1322         if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1323           if (LHSOrig->getType() != CI.getType())
1324             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1325           if (RHSOrig->getType() != CI.getType())
1326             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1327           Instruction *RI =
1328             BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
1329           RI->copyFastMathFlags(OpI);
1330           return RI;
1331         }
1332         break;
1333       case Instruction::FRem:
1334         // Remainder is straightforward.  Remainder is always exact, so the
1335         // type of OpI doesn't enter into things at all.  We simply evaluate
1336         // in whichever source type is larger, then convert to the
1337         // destination type.
1338         if (SrcWidth == OpWidth)
1339           break;
1340         if (LHSWidth < SrcWidth)
1341           LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
1342         else if (RHSWidth <= SrcWidth)
1343           RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
1344         if (LHSOrig != OpI->getOperand(0) || RHSOrig != OpI->getOperand(1)) {
1345           Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
1346           if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
1347             RI->copyFastMathFlags(OpI);
1348           return CastInst::CreateFPCast(ExactResult, CI.getType());
1349         }
1350     }
1351 
1352     // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1353     if (BinaryOperator::isFNeg(OpI)) {
1354       Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
1355                                                  CI.getType());
1356       Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
1357       RI->copyFastMathFlags(OpI);
1358       return RI;
1359     }
1360   }
1361 
1362   // (fptrunc (select cond, R1, Cst)) -->
1363   // (select cond, (fptrunc R1), (fptrunc Cst))
1364   //
1365   //  - but only if this isn't part of a min/max operation, else we'll
1366   // ruin min/max canonical form which is to have the select and
1367   // compare's operands be of the same type with no casts to look through.
1368   Value *LHS, *RHS;
1369   SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
1370   if (SI &&
1371       (isa<ConstantFP>(SI->getOperand(1)) ||
1372        isa<ConstantFP>(SI->getOperand(2))) &&
1373       matchSelectPattern(SI, LHS, RHS).Flavor == SPF_UNKNOWN) {
1374     Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
1375                                              CI.getType());
1376     Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
1377                                              CI.getType());
1378     return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
1379   }
1380 
1381   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
1382   if (II) {
1383     switch (II->getIntrinsicID()) {
1384       default: break;
1385       case Intrinsic::fabs: {
1386         // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1387         Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
1388                                                    CI.getType());
1389         Type *IntrinsicType[] = { CI.getType() };
1390         Function *Overload = Intrinsic::getDeclaration(
1391             CI.getModule(), II->getIntrinsicID(), IntrinsicType);
1392 
1393         SmallVector<OperandBundleDef, 1> OpBundles;
1394         II->getOperandBundlesAsDefs(OpBundles);
1395 
1396         Value *Args[] = { InnerTrunc };
1397         return CallInst::Create(Overload, Args, OpBundles, II->getName());
1398       }
1399     }
1400   }
1401 
1402   return nullptr;
1403 }
1404 
1405 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1406   return commonCastTransforms(CI);
1407 }
1408 
1409 // fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
1410 // This is safe if the intermediate type has enough bits in its mantissa to
1411 // accurately represent all values of X.  For example, this won't work with
1412 // i64 -> float -> i64.
1413 Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) {
1414   if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
1415     return nullptr;
1416   Instruction *OpI = cast<Instruction>(FI.getOperand(0));
1417 
1418   Value *SrcI = OpI->getOperand(0);
1419   Type *FITy = FI.getType();
1420   Type *OpITy = OpI->getType();
1421   Type *SrcTy = SrcI->getType();
1422   bool IsInputSigned = isa<SIToFPInst>(OpI);
1423   bool IsOutputSigned = isa<FPToSIInst>(FI);
1424 
1425   // We can safely assume the conversion won't overflow the output range,
1426   // because (for example) (uint8_t)18293.f is undefined behavior.
1427 
1428   // Since we can assume the conversion won't overflow, our decision as to
1429   // whether the input will fit in the float should depend on the minimum
1430   // of the input range and output range.
1431 
1432   // This means this is also safe for a signed input and unsigned output, since
1433   // a negative input would lead to undefined behavior.
1434   int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned;
1435   int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned;
1436   int ActualSize = std::min(InputSize, OutputSize);
1437 
1438   if (ActualSize <= OpITy->getFPMantissaWidth()) {
1439     if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) {
1440       if (IsInputSigned && IsOutputSigned)
1441         return new SExtInst(SrcI, FITy);
1442       return new ZExtInst(SrcI, FITy);
1443     }
1444     if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits())
1445       return new TruncInst(SrcI, FITy);
1446     if (SrcTy == FITy)
1447       return replaceInstUsesWith(FI, SrcI);
1448     return new BitCastInst(SrcI, FITy);
1449   }
1450   return nullptr;
1451 }
1452 
1453 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1454   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1455   if (!OpI)
1456     return commonCastTransforms(FI);
1457 
1458   if (Instruction *I = FoldItoFPtoI(FI))
1459     return I;
1460 
1461   return commonCastTransforms(FI);
1462 }
1463 
1464 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1465   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1466   if (!OpI)
1467     return commonCastTransforms(FI);
1468 
1469   if (Instruction *I = FoldItoFPtoI(FI))
1470     return I;
1471 
1472   return commonCastTransforms(FI);
1473 }
1474 
1475 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1476   return commonCastTransforms(CI);
1477 }
1478 
1479 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1480   return commonCastTransforms(CI);
1481 }
1482 
1483 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1484   // If the source integer type is not the intptr_t type for this target, do a
1485   // trunc or zext to the intptr_t type, then inttoptr of it.  This allows the
1486   // cast to be exposed to other transforms.
1487   unsigned AS = CI.getAddressSpace();
1488   if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
1489       DL.getPointerSizeInBits(AS)) {
1490     Type *Ty = DL.getIntPtrType(CI.getContext(), AS);
1491     if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1492       Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
1493 
1494     Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
1495     return new IntToPtrInst(P, CI.getType());
1496   }
1497 
1498   if (Instruction *I = commonCastTransforms(CI))
1499     return I;
1500 
1501   return nullptr;
1502 }
1503 
1504 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1505 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1506   Value *Src = CI.getOperand(0);
1507 
1508   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1509     // If casting the result of a getelementptr instruction with no offset, turn
1510     // this into a cast of the original pointer!
1511     if (GEP->hasAllZeroIndices() &&
1512         // If CI is an addrspacecast and GEP changes the poiner type, merging
1513         // GEP into CI would undo canonicalizing addrspacecast with different
1514         // pointer types, causing infinite loops.
1515         (!isa<AddrSpaceCastInst>(CI) ||
1516           GEP->getType() == GEP->getPointerOperand()->getType())) {
1517       // Changing the cast operand is usually not a good idea but it is safe
1518       // here because the pointer operand is being replaced with another
1519       // pointer operand so the opcode doesn't need to change.
1520       Worklist.Add(GEP);
1521       CI.setOperand(0, GEP->getOperand(0));
1522       return &CI;
1523     }
1524   }
1525 
1526   return commonCastTransforms(CI);
1527 }
1528 
1529 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1530   // If the destination integer type is not the intptr_t type for this target,
1531   // do a ptrtoint to intptr_t then do a trunc or zext.  This allows the cast
1532   // to be exposed to other transforms.
1533 
1534   Type *Ty = CI.getType();
1535   unsigned AS = CI.getPointerAddressSpace();
1536 
1537   if (Ty->getScalarSizeInBits() == DL.getPointerSizeInBits(AS))
1538     return commonPointerCastTransforms(CI);
1539 
1540   Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS);
1541   if (Ty->isVectorTy()) // Handle vectors of pointers.
1542     PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1543 
1544   Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
1545   return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
1546 }
1547 
1548 /// This input value (which is known to have vector type) is being zero extended
1549 /// or truncated to the specified vector type.
1550 /// Try to replace it with a shuffle (and vector/vector bitcast) if possible.
1551 ///
1552 /// The source and destination vector types may have different element types.
1553 static Instruction *optimizeVectorResize(Value *InVal, VectorType *DestTy,
1554                                          InstCombiner &IC) {
1555   // We can only do this optimization if the output is a multiple of the input
1556   // element size, or the input is a multiple of the output element size.
1557   // Convert the input type to have the same element type as the output.
1558   VectorType *SrcTy = cast<VectorType>(InVal->getType());
1559 
1560   if (SrcTy->getElementType() != DestTy->getElementType()) {
1561     // The input types don't need to be identical, but for now they must be the
1562     // same size.  There is no specific reason we couldn't handle things like
1563     // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1564     // there yet.
1565     if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1566         DestTy->getElementType()->getPrimitiveSizeInBits())
1567       return nullptr;
1568 
1569     SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1570     InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1571   }
1572 
1573   // Now that the element types match, get the shuffle mask and RHS of the
1574   // shuffle to use, which depends on whether we're increasing or decreasing the
1575   // size of the input.
1576   SmallVector<uint32_t, 16> ShuffleMask;
1577   Value *V2;
1578 
1579   if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1580     // If we're shrinking the number of elements, just shuffle in the low
1581     // elements from the input and use undef as the second shuffle input.
1582     V2 = UndefValue::get(SrcTy);
1583     for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1584       ShuffleMask.push_back(i);
1585 
1586   } else {
1587     // If we're increasing the number of elements, shuffle in all of the
1588     // elements from InVal and fill the rest of the result elements with zeros
1589     // from a constant zero.
1590     V2 = Constant::getNullValue(SrcTy);
1591     unsigned SrcElts = SrcTy->getNumElements();
1592     for (unsigned i = 0, e = SrcElts; i != e; ++i)
1593       ShuffleMask.push_back(i);
1594 
1595     // The excess elements reference the first element of the zero input.
1596     for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1597       ShuffleMask.push_back(SrcElts);
1598   }
1599 
1600   return new ShuffleVectorInst(InVal, V2,
1601                                ConstantDataVector::get(V2->getContext(),
1602                                                        ShuffleMask));
1603 }
1604 
1605 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
1606   return Value % Ty->getPrimitiveSizeInBits() == 0;
1607 }
1608 
1609 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
1610   return Value / Ty->getPrimitiveSizeInBits();
1611 }
1612 
1613 /// V is a value which is inserted into a vector of VecEltTy.
1614 /// Look through the value to see if we can decompose it into
1615 /// insertions into the vector.  See the example in the comment for
1616 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
1617 /// The type of V is always a non-zero multiple of VecEltTy's size.
1618 /// Shift is the number of bits between the lsb of V and the lsb of
1619 /// the vector.
1620 ///
1621 /// This returns false if the pattern can't be matched or true if it can,
1622 /// filling in Elements with the elements found here.
1623 static bool collectInsertionElements(Value *V, unsigned Shift,
1624                                      SmallVectorImpl<Value *> &Elements,
1625                                      Type *VecEltTy, bool isBigEndian) {
1626   assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1627          "Shift should be a multiple of the element type size");
1628 
1629   // Undef values never contribute useful bits to the result.
1630   if (isa<UndefValue>(V)) return true;
1631 
1632   // If we got down to a value of the right type, we win, try inserting into the
1633   // right element.
1634   if (V->getType() == VecEltTy) {
1635     // Inserting null doesn't actually insert any elements.
1636     if (Constant *C = dyn_cast<Constant>(V))
1637       if (C->isNullValue())
1638         return true;
1639 
1640     unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
1641     if (isBigEndian)
1642       ElementIndex = Elements.size() - ElementIndex - 1;
1643 
1644     // Fail if multiple elements are inserted into this slot.
1645     if (Elements[ElementIndex])
1646       return false;
1647 
1648     Elements[ElementIndex] = V;
1649     return true;
1650   }
1651 
1652   if (Constant *C = dyn_cast<Constant>(V)) {
1653     // Figure out the # elements this provides, and bitcast it or slice it up
1654     // as required.
1655     unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1656                                         VecEltTy);
1657     // If the constant is the size of a vector element, we just need to bitcast
1658     // it to the right type so it gets properly inserted.
1659     if (NumElts == 1)
1660       return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1661                                       Shift, Elements, VecEltTy, isBigEndian);
1662 
1663     // Okay, this is a constant that covers multiple elements.  Slice it up into
1664     // pieces and insert each element-sized piece into the vector.
1665     if (!isa<IntegerType>(C->getType()))
1666       C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1667                                        C->getType()->getPrimitiveSizeInBits()));
1668     unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
1669     Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
1670 
1671     for (unsigned i = 0; i != NumElts; ++i) {
1672       unsigned ShiftI = Shift+i*ElementSize;
1673       Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1674                                                                   ShiftI));
1675       Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1676       if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
1677                                     isBigEndian))
1678         return false;
1679     }
1680     return true;
1681   }
1682 
1683   if (!V->hasOneUse()) return false;
1684 
1685   Instruction *I = dyn_cast<Instruction>(V);
1686   if (!I) return false;
1687   switch (I->getOpcode()) {
1688   default: return false; // Unhandled case.
1689   case Instruction::BitCast:
1690     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1691                                     isBigEndian);
1692   case Instruction::ZExt:
1693     if (!isMultipleOfTypeSize(
1694                           I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1695                               VecEltTy))
1696       return false;
1697     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1698                                     isBigEndian);
1699   case Instruction::Or:
1700     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1701                                     isBigEndian) &&
1702            collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
1703                                     isBigEndian);
1704   case Instruction::Shl: {
1705     // Must be shifting by a constant that is a multiple of the element size.
1706     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1707     if (!CI) return false;
1708     Shift += CI->getZExtValue();
1709     if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
1710     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1711                                     isBigEndian);
1712   }
1713 
1714   }
1715 }
1716 
1717 
1718 /// If the input is an 'or' instruction, we may be doing shifts and ors to
1719 /// assemble the elements of the vector manually.
1720 /// Try to rip the code out and replace it with insertelements.  This is to
1721 /// optimize code like this:
1722 ///
1723 ///    %tmp37 = bitcast float %inc to i32
1724 ///    %tmp38 = zext i32 %tmp37 to i64
1725 ///    %tmp31 = bitcast float %inc5 to i32
1726 ///    %tmp32 = zext i32 %tmp31 to i64
1727 ///    %tmp33 = shl i64 %tmp32, 32
1728 ///    %ins35 = or i64 %tmp33, %tmp38
1729 ///    %tmp43 = bitcast i64 %ins35 to <2 x float>
1730 ///
1731 /// Into two insertelements that do "buildvector{%inc, %inc5}".
1732 static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI,
1733                                                 InstCombiner &IC) {
1734   VectorType *DestVecTy = cast<VectorType>(CI.getType());
1735   Value *IntInput = CI.getOperand(0);
1736 
1737   SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1738   if (!collectInsertionElements(IntInput, 0, Elements,
1739                                 DestVecTy->getElementType(),
1740                                 IC.getDataLayout().isBigEndian()))
1741     return nullptr;
1742 
1743   // If we succeeded, we know that all of the element are specified by Elements
1744   // or are zero if Elements has a null entry.  Recast this as a set of
1745   // insertions.
1746   Value *Result = Constant::getNullValue(CI.getType());
1747   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1748     if (!Elements[i]) continue;  // Unset element.
1749 
1750     Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1751                                              IC.Builder->getInt32(i));
1752   }
1753 
1754   return Result;
1755 }
1756 
1757 /// Canonicalize scalar bitcasts of extracted elements into a bitcast of the
1758 /// vector followed by extract element. The backend tends to handle bitcasts of
1759 /// vectors better than bitcasts of scalars because vector registers are
1760 /// usually not type-specific like scalar integer or scalar floating-point.
1761 static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast,
1762                                               InstCombiner &IC,
1763                                               const DataLayout &DL) {
1764   // TODO: Create and use a pattern matcher for ExtractElementInst.
1765   auto *ExtElt = dyn_cast<ExtractElementInst>(BitCast.getOperand(0));
1766   if (!ExtElt || !ExtElt->hasOneUse())
1767     return nullptr;
1768 
1769   // The bitcast must be to a vectorizable type, otherwise we can't make a new
1770   // type to extract from.
1771   Type *DestType = BitCast.getType();
1772   if (!VectorType::isValidElementType(DestType))
1773     return nullptr;
1774 
1775   unsigned NumElts = ExtElt->getVectorOperandType()->getNumElements();
1776   auto *NewVecType = VectorType::get(DestType, NumElts);
1777   auto *NewBC = IC.Builder->CreateBitCast(ExtElt->getVectorOperand(),
1778                                           NewVecType, "bc");
1779   return ExtractElementInst::Create(NewBC, ExtElt->getIndexOperand());
1780 }
1781 
1782 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1783   // If the operands are integer typed then apply the integer transforms,
1784   // otherwise just apply the common ones.
1785   Value *Src = CI.getOperand(0);
1786   Type *SrcTy = Src->getType();
1787   Type *DestTy = CI.getType();
1788 
1789   // Get rid of casts from one type to the same type. These are useless and can
1790   // be replaced by the operand.
1791   if (DestTy == Src->getType())
1792     return replaceInstUsesWith(CI, Src);
1793 
1794   if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1795     PointerType *SrcPTy = cast<PointerType>(SrcTy);
1796     Type *DstElTy = DstPTy->getElementType();
1797     Type *SrcElTy = SrcPTy->getElementType();
1798 
1799     // If we are casting a alloca to a pointer to a type of the same
1800     // size, rewrite the allocation instruction to allocate the "right" type.
1801     // There is no need to modify malloc calls because it is their bitcast that
1802     // needs to be cleaned up.
1803     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1804       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1805         return V;
1806 
1807     // When the type pointed to is not sized the cast cannot be
1808     // turned into a gep.
1809     Type *PointeeType =
1810         cast<PointerType>(Src->getType()->getScalarType())->getElementType();
1811     if (!PointeeType->isSized())
1812       return nullptr;
1813 
1814     // If the source and destination are pointers, and this cast is equivalent
1815     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
1816     // This can enhance SROA and other transforms that want type-safe pointers.
1817     unsigned NumZeros = 0;
1818     while (SrcElTy != DstElTy &&
1819            isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
1820            SrcElTy->getNumContainedTypes() /* not "{}" */) {
1821       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(0U);
1822       ++NumZeros;
1823     }
1824 
1825     // If we found a path from the src to dest, create the getelementptr now.
1826     if (SrcElTy == DstElTy) {
1827       SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder->getInt32(0));
1828       return GetElementPtrInst::CreateInBounds(Src, Idxs);
1829     }
1830   }
1831 
1832   if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1833     if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
1834       Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1835       return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1836                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1837       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1838     }
1839 
1840     if (isa<IntegerType>(SrcTy)) {
1841       // If this is a cast from an integer to vector, check to see if the input
1842       // is a trunc or zext of a bitcast from vector.  If so, we can replace all
1843       // the casts with a shuffle and (potentially) a bitcast.
1844       if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1845         CastInst *SrcCast = cast<CastInst>(Src);
1846         if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1847           if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1848             if (Instruction *I = optimizeVectorResize(BCIn->getOperand(0),
1849                                                cast<VectorType>(DestTy), *this))
1850               return I;
1851       }
1852 
1853       // If the input is an 'or' instruction, we may be doing shifts and ors to
1854       // assemble the elements of the vector manually.  Try to rip the code out
1855       // and replace it with insertelements.
1856       if (Value *V = optimizeIntegerToVectorInsertions(CI, *this))
1857         return replaceInstUsesWith(CI, V);
1858     }
1859   }
1860 
1861   if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1862     if (SrcVTy->getNumElements() == 1) {
1863       // If our destination is not a vector, then make this a straight
1864       // scalar-scalar cast.
1865       if (!DestTy->isVectorTy()) {
1866         Value *Elem =
1867           Builder->CreateExtractElement(Src,
1868                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1869         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1870       }
1871 
1872       // Otherwise, see if our source is an insert. If so, then use the scalar
1873       // component directly.
1874       if (InsertElementInst *IEI =
1875             dyn_cast<InsertElementInst>(CI.getOperand(0)))
1876         return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
1877                                 DestTy);
1878     }
1879   }
1880 
1881   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1882     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
1883     // a bitcast to a vector with the same # elts.
1884     if (SVI->hasOneUse() && DestTy->isVectorTy() &&
1885         DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
1886         SVI->getType()->getNumElements() ==
1887         SVI->getOperand(0)->getType()->getVectorNumElements()) {
1888       BitCastInst *Tmp;
1889       // If either of the operands is a cast from CI.getType(), then
1890       // evaluating the shuffle in the casted destination's type will allow
1891       // us to eliminate at least one cast.
1892       if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1893            Tmp->getOperand(0)->getType() == DestTy) ||
1894           ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1895            Tmp->getOperand(0)->getType() == DestTy)) {
1896         Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1897         Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1898         // Return a new shuffle vector.  Use the same element ID's, as we
1899         // know the vector types match #elts.
1900         return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1901       }
1902     }
1903   }
1904 
1905   if (Instruction *I = canonicalizeBitCastExtElt(CI, *this, DL))
1906     return I;
1907 
1908   if (SrcTy->isPointerTy())
1909     return commonPointerCastTransforms(CI);
1910   return commonCastTransforms(CI);
1911 }
1912 
1913 Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
1914   // If the destination pointer element type is not the same as the source's
1915   // first do a bitcast to the destination type, and then the addrspacecast.
1916   // This allows the cast to be exposed to other transforms.
1917   Value *Src = CI.getOperand(0);
1918   PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
1919   PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
1920 
1921   Type *DestElemTy = DestTy->getElementType();
1922   if (SrcTy->getElementType() != DestElemTy) {
1923     Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
1924     if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
1925       // Handle vectors of pointers.
1926       MidTy = VectorType::get(MidTy, VT->getNumElements());
1927     }
1928 
1929     Value *NewBitCast = Builder->CreateBitCast(Src, MidTy);
1930     return new AddrSpaceCastInst(NewBitCast, CI.getType());
1931   }
1932 
1933   return commonPointerCastTransforms(CI);
1934 }
1935