e018b351082a23b7abc229ba7f8d415d01ed852d
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineCasts.cpp
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"
17 using namespace llvm;
18 using 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 ///
24 static 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.
70 Instruction *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.
154 Value *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.
228 static Instruction::CastOps 
229 isEliminableCastPair(
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.
261 bool 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.
274 Instruction *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 ///
318 static 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
414 Instruction *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.
455 Instruction *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.
601 static 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
699 Instruction *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 ///
849 static 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
909 Instruction *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 the input is a shl/ashr pair of a same constant, then this is a sign
959   // extension from a smaller value.  If we could trust arbitrary bitwidth
960   // integers, we could turn this into a truncate to the smaller bit and then
961   // use a sext for the whole extension.  Since we don't, look deeper and check
962   // for a truncate.  If the source and dest are the same type, eliminate the
963   // trunc and extend and just do shifts.  For example, turn:
964   //   %a = trunc i32 %i to i8
965   //   %b = shl i8 %a, 6
966   //   %c = ashr i8 %b, 6
967   //   %d = sext i8 %c to i32
968   // into:
969   //   %a = shl i32 %i, 30
970   //   %d = ashr i32 %a, 30
971   Value *A = 0;
972   // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
973   ConstantInt *BA = 0, *CA = 0;
974   if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
975                         m_ConstantInt(CA))) &&
976       BA == CA && A->getType() == CI.getType()) {
977     unsigned MidSize = Src->getType()->getScalarSizeInBits();
978     unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
979     unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
980     Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
981     A = Builder->CreateShl(A, ShAmtV, CI.getName());
982     return BinaryOperator::CreateAShr(A, ShAmtV);
983   }
984   
985   return 0;
986 }
987
988
989 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
990 /// in the specified FP type without changing its value.
991 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
992   bool losesInfo;
993   APFloat F = CFP->getValueAPF();
994   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
995   if (!losesInfo)
996     return ConstantFP::get(CFP->getContext(), F);
997   return 0;
998 }
999
1000 /// LookThroughFPExtensions - If this is an fp extension instruction, look
1001 /// through it until we get the source value.
1002 static Value *LookThroughFPExtensions(Value *V) {
1003   if (Instruction *I = dyn_cast<Instruction>(V))
1004     if (I->getOpcode() == Instruction::FPExt)
1005       return LookThroughFPExtensions(I->getOperand(0));
1006   
1007   // If this value is a constant, return the constant in the smallest FP type
1008   // that can accurately represent it.  This allows us to turn
1009   // (float)((double)X+2.0) into x+2.0f.
1010   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1011     if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1012       return V;  // No constant folding of this.
1013     // See if the value can be truncated to float and then reextended.
1014     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1015       return V;
1016     if (CFP->getType()->isDoubleTy())
1017       return V;  // Won't shrink.
1018     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1019       return V;
1020     // Don't try to shrink to various long double types.
1021   }
1022   
1023   return V;
1024 }
1025
1026 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1027   if (Instruction *I = commonCastTransforms(CI))
1028     return I;
1029   
1030   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1031   // smaller than the destination type, we can eliminate the truncate by doing
1032   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well
1033   // as many builtins (sqrt, etc).
1034   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1035   if (OpI && OpI->hasOneUse()) {
1036     switch (OpI->getOpcode()) {
1037     default: break;
1038     case Instruction::FAdd:
1039     case Instruction::FSub:
1040     case Instruction::FMul:
1041     case Instruction::FDiv:
1042     case Instruction::FRem:
1043       const Type *SrcTy = OpI->getType();
1044       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1045       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1046       if (LHSTrunc->getType() != SrcTy && 
1047           RHSTrunc->getType() != SrcTy) {
1048         unsigned DstSize = CI.getType()->getScalarSizeInBits();
1049         // If the source types were both smaller than the destination type of
1050         // the cast, do this xform.
1051         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1052             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1053           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1054           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1055           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1056         }
1057       }
1058       break;  
1059     }
1060   }
1061   return 0;
1062 }
1063
1064 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1065   return commonCastTransforms(CI);
1066 }
1067
1068 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1069   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1070   if (OpI == 0)
1071     return commonCastTransforms(FI);
1072
1073   // fptoui(uitofp(X)) --> X
1074   // fptoui(sitofp(X)) --> X
1075   // This is safe if the intermediate type has enough bits in its mantissa to
1076   // accurately represent all values of X.  For example, do not do this with
1077   // i64->float->i64.  This is also safe for sitofp case, because any negative
1078   // 'X' value would cause an undefined result for the fptoui. 
1079   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1080       OpI->getOperand(0)->getType() == FI.getType() &&
1081       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1082                     OpI->getType()->getFPMantissaWidth())
1083     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1084
1085   return commonCastTransforms(FI);
1086 }
1087
1088 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1089   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1090   if (OpI == 0)
1091     return commonCastTransforms(FI);
1092   
1093   // fptosi(sitofp(X)) --> X
1094   // fptosi(uitofp(X)) --> X
1095   // This is safe if the intermediate type has enough bits in its mantissa to
1096   // accurately represent all values of X.  For example, do not do this with
1097   // i64->float->i64.  This is also safe for sitofp case, because any negative
1098   // 'X' value would cause an undefined result for the fptoui. 
1099   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1100       OpI->getOperand(0)->getType() == FI.getType() &&
1101       (int)FI.getType()->getScalarSizeInBits() <=
1102                     OpI->getType()->getFPMantissaWidth())
1103     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1104   
1105   return commonCastTransforms(FI);
1106 }
1107
1108 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1109   return commonCastTransforms(CI);
1110 }
1111
1112 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1113   return commonCastTransforms(CI);
1114 }
1115
1116 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1117   // If the source integer type is larger than the intptr_t type for
1118   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
1119   // allows the trunc to be exposed to other transforms.  Don't do this for
1120   // extending inttoptr's, because we don't know if the target sign or zero
1121   // extends to pointers.
1122   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1123       TD->getPointerSizeInBits()) {
1124     Value *P = Builder->CreateTrunc(CI.getOperand(0),
1125                                     TD->getIntPtrType(CI.getContext()), "tmp");
1126     return new IntToPtrInst(P, CI.getType());
1127   }
1128   
1129   if (Instruction *I = commonCastTransforms(CI))
1130     return I;
1131
1132   return 0;
1133 }
1134
1135 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1136 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1137   Value *Src = CI.getOperand(0);
1138   
1139   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1140     // If casting the result of a getelementptr instruction with no offset, turn
1141     // this into a cast of the original pointer!
1142     if (GEP->hasAllZeroIndices()) {
1143       // Changing the cast operand is usually not a good idea but it is safe
1144       // here because the pointer operand is being replaced with another 
1145       // pointer operand so the opcode doesn't need to change.
1146       Worklist.Add(GEP);
1147       CI.setOperand(0, GEP->getOperand(0));
1148       return &CI;
1149     }
1150     
1151     // If the GEP has a single use, and the base pointer is a bitcast, and the
1152     // GEP computes a constant offset, see if we can convert these three
1153     // instructions into fewer.  This typically happens with unions and other
1154     // non-type-safe code.
1155     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1156         GEP->hasAllConstantIndices()) {
1157       // We are guaranteed to get a constant from EmitGEPOffset.
1158       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1159       int64_t Offset = OffsetV->getSExtValue();
1160       
1161       // Get the base pointer input of the bitcast, and the type it points to.
1162       Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1163       const Type *GEPIdxTy =
1164       cast<PointerType>(OrigBase->getType())->getElementType();
1165       SmallVector<Value*, 8> NewIndices;
1166       if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1167         // If we were able to index down into an element, create the GEP
1168         // and bitcast the result.  This eliminates one bitcast, potentially
1169         // two.
1170         Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1171         Builder->CreateInBoundsGEP(OrigBase,
1172                                    NewIndices.begin(), NewIndices.end()) :
1173         Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1174         NGEP->takeName(GEP);
1175         
1176         if (isa<BitCastInst>(CI))
1177           return new BitCastInst(NGEP, CI.getType());
1178         assert(isa<PtrToIntInst>(CI));
1179         return new PtrToIntInst(NGEP, CI.getType());
1180       }      
1181     }
1182   }
1183   
1184   return commonCastTransforms(CI);
1185 }
1186
1187 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1188   // If the destination integer type is smaller than the intptr_t type for
1189   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
1190   // trunc to be exposed to other transforms.  Don't do this for extending
1191   // ptrtoint's, because we don't know if the target sign or zero extends its
1192   // pointers.
1193   if (TD &&
1194       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1195     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1196                                        TD->getIntPtrType(CI.getContext()),
1197                                        "tmp");
1198     return new TruncInst(P, CI.getType());
1199   }
1200   
1201   return commonPointerCastTransforms(CI);
1202 }
1203
1204 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1205   // If the operands are integer typed then apply the integer transforms,
1206   // otherwise just apply the common ones.
1207   Value *Src = CI.getOperand(0);
1208   const Type *SrcTy = Src->getType();
1209   const Type *DestTy = CI.getType();
1210
1211   // Get rid of casts from one type to the same type. These are useless and can
1212   // be replaced by the operand.
1213   if (DestTy == Src->getType())
1214     return ReplaceInstUsesWith(CI, Src);
1215
1216   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1217     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1218     const Type *DstElTy = DstPTy->getElementType();
1219     const Type *SrcElTy = SrcPTy->getElementType();
1220     
1221     // If the address spaces don't match, don't eliminate the bitcast, which is
1222     // required for changing types.
1223     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1224       return 0;
1225     
1226     // If we are casting a alloca to a pointer to a type of the same
1227     // size, rewrite the allocation instruction to allocate the "right" type.
1228     // There is no need to modify malloc calls because it is their bitcast that
1229     // needs to be cleaned up.
1230     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1231       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1232         return V;
1233     
1234     // If the source and destination are pointers, and this cast is equivalent
1235     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
1236     // This can enhance SROA and other transforms that want type-safe pointers.
1237     Constant *ZeroUInt =
1238       Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1239     unsigned NumZeros = 0;
1240     while (SrcElTy != DstElTy && 
1241            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1242            SrcElTy->getNumContainedTypes() /* not "{}" */) {
1243       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1244       ++NumZeros;
1245     }
1246
1247     // If we found a path from the src to dest, create the getelementptr now.
1248     if (SrcElTy == DstElTy) {
1249       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1250       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
1251                                                ((Instruction*)NULL));
1252     }
1253   }
1254
1255   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1256     if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1257       Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1258       return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1259                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1260       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1261     }
1262   }
1263
1264   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1265     if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1266       Value *Elem = 
1267         Builder->CreateExtractElement(Src,
1268                    Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1269       return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1270     }
1271   }
1272
1273   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1274     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
1275     // a bitconvert to a vector with the same # elts.
1276     if (SVI->hasOneUse() && isa<VectorType>(DestTy) && 
1277         cast<VectorType>(DestTy)->getNumElements() ==
1278               SVI->getType()->getNumElements() &&
1279         SVI->getType()->getNumElements() ==
1280           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1281       BitCastInst *Tmp;
1282       // If either of the operands is a cast from CI.getType(), then
1283       // evaluating the shuffle in the casted destination's type will allow
1284       // us to eliminate at least one cast.
1285       if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) && 
1286            Tmp->getOperand(0)->getType() == DestTy) ||
1287           ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) && 
1288            Tmp->getOperand(0)->getType() == DestTy)) {
1289         Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1290         Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1291         // Return a new shuffle vector.  Use the same element ID's, as we
1292         // know the vector types match #elts.
1293         return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1294       }
1295     }
1296   }
1297   
1298   if (isa<PointerType>(SrcTy))
1299     return commonPointerCastTransforms(CI);
1300   return commonCastTransforms(CI);
1301 }