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