InstCombineCasts.cpp revision 202878
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 "InstCombine.h"
15#include "llvm/Target/TargetData.h"
16#include "llvm/Support/PatternMatch.h"
17using namespace llvm;
18using namespace PatternMatch;
19
20/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
21/// expression.  If so, decompose it, returning some value X, such that Val is
22/// X*Scale+Offset.
23///
24static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
25                                        int &Offset) {
26  assert(Val->getType()->isInteger(32) && "Unexpected allocation size type!");
27  if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28    Offset = CI->getZExtValue();
29    Scale  = 0;
30    return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
31  }
32
33  if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
34    if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
35      if (I->getOpcode() == Instruction::Shl) {
36        // This is a value scaled by '1 << the shift amt'.
37        Scale = 1U << RHS->getZExtValue();
38        Offset = 0;
39        return I->getOperand(0);
40      }
41
42      if (I->getOpcode() == Instruction::Mul) {
43        // This value is scaled by 'RHS'.
44        Scale = RHS->getZExtValue();
45        Offset = 0;
46        return I->getOperand(0);
47      }
48
49      if (I->getOpcode() == Instruction::Add) {
50        // We have X+C.  Check to see if we really have (X*C2)+C1,
51        // where C1 is divisible by C2.
52        unsigned SubScale;
53        Value *SubVal =
54          DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
55        Offset += RHS->getZExtValue();
56        Scale = SubScale;
57        return SubVal;
58      }
59    }
60  }
61
62  // Otherwise, we can't look past this.
63  Scale = 1;
64  Offset = 0;
65  return Val;
66}
67
68/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
69/// try to eliminate the cast by moving the type information into the alloc.
70Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
71                                                   AllocaInst &AI) {
72  // This requires TargetData to get the alloca alignment and size information.
73  if (!TD) return 0;
74
75  const PointerType *PTy = cast<PointerType>(CI.getType());
76
77  BuilderTy AllocaBuilder(*Builder);
78  AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
79
80  // Get the type really allocated and the type casted to.
81  const Type *AllocElTy = AI.getAllocatedType();
82  const Type *CastElTy = PTy->getElementType();
83  if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
84
85  unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
86  unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
87  if (CastElTyAlign < AllocElTyAlign) return 0;
88
89  // If the allocation has multiple uses, only promote it if we are strictly
90  // increasing the alignment of the resultant allocation.  If we keep it the
91  // same, we open the door to infinite loops of various kinds.  (A reference
92  // from a dbg.declare doesn't count as a use for this purpose.)
93  if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
94      CastElTyAlign == AllocElTyAlign) return 0;
95
96  uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
97  uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
98  if (CastElTySize == 0 || AllocElTySize == 0) return 0;
99
100  // See if we can satisfy the modulus by pulling a scale out of the array
101  // size argument.
102  unsigned ArraySizeScale;
103  int ArrayOffset;
104  Value *NumElements = // See if the array size is a decomposable linear expr.
105    DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
106
107  // If we can now satisfy the modulus, by using a non-1 scale, we really can
108  // do the xform.
109  if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
110      (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
111
112  unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
113  Value *Amt = 0;
114  if (Scale == 1) {
115    Amt = NumElements;
116  } else {
117    Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
118    // Insert before the alloca, not before the cast.
119    Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
120  }
121
122  if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
123    Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
124                                  Offset, true);
125    Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
126  }
127
128  AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
129  New->setAlignment(AI.getAlignment());
130  New->takeName(&AI);
131
132  // If the allocation has one real use plus a dbg.declare, just remove the
133  // declare.
134  if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
135    EraseInstFromFunction(*(Instruction*)DI);
136  }
137  // If the allocation has multiple real uses, insert a cast and change all
138  // things that used it to use the new cast.  This will also hack on CI, but it
139  // will die soon.
140  else if (!AI.hasOneUse()) {
141    // New is the allocation instruction, pointer typed. AI is the original
142    // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
143    Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
144    AI.replaceAllUsesWith(NewCast);
145  }
146  return ReplaceInstUsesWith(CI, New);
147}
148
149
150
151/// EvaluateInDifferentType - Given an expression that
152/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
153/// insert the code to evaluate the expression.
154Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
155                                             bool isSigned) {
156  if (Constant *C = dyn_cast<Constant>(V)) {
157    C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
158    // If we got a constantexpr back, try to simplify it with TD info.
159    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
160      C = ConstantFoldConstantExpression(CE, TD);
161    return C;
162  }
163
164  // Otherwise, it must be an instruction.
165  Instruction *I = cast<Instruction>(V);
166  Instruction *Res = 0;
167  unsigned Opc = I->getOpcode();
168  switch (Opc) {
169  case Instruction::Add:
170  case Instruction::Sub:
171  case Instruction::Mul:
172  case Instruction::And:
173  case Instruction::Or:
174  case Instruction::Xor:
175  case Instruction::AShr:
176  case Instruction::LShr:
177  case Instruction::Shl:
178  case Instruction::UDiv:
179  case Instruction::URem: {
180    Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
181    Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
182    Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
183    break;
184  }
185  case Instruction::Trunc:
186  case Instruction::ZExt:
187  case Instruction::SExt:
188    // If the source type of the cast is the type we're trying for then we can
189    // just return the source.  There's no need to insert it because it is not
190    // new.
191    if (I->getOperand(0)->getType() == Ty)
192      return I->getOperand(0);
193
194    // Otherwise, must be the same type of cast, so just reinsert a new one.
195    // This also handles the case of zext(trunc(x)) -> zext(x).
196    Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
197                                      Opc == Instruction::SExt);
198    break;
199  case Instruction::Select: {
200    Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
201    Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
202    Res = SelectInst::Create(I->getOperand(0), True, False);
203    break;
204  }
205  case Instruction::PHI: {
206    PHINode *OPN = cast<PHINode>(I);
207    PHINode *NPN = PHINode::Create(Ty);
208    for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
209      Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
210      NPN->addIncoming(V, OPN->getIncomingBlock(i));
211    }
212    Res = NPN;
213    break;
214  }
215  default:
216    // TODO: Can handle more cases here.
217    llvm_unreachable("Unreachable!");
218    break;
219  }
220
221  Res->takeName(I);
222  return InsertNewInstBefore(Res, *I);
223}
224
225
226/// This function is a wrapper around CastInst::isEliminableCastPair. It
227/// simply extracts arguments and returns what that function returns.
228static Instruction::CastOps
229isEliminableCastPair(
230  const CastInst *CI, ///< The first cast instruction
231  unsigned opcode,       ///< The opcode of the second cast instruction
232  const Type *DstTy,     ///< The target type for the second cast instruction
233  TargetData *TD         ///< The target data for pointer size
234) {
235
236  const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
237  const Type *MidTy = CI->getType();                  // B from above
238
239  // Get the opcodes of the two Cast instructions
240  Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
241  Instruction::CastOps secondOp = Instruction::CastOps(opcode);
242
243  unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
244                                                DstTy,
245                                  TD ? TD->getIntPtrType(CI->getContext()) : 0);
246
247  // We don't want to form an inttoptr or ptrtoint that converts to an integer
248  // type that differs from the pointer size.
249  if ((Res == Instruction::IntToPtr &&
250          (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
251      (Res == Instruction::PtrToInt &&
252          (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
253    Res = 0;
254
255  return Instruction::CastOps(Res);
256}
257
258/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
259/// in any code being generated.  It does not require codegen if V is simple
260/// enough or if the cast can be folded into other casts.
261bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
262                                     const Type *Ty) {
263  if (V->getType() == Ty || isa<Constant>(V)) return false;
264
265  // If this is another cast that can be eliminated, it isn't codegen either.
266  if (const CastInst *CI = dyn_cast<CastInst>(V))
267    if (isEliminableCastPair(CI, opcode, Ty, TD))
268      return false;
269  return true;
270}
271
272
273/// @brief Implement the transforms common to all CastInst visitors.
274Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
275  Value *Src = CI.getOperand(0);
276
277  // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
278  // eliminate it now.
279  if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
280    if (Instruction::CastOps opc =
281        isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
282      // The first cast (CSrc) is eliminable so we need to fix up or replace
283      // the second cast (CI). CSrc will then have a good chance of being dead.
284      return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
285    }
286  }
287
288  // If we are casting a select then fold the cast into the select
289  if (SelectInst *SI = dyn_cast<SelectInst>(Src))
290    if (Instruction *NV = FoldOpIntoSelect(CI, SI))
291      return NV;
292
293  // If we are casting a PHI then fold the cast into the PHI
294  if (isa<PHINode>(Src)) {
295    // We don't do this if this would create a PHI node with an illegal type if
296    // it is currently legal.
297    if (!isa<IntegerType>(Src->getType()) ||
298        !isa<IntegerType>(CI.getType()) ||
299        ShouldChangeType(CI.getType(), Src->getType()))
300      if (Instruction *NV = FoldOpIntoPhi(CI))
301        return NV;
302  }
303
304  return 0;
305}
306
307/// CanEvaluateTruncated - Return true if we can evaluate the specified
308/// expression tree as type Ty instead of its larger type, and arrive with the
309/// same value.  This is used by code that tries to eliminate truncates.
310///
311/// Ty will always be a type smaller than V.  We should return true if trunc(V)
312/// can be computed by computing V in the smaller type.  If V is an instruction,
313/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
314/// makes sense if x and y can be efficiently truncated.
315///
316/// This function works on both vectors and scalars.
317///
318static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
319  // We can always evaluate constants in another type.
320  if (isa<Constant>(V))
321    return true;
322
323  Instruction *I = dyn_cast<Instruction>(V);
324  if (!I) return false;
325
326  const Type *OrigTy = V->getType();
327
328  // If this is an extension from the dest type, we can eliminate it, even if it
329  // has multiple uses.
330  if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
331      I->getOperand(0)->getType() == Ty)
332    return true;
333
334  // We can't extend or shrink something that has multiple uses: doing so would
335  // require duplicating the instruction in general, which isn't profitable.
336  if (!I->hasOneUse()) return false;
337
338  unsigned Opc = I->getOpcode();
339  switch (Opc) {
340  case Instruction::Add:
341  case Instruction::Sub:
342  case Instruction::Mul:
343  case Instruction::And:
344  case Instruction::Or:
345  case Instruction::Xor:
346    // These operators can all arbitrarily be extended or truncated.
347    return CanEvaluateTruncated(I->getOperand(0), Ty) &&
348           CanEvaluateTruncated(I->getOperand(1), Ty);
349
350  case Instruction::UDiv:
351  case Instruction::URem: {
352    // UDiv and URem can be truncated if all the truncated bits are zero.
353    uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
354    uint32_t BitWidth = Ty->getScalarSizeInBits();
355    if (BitWidth < OrigBitWidth) {
356      APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
357      if (MaskedValueIsZero(I->getOperand(0), Mask) &&
358          MaskedValueIsZero(I->getOperand(1), Mask)) {
359        return CanEvaluateTruncated(I->getOperand(0), Ty) &&
360               CanEvaluateTruncated(I->getOperand(1), Ty);
361      }
362    }
363    break;
364  }
365  case Instruction::Shl:
366    // If we are truncating the result of this SHL, and if it's a shift of a
367    // constant amount, we can always perform a SHL in a smaller type.
368    if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
369      uint32_t BitWidth = Ty->getScalarSizeInBits();
370      if (CI->getLimitedValue(BitWidth) < BitWidth)
371        return CanEvaluateTruncated(I->getOperand(0), Ty);
372    }
373    break;
374  case Instruction::LShr:
375    // If this is a truncate of a logical shr, we can truncate it to a smaller
376    // lshr iff we know that the bits we would otherwise be shifting in are
377    // already zeros.
378    if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
379      uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
380      uint32_t BitWidth = Ty->getScalarSizeInBits();
381      if (MaskedValueIsZero(I->getOperand(0),
382            APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
383          CI->getLimitedValue(BitWidth) < BitWidth) {
384        return CanEvaluateTruncated(I->getOperand(0), Ty);
385      }
386    }
387    break;
388  case Instruction::Trunc:
389    // trunc(trunc(x)) -> trunc(x)
390    return true;
391  case Instruction::Select: {
392    SelectInst *SI = cast<SelectInst>(I);
393    return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
394           CanEvaluateTruncated(SI->getFalseValue(), Ty);
395  }
396  case Instruction::PHI: {
397    // We can change a phi if we can change all operands.  Note that we never
398    // get into trouble with cyclic PHIs here because we only consider
399    // instructions with a single use.
400    PHINode *PN = cast<PHINode>(I);
401    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
402      if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
403        return false;
404    return true;
405  }
406  default:
407    // TODO: Can handle more cases here.
408    break;
409  }
410
411  return false;
412}
413
414Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
415  if (Instruction *Result = commonCastTransforms(CI))
416    return Result;
417
418  // See if we can simplify any instructions used by the input whose sole
419  // purpose is to compute bits we don't care about.
420  if (SimplifyDemandedInstructionBits(CI))
421    return &CI;
422
423  Value *Src = CI.getOperand(0);
424  const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
425
426  // Attempt to truncate the entire input expression tree to the destination
427  // type.   Only do this if the dest type is a simple type, don't convert the
428  // expression tree to something weird like i93 unless the source is also
429  // strange.
430  if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
431      CanEvaluateTruncated(Src, DestTy)) {
432
433    // If this cast is a truncate, evaluting in a different type always
434    // eliminates the cast, so it is always a win.
435    DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
436          " to avoid cast: " << CI);
437    Value *Res = EvaluateInDifferentType(Src, DestTy, false);
438    assert(Res->getType() == DestTy);
439    return ReplaceInstUsesWith(CI, Res);
440  }
441
442  // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
443  if (DestTy->getScalarSizeInBits() == 1) {
444    Constant *One = ConstantInt::get(Src->getType(), 1);
445    Src = Builder->CreateAnd(Src, One, "tmp");
446    Value *Zero = Constant::getNullValue(Src->getType());
447    return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
448  }
449
450  return 0;
451}
452
453/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
454/// in order to eliminate the icmp.
455Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
456                                             bool DoXform) {
457  // If we are just checking for a icmp eq of a single bit and zext'ing it
458  // to an integer, then shift the bit to the appropriate place and then
459  // cast to integer to avoid the comparison.
460  if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
461    const APInt &Op1CV = Op1C->getValue();
462
463    // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
464    // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
465    if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
466        (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
467      if (!DoXform) return ICI;
468
469      Value *In = ICI->getOperand(0);
470      Value *Sh = ConstantInt::get(In->getType(),
471                                   In->getType()->getScalarSizeInBits()-1);
472      In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
473      if (In->getType() != CI.getType())
474        In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
475
476      if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
477        Constant *One = ConstantInt::get(In->getType(), 1);
478        In = Builder->CreateXor(In, One, In->getName()+".not");
479      }
480
481      return ReplaceInstUsesWith(CI, In);
482    }
483
484
485
486    // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
487    // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
488    // zext (X == 1) to i32 --> X        iff X has only the low bit set.
489    // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
490    // zext (X != 0) to i32 --> X        iff X has only the low bit set.
491    // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
492    // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
493    // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
494    if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
495        // This only works for EQ and NE
496        ICI->isEquality()) {
497      // If Op1C some other power of two, convert:
498      uint32_t BitWidth = Op1C->getType()->getBitWidth();
499      APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
500      APInt TypeMask(APInt::getAllOnesValue(BitWidth));
501      ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
502
503      APInt KnownZeroMask(~KnownZero);
504      if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
505        if (!DoXform) return ICI;
506
507        bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
508        if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
509          // (X&4) == 2 --> false
510          // (X&4) != 2 --> true
511          Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
512                                           isNE);
513          Res = ConstantExpr::getZExt(Res, CI.getType());
514          return ReplaceInstUsesWith(CI, Res);
515        }
516
517        uint32_t ShiftAmt = KnownZeroMask.logBase2();
518        Value *In = ICI->getOperand(0);
519        if (ShiftAmt) {
520          // Perform a logical shr by shiftamt.
521          // Insert the shift to put the result in the low bit.
522          In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
523                                   In->getName()+".lobit");
524        }
525
526        if ((Op1CV != 0) == isNE) { // Toggle the low bit.
527          Constant *One = ConstantInt::get(In->getType(), 1);
528          In = Builder->CreateXor(In, One, "tmp");
529        }
530
531        if (CI.getType() == In->getType())
532          return ReplaceInstUsesWith(CI, In);
533        else
534          return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
535      }
536    }
537  }
538
539  // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
540  // It is also profitable to transform icmp eq into not(xor(A, B)) because that
541  // may lead to additional simplifications.
542  if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
543    if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
544      uint32_t BitWidth = ITy->getBitWidth();
545      Value *LHS = ICI->getOperand(0);
546      Value *RHS = ICI->getOperand(1);
547
548      APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
549      APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
550      APInt TypeMask(APInt::getAllOnesValue(BitWidth));
551      ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
552      ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
553
554      if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
555        APInt KnownBits = KnownZeroLHS | KnownOneLHS;
556        APInt UnknownBit = ~KnownBits;
557        if (UnknownBit.countPopulation() == 1) {
558          if (!DoXform) return ICI;
559
560          Value *Result = Builder->CreateXor(LHS, RHS);
561
562          // Mask off any bits that are set and won't be shifted away.
563          if (KnownOneLHS.uge(UnknownBit))
564            Result = Builder->CreateAnd(Result,
565                                        ConstantInt::get(ITy, UnknownBit));
566
567          // Shift the bit we're testing down to the lsb.
568          Result = Builder->CreateLShr(
569               Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
570
571          if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
572            Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
573          Result->takeName(ICI);
574          return ReplaceInstUsesWith(CI, Result);
575        }
576      }
577    }
578  }
579
580  return 0;
581}
582
583/// CanEvaluateZExtd - Determine if the specified value can be computed in the
584/// specified wider type and produce the same low bits.  If not, return false.
585///
586/// If this function returns true, it can also return a non-zero number of bits
587/// (in BitsToClear) which indicates that the value it computes is correct for
588/// the zero extend, but that the additional BitsToClear bits need to be zero'd
589/// out.  For example, to promote something like:
590///
591///   %B = trunc i64 %A to i32
592///   %C = lshr i32 %B, 8
593///   %E = zext i32 %C to i64
594///
595/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
596/// set to 8 to indicate that the promoted value needs to have bits 24-31
597/// cleared in addition to bits 32-63.  Since an 'and' will be generated to
598/// clear the top bits anyway, doing this has no extra cost.
599///
600/// This function works on both vectors and scalars.
601static bool CanEvaluateZExtd(Value *V, const Type *Ty, unsigned &BitsToClear) {
602  BitsToClear = 0;
603  if (isa<Constant>(V))
604    return true;
605
606  Instruction *I = dyn_cast<Instruction>(V);
607  if (!I) return false;
608
609  // If the input is a truncate from the destination type, we can trivially
610  // eliminate it, even if it has multiple uses.
611  // FIXME: This is currently disabled until codegen can handle this without
612  // pessimizing code, PR5997.
613  if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
614    return true;
615
616  // We can't extend or shrink something that has multiple uses: doing so would
617  // require duplicating the instruction in general, which isn't profitable.
618  if (!I->hasOneUse()) return false;
619
620  unsigned Opc = I->getOpcode(), Tmp;
621  switch (Opc) {
622  case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
623  case Instruction::SExt:  // zext(sext(x)) -> sext(x).
624  case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
625    return true;
626  case Instruction::And:
627  case Instruction::Or:
628  case Instruction::Xor:
629  case Instruction::Add:
630  case Instruction::Sub:
631  case Instruction::Mul:
632  case Instruction::Shl:
633    if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
634        !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
635      return false;
636    // These can all be promoted if neither operand has 'bits to clear'.
637    if (BitsToClear == 0 && Tmp == 0)
638      return true;
639
640    // If the operation is an AND/OR/XOR and the bits to clear are zero in the
641    // other side, BitsToClear is ok.
642    if (Tmp == 0 &&
643        (Opc == Instruction::And || Opc == Instruction::Or ||
644         Opc == Instruction::Xor)) {
645      // We use MaskedValueIsZero here for generality, but the case we care
646      // about the most is constant RHS.
647      unsigned VSize = V->getType()->getScalarSizeInBits();
648      if (MaskedValueIsZero(I->getOperand(1),
649                            APInt::getHighBitsSet(VSize, BitsToClear)))
650        return true;
651    }
652
653    // Otherwise, we don't know how to analyze this BitsToClear case yet.
654    return false;
655
656  case Instruction::LShr:
657    // We can promote lshr(x, cst) if we can promote x.  This requires the
658    // ultimate 'and' to clear out the high zero bits we're clearing out though.
659    if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
660      if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
661        return false;
662      BitsToClear += Amt->getZExtValue();
663      if (BitsToClear > V->getType()->getScalarSizeInBits())
664        BitsToClear = V->getType()->getScalarSizeInBits();
665      return true;
666    }
667    // Cannot promote variable LSHR.
668    return false;
669  case Instruction::Select:
670    if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
671        !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
672        // TODO: If important, we could handle the case when the BitsToClear are
673        // known zero in the disagreeing side.
674        Tmp != BitsToClear)
675      return false;
676    return true;
677
678  case Instruction::PHI: {
679    // We can change a phi if we can change all operands.  Note that we never
680    // get into trouble with cyclic PHIs here because we only consider
681    // instructions with a single use.
682    PHINode *PN = cast<PHINode>(I);
683    if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
684      return false;
685    for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
686      if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
687          // TODO: If important, we could handle the case when the BitsToClear
688          // are known zero in the disagreeing input.
689          Tmp != BitsToClear)
690        return false;
691    return true;
692  }
693  default:
694    // TODO: Can handle more cases here.
695    return false;
696  }
697}
698
699Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
700  // If this zero extend is only used by a truncate, let the truncate by
701  // eliminated before we try to optimize this zext.
702  if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
703    return 0;
704
705  // If one of the common conversion will work, do it.
706  if (Instruction *Result = commonCastTransforms(CI))
707    return Result;
708
709  // See if we can simplify any instructions used by the input whose sole
710  // purpose is to compute bits we don't care about.
711  if (SimplifyDemandedInstructionBits(CI))
712    return &CI;
713
714  Value *Src = CI.getOperand(0);
715  const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
716
717  // Attempt to extend the entire input expression tree to the destination
718  // type.   Only do this if the dest type is a simple type, don't convert the
719  // expression tree to something weird like i93 unless the source is also
720  // strange.
721  unsigned BitsToClear;
722  if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
723      CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
724    assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
725           "Unreasonable BitsToClear");
726
727    // Okay, we can transform this!  Insert the new expression now.
728    DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
729          " to avoid zero extend: " << CI);
730    Value *Res = EvaluateInDifferentType(Src, DestTy, false);
731    assert(Res->getType() == DestTy);
732
733    uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
734    uint32_t DestBitSize = DestTy->getScalarSizeInBits();
735
736    // If the high bits are already filled with zeros, just replace this
737    // cast with the result.
738    if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
739                                                     DestBitSize-SrcBitsKept)))
740      return ReplaceInstUsesWith(CI, Res);
741
742    // We need to emit an AND to clear the high bits.
743    Constant *C = ConstantInt::get(Res->getType(),
744                               APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
745    return BinaryOperator::CreateAnd(Res, C);
746  }
747
748  // If this is a TRUNC followed by a ZEXT then we are dealing with integral
749  // types and if the sizes are just right we can convert this into a logical
750  // 'and' which will be much cheaper than the pair of casts.
751  if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
752    // TODO: Subsume this into EvaluateInDifferentType.
753
754    // Get the sizes of the types involved.  We know that the intermediate type
755    // will be smaller than A or C, but don't know the relation between A and C.
756    Value *A = CSrc->getOperand(0);
757    unsigned SrcSize = A->getType()->getScalarSizeInBits();
758    unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
759    unsigned DstSize = CI.getType()->getScalarSizeInBits();
760    // If we're actually extending zero bits, then if
761    // SrcSize <  DstSize: zext(a & mask)
762    // SrcSize == DstSize: a & mask
763    // SrcSize  > DstSize: trunc(a) & mask
764    if (SrcSize < DstSize) {
765      APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
766      Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
767      Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
768      return new ZExtInst(And, CI.getType());
769    }
770
771    if (SrcSize == DstSize) {
772      APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
773      return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
774                                                           AndValue));
775    }
776    if (SrcSize > DstSize) {
777      Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
778      APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
779      return BinaryOperator::CreateAnd(Trunc,
780                                       ConstantInt::get(Trunc->getType(),
781                                                        AndValue));
782    }
783  }
784
785  if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
786    return transformZExtICmp(ICI, CI);
787
788  BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
789  if (SrcI && SrcI->getOpcode() == Instruction::Or) {
790    // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
791    // of the (zext icmp) will be transformed.
792    ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
793    ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
794    if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
795        (transformZExtICmp(LHS, CI, false) ||
796         transformZExtICmp(RHS, CI, false))) {
797      Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
798      Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
799      return BinaryOperator::Create(Instruction::Or, LCast, RCast);
800    }
801  }
802
803  // zext(trunc(t) & C) -> (t & zext(C)).
804  if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
805    if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
806      if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
807        Value *TI0 = TI->getOperand(0);
808        if (TI0->getType() == CI.getType())
809          return
810            BinaryOperator::CreateAnd(TI0,
811                                ConstantExpr::getZExt(C, CI.getType()));
812      }
813
814  // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
815  if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
816    if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
817      if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
818        if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
819            And->getOperand(1) == C)
820          if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
821            Value *TI0 = TI->getOperand(0);
822            if (TI0->getType() == CI.getType()) {
823              Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
824              Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
825              return BinaryOperator::CreateXor(NewAnd, ZC);
826            }
827          }
828
829  // zext (xor i1 X, true) to i32  --> xor (zext i1 X to i32), 1
830  Value *X;
831  if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isInteger(1) &&
832      match(SrcI, m_Not(m_Value(X))) &&
833      (!X->hasOneUse() || !isa<CmpInst>(X))) {
834    Value *New = Builder->CreateZExt(X, CI.getType());
835    return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
836  }
837
838  return 0;
839}
840
841/// CanEvaluateSExtd - Return true if we can take the specified value
842/// and return it as type Ty without inserting any new casts and without
843/// changing the value of the common low bits.  This is used by code that tries
844/// to promote integer operations to a wider types will allow us to eliminate
845/// the extension.
846///
847/// This function works on both vectors and scalars.
848///
849static bool CanEvaluateSExtd(Value *V, const Type *Ty) {
850  assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
851         "Can't sign extend type to a smaller type");
852  // If this is a constant, it can be trivially promoted.
853  if (isa<Constant>(V))
854    return true;
855
856  Instruction *I = dyn_cast<Instruction>(V);
857  if (!I) return false;
858
859  // If this is a truncate from the dest type, we can trivially eliminate it,
860  // even if it has multiple uses.
861  // FIXME: This is currently disabled until codegen can handle this without
862  // pessimizing code, PR5997.
863  if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
864    return true;
865
866  // We can't extend or shrink something that has multiple uses: doing so would
867  // require duplicating the instruction in general, which isn't profitable.
868  if (!I->hasOneUse()) return false;
869
870  switch (I->getOpcode()) {
871  case Instruction::SExt:  // sext(sext(x)) -> sext(x)
872  case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
873  case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
874    return true;
875  case Instruction::And:
876  case Instruction::Or:
877  case Instruction::Xor:
878  case Instruction::Add:
879  case Instruction::Sub:
880  case Instruction::Mul:
881    // These operators can all arbitrarily be extended if their inputs can.
882    return CanEvaluateSExtd(I->getOperand(0), Ty) &&
883           CanEvaluateSExtd(I->getOperand(1), Ty);
884
885  //case Instruction::Shl:   TODO
886  //case Instruction::LShr:  TODO
887
888  case Instruction::Select:
889    return CanEvaluateSExtd(I->getOperand(1), Ty) &&
890           CanEvaluateSExtd(I->getOperand(2), Ty);
891
892  case Instruction::PHI: {
893    // We can change a phi if we can change all operands.  Note that we never
894    // get into trouble with cyclic PHIs here because we only consider
895    // instructions with a single use.
896    PHINode *PN = cast<PHINode>(I);
897    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
898      if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
899    return true;
900  }
901  default:
902    // TODO: Can handle more cases here.
903    break;
904  }
905
906  return false;
907}
908
909Instruction *InstCombiner::visitSExt(SExtInst &CI) {
910  // If this sign extend is only used by a truncate, let the truncate by
911  // eliminated before we try to optimize this zext.
912  if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
913    return 0;
914
915  if (Instruction *I = commonCastTransforms(CI))
916    return I;
917
918  // See if we can simplify any instructions used by the input whose sole
919  // purpose is to compute bits we don't care about.
920  if (SimplifyDemandedInstructionBits(CI))
921    return &CI;
922
923  Value *Src = CI.getOperand(0);
924  const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
925
926  // Canonicalize sign-extend from i1 to a select.
927  if (Src->getType()->isInteger(1))
928    return SelectInst::Create(Src,
929                              Constant::getAllOnesValue(CI.getType()),
930                              Constant::getNullValue(CI.getType()));
931
932  // Attempt to extend the entire input expression tree to the destination
933  // type.   Only do this if the dest type is a simple type, don't convert the
934  // expression tree to something weird like i93 unless the source is also
935  // strange.
936  if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
937      CanEvaluateSExtd(Src, DestTy)) {
938    // Okay, we can transform this!  Insert the new expression now.
939    DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
940          " to avoid sign extend: " << CI);
941    Value *Res = EvaluateInDifferentType(Src, DestTy, true);
942    assert(Res->getType() == DestTy);
943
944    uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
945    uint32_t DestBitSize = DestTy->getScalarSizeInBits();
946
947    // If the high bits are already filled with sign bit, just replace this
948    // cast with the result.
949    if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
950      return ReplaceInstUsesWith(CI, Res);
951
952    // We need to emit a shl + ashr to do the sign extend.
953    Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
954    return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
955                                      ShAmt);
956  }
957
958  // If this input is a trunc from our destination, then turn sext(trunc(x))
959  // into shifts.
960  if (TruncInst *TI = dyn_cast<TruncInst>(Src))
961    if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
962      uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
963      uint32_t DestBitSize = DestTy->getScalarSizeInBits();
964
965      // We need to emit a shl + ashr to do the sign extend.
966      Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
967      Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
968      return BinaryOperator::CreateAShr(Res, ShAmt);
969    }
970
971  // If the input is a shl/ashr pair of a same constant, then this is a sign
972  // extension from a smaller value.  If we could trust arbitrary bitwidth
973  // integers, we could turn this into a truncate to the smaller bit and then
974  // use a sext for the whole extension.  Since we don't, look deeper and check
975  // for a truncate.  If the source and dest are the same type, eliminate the
976  // trunc and extend and just do shifts.  For example, turn:
977  //   %a = trunc i32 %i to i8
978  //   %b = shl i8 %a, 6
979  //   %c = ashr i8 %b, 6
980  //   %d = sext i8 %c to i32
981  // into:
982  //   %a = shl i32 %i, 30
983  //   %d = ashr i32 %a, 30
984  Value *A = 0;
985  // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
986  ConstantInt *BA = 0, *CA = 0;
987  if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
988                        m_ConstantInt(CA))) &&
989      BA == CA && A->getType() == CI.getType()) {
990    unsigned MidSize = Src->getType()->getScalarSizeInBits();
991    unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
992    unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
993    Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
994    A = Builder->CreateShl(A, ShAmtV, CI.getName());
995    return BinaryOperator::CreateAShr(A, ShAmtV);
996  }
997
998  return 0;
999}
1000
1001
1002/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1003/// in the specified FP type without changing its value.
1004static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1005  bool losesInfo;
1006  APFloat F = CFP->getValueAPF();
1007  (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1008  if (!losesInfo)
1009    return ConstantFP::get(CFP->getContext(), F);
1010  return 0;
1011}
1012
1013/// LookThroughFPExtensions - If this is an fp extension instruction, look
1014/// through it until we get the source value.
1015static Value *LookThroughFPExtensions(Value *V) {
1016  if (Instruction *I = dyn_cast<Instruction>(V))
1017    if (I->getOpcode() == Instruction::FPExt)
1018      return LookThroughFPExtensions(I->getOperand(0));
1019
1020  // If this value is a constant, return the constant in the smallest FP type
1021  // that can accurately represent it.  This allows us to turn
1022  // (float)((double)X+2.0) into x+2.0f.
1023  if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1024    if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1025      return V;  // No constant folding of this.
1026    // See if the value can be truncated to float and then reextended.
1027    if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1028      return V;
1029    if (CFP->getType()->isDoubleTy())
1030      return V;  // Won't shrink.
1031    if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1032      return V;
1033    // Don't try to shrink to various long double types.
1034  }
1035
1036  return V;
1037}
1038
1039Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1040  if (Instruction *I = commonCastTransforms(CI))
1041    return I;
1042
1043  // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1044  // smaller than the destination type, we can eliminate the truncate by doing
1045  // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well
1046  // as many builtins (sqrt, etc).
1047  BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1048  if (OpI && OpI->hasOneUse()) {
1049    switch (OpI->getOpcode()) {
1050    default: break;
1051    case Instruction::FAdd:
1052    case Instruction::FSub:
1053    case Instruction::FMul:
1054    case Instruction::FDiv:
1055    case Instruction::FRem:
1056      const Type *SrcTy = OpI->getType();
1057      Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1058      Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1059      if (LHSTrunc->getType() != SrcTy &&
1060          RHSTrunc->getType() != SrcTy) {
1061        unsigned DstSize = CI.getType()->getScalarSizeInBits();
1062        // If the source types were both smaller than the destination type of
1063        // the cast, do this xform.
1064        if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1065            RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1066          LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1067          RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1068          return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1069        }
1070      }
1071      break;
1072    }
1073  }
1074  return 0;
1075}
1076
1077Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1078  return commonCastTransforms(CI);
1079}
1080
1081Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1082  Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1083  if (OpI == 0)
1084    return commonCastTransforms(FI);
1085
1086  // fptoui(uitofp(X)) --> X
1087  // fptoui(sitofp(X)) --> X
1088  // This is safe if the intermediate type has enough bits in its mantissa to
1089  // accurately represent all values of X.  For example, do not do this with
1090  // i64->float->i64.  This is also safe for sitofp case, because any negative
1091  // 'X' value would cause an undefined result for the fptoui.
1092  if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1093      OpI->getOperand(0)->getType() == FI.getType() &&
1094      (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1095                    OpI->getType()->getFPMantissaWidth())
1096    return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1097
1098  return commonCastTransforms(FI);
1099}
1100
1101Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1102  Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1103  if (OpI == 0)
1104    return commonCastTransforms(FI);
1105
1106  // fptosi(sitofp(X)) --> X
1107  // fptosi(uitofp(X)) --> X
1108  // This is safe if the intermediate type has enough bits in its mantissa to
1109  // accurately represent all values of X.  For example, do not do this with
1110  // i64->float->i64.  This is also safe for sitofp case, because any negative
1111  // 'X' value would cause an undefined result for the fptoui.
1112  if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1113      OpI->getOperand(0)->getType() == FI.getType() &&
1114      (int)FI.getType()->getScalarSizeInBits() <=
1115                    OpI->getType()->getFPMantissaWidth())
1116    return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1117
1118  return commonCastTransforms(FI);
1119}
1120
1121Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1122  return commonCastTransforms(CI);
1123}
1124
1125Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1126  return commonCastTransforms(CI);
1127}
1128
1129Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1130  // If the source integer type is larger than the intptr_t type for
1131  // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
1132  // allows the trunc to be exposed to other transforms.  Don't do this for
1133  // extending inttoptr's, because we don't know if the target sign or zero
1134  // extends to pointers.
1135  if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1136      TD->getPointerSizeInBits()) {
1137    Value *P = Builder->CreateTrunc(CI.getOperand(0),
1138                                    TD->getIntPtrType(CI.getContext()), "tmp");
1139    return new IntToPtrInst(P, CI.getType());
1140  }
1141
1142  if (Instruction *I = commonCastTransforms(CI))
1143    return I;
1144
1145  return 0;
1146}
1147
1148/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1149Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1150  Value *Src = CI.getOperand(0);
1151
1152  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1153    // If casting the result of a getelementptr instruction with no offset, turn
1154    // this into a cast of the original pointer!
1155    if (GEP->hasAllZeroIndices()) {
1156      // Changing the cast operand is usually not a good idea but it is safe
1157      // here because the pointer operand is being replaced with another
1158      // pointer operand so the opcode doesn't need to change.
1159      Worklist.Add(GEP);
1160      CI.setOperand(0, GEP->getOperand(0));
1161      return &CI;
1162    }
1163
1164    // If the GEP has a single use, and the base pointer is a bitcast, and the
1165    // GEP computes a constant offset, see if we can convert these three
1166    // instructions into fewer.  This typically happens with unions and other
1167    // non-type-safe code.
1168    if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1169        GEP->hasAllConstantIndices()) {
1170      // We are guaranteed to get a constant from EmitGEPOffset.
1171      ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1172      int64_t Offset = OffsetV->getSExtValue();
1173
1174      // Get the base pointer input of the bitcast, and the type it points to.
1175      Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1176      const Type *GEPIdxTy =
1177      cast<PointerType>(OrigBase->getType())->getElementType();
1178      SmallVector<Value*, 8> NewIndices;
1179      if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1180        // If we were able to index down into an element, create the GEP
1181        // and bitcast the result.  This eliminates one bitcast, potentially
1182        // two.
1183        Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1184        Builder->CreateInBoundsGEP(OrigBase,
1185                                   NewIndices.begin(), NewIndices.end()) :
1186        Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1187        NGEP->takeName(GEP);
1188
1189        if (isa<BitCastInst>(CI))
1190          return new BitCastInst(NGEP, CI.getType());
1191        assert(isa<PtrToIntInst>(CI));
1192        return new PtrToIntInst(NGEP, CI.getType());
1193      }
1194    }
1195  }
1196
1197  return commonCastTransforms(CI);
1198}
1199
1200Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1201  // If the destination integer type is smaller than the intptr_t type for
1202  // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
1203  // trunc to be exposed to other transforms.  Don't do this for extending
1204  // ptrtoint's, because we don't know if the target sign or zero extends its
1205  // pointers.
1206  if (TD &&
1207      CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1208    Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1209                                       TD->getIntPtrType(CI.getContext()),
1210                                       "tmp");
1211    return new TruncInst(P, CI.getType());
1212  }
1213
1214  return commonPointerCastTransforms(CI);
1215}
1216
1217Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1218  // If the operands are integer typed then apply the integer transforms,
1219  // otherwise just apply the common ones.
1220  Value *Src = CI.getOperand(0);
1221  const Type *SrcTy = Src->getType();
1222  const Type *DestTy = CI.getType();
1223
1224  // Get rid of casts from one type to the same type. These are useless and can
1225  // be replaced by the operand.
1226  if (DestTy == Src->getType())
1227    return ReplaceInstUsesWith(CI, Src);
1228
1229  if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1230    const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1231    const Type *DstElTy = DstPTy->getElementType();
1232    const Type *SrcElTy = SrcPTy->getElementType();
1233
1234    // If the address spaces don't match, don't eliminate the bitcast, which is
1235    // required for changing types.
1236    if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1237      return 0;
1238
1239    // If we are casting a alloca to a pointer to a type of the same
1240    // size, rewrite the allocation instruction to allocate the "right" type.
1241    // There is no need to modify malloc calls because it is their bitcast that
1242    // needs to be cleaned up.
1243    if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1244      if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1245        return V;
1246
1247    // If the source and destination are pointers, and this cast is equivalent
1248    // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
1249    // This can enhance SROA and other transforms that want type-safe pointers.
1250    Constant *ZeroUInt =
1251      Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1252    unsigned NumZeros = 0;
1253    while (SrcElTy != DstElTy &&
1254           isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1255           SrcElTy->getNumContainedTypes() /* not "{}" */) {
1256      SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1257      ++NumZeros;
1258    }
1259
1260    // If we found a path from the src to dest, create the getelementptr now.
1261    if (SrcElTy == DstElTy) {
1262      SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1263      return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
1264                                               ((Instruction*)NULL));
1265    }
1266  }
1267
1268  if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1269    if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1270      Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1271      return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1272                     Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1273      // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1274    }
1275  }
1276
1277  if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1278    if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1279      Value *Elem =
1280        Builder->CreateExtractElement(Src,
1281                   Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1282      return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1283    }
1284  }
1285
1286  if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1287    // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
1288    // a bitconvert to a vector with the same # elts.
1289    if (SVI->hasOneUse() && isa<VectorType>(DestTy) &&
1290        cast<VectorType>(DestTy)->getNumElements() ==
1291              SVI->getType()->getNumElements() &&
1292        SVI->getType()->getNumElements() ==
1293          cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1294      BitCastInst *Tmp;
1295      // If either of the operands is a cast from CI.getType(), then
1296      // evaluating the shuffle in the casted destination's type will allow
1297      // us to eliminate at least one cast.
1298      if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1299           Tmp->getOperand(0)->getType() == DestTy) ||
1300          ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1301           Tmp->getOperand(0)->getType() == DestTy)) {
1302        Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1303        Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1304        // Return a new shuffle vector.  Use the same element ID's, as we
1305        // know the vector types match #elts.
1306        return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1307      }
1308    }
1309  }
1310
1311  if (isa<PointerType>(SrcTy))
1312    return commonPointerCastTransforms(CI);
1313  return commonCastTransforms(CI);
1314}
1315