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