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