Null initialize a few variables flagged by
[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                                         uint64_t &Offset) {
26   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
27     Offset = CI->getZExtValue();
28     Scale  = 0;
29     return ConstantInt::get(Val->getType(), 0);
30   }
31   
32   if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
33     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
34       if (I->getOpcode() == Instruction::Shl) {
35         // This is a value scaled by '1 << the shift amt'.
36         Scale = UINT64_C(1) << RHS->getZExtValue();
37         Offset = 0;
38         return I->getOperand(0);
39       }
40       
41       if (I->getOpcode() == Instruction::Mul) {
42         // This value is scaled by 'RHS'.
43         Scale = RHS->getZExtValue();
44         Offset = 0;
45         return I->getOperand(0);
46       }
47       
48       if (I->getOpcode() == Instruction::Add) {
49         // We have X+C.  Check to see if we really have (X*C2)+C1, 
50         // where C1 is divisible by C2.
51         unsigned SubScale;
52         Value *SubVal = 
53           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
54         Offset += RHS->getZExtValue();
55         Scale = SubScale;
56         return SubVal;
57       }
58     }
59   }
60
61   // Otherwise, we can't look past this.
62   Scale = 1;
63   Offset = 0;
64   return Val;
65 }
66
67 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
68 /// try to eliminate the cast by moving the type information into the alloc.
69 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
70                                                    AllocaInst &AI) {
71   // This requires TargetData to get the alloca alignment and size information.
72   if (!TD) return 0;
73
74   const PointerType *PTy = cast<PointerType>(CI.getType());
75   
76   BuilderTy AllocaBuilder(*Builder);
77   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
78
79   // Get the type really allocated and the type casted to.
80   const Type *AllocElTy = AI.getAllocatedType();
81   const Type *CastElTy = PTy->getElementType();
82   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
83
84   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
85   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
86   if (CastElTyAlign < AllocElTyAlign) return 0;
87
88   // If the allocation has multiple uses, only promote it if we are strictly
89   // increasing the alignment of the resultant allocation.  If we keep it the
90   // same, we open the door to infinite loops of various kinds.  (A reference
91   // from a dbg.declare doesn't count as a use for this purpose.)
92   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
93       CastElTyAlign == AllocElTyAlign) return 0;
94
95   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
96   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
97   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
98
99   // See if we can satisfy the modulus by pulling a scale out of the array
100   // size argument.
101   unsigned ArraySizeScale;
102   uint64_t ArrayOffset;
103   Value *NumElements = // See if the array size is a decomposable linear expr.
104     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
105  
106   // If we can now satisfy the modulus, by using a non-1 scale, we really can
107   // do the xform.
108   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
109       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
110
111   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
112   Value *Amt = 0;
113   if (Scale == 1) {
114     Amt = NumElements;
115   } else {
116     Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
117     // Insert before the alloca, not before the cast.
118     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
119   }
120   
121   if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
122     Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
123                                   Offset, true);
124     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
125   }
126   
127   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
128   New->setAlignment(AI.getAlignment());
129   New->takeName(&AI);
130   
131   // If the allocation has one real use plus a dbg.declare, just remove the
132   // declare.
133   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
134     EraseInstFromFunction(*(Instruction*)DI);
135   }
136   // If the allocation has multiple real uses, insert a cast and change all
137   // things that used it to use the new cast.  This will also hack on CI, but it
138   // will die soon.
139   else if (!AI.hasOneUse()) {
140     // New is the allocation instruction, pointer typed. AI is the original
141     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
142     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
143     AI.replaceAllUsesWith(NewCast);
144   }
145   return ReplaceInstUsesWith(CI, New);
146 }
147
148
149
150 /// EvaluateInDifferentType - Given an expression that 
151 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
152 /// insert the code to evaluate the expression.
153 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
154                                              bool isSigned) {
155   if (Constant *C = dyn_cast<Constant>(V)) {
156     C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
157     // If we got a constantexpr back, try to simplify it with TD info.
158     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
159       C = ConstantFoldConstantExpression(CE, TD);
160     return C;
161   }
162
163   // Otherwise, it must be an instruction.
164   Instruction *I = cast<Instruction>(V);
165   Instruction *Res = 0;
166   unsigned Opc = I->getOpcode();
167   switch (Opc) {
168   case Instruction::Add:
169   case Instruction::Sub:
170   case Instruction::Mul:
171   case Instruction::And:
172   case Instruction::Or:
173   case Instruction::Xor:
174   case Instruction::AShr:
175   case Instruction::LShr:
176   case Instruction::Shl:
177   case Instruction::UDiv:
178   case Instruction::URem: {
179     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
180     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
181     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
182     break;
183   }    
184   case Instruction::Trunc:
185   case Instruction::ZExt:
186   case Instruction::SExt:
187     // If the source type of the cast is the type we're trying for then we can
188     // just return the source.  There's no need to insert it because it is not
189     // new.
190     if (I->getOperand(0)->getType() == Ty)
191       return I->getOperand(0);
192     
193     // Otherwise, must be the same type of cast, so just reinsert a new one.
194     // This also handles the case of zext(trunc(x)) -> zext(x).
195     Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
196                                       Opc == Instruction::SExt);
197     break;
198   case Instruction::Select: {
199     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
200     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
201     Res = SelectInst::Create(I->getOperand(0), True, False);
202     break;
203   }
204   case Instruction::PHI: {
205     PHINode *OPN = cast<PHINode>(I);
206     PHINode *NPN = PHINode::Create(Ty);
207     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
208       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
209       NPN->addIncoming(V, OPN->getIncomingBlock(i));
210     }
211     Res = NPN;
212     break;
213   }
214   default: 
215     // TODO: Can handle more cases here.
216     llvm_unreachable("Unreachable!");
217     break;
218   }
219   
220   Res->takeName(I);
221   return InsertNewInstBefore(Res, *I);
222 }
223
224
225 /// This function is a wrapper around CastInst::isEliminableCastPair. It
226 /// simply extracts arguments and returns what that function returns.
227 static Instruction::CastOps 
228 isEliminableCastPair(
229   const CastInst *CI, ///< The first cast instruction
230   unsigned opcode,       ///< The opcode of the second cast instruction
231   const Type *DstTy,     ///< The target type for the second cast instruction
232   TargetData *TD         ///< The target data for pointer size
233 ) {
234
235   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
236   const Type *MidTy = CI->getType();                  // B from above
237
238   // Get the opcodes of the two Cast instructions
239   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
240   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
241
242   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
243                                                 DstTy,
244                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
245   
246   // We don't want to form an inttoptr or ptrtoint that converts to an integer
247   // type that differs from the pointer size.
248   if ((Res == Instruction::IntToPtr &&
249           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
250       (Res == Instruction::PtrToInt &&
251           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
252     Res = 0;
253   
254   return Instruction::CastOps(Res);
255 }
256
257 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
258 /// results in any code being generated and is interesting to optimize out. If
259 /// the cast can be eliminated by some other simple transformation, we prefer
260 /// to do the simplification first.
261 bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
262                                       const Type *Ty) {
263   // Noop casts and casts of constants should be eliminated trivially.
264   if (V->getType() == Ty || isa<Constant>(V)) return false;
265   
266   // If this is another cast that can be eliminated, we prefer to have it
267   // eliminated.
268   if (const CastInst *CI = dyn_cast<CastInst>(V))
269     if (isEliminableCastPair(CI, opc, Ty, TD))
270       return false;
271   
272   // If this is a vector sext from a compare, then we don't want to break the
273   // idiom where each element of the extended vector is either zero or all ones.
274   if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
275     return false;
276   
277   return true;
278 }
279
280
281 /// @brief Implement the transforms common to all CastInst visitors.
282 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
283   Value *Src = CI.getOperand(0);
284
285   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
286   // eliminate it now.
287   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
288     if (Instruction::CastOps opc = 
289         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
290       // The first cast (CSrc) is eliminable so we need to fix up or replace
291       // the second cast (CI). CSrc will then have a good chance of being dead.
292       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
293     }
294   }
295
296   // If we are casting a select then fold the cast into the select
297   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
298     if (Instruction *NV = FoldOpIntoSelect(CI, SI))
299       return NV;
300
301   // If we are casting a PHI then fold the cast into the PHI
302   if (isa<PHINode>(Src)) {
303     // We don't do this if this would create a PHI node with an illegal type if
304     // it is currently legal.
305     if (!Src->getType()->isIntegerTy() ||
306         !CI.getType()->isIntegerTy() ||
307         ShouldChangeType(CI.getType(), Src->getType()))
308       if (Instruction *NV = FoldOpIntoPhi(CI))
309         return NV;
310   }
311   
312   return 0;
313 }
314
315 /// CanEvaluateTruncated - Return true if we can evaluate the specified
316 /// expression tree as type Ty instead of its larger type, and arrive with the
317 /// same value.  This is used by code that tries to eliminate truncates.
318 ///
319 /// Ty will always be a type smaller than V.  We should return true if trunc(V)
320 /// can be computed by computing V in the smaller type.  If V is an instruction,
321 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
322 /// makes sense if x and y can be efficiently truncated.
323 ///
324 /// This function works on both vectors and scalars.
325 ///
326 static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
327   // We can always evaluate constants in another type.
328   if (isa<Constant>(V))
329     return true;
330   
331   Instruction *I = dyn_cast<Instruction>(V);
332   if (!I) return false;
333   
334   const Type *OrigTy = V->getType();
335   
336   // If this is an extension from the dest type, we can eliminate it, even if it
337   // has multiple uses.
338   if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) && 
339       I->getOperand(0)->getType() == Ty)
340     return true;
341
342   // We can't extend or shrink something that has multiple uses: doing so would
343   // require duplicating the instruction in general, which isn't profitable.
344   if (!I->hasOneUse()) return false;
345
346   unsigned Opc = I->getOpcode();
347   switch (Opc) {
348   case Instruction::Add:
349   case Instruction::Sub:
350   case Instruction::Mul:
351   case Instruction::And:
352   case Instruction::Or:
353   case Instruction::Xor:
354     // These operators can all arbitrarily be extended or truncated.
355     return CanEvaluateTruncated(I->getOperand(0), Ty) &&
356            CanEvaluateTruncated(I->getOperand(1), Ty);
357
358   case Instruction::UDiv:
359   case Instruction::URem: {
360     // UDiv and URem can be truncated if all the truncated bits are zero.
361     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
362     uint32_t BitWidth = Ty->getScalarSizeInBits();
363     if (BitWidth < OrigBitWidth) {
364       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
365       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
366           MaskedValueIsZero(I->getOperand(1), Mask)) {
367         return CanEvaluateTruncated(I->getOperand(0), Ty) &&
368                CanEvaluateTruncated(I->getOperand(1), Ty);
369       }
370     }
371     break;
372   }
373   case Instruction::Shl:
374     // If we are truncating the result of this SHL, and if it's a shift of a
375     // constant amount, we can always perform a SHL in a smaller type.
376     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
377       uint32_t BitWidth = Ty->getScalarSizeInBits();
378       if (CI->getLimitedValue(BitWidth) < BitWidth)
379         return CanEvaluateTruncated(I->getOperand(0), Ty);
380     }
381     break;
382   case Instruction::LShr:
383     // If this is a truncate of a logical shr, we can truncate it to a smaller
384     // lshr iff we know that the bits we would otherwise be shifting in are
385     // already zeros.
386     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
387       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
388       uint32_t BitWidth = Ty->getScalarSizeInBits();
389       if (MaskedValueIsZero(I->getOperand(0),
390             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
391           CI->getLimitedValue(BitWidth) < BitWidth) {
392         return CanEvaluateTruncated(I->getOperand(0), Ty);
393       }
394     }
395     break;
396   case Instruction::Trunc:
397     // trunc(trunc(x)) -> trunc(x)
398     return true;
399   case Instruction::ZExt:
400   case Instruction::SExt:
401     // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
402     // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
403     return true;
404   case Instruction::Select: {
405     SelectInst *SI = cast<SelectInst>(I);
406     return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
407            CanEvaluateTruncated(SI->getFalseValue(), Ty);
408   }
409   case Instruction::PHI: {
410     // We can change a phi if we can change all operands.  Note that we never
411     // get into trouble with cyclic PHIs here because we only consider
412     // instructions with a single use.
413     PHINode *PN = cast<PHINode>(I);
414     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
415       if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
416         return false;
417     return true;
418   }
419   default:
420     // TODO: Can handle more cases here.
421     break;
422   }
423   
424   return false;
425 }
426
427 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
428   if (Instruction *Result = commonCastTransforms(CI))
429     return Result;
430   
431   // See if we can simplify any instructions used by the input whose sole 
432   // purpose is to compute bits we don't care about.
433   if (SimplifyDemandedInstructionBits(CI))
434     return &CI;
435   
436   Value *Src = CI.getOperand(0);
437   const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
438   
439   // Attempt to truncate the entire input expression tree to the destination
440   // type.   Only do this if the dest type is a simple type, don't convert the
441   // expression tree to something weird like i93 unless the source is also
442   // strange.
443   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
444       CanEvaluateTruncated(Src, DestTy)) {
445       
446     // If this cast is a truncate, evaluting in a different type always
447     // eliminates the cast, so it is always a win.
448     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
449           " to avoid cast: " << CI << '\n');
450     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
451     assert(Res->getType() == DestTy);
452     return ReplaceInstUsesWith(CI, Res);
453   }
454
455   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
456   if (DestTy->getScalarSizeInBits() == 1) {
457     Constant *One = ConstantInt::get(Src->getType(), 1);
458     Src = Builder->CreateAnd(Src, One, "tmp");
459     Value *Zero = Constant::getNullValue(Src->getType());
460     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
461   }
462   
463   // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
464   Value *A = 0; ConstantInt *Cst = 0;
465   if (Src->hasOneUse() &&
466       match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
467     // We have three types to worry about here, the type of A, the source of
468     // the truncate (MidSize), and the destination of the truncate. We know that
469     // ASize < MidSize   and MidSize > ResultSize, but don't know the relation
470     // between ASize and ResultSize.
471     unsigned ASize = A->getType()->getPrimitiveSizeInBits();
472     
473     // If the shift amount is larger than the size of A, then the result is
474     // known to be zero because all the input bits got shifted out.
475     if (Cst->getZExtValue() >= ASize)
476       return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
477
478     // Since we're doing an lshr and a zero extend, and know that the shift
479     // amount is smaller than ASize, it is always safe to do the shift in A's
480     // type, then zero extend or truncate to the result.
481     Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
482     Shift->takeName(Src);
483     return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
484   }
485   
486   // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
487   // type isn't non-native.
488   if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
489       ShouldChangeType(Src->getType(), CI.getType()) &&
490       match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
491     Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
492     return BinaryOperator::CreateAnd(NewTrunc,
493                                      ConstantExpr::getTrunc(Cst, CI.getType()));
494   }
495
496   return 0;
497 }
498
499 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
500 /// in order to eliminate the icmp.
501 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
502                                              bool DoXform) {
503   // If we are just checking for a icmp eq of a single bit and zext'ing it
504   // to an integer, then shift the bit to the appropriate place and then
505   // cast to integer to avoid the comparison.
506   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
507     const APInt &Op1CV = Op1C->getValue();
508       
509     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
510     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
511     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
512         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
513       if (!DoXform) return ICI;
514
515       Value *In = ICI->getOperand(0);
516       Value *Sh = ConstantInt::get(In->getType(),
517                                    In->getType()->getScalarSizeInBits()-1);
518       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
519       if (In->getType() != CI.getType())
520         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
521
522       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
523         Constant *One = ConstantInt::get(In->getType(), 1);
524         In = Builder->CreateXor(In, One, In->getName()+".not");
525       }
526
527       return ReplaceInstUsesWith(CI, In);
528     }
529       
530       
531       
532     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
533     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
534     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
535     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
536     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
537     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
538     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
539     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
540     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
541         // This only works for EQ and NE
542         ICI->isEquality()) {
543       // If Op1C some other power of two, convert:
544       uint32_t BitWidth = Op1C->getType()->getBitWidth();
545       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
546       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
547       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
548         
549       APInt KnownZeroMask(~KnownZero);
550       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
551         if (!DoXform) return ICI;
552
553         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
554         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
555           // (X&4) == 2 --> false
556           // (X&4) != 2 --> true
557           Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
558                                            isNE);
559           Res = ConstantExpr::getZExt(Res, CI.getType());
560           return ReplaceInstUsesWith(CI, Res);
561         }
562           
563         uint32_t ShiftAmt = KnownZeroMask.logBase2();
564         Value *In = ICI->getOperand(0);
565         if (ShiftAmt) {
566           // Perform a logical shr by shiftamt.
567           // Insert the shift to put the result in the low bit.
568           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
569                                    In->getName()+".lobit");
570         }
571           
572         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
573           Constant *One = ConstantInt::get(In->getType(), 1);
574           In = Builder->CreateXor(In, One, "tmp");
575         }
576           
577         if (CI.getType() == In->getType())
578           return ReplaceInstUsesWith(CI, In);
579         return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
580       }
581     }
582   }
583
584   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
585   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
586   // may lead to additional simplifications.
587   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
588     if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
589       uint32_t BitWidth = ITy->getBitWidth();
590       Value *LHS = ICI->getOperand(0);
591       Value *RHS = ICI->getOperand(1);
592
593       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
594       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
595       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
596       ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
597       ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
598
599       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
600         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
601         APInt UnknownBit = ~KnownBits;
602         if (UnknownBit.countPopulation() == 1) {
603           if (!DoXform) return ICI;
604
605           Value *Result = Builder->CreateXor(LHS, RHS);
606
607           // Mask off any bits that are set and won't be shifted away.
608           if (KnownOneLHS.uge(UnknownBit))
609             Result = Builder->CreateAnd(Result,
610                                         ConstantInt::get(ITy, UnknownBit));
611
612           // Shift the bit we're testing down to the lsb.
613           Result = Builder->CreateLShr(
614                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
615
616           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
617             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
618           Result->takeName(ICI);
619           return ReplaceInstUsesWith(CI, Result);
620         }
621       }
622     }
623   }
624
625   return 0;
626 }
627
628 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
629 /// specified wider type and produce the same low bits.  If not, return false.
630 ///
631 /// If this function returns true, it can also return a non-zero number of bits
632 /// (in BitsToClear) which indicates that the value it computes is correct for
633 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
634 /// out.  For example, to promote something like:
635 ///
636 ///   %B = trunc i64 %A to i32
637 ///   %C = lshr i32 %B, 8
638 ///   %E = zext i32 %C to i64
639 ///
640 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
641 /// set to 8 to indicate that the promoted value needs to have bits 24-31
642 /// cleared in addition to bits 32-63.  Since an 'and' will be generated to
643 /// clear the top bits anyway, doing this has no extra cost.
644 ///
645 /// This function works on both vectors and scalars.
646 static bool CanEvaluateZExtd(Value *V, const Type *Ty, unsigned &BitsToClear) {
647   BitsToClear = 0;
648   if (isa<Constant>(V))
649     return true;
650   
651   Instruction *I = dyn_cast<Instruction>(V);
652   if (!I) return false;
653   
654   // If the input is a truncate from the destination type, we can trivially
655   // eliminate it, even if it has multiple uses.
656   // FIXME: This is currently disabled until codegen can handle this without
657   // pessimizing code, PR5997.
658   if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
659     return true;
660   
661   // We can't extend or shrink something that has multiple uses: doing so would
662   // require duplicating the instruction in general, which isn't profitable.
663   if (!I->hasOneUse()) return false;
664   
665   unsigned Opc = I->getOpcode(), Tmp;
666   switch (Opc) {
667   case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
668   case Instruction::SExt:  // zext(sext(x)) -> sext(x).
669   case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
670     return true;
671   case Instruction::And:
672   case Instruction::Or:
673   case Instruction::Xor:
674   case Instruction::Add:
675   case Instruction::Sub:
676   case Instruction::Mul:
677   case Instruction::Shl:
678     if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
679         !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
680       return false;
681     // These can all be promoted if neither operand has 'bits to clear'.
682     if (BitsToClear == 0 && Tmp == 0)
683       return true;
684       
685     // If the operation is an AND/OR/XOR and the bits to clear are zero in the
686     // other side, BitsToClear is ok.
687     if (Tmp == 0 &&
688         (Opc == Instruction::And || Opc == Instruction::Or ||
689          Opc == Instruction::Xor)) {
690       // We use MaskedValueIsZero here for generality, but the case we care
691       // about the most is constant RHS.
692       unsigned VSize = V->getType()->getScalarSizeInBits();
693       if (MaskedValueIsZero(I->getOperand(1),
694                             APInt::getHighBitsSet(VSize, BitsToClear)))
695         return true;
696     }
697       
698     // Otherwise, we don't know how to analyze this BitsToClear case yet.
699     return false;
700       
701   case Instruction::LShr:
702     // We can promote lshr(x, cst) if we can promote x.  This requires the
703     // ultimate 'and' to clear out the high zero bits we're clearing out though.
704     if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
705       if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
706         return false;
707       BitsToClear += Amt->getZExtValue();
708       if (BitsToClear > V->getType()->getScalarSizeInBits())
709         BitsToClear = V->getType()->getScalarSizeInBits();
710       return true;
711     }
712     // Cannot promote variable LSHR.
713     return false;
714   case Instruction::Select:
715     if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
716         !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
717         // TODO: If important, we could handle the case when the BitsToClear are
718         // known zero in the disagreeing side.
719         Tmp != BitsToClear)
720       return false;
721     return true;
722       
723   case Instruction::PHI: {
724     // We can change a phi if we can change all operands.  Note that we never
725     // get into trouble with cyclic PHIs here because we only consider
726     // instructions with a single use.
727     PHINode *PN = cast<PHINode>(I);
728     if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
729       return false;
730     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
731       if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
732           // TODO: If important, we could handle the case when the BitsToClear
733           // are known zero in the disagreeing input.
734           Tmp != BitsToClear)
735         return false;
736     return true;
737   }
738   default:
739     // TODO: Can handle more cases here.
740     return false;
741   }
742 }
743
744 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
745   // If this zero extend is only used by a truncate, let the truncate by
746   // eliminated before we try to optimize this zext.
747   if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
748     return 0;
749   
750   // If one of the common conversion will work, do it.
751   if (Instruction *Result = commonCastTransforms(CI))
752     return Result;
753
754   // See if we can simplify any instructions used by the input whose sole 
755   // purpose is to compute bits we don't care about.
756   if (SimplifyDemandedInstructionBits(CI))
757     return &CI;
758   
759   Value *Src = CI.getOperand(0);
760   const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
761   
762   // Attempt to extend the entire input expression tree to the destination
763   // type.   Only do this if the dest type is a simple type, don't convert the
764   // expression tree to something weird like i93 unless the source is also
765   // strange.
766   unsigned BitsToClear;
767   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
768       CanEvaluateZExtd(Src, DestTy, BitsToClear)) { 
769     assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
770            "Unreasonable BitsToClear");
771     
772     // Okay, we can transform this!  Insert the new expression now.
773     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
774           " to avoid zero extend: " << CI);
775     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
776     assert(Res->getType() == DestTy);
777     
778     uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
779     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
780     
781     // If the high bits are already filled with zeros, just replace this
782     // cast with the result.
783     if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
784                                                      DestBitSize-SrcBitsKept)))
785       return ReplaceInstUsesWith(CI, Res);
786     
787     // We need to emit an AND to clear the high bits.
788     Constant *C = ConstantInt::get(Res->getType(),
789                                APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
790     return BinaryOperator::CreateAnd(Res, C);
791   }
792
793   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
794   // types and if the sizes are just right we can convert this into a logical
795   // 'and' which will be much cheaper than the pair of casts.
796   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
797     // TODO: Subsume this into EvaluateInDifferentType.
798     
799     // Get the sizes of the types involved.  We know that the intermediate type
800     // will be smaller than A or C, but don't know the relation between A and C.
801     Value *A = CSrc->getOperand(0);
802     unsigned SrcSize = A->getType()->getScalarSizeInBits();
803     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
804     unsigned DstSize = CI.getType()->getScalarSizeInBits();
805     // If we're actually extending zero bits, then if
806     // SrcSize <  DstSize: zext(a & mask)
807     // SrcSize == DstSize: a & mask
808     // SrcSize  > DstSize: trunc(a) & mask
809     if (SrcSize < DstSize) {
810       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
811       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
812       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
813       return new ZExtInst(And, CI.getType());
814     }
815     
816     if (SrcSize == DstSize) {
817       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
818       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
819                                                            AndValue));
820     }
821     if (SrcSize > DstSize) {
822       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
823       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
824       return BinaryOperator::CreateAnd(Trunc, 
825                                        ConstantInt::get(Trunc->getType(),
826                                                         AndValue));
827     }
828   }
829
830   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
831     return transformZExtICmp(ICI, CI);
832
833   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
834   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
835     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
836     // of the (zext icmp) will be transformed.
837     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
838     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
839     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
840         (transformZExtICmp(LHS, CI, false) ||
841          transformZExtICmp(RHS, CI, false))) {
842       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
843       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
844       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
845     }
846   }
847
848   // zext(trunc(t) & C) -> (t & zext(C)).
849   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
850     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
851       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
852         Value *TI0 = TI->getOperand(0);
853         if (TI0->getType() == CI.getType())
854           return
855             BinaryOperator::CreateAnd(TI0,
856                                 ConstantExpr::getZExt(C, CI.getType()));
857       }
858
859   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
860   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
861     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
862       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
863         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
864             And->getOperand(1) == C)
865           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
866             Value *TI0 = TI->getOperand(0);
867             if (TI0->getType() == CI.getType()) {
868               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
869               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
870               return BinaryOperator::CreateXor(NewAnd, ZC);
871             }
872           }
873
874   // zext (xor i1 X, true) to i32  --> xor (zext i1 X to i32), 1
875   Value *X;
876   if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
877       match(SrcI, m_Not(m_Value(X))) &&
878       (!X->hasOneUse() || !isa<CmpInst>(X))) {
879     Value *New = Builder->CreateZExt(X, CI.getType());
880     return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
881   }
882   
883   return 0;
884 }
885
886 /// CanEvaluateSExtd - Return true if we can take the specified value
887 /// and return it as type Ty without inserting any new casts and without
888 /// changing the value of the common low bits.  This is used by code that tries
889 /// to promote integer operations to a wider types will allow us to eliminate
890 /// the extension.
891 ///
892 /// This function works on both vectors and scalars.
893 ///
894 static bool CanEvaluateSExtd(Value *V, const Type *Ty) {
895   assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
896          "Can't sign extend type to a smaller type");
897   // If this is a constant, it can be trivially promoted.
898   if (isa<Constant>(V))
899     return true;
900   
901   Instruction *I = dyn_cast<Instruction>(V);
902   if (!I) return false;
903   
904   // If this is a truncate from the dest type, we can trivially eliminate it,
905   // even if it has multiple uses.
906   // FIXME: This is currently disabled until codegen can handle this without
907   // pessimizing code, PR5997.
908   if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
909     return true;
910   
911   // We can't extend or shrink something that has multiple uses: doing so would
912   // require duplicating the instruction in general, which isn't profitable.
913   if (!I->hasOneUse()) return false;
914
915   switch (I->getOpcode()) {
916   case Instruction::SExt:  // sext(sext(x)) -> sext(x)
917   case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
918   case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
919     return true;
920   case Instruction::And:
921   case Instruction::Or:
922   case Instruction::Xor:
923   case Instruction::Add:
924   case Instruction::Sub:
925   case Instruction::Mul:
926     // These operators can all arbitrarily be extended if their inputs can.
927     return CanEvaluateSExtd(I->getOperand(0), Ty) &&
928            CanEvaluateSExtd(I->getOperand(1), Ty);
929       
930   //case Instruction::Shl:   TODO
931   //case Instruction::LShr:  TODO
932       
933   case Instruction::Select:
934     return CanEvaluateSExtd(I->getOperand(1), Ty) &&
935            CanEvaluateSExtd(I->getOperand(2), Ty);
936       
937   case Instruction::PHI: {
938     // We can change a phi if we can change all operands.  Note that we never
939     // get into trouble with cyclic PHIs here because we only consider
940     // instructions with a single use.
941     PHINode *PN = cast<PHINode>(I);
942     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
943       if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
944     return true;
945   }
946   default:
947     // TODO: Can handle more cases here.
948     break;
949   }
950   
951   return false;
952 }
953
954 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
955   // If this sign extend is only used by a truncate, let the truncate by
956   // eliminated before we try to optimize this zext.
957   if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
958     return 0;
959   
960   if (Instruction *I = commonCastTransforms(CI))
961     return I;
962   
963   // See if we can simplify any instructions used by the input whose sole 
964   // purpose is to compute bits we don't care about.
965   if (SimplifyDemandedInstructionBits(CI))
966     return &CI;
967   
968   Value *Src = CI.getOperand(0);
969   const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
970
971   // Attempt to extend the entire input expression tree to the destination
972   // type.   Only do this if the dest type is a simple type, don't convert the
973   // expression tree to something weird like i93 unless the source is also
974   // strange.
975   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
976       CanEvaluateSExtd(Src, DestTy)) {
977     // Okay, we can transform this!  Insert the new expression now.
978     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
979           " to avoid sign extend: " << CI);
980     Value *Res = EvaluateInDifferentType(Src, DestTy, true);
981     assert(Res->getType() == DestTy);
982
983     uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
984     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
985
986     // If the high bits are already filled with sign bit, just replace this
987     // cast with the result.
988     if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
989       return ReplaceInstUsesWith(CI, Res);
990     
991     // We need to emit a shl + ashr to do the sign extend.
992     Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
993     return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
994                                       ShAmt);
995   }
996
997   // If this input is a trunc from our destination, then turn sext(trunc(x))
998   // into shifts.
999   if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1000     if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1001       uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1002       uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1003       
1004       // We need to emit a shl + ashr to do the sign extend.
1005       Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1006       Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1007       return BinaryOperator::CreateAShr(Res, ShAmt);
1008     }
1009   
1010   
1011   // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
1012   // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
1013   {
1014   ICmpInst::Predicate Pred; Value *CmpLHS; ConstantInt *CmpRHS;
1015   if (match(Src, m_ICmp(Pred, m_Value(CmpLHS), m_ConstantInt(CmpRHS)))) {
1016     // sext (x <s  0) to i32 --> x>>s31       true if signbit set.
1017     // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
1018     if ((Pred == ICmpInst::ICMP_SLT && CmpRHS->isZero()) ||
1019         (Pred == ICmpInst::ICMP_SGT && CmpRHS->isAllOnesValue())) {
1020       Value *Sh = ConstantInt::get(CmpLHS->getType(),
1021                                    CmpLHS->getType()->getScalarSizeInBits()-1);
1022       Value *In = Builder->CreateAShr(CmpLHS, Sh, CmpLHS->getName()+".lobit");
1023       if (In->getType() != CI.getType())
1024         In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/, "tmp");
1025       
1026       if (Pred == ICmpInst::ICMP_SGT)
1027         In = Builder->CreateNot(In, In->getName()+".not");
1028       return ReplaceInstUsesWith(CI, In);
1029     }
1030   }
1031   }
1032
1033   // vector (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed.
1034   if (const VectorType *VTy = dyn_cast<VectorType>(DestTy)) {
1035     ICmpInst::Predicate Pred; Value *CmpLHS;
1036     if (match(Src, m_ICmp(Pred, m_Value(CmpLHS), m_Zero()))) {
1037       if (Pred == ICmpInst::ICMP_SLT && CmpLHS->getType() == DestTy) {
1038         const Type *EltTy = VTy->getElementType();
1039
1040         // splat the shift constant to a cosntant vector
1041         Constant *Sh = ConstantInt::get(EltTy, EltTy->getScalarSizeInBits()-1);
1042         std::vector<Constant *> Elts(VTy->getNumElements(), Sh);
1043         Constant *VSh = ConstantVector::get(Elts);
1044
1045         Value *In = Builder->CreateAShr(CmpLHS, VSh,CmpLHS->getName()+".lobit");
1046         return ReplaceInstUsesWith(CI, In);
1047       }
1048     }
1049   }
1050
1051   // If the input is a shl/ashr pair of a same constant, then this is a sign
1052   // extension from a smaller value.  If we could trust arbitrary bitwidth
1053   // integers, we could turn this into a truncate to the smaller bit and then
1054   // use a sext for the whole extension.  Since we don't, look deeper and check
1055   // for a truncate.  If the source and dest are the same type, eliminate the
1056   // trunc and extend and just do shifts.  For example, turn:
1057   //   %a = trunc i32 %i to i8
1058   //   %b = shl i8 %a, 6
1059   //   %c = ashr i8 %b, 6
1060   //   %d = sext i8 %c to i32
1061   // into:
1062   //   %a = shl i32 %i, 30
1063   //   %d = ashr i32 %a, 30
1064   Value *A = 0;
1065   // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1066   ConstantInt *BA = 0, *CA = 0;
1067   if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1068                         m_ConstantInt(CA))) &&
1069       BA == CA && A->getType() == CI.getType()) {
1070     unsigned MidSize = Src->getType()->getScalarSizeInBits();
1071     unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1072     unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1073     Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1074     A = Builder->CreateShl(A, ShAmtV, CI.getName());
1075     return BinaryOperator::CreateAShr(A, ShAmtV);
1076   }
1077   
1078   return 0;
1079 }
1080
1081
1082 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1083 /// in the specified FP type without changing its value.
1084 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1085   bool losesInfo;
1086   APFloat F = CFP->getValueAPF();
1087   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1088   if (!losesInfo)
1089     return ConstantFP::get(CFP->getContext(), F);
1090   return 0;
1091 }
1092
1093 /// LookThroughFPExtensions - If this is an fp extension instruction, look
1094 /// through it until we get the source value.
1095 static Value *LookThroughFPExtensions(Value *V) {
1096   if (Instruction *I = dyn_cast<Instruction>(V))
1097     if (I->getOpcode() == Instruction::FPExt)
1098       return LookThroughFPExtensions(I->getOperand(0));
1099   
1100   // If this value is a constant, return the constant in the smallest FP type
1101   // that can accurately represent it.  This allows us to turn
1102   // (float)((double)X+2.0) into x+2.0f.
1103   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1104     if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1105       return V;  // No constant folding of this.
1106     // See if the value can be truncated to float and then reextended.
1107     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1108       return V;
1109     if (CFP->getType()->isDoubleTy())
1110       return V;  // Won't shrink.
1111     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1112       return V;
1113     // Don't try to shrink to various long double types.
1114   }
1115   
1116   return V;
1117 }
1118
1119 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1120   if (Instruction *I = commonCastTransforms(CI))
1121     return I;
1122   
1123   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1124   // smaller than the destination type, we can eliminate the truncate by doing
1125   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well
1126   // as many builtins (sqrt, etc).
1127   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1128   if (OpI && OpI->hasOneUse()) {
1129     switch (OpI->getOpcode()) {
1130     default: break;
1131     case Instruction::FAdd:
1132     case Instruction::FSub:
1133     case Instruction::FMul:
1134     case Instruction::FDiv:
1135     case Instruction::FRem:
1136       const Type *SrcTy = OpI->getType();
1137       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1138       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1139       if (LHSTrunc->getType() != SrcTy && 
1140           RHSTrunc->getType() != SrcTy) {
1141         unsigned DstSize = CI.getType()->getScalarSizeInBits();
1142         // If the source types were both smaller than the destination type of
1143         // the cast, do this xform.
1144         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1145             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1146           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1147           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1148           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1149         }
1150       }
1151       break;  
1152     }
1153   }
1154   
1155   // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
1156   // NOTE: This should be disabled by -fno-builtin-sqrt if we ever support it.
1157   CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
1158   if (Call && Call->getCalledFunction() &&
1159       Call->getCalledFunction()->getName() == "sqrt" &&
1160       Call->getNumArgOperands() == 1) {
1161     CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1162     if (Arg && Arg->getOpcode() == Instruction::FPExt &&
1163         CI.getType()->isFloatTy() &&
1164         Call->getType()->isDoubleTy() &&
1165         Arg->getType()->isDoubleTy() &&
1166         Arg->getOperand(0)->getType()->isFloatTy()) {
1167       Function *Callee = Call->getCalledFunction();
1168       Module *M = CI.getParent()->getParent()->getParent();
1169       Constant *SqrtfFunc = M->getOrInsertFunction("sqrtf", 
1170                                                    Callee->getAttributes(),
1171                                                    Builder->getFloatTy(),
1172                                                    Builder->getFloatTy(),
1173                                                    NULL);
1174       CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1175                                        "sqrtfcall");
1176       ret->setAttributes(Callee->getAttributes());
1177       
1178       
1179       // Remove the old Call.  With -fmath-errno, it won't get marked readnone.
1180       Call->replaceAllUsesWith(UndefValue::get(Call->getType()));
1181       EraseInstFromFunction(*Call);
1182       return ret;
1183     }
1184   }
1185   
1186   return 0;
1187 }
1188
1189 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1190   return commonCastTransforms(CI);
1191 }
1192
1193 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1194   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1195   if (OpI == 0)
1196     return commonCastTransforms(FI);
1197
1198   // fptoui(uitofp(X)) --> X
1199   // fptoui(sitofp(X)) --> X
1200   // This is safe if the intermediate type has enough bits in its mantissa to
1201   // accurately represent all values of X.  For example, do not do this with
1202   // i64->float->i64.  This is also safe for sitofp case, because any negative
1203   // 'X' value would cause an undefined result for the fptoui. 
1204   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1205       OpI->getOperand(0)->getType() == FI.getType() &&
1206       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1207                     OpI->getType()->getFPMantissaWidth())
1208     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1209
1210   return commonCastTransforms(FI);
1211 }
1212
1213 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1214   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1215   if (OpI == 0)
1216     return commonCastTransforms(FI);
1217   
1218   // fptosi(sitofp(X)) --> X
1219   // fptosi(uitofp(X)) --> X
1220   // This is safe if the intermediate type has enough bits in its mantissa to
1221   // accurately represent all values of X.  For example, do not do this with
1222   // i64->float->i64.  This is also safe for sitofp case, because any negative
1223   // 'X' value would cause an undefined result for the fptoui. 
1224   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1225       OpI->getOperand(0)->getType() == FI.getType() &&
1226       (int)FI.getType()->getScalarSizeInBits() <=
1227                     OpI->getType()->getFPMantissaWidth())
1228     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1229   
1230   return commonCastTransforms(FI);
1231 }
1232
1233 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1234   return commonCastTransforms(CI);
1235 }
1236
1237 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1238   return commonCastTransforms(CI);
1239 }
1240
1241 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1242   // If the source integer type is not the intptr_t type for this target, do a
1243   // trunc or zext to the intptr_t type, then inttoptr of it.  This allows the
1244   // cast to be exposed to other transforms.
1245   if (TD) {
1246     if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1247         TD->getPointerSizeInBits()) {
1248       Value *P = Builder->CreateTrunc(CI.getOperand(0),
1249                                       TD->getIntPtrType(CI.getContext()), "tmp");
1250       return new IntToPtrInst(P, CI.getType());
1251     }
1252     if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1253         TD->getPointerSizeInBits()) {
1254       Value *P = Builder->CreateZExt(CI.getOperand(0),
1255                                      TD->getIntPtrType(CI.getContext()), "tmp");
1256       return new IntToPtrInst(P, CI.getType());
1257     }
1258   }
1259   
1260   if (Instruction *I = commonCastTransforms(CI))
1261     return I;
1262
1263   return 0;
1264 }
1265
1266 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1267 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1268   Value *Src = CI.getOperand(0);
1269   
1270   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1271     // If casting the result of a getelementptr instruction with no offset, turn
1272     // this into a cast of the original pointer!
1273     if (GEP->hasAllZeroIndices()) {
1274       // Changing the cast operand is usually not a good idea but it is safe
1275       // here because the pointer operand is being replaced with another 
1276       // pointer operand so the opcode doesn't need to change.
1277       Worklist.Add(GEP);
1278       CI.setOperand(0, GEP->getOperand(0));
1279       return &CI;
1280     }
1281     
1282     // If the GEP has a single use, and the base pointer is a bitcast, and the
1283     // GEP computes a constant offset, see if we can convert these three
1284     // instructions into fewer.  This typically happens with unions and other
1285     // non-type-safe code.
1286     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1287         GEP->hasAllConstantIndices()) {
1288       // We are guaranteed to get a constant from EmitGEPOffset.
1289       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1290       int64_t Offset = OffsetV->getSExtValue();
1291       
1292       // Get the base pointer input of the bitcast, and the type it points to.
1293       Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1294       const Type *GEPIdxTy =
1295       cast<PointerType>(OrigBase->getType())->getElementType();
1296       SmallVector<Value*, 8> NewIndices;
1297       if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1298         // If we were able to index down into an element, create the GEP
1299         // and bitcast the result.  This eliminates one bitcast, potentially
1300         // two.
1301         Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1302         Builder->CreateInBoundsGEP(OrigBase,
1303                                    NewIndices.begin(), NewIndices.end()) :
1304         Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1305         NGEP->takeName(GEP);
1306         
1307         if (isa<BitCastInst>(CI))
1308           return new BitCastInst(NGEP, CI.getType());
1309         assert(isa<PtrToIntInst>(CI));
1310         return new PtrToIntInst(NGEP, CI.getType());
1311       }      
1312     }
1313   }
1314   
1315   return commonCastTransforms(CI);
1316 }
1317
1318 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1319   // If the destination integer type is not the intptr_t type for this target,
1320   // do a ptrtoint to intptr_t then do a trunc or zext.  This allows the cast
1321   // to be exposed to other transforms.
1322   if (TD) {
1323     if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1324       Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1325                                          TD->getIntPtrType(CI.getContext()),
1326                                          "tmp");
1327       return new TruncInst(P, CI.getType());
1328     }
1329     if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1330       Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1331                                          TD->getIntPtrType(CI.getContext()),
1332                                          "tmp");
1333       return new ZExtInst(P, CI.getType());
1334     }
1335   }
1336   
1337   return commonPointerCastTransforms(CI);
1338 }
1339
1340 /// OptimizeVectorResize - This input value (which is known to have vector type)
1341 /// is being zero extended or truncated to the specified vector type.  Try to
1342 /// replace it with a shuffle (and vector/vector bitcast) if possible.
1343 ///
1344 /// The source and destination vector types may have different element types.
1345 static Instruction *OptimizeVectorResize(Value *InVal, const VectorType *DestTy,
1346                                          InstCombiner &IC) {
1347   // We can only do this optimization if the output is a multiple of the input
1348   // element size, or the input is a multiple of the output element size.
1349   // Convert the input type to have the same element type as the output.
1350   const VectorType *SrcTy = cast<VectorType>(InVal->getType());
1351   
1352   if (SrcTy->getElementType() != DestTy->getElementType()) {
1353     // The input types don't need to be identical, but for now they must be the
1354     // same size.  There is no specific reason we couldn't handle things like
1355     // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1356     // there yet. 
1357     if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1358         DestTy->getElementType()->getPrimitiveSizeInBits())
1359       return 0;
1360     
1361     SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1362     InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1363   }
1364   
1365   // Now that the element types match, get the shuffle mask and RHS of the
1366   // shuffle to use, which depends on whether we're increasing or decreasing the
1367   // size of the input.
1368   SmallVector<Constant*, 16> ShuffleMask;
1369   Value *V2;
1370   const IntegerType *Int32Ty = Type::getInt32Ty(SrcTy->getContext());
1371   
1372   if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1373     // If we're shrinking the number of elements, just shuffle in the low
1374     // elements from the input and use undef as the second shuffle input.
1375     V2 = UndefValue::get(SrcTy);
1376     for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1377       ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1378     
1379   } else {
1380     // If we're increasing the number of elements, shuffle in all of the
1381     // elements from InVal and fill the rest of the result elements with zeros
1382     // from a constant zero.
1383     V2 = Constant::getNullValue(SrcTy);
1384     unsigned SrcElts = SrcTy->getNumElements();
1385     for (unsigned i = 0, e = SrcElts; i != e; ++i)
1386       ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1387
1388     // The excess elements reference the first element of the zero input.
1389     ShuffleMask.append(DestTy->getNumElements()-SrcElts,
1390                        ConstantInt::get(Int32Ty, SrcElts));
1391   }
1392   
1393   Constant *Mask = ConstantVector::get(ShuffleMask.data(), ShuffleMask.size());
1394   return new ShuffleVectorInst(InVal, V2, Mask);
1395 }
1396
1397 static bool isMultipleOfTypeSize(unsigned Value, const Type *Ty) {
1398   return Value % Ty->getPrimitiveSizeInBits() == 0;
1399 }
1400
1401 static unsigned getTypeSizeIndex(unsigned Value, const Type *Ty) {
1402   return Value / Ty->getPrimitiveSizeInBits();
1403 }
1404
1405 /// CollectInsertionElements - V is a value which is inserted into a vector of
1406 /// VecEltTy.  Look through the value to see if we can decompose it into
1407 /// insertions into the vector.  See the example in the comment for
1408 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
1409 /// The type of V is always a non-zero multiple of VecEltTy's size.
1410 ///
1411 /// This returns false if the pattern can't be matched or true if it can,
1412 /// filling in Elements with the elements found here.
1413 static bool CollectInsertionElements(Value *V, unsigned ElementIndex,
1414                                      SmallVectorImpl<Value*> &Elements,
1415                                      const Type *VecEltTy) {
1416   // Undef values never contribute useful bits to the result.
1417   if (isa<UndefValue>(V)) return true;
1418   
1419   // If we got down to a value of the right type, we win, try inserting into the
1420   // right element.
1421   if (V->getType() == VecEltTy) {
1422     // Inserting null doesn't actually insert any elements.
1423     if (Constant *C = dyn_cast<Constant>(V))
1424       if (C->isNullValue())
1425         return true;
1426     
1427     // Fail if multiple elements are inserted into this slot.
1428     if (ElementIndex >= Elements.size() || Elements[ElementIndex] != 0)
1429       return false;
1430     
1431     Elements[ElementIndex] = V;
1432     return true;
1433   }
1434   
1435   if (Constant *C = dyn_cast<Constant>(V)) {
1436     // Figure out the # elements this provides, and bitcast it or slice it up
1437     // as required.
1438     unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1439                                         VecEltTy);
1440     // If the constant is the size of a vector element, we just need to bitcast
1441     // it to the right type so it gets properly inserted.
1442     if (NumElts == 1)
1443       return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1444                                       ElementIndex, Elements, VecEltTy);
1445     
1446     // Okay, this is a constant that covers multiple elements.  Slice it up into
1447     // pieces and insert each element-sized piece into the vector.
1448     if (!isa<IntegerType>(C->getType()))
1449       C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1450                                        C->getType()->getPrimitiveSizeInBits()));
1451     unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
1452     const Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
1453     
1454     for (unsigned i = 0; i != NumElts; ++i) {
1455       Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1456                                                                i*ElementSize));
1457       Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1458       if (!CollectInsertionElements(Piece, ElementIndex+i, Elements, VecEltTy))
1459         return false;
1460     }
1461     return true;
1462   }
1463   
1464   if (!V->hasOneUse()) return false;
1465   
1466   Instruction *I = dyn_cast<Instruction>(V);
1467   if (I == 0) return false;
1468   switch (I->getOpcode()) {
1469   default: return false; // Unhandled case.
1470   case Instruction::BitCast:
1471     return CollectInsertionElements(I->getOperand(0), ElementIndex,
1472                                     Elements, VecEltTy);  
1473   case Instruction::ZExt:
1474     if (!isMultipleOfTypeSize(
1475                           I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1476                               VecEltTy))
1477       return false;
1478     return CollectInsertionElements(I->getOperand(0), ElementIndex,
1479                                     Elements, VecEltTy);  
1480   case Instruction::Or:
1481     return CollectInsertionElements(I->getOperand(0), ElementIndex,
1482                                     Elements, VecEltTy) &&
1483            CollectInsertionElements(I->getOperand(1), ElementIndex,
1484                                     Elements, VecEltTy);
1485   case Instruction::Shl: {
1486     // Must be shifting by a constant that is a multiple of the element size.
1487     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1488     if (CI == 0) return false;
1489     if (!isMultipleOfTypeSize(CI->getZExtValue(), VecEltTy)) return false;
1490     unsigned IndexShift = getTypeSizeIndex(CI->getZExtValue(), VecEltTy);
1491     
1492     return CollectInsertionElements(I->getOperand(0), ElementIndex+IndexShift,
1493                                     Elements, VecEltTy);
1494   }
1495       
1496   }
1497 }
1498
1499
1500 /// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1501 /// may be doing shifts and ors to assemble the elements of the vector manually.
1502 /// Try to rip the code out and replace it with insertelements.  This is to
1503 /// optimize code like this:
1504 ///
1505 ///    %tmp37 = bitcast float %inc to i32
1506 ///    %tmp38 = zext i32 %tmp37 to i64
1507 ///    %tmp31 = bitcast float %inc5 to i32
1508 ///    %tmp32 = zext i32 %tmp31 to i64
1509 ///    %tmp33 = shl i64 %tmp32, 32
1510 ///    %ins35 = or i64 %tmp33, %tmp38
1511 ///    %tmp43 = bitcast i64 %ins35 to <2 x float>
1512 ///
1513 /// Into two insertelements that do "buildvector{%inc, %inc5}".
1514 static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1515                                                 InstCombiner &IC) {
1516   const VectorType *DestVecTy = cast<VectorType>(CI.getType());
1517   Value *IntInput = CI.getOperand(0);
1518
1519   SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1520   if (!CollectInsertionElements(IntInput, 0, Elements,
1521                                 DestVecTy->getElementType()))
1522     return 0;
1523
1524   // If we succeeded, we know that all of the element are specified by Elements
1525   // or are zero if Elements has a null entry.  Recast this as a set of
1526   // insertions.
1527   Value *Result = Constant::getNullValue(CI.getType());
1528   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1529     if (Elements[i] == 0) continue;  // Unset element.
1530     
1531     Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1532                                              IC.Builder->getInt32(i));
1533   }
1534   
1535   return Result;
1536 }
1537
1538
1539 /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1540 /// bitcast.  The various long double bitcasts can't get in here.
1541 static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
1542   Value *Src = CI.getOperand(0);
1543   const Type *DestTy = CI.getType();
1544
1545   // If this is a bitcast from int to float, check to see if the int is an
1546   // extraction from a vector.
1547   Value *VecInput = 0;
1548   // bitcast(trunc(bitcast(somevector)))
1549   if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1550       isa<VectorType>(VecInput->getType())) {
1551     const VectorType *VecTy = cast<VectorType>(VecInput->getType());
1552     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1553
1554     if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1555       // If the element type of the vector doesn't match the result type,
1556       // bitcast it to be a vector type we can extract from.
1557       if (VecTy->getElementType() != DestTy) {
1558         VecTy = VectorType::get(DestTy,
1559                                 VecTy->getPrimitiveSizeInBits() / DestWidth);
1560         VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1561       }
1562     
1563       return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
1564     }
1565   }
1566   
1567   // bitcast(trunc(lshr(bitcast(somevector), cst))
1568   ConstantInt *ShAmt = 0;
1569   if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1570                                 m_ConstantInt(ShAmt)))) &&
1571       isa<VectorType>(VecInput->getType())) {
1572     const VectorType *VecTy = cast<VectorType>(VecInput->getType());
1573     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1574     if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1575         ShAmt->getZExtValue() % DestWidth == 0) {
1576       // If the element type of the vector doesn't match the result type,
1577       // bitcast it to be a vector type we can extract from.
1578       if (VecTy->getElementType() != DestTy) {
1579         VecTy = VectorType::get(DestTy,
1580                                 VecTy->getPrimitiveSizeInBits() / DestWidth);
1581         VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1582       }
1583       
1584       unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1585       return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1586     }
1587   }
1588   return 0;
1589 }
1590
1591 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1592   // If the operands are integer typed then apply the integer transforms,
1593   // otherwise just apply the common ones.
1594   Value *Src = CI.getOperand(0);
1595   const Type *SrcTy = Src->getType();
1596   const Type *DestTy = CI.getType();
1597
1598   // Get rid of casts from one type to the same type. These are useless and can
1599   // be replaced by the operand.
1600   if (DestTy == Src->getType())
1601     return ReplaceInstUsesWith(CI, Src);
1602
1603   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1604     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1605     const Type *DstElTy = DstPTy->getElementType();
1606     const Type *SrcElTy = SrcPTy->getElementType();
1607     
1608     // If the address spaces don't match, don't eliminate the bitcast, which is
1609     // required for changing types.
1610     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1611       return 0;
1612     
1613     // If we are casting a alloca to a pointer to a type of the same
1614     // size, rewrite the allocation instruction to allocate the "right" type.
1615     // There is no need to modify malloc calls because it is their bitcast that
1616     // needs to be cleaned up.
1617     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1618       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1619         return V;
1620     
1621     // If the source and destination are pointers, and this cast is equivalent
1622     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
1623     // This can enhance SROA and other transforms that want type-safe pointers.
1624     Constant *ZeroUInt =
1625       Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1626     unsigned NumZeros = 0;
1627     while (SrcElTy != DstElTy && 
1628            isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
1629            SrcElTy->getNumContainedTypes() /* not "{}" */) {
1630       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1631       ++NumZeros;
1632     }
1633
1634     // If we found a path from the src to dest, create the getelementptr now.
1635     if (SrcElTy == DstElTy) {
1636       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1637       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
1638                                                ((Instruction*)NULL));
1639     }
1640   }
1641   
1642   // Try to optimize int -> float bitcasts.
1643   if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1644     if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1645       return I;
1646
1647   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1648     if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
1649       Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1650       return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1651                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1652       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1653     }
1654     
1655     if (isa<IntegerType>(SrcTy)) {
1656       // If this is a cast from an integer to vector, check to see if the input
1657       // is a trunc or zext of a bitcast from vector.  If so, we can replace all
1658       // the casts with a shuffle and (potentially) a bitcast.
1659       if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1660         CastInst *SrcCast = cast<CastInst>(Src);
1661         if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1662           if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1663             if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
1664                                                cast<VectorType>(DestTy), *this))
1665               return I;
1666       }
1667       
1668       // If the input is an 'or' instruction, we may be doing shifts and ors to
1669       // assemble the elements of the vector manually.  Try to rip the code out
1670       // and replace it with insertelements.
1671       if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1672         return ReplaceInstUsesWith(CI, V);
1673     }
1674   }
1675
1676   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1677     if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
1678       Value *Elem = 
1679         Builder->CreateExtractElement(Src,
1680                    Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1681       return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1682     }
1683   }
1684
1685   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1686     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
1687     // a bitcast to a vector with the same # elts.
1688     if (SVI->hasOneUse() && DestTy->isVectorTy() && 
1689         cast<VectorType>(DestTy)->getNumElements() ==
1690               SVI->getType()->getNumElements() &&
1691         SVI->getType()->getNumElements() ==
1692           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1693       BitCastInst *Tmp;
1694       // If either of the operands is a cast from CI.getType(), then
1695       // evaluating the shuffle in the casted destination's type will allow
1696       // us to eliminate at least one cast.
1697       if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) && 
1698            Tmp->getOperand(0)->getType() == DestTy) ||
1699           ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) && 
1700            Tmp->getOperand(0)->getType() == DestTy)) {
1701         Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1702         Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1703         // Return a new shuffle vector.  Use the same element ID's, as we
1704         // know the vector types match #elts.
1705         return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1706       }
1707     }
1708   }
1709   
1710   if (SrcTy->isPointerTy())
1711     return commonPointerCastTransforms(CI);
1712   return commonCastTransforms(CI);
1713 }