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