blob: c2b862a5ff303688dbab6c1b81046302558329fa [file] [log] [blame]
Chris Lattner80f43d32010-01-04 07:53:58 +00001//===- 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"
Eli Friedman74703252011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000016#include "llvm/IR/DataLayout.h"
Stephen Hines36b56882014-04-23 16:57:46 -070017#include "llvm/IR/PatternMatch.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner80f43d32010-01-04 07:53:58 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000022/// 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///
26static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Dan Gohman28d2e0a2010-05-28 04:33:04 +000027 uint64_t &Offset) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000028 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
29 Offset = CI->getZExtValue();
30 Scale = 0;
Dan Gohman28d2e0a2010-05-28 04:33:04 +000031 return ConstantInt::get(Val->getType(), 0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000032 }
Craig Topperb57c2922013-01-24 05:22:40 +000033
Chris Lattnerf86d7992010-01-05 20:57:30 +000034 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Bob Wilsone2e86f62011-07-08 22:09:33 +000035 // Cannot look past anything that might overflow.
36 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
Stepan Dyatkovskiy3f71cf12012-05-05 07:09:40 +000037 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
Bob Wilsone2e86f62011-07-08 22:09:33 +000038 Scale = 1;
39 Offset = 0;
40 return Val;
41 }
42
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000043 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'.
Dan Gohman28d2e0a2010-05-28 04:33:04 +000046 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000047 Offset = 0;
48 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000049 }
Craig Topperb57c2922013-01-24 05:22:40 +000050
Chris Lattnerf86d7992010-01-05 20:57:30 +000051 if (I->getOpcode() == Instruction::Mul) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000052 // This value is scaled by 'RHS'.
53 Scale = RHS->getZExtValue();
54 Offset = 0;
55 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000056 }
Craig Topperb57c2922013-01-24 05:22:40 +000057
Chris Lattnerf86d7992010-01-05 20:57:30 +000058 if (I->getOpcode() == Instruction::Add) {
Craig Topperb57c2922013-01-24 05:22:40 +000059 // We have X+C. Check to see if we really have (X*C2)+C1,
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000060 // where C1 is divisible by C2.
61 unsigned SubScale;
Craig Topperb57c2922013-01-24 05:22:40 +000062 Value *SubVal =
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000063 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.
79Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
80 AllocaInst &AI) {
Micah Villmow3574eca2012-10-08 16:38:25 +000081 // This requires DataLayout to get the alloca alignment and size information.
Stephen Hines36b56882014-04-23 16:57:46 -070082 if (!DL) return 0;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000083
Chris Lattnerdb125cf2011-07-18 04:54:35 +000084 PointerType *PTy = cast<PointerType>(CI.getType());
Craig Topperb57c2922013-01-24 05:22:40 +000085
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000086 BuilderTy AllocaBuilder(*Builder);
87 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
88
89 // Get the type really allocated and the type casted to.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000090 Type *AllocElTy = AI.getAllocatedType();
91 Type *CastElTy = PTy->getElementType();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000092 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
93
Stephen Hines36b56882014-04-23 16:57:46 -070094 unsigned AllocElTyAlign = DL->getABITypeAlignment(AllocElTy);
95 unsigned CastElTyAlign = DL->getABITypeAlignment(CastElTy);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000096 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
Devang Patel5aa3fa62011-03-08 22:12:11 +0000100 // same, we open the door to infinite loops of various kinds.
101 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000102
Stephen Hines36b56882014-04-23 16:57:46 -0700103 uint64_t AllocElTySize = DL->getTypeAllocSize(AllocElTy);
104 uint64_t CastElTySize = DL->getTypeAllocSize(CastElTy);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000105 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
106
Jim Grosbach186d8a32013-03-06 05:44:53 +0000107 // If the allocation has multiple uses, only promote it if we're not
108 // shrinking the amount of memory being allocated.
Stephen Hines36b56882014-04-23 16:57:46 -0700109 uint64_t AllocElTyStoreSize = DL->getTypeStoreSize(AllocElTy);
110 uint64_t CastElTyStoreSize = DL->getTypeStoreSize(CastElTy);
Jim Grosbach186d8a32013-03-06 05:44:53 +0000111 if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return 0;
112
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000113 // See if we can satisfy the modulus by pulling a scale out of the array
114 // size argument.
115 unsigned ArraySizeScale;
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000116 uint64_t ArrayOffset;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000117 Value *NumElements = // See if the array size is a decomposable linear expr.
118 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Craig Topperb57c2922013-01-24 05:22:40 +0000119
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000120 // If we can now satisfy the modulus, by using a non-1 scale, we really can
121 // do the xform.
122 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
123 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
124
125 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
126 Value *Amt = 0;
127 if (Scale == 1) {
128 Amt = NumElements;
129 } else {
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000130 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000131 // Insert before the alloca, not before the cast.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000132 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000133 }
Craig Topperb57c2922013-01-24 05:22:40 +0000134
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000135 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
136 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000137 Offset, true);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000138 Amt = AllocaBuilder.CreateAdd(Amt, Off);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000139 }
Craig Topperb57c2922013-01-24 05:22:40 +0000140
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000141 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
142 New->setAlignment(AI.getAlignment());
143 New->takeName(&AI);
Craig Topperb57c2922013-01-24 05:22:40 +0000144
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000145 // If the allocation has multiple real uses, insert a cast and change all
146 // things that used it to use the new cast. This will also hack on CI, but it
147 // will die soon.
Devang Patel5aa3fa62011-03-08 22:12:11 +0000148 if (!AI.hasOneUse()) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000149 // New is the allocation instruction, pointer typed. AI is the original
150 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
151 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Eli Friedman3e22cb92011-05-18 00:32:01 +0000152 ReplaceInstUsesWith(AI, NewCast);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000153 }
154 return ReplaceInstUsesWith(CI, New);
155}
156
Craig Topperb57c2922013-01-24 05:22:40 +0000157/// EvaluateInDifferentType - Given an expression that
Chris Lattner14bf8f02010-01-08 19:19:23 +0000158/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000159/// insert the code to evaluate the expression.
Craig Topperb57c2922013-01-24 05:22:40 +0000160Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
Chris Lattner5f0290e2010-01-04 07:54:59 +0000161 bool isSigned) {
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000162 if (Constant *C = dyn_cast<Constant>(V)) {
163 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Stephen Hines36b56882014-04-23 16:57:46 -0700164 // If we got a constantexpr back, try to simplify it with DL info.
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000165 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Stephen Hines36b56882014-04-23 16:57:46 -0700166 C = ConstantFoldConstantExpression(CE, DL, TLI);
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000167 return C;
168 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000169
170 // Otherwise, it must be an instruction.
171 Instruction *I = cast<Instruction>(V);
172 Instruction *Res = 0;
173 unsigned Opc = I->getOpcode();
174 switch (Opc) {
175 case Instruction::Add:
176 case Instruction::Sub:
177 case Instruction::Mul:
178 case Instruction::And:
179 case Instruction::Or:
180 case Instruction::Xor:
181 case Instruction::AShr:
182 case Instruction::LShr:
183 case Instruction::Shl:
184 case Instruction::UDiv:
185 case Instruction::URem: {
186 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
187 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
188 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
189 break;
Craig Topperb57c2922013-01-24 05:22:40 +0000190 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000191 case Instruction::Trunc:
192 case Instruction::ZExt:
193 case Instruction::SExt:
194 // If the source type of the cast is the type we're trying for then we can
195 // just return the source. There's no need to insert it because it is not
196 // new.
197 if (I->getOperand(0)->getType() == Ty)
198 return I->getOperand(0);
Craig Topperb57c2922013-01-24 05:22:40 +0000199
Chris Lattner5f0290e2010-01-04 07:54:59 +0000200 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000201 // This also handles the case of zext(trunc(x)) -> zext(x).
202 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
203 Opc == Instruction::SExt);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000204 break;
205 case Instruction::Select: {
206 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
207 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
208 Res = SelectInst::Create(I->getOperand(0), True, False);
209 break;
210 }
211 case Instruction::PHI: {
212 PHINode *OPN = cast<PHINode>(I);
Jay Foad3ecfc862011-03-30 11:28:46 +0000213 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
Chris Lattner5f0290e2010-01-04 07:54:59 +0000214 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
215 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
216 NPN->addIncoming(V, OPN->getIncomingBlock(i));
217 }
218 Res = NPN;
219 break;
220 }
Craig Topperb57c2922013-01-24 05:22:40 +0000221 default:
Chris Lattner5f0290e2010-01-04 07:54:59 +0000222 // TODO: Can handle more cases here.
223 llvm_unreachable("Unreachable!");
Chris Lattner5f0290e2010-01-04 07:54:59 +0000224 }
Craig Topperb57c2922013-01-24 05:22:40 +0000225
Chris Lattner5f0290e2010-01-04 07:54:59 +0000226 Res->takeName(I);
Eli Friedmana311c342011-05-27 00:19:40 +0000227 return InsertNewInstWith(Res, *I);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000228}
Chris Lattner80f43d32010-01-04 07:53:58 +0000229
230
231/// This function is a wrapper around CastInst::isEliminableCastPair. It
232/// simply extracts arguments and returns what that function returns.
Craig Topperb57c2922013-01-24 05:22:40 +0000233static Instruction::CastOps
Chris Lattner80f43d32010-01-04 07:53:58 +0000234isEliminableCastPair(
235 const CastInst *CI, ///< The first cast instruction
236 unsigned opcode, ///< The opcode of the second cast instruction
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237 Type *DstTy, ///< The target type for the second cast instruction
Stephen Hines36b56882014-04-23 16:57:46 -0700238 const DataLayout *DL ///< The target data for pointer size
Chris Lattner80f43d32010-01-04 07:53:58 +0000239) {
240
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000241 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
242 Type *MidTy = CI->getType(); // B from above
Chris Lattner80f43d32010-01-04 07:53:58 +0000243
244 // Get the opcodes of the two Cast instructions
245 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
246 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Stephen Hines36b56882014-04-23 16:57:46 -0700247 Type *SrcIntPtrTy = DL && SrcTy->isPtrOrPtrVectorTy() ?
248 DL->getIntPtrType(SrcTy) : 0;
249 Type *MidIntPtrTy = DL && MidTy->isPtrOrPtrVectorTy() ?
250 DL->getIntPtrType(MidTy) : 0;
251 Type *DstIntPtrTy = DL && DstTy->isPtrOrPtrVectorTy() ?
252 DL->getIntPtrType(DstTy) : 0;
Chris Lattner80f43d32010-01-04 07:53:58 +0000253 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Duncan Sands446cf942012-10-30 16:03:32 +0000254 DstTy, SrcIntPtrTy, MidIntPtrTy,
255 DstIntPtrTy);
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000256
Chris Lattner80f43d32010-01-04 07:53:58 +0000257 // We don't want to form an inttoptr or ptrtoint that converts to an integer
258 // type that differs from the pointer size.
Duncan Sands446cf942012-10-30 16:03:32 +0000259 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
260 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
Chris Lattner80f43d32010-01-04 07:53:58 +0000261 Res = 0;
Craig Topperb57c2922013-01-24 05:22:40 +0000262
Chris Lattner80f43d32010-01-04 07:53:58 +0000263 return Instruction::CastOps(Res);
264}
265
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000266/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
267/// results in any code being generated and is interesting to optimize out. If
268/// the cast can be eliminated by some other simple transformation, we prefer
269/// to do the simplification first.
270bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000271 Type *Ty) {
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000272 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner80f43d32010-01-04 07:53:58 +0000273 if (V->getType() == Ty || isa<Constant>(V)) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000274
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000275 // If this is another cast that can be eliminated, we prefer to have it
276 // eliminated.
Chris Lattner80f43d32010-01-04 07:53:58 +0000277 if (const CastInst *CI = dyn_cast<CastInst>(V))
Stephen Hines36b56882014-04-23 16:57:46 -0700278 if (isEliminableCastPair(CI, opc, Ty, DL))
Chris Lattner80f43d32010-01-04 07:53:58 +0000279 return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000280
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000281 // If this is a vector sext from a compare, then we don't want to break the
282 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands1df98592010-02-16 11:11:14 +0000283 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000284 return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000285
Chris Lattner80f43d32010-01-04 07:53:58 +0000286 return true;
287}
288
289
290/// @brief Implement the transforms common to all CastInst visitors.
291Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
292 Value *Src = CI.getOperand(0);
293
294 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
295 // eliminate it now.
296 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Craig Topperb57c2922013-01-24 05:22:40 +0000297 if (Instruction::CastOps opc =
Stephen Hines36b56882014-04-23 16:57:46 -0700298 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000299 // The first cast (CSrc) is eliminable so we need to fix up or replace
300 // the second cast (CI). CSrc will then have a good chance of being dead.
301 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
302 }
303 }
304
305 // If we are casting a select then fold the cast into the select
306 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
307 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
308 return NV;
309
310 // If we are casting a PHI then fold the cast into the PHI
311 if (isa<PHINode>(Src)) {
312 // We don't do this if this would create a PHI node with an illegal type if
313 // it is currently legal.
Duncan Sands1df98592010-02-16 11:11:14 +0000314 if (!Src->getType()->isIntegerTy() ||
315 !CI.getType()->isIntegerTy() ||
Chris Lattner80f43d32010-01-04 07:53:58 +0000316 ShouldChangeType(CI.getType(), Src->getType()))
317 if (Instruction *NV = FoldOpIntoPhi(CI))
318 return NV;
319 }
Craig Topperb57c2922013-01-24 05:22:40 +0000320
Chris Lattner80f43d32010-01-04 07:53:58 +0000321 return 0;
322}
323
Chris Lattner75215c92010-01-10 00:58:42 +0000324/// CanEvaluateTruncated - Return true if we can evaluate the specified
325/// expression tree as type Ty instead of its larger type, and arrive with the
326/// same value. This is used by code that tries to eliminate truncates.
327///
328/// Ty will always be a type smaller than V. We should return true if trunc(V)
329/// can be computed by computing V in the smaller type. If V is an instruction,
330/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
331/// makes sense if x and y can be efficiently truncated.
332///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000333/// This function works on both vectors and scalars.
334///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000335static bool CanEvaluateTruncated(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000336 // We can always evaluate constants in another type.
337 if (isa<Constant>(V))
338 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000339
Chris Lattner75215c92010-01-10 00:58:42 +0000340 Instruction *I = dyn_cast<Instruction>(V);
341 if (!I) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000342
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000343 Type *OrigTy = V->getType();
Craig Topperb57c2922013-01-24 05:22:40 +0000344
Chris Lattnera958cbf2010-01-11 22:45:25 +0000345 // If this is an extension from the dest type, we can eliminate it, even if it
346 // has multiple uses.
Craig Topperb57c2922013-01-24 05:22:40 +0000347 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000348 I->getOperand(0)->getType() == Ty)
349 return true;
350
351 // We can't extend or shrink something that has multiple uses: doing so would
352 // require duplicating the instruction in general, which isn't profitable.
353 if (!I->hasOneUse()) return false;
354
355 unsigned Opc = I->getOpcode();
356 switch (Opc) {
357 case Instruction::Add:
358 case Instruction::Sub:
359 case Instruction::Mul:
360 case Instruction::And:
361 case Instruction::Or:
362 case Instruction::Xor:
363 // These operators can all arbitrarily be extended or truncated.
364 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
365 CanEvaluateTruncated(I->getOperand(1), Ty);
366
367 case Instruction::UDiv:
368 case Instruction::URem: {
369 // UDiv and URem can be truncated if all the truncated bits are zero.
370 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
371 uint32_t BitWidth = Ty->getScalarSizeInBits();
372 if (BitWidth < OrigBitWidth) {
373 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
374 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
375 MaskedValueIsZero(I->getOperand(1), Mask)) {
376 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
377 CanEvaluateTruncated(I->getOperand(1), Ty);
378 }
379 }
380 break;
381 }
382 case Instruction::Shl:
383 // If we are truncating the result of this SHL, and if it's a shift of a
384 // constant amount, we can always perform a SHL in a smaller type.
385 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
386 uint32_t BitWidth = Ty->getScalarSizeInBits();
387 if (CI->getLimitedValue(BitWidth) < BitWidth)
388 return CanEvaluateTruncated(I->getOperand(0), Ty);
389 }
390 break;
391 case Instruction::LShr:
392 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000393 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattner75215c92010-01-10 00:58:42 +0000394 // already zeros.
395 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
396 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
397 uint32_t BitWidth = Ty->getScalarSizeInBits();
398 if (MaskedValueIsZero(I->getOperand(0),
399 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
400 CI->getLimitedValue(BitWidth) < BitWidth) {
401 return CanEvaluateTruncated(I->getOperand(0), Ty);
402 }
403 }
404 break;
405 case Instruction::Trunc:
406 // trunc(trunc(x)) -> trunc(x)
407 return true;
Chris Lattnerf9d05ab2010-08-27 20:32:06 +0000408 case Instruction::ZExt:
409 case Instruction::SExt:
410 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
411 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
412 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000413 case Instruction::Select: {
414 SelectInst *SI = cast<SelectInst>(I);
415 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
416 CanEvaluateTruncated(SI->getFalseValue(), Ty);
417 }
418 case Instruction::PHI: {
419 // We can change a phi if we can change all operands. Note that we never
420 // get into trouble with cyclic PHIs here because we only consider
421 // instructions with a single use.
422 PHINode *PN = cast<PHINode>(I);
423 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
424 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
425 return false;
426 return true;
427 }
428 default:
429 // TODO: Can handle more cases here.
430 break;
431 }
Craig Topperb57c2922013-01-24 05:22:40 +0000432
Chris Lattner75215c92010-01-10 00:58:42 +0000433 return false;
434}
435
436Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000437 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner75215c92010-01-10 00:58:42 +0000438 return Result;
Craig Topperb57c2922013-01-24 05:22:40 +0000439
440 // See if we can simplify any instructions used by the input whose sole
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000441 // purpose is to compute bits we don't care about.
442 if (SimplifyDemandedInstructionBits(CI))
443 return &CI;
Craig Topperb57c2922013-01-24 05:22:40 +0000444
Chris Lattner75215c92010-01-10 00:58:42 +0000445 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000446 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
Craig Topperb57c2922013-01-24 05:22:40 +0000447
Chris Lattner75215c92010-01-10 00:58:42 +0000448 // Attempt to truncate the entire input expression tree to the destination
449 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner80f43d32010-01-04 07:53:58 +0000450 // expression tree to something weird like i93 unless the source is also
451 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +0000452 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000453 CanEvaluateTruncated(Src, DestTy)) {
Craig Topperb57c2922013-01-24 05:22:40 +0000454
Chris Lattner80f43d32010-01-04 07:53:58 +0000455 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000456 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000457 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohman5b71dce2010-05-25 21:50:35 +0000458 " to avoid cast: " << CI << '\n');
Chris Lattner075f6922010-01-07 23:41:00 +0000459 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
460 assert(Res->getType() == DestTy);
461 return ReplaceInstUsesWith(CI, Res);
462 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000463
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000464 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
465 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000466 Constant *One = ConstantInt::get(Src->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000467 Src = Builder->CreateAnd(Src, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000468 Value *Zero = Constant::getNullValue(Src->getType());
469 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
470 }
Craig Topperb57c2922013-01-24 05:22:40 +0000471
Chris Lattner784f3332010-08-27 18:31:05 +0000472 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
473 Value *A = 0; ConstantInt *Cst = 0;
Chris Lattner62fe4062011-01-15 06:32:33 +0000474 if (Src->hasOneUse() &&
475 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
Chris Lattner784f3332010-08-27 18:31:05 +0000476 // We have three types to worry about here, the type of A, the source of
477 // the truncate (MidSize), and the destination of the truncate. We know that
478 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
479 // between ASize and ResultSize.
480 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
Craig Topperb57c2922013-01-24 05:22:40 +0000481
Chris Lattner784f3332010-08-27 18:31:05 +0000482 // If the shift amount is larger than the size of A, then the result is
483 // known to be zero because all the input bits got shifted out.
484 if (Cst->getZExtValue() >= ASize)
485 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
486
487 // Since we're doing an lshr and a zero extend, and know that the shift
488 // amount is smaller than ASize, it is always safe to do the shift in A's
489 // type, then zero extend or truncate to the result.
490 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
491 Shift->takeName(Src);
492 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
493 }
Craig Topperb57c2922013-01-24 05:22:40 +0000494
Chris Lattner62fe4062011-01-15 06:32:33 +0000495 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
496 // type isn't non-native.
497 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
498 ShouldChangeType(Src->getType(), CI.getType()) &&
499 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
500 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
501 return BinaryOperator::CreateAnd(NewTrunc,
502 ConstantExpr::getTrunc(Cst, CI.getType()));
503 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000504
Chris Lattner80f43d32010-01-04 07:53:58 +0000505 return 0;
506}
507
508/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
509/// in order to eliminate the icmp.
510Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
511 bool DoXform) {
512 // If we are just checking for a icmp eq of a single bit and zext'ing it
513 // to an integer, then shift the bit to the appropriate place and then
514 // cast to integer to avoid the comparison.
515 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
516 const APInt &Op1CV = Op1C->getValue();
Craig Topperb57c2922013-01-24 05:22:40 +0000517
Chris Lattner80f43d32010-01-04 07:53:58 +0000518 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
519 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
520 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
521 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
522 if (!DoXform) return ICI;
523
524 Value *In = ICI->getOperand(0);
525 Value *Sh = ConstantInt::get(In->getType(),
526 In->getType()->getScalarSizeInBits()-1);
527 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
528 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000529 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000530
531 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
532 Constant *One = ConstantInt::get(In->getType(), 1);
533 In = Builder->CreateXor(In, One, In->getName()+".not");
534 }
535
536 return ReplaceInstUsesWith(CI, In);
537 }
Chad Rosiercaebb1e2011-11-30 01:59:59 +0000538
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000539 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
540 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
541 // zext (X == 1) to i32 --> X iff X has only the low bit set.
542 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
543 // zext (X != 0) to i32 --> X iff X has only the low bit set.
544 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
545 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
546 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Craig Topperb57c2922013-01-24 05:22:40 +0000547 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
Chris Lattner80f43d32010-01-04 07:53:58 +0000548 // This only works for EQ and NE
549 ICI->isEquality()) {
550 // If Op1C some other power of two, convert:
551 uint32_t BitWidth = Op1C->getType()->getBitWidth();
552 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000553 ComputeMaskedBits(ICI->getOperand(0), KnownZero, KnownOne);
Craig Topperb57c2922013-01-24 05:22:40 +0000554
Chris Lattner80f43d32010-01-04 07:53:58 +0000555 APInt KnownZeroMask(~KnownZero);
556 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
557 if (!DoXform) return ICI;
558
559 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
560 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
561 // (X&4) == 2 --> false
562 // (X&4) != 2 --> true
563 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
564 isNE);
565 Res = ConstantExpr::getZExt(Res, CI.getType());
566 return ReplaceInstUsesWith(CI, Res);
567 }
Craig Topperb57c2922013-01-24 05:22:40 +0000568
Chris Lattner80f43d32010-01-04 07:53:58 +0000569 uint32_t ShiftAmt = KnownZeroMask.logBase2();
570 Value *In = ICI->getOperand(0);
571 if (ShiftAmt) {
572 // Perform a logical shr by shiftamt.
573 // Insert the shift to put the result in the low bit.
574 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
575 In->getName()+".lobit");
576 }
Craig Topperb57c2922013-01-24 05:22:40 +0000577
Chris Lattner80f43d32010-01-04 07:53:58 +0000578 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
579 Constant *One = ConstantInt::get(In->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000580 In = Builder->CreateXor(In, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000581 }
Craig Topperb57c2922013-01-24 05:22:40 +0000582
Chris Lattner80f43d32010-01-04 07:53:58 +0000583 if (CI.getType() == In->getType())
584 return ReplaceInstUsesWith(CI, In);
Chris Lattner29cc0b32010-08-27 22:24:38 +0000585 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000586 }
587 }
588 }
589
590 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
591 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
592 // may lead to additional simplifications.
593 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000594 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000595 uint32_t BitWidth = ITy->getBitWidth();
596 Value *LHS = ICI->getOperand(0);
597 Value *RHS = ICI->getOperand(1);
598
599 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
600 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000601 ComputeMaskedBits(LHS, KnownZeroLHS, KnownOneLHS);
602 ComputeMaskedBits(RHS, KnownZeroRHS, KnownOneRHS);
Chris Lattner80f43d32010-01-04 07:53:58 +0000603
604 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
605 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
606 APInt UnknownBit = ~KnownBits;
607 if (UnknownBit.countPopulation() == 1) {
608 if (!DoXform) return ICI;
609
610 Value *Result = Builder->CreateXor(LHS, RHS);
611
612 // Mask off any bits that are set and won't be shifted away.
613 if (KnownOneLHS.uge(UnknownBit))
614 Result = Builder->CreateAnd(Result,
615 ConstantInt::get(ITy, UnknownBit));
616
617 // Shift the bit we're testing down to the lsb.
618 Result = Builder->CreateLShr(
619 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
620
621 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
622 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
623 Result->takeName(ICI);
624 return ReplaceInstUsesWith(CI, Result);
625 }
626 }
627 }
628 }
629
630 return 0;
631}
632
Chris Lattner75215c92010-01-10 00:58:42 +0000633/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000634/// specified wider type and produce the same low bits. If not, return false.
635///
Chris Lattner789162a2010-01-11 03:32:00 +0000636/// If this function returns true, it can also return a non-zero number of bits
637/// (in BitsToClear) which indicates that the value it computes is correct for
638/// the zero extend, but that the additional BitsToClear bits need to be zero'd
639/// out. For example, to promote something like:
640///
641/// %B = trunc i64 %A to i32
642/// %C = lshr i32 %B, 8
643/// %E = zext i32 %C to i64
644///
645/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
646/// set to 8 to indicate that the promoted value needs to have bits 24-31
647/// cleared in addition to bits 32-63. Since an 'and' will be generated to
648/// clear the top bits anyway, doing this has no extra cost.
649///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000650/// This function works on both vectors and scalars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000651static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
Chris Lattner789162a2010-01-11 03:32:00 +0000652 BitsToClear = 0;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000653 if (isa<Constant>(V))
654 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000655
Chris Lattner75215c92010-01-10 00:58:42 +0000656 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner9e390dd2010-01-10 02:50:04 +0000657 if (!I) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000658
Chris Lattner75215c92010-01-10 00:58:42 +0000659 // If the input is a truncate from the destination type, we can trivially
Jakob Stoklund Olesen7ee3ca12012-06-22 16:36:43 +0000660 // eliminate it.
661 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner9e390dd2010-01-10 02:50:04 +0000662 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000663
Chris Lattner75215c92010-01-10 00:58:42 +0000664 // We can't extend or shrink something that has multiple uses: doing so would
665 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000666 if (!I->hasOneUse()) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000667
Chris Lattner789162a2010-01-11 03:32:00 +0000668 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattner75215c92010-01-10 00:58:42 +0000669 switch (Opc) {
Chris Lattner9ee947c2010-01-10 20:25:54 +0000670 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
671 case Instruction::SExt: // zext(sext(x)) -> sext(x).
672 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
673 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000674 case Instruction::And:
Chris Lattner75215c92010-01-10 00:58:42 +0000675 case Instruction::Or:
676 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000677 case Instruction::Add:
678 case Instruction::Sub:
679 case Instruction::Mul:
Chris Lattner789162a2010-01-11 03:32:00 +0000680 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
681 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
682 return false;
683 // These can all be promoted if neither operand has 'bits to clear'.
684 if (BitsToClear == 0 && Tmp == 0)
685 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000686
Chris Lattner7acc4b12010-01-11 04:05:13 +0000687 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
688 // other side, BitsToClear is ok.
689 if (Tmp == 0 &&
690 (Opc == Instruction::And || Opc == Instruction::Or ||
691 Opc == Instruction::Xor)) {
692 // We use MaskedValueIsZero here for generality, but the case we care
693 // about the most is constant RHS.
694 unsigned VSize = V->getType()->getScalarSizeInBits();
695 if (MaskedValueIsZero(I->getOperand(1),
696 APInt::getHighBitsSet(VSize, BitsToClear)))
697 return true;
698 }
Craig Topperb57c2922013-01-24 05:22:40 +0000699
Chris Lattner7acc4b12010-01-11 04:05:13 +0000700 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner789162a2010-01-11 03:32:00 +0000701 return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000702
Benjamin Kramer7159a302013-05-10 16:26:37 +0000703 case Instruction::Shl:
704 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the
705 // upper bits we can reduce BitsToClear by the shift amount.
706 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
707 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
708 return false;
709 uint64_t ShiftAmt = Amt->getZExtValue();
710 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
711 return true;
712 }
713 return false;
Chris Lattner789162a2010-01-11 03:32:00 +0000714 case Instruction::LShr:
715 // We can promote lshr(x, cst) if we can promote x. This requires the
716 // ultimate 'and' to clear out the high zero bits we're clearing out though.
717 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
718 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
719 return false;
720 BitsToClear += Amt->getZExtValue();
721 if (BitsToClear > V->getType()->getScalarSizeInBits())
722 BitsToClear = V->getType()->getScalarSizeInBits();
723 return true;
724 }
725 // Cannot promote variable LSHR.
726 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000727 case Instruction::Select:
Chris Lattner789162a2010-01-11 03:32:00 +0000728 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
729 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000730 // TODO: If important, we could handle the case when the BitsToClear are
731 // known zero in the disagreeing side.
Chris Lattner789162a2010-01-11 03:32:00 +0000732 Tmp != BitsToClear)
733 return false;
734 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000735
Chris Lattner75215c92010-01-10 00:58:42 +0000736 case Instruction::PHI: {
737 // We can change a phi if we can change all operands. Note that we never
738 // get into trouble with cyclic PHIs here because we only consider
739 // instructions with a single use.
740 PHINode *PN = cast<PHINode>(I);
Chris Lattner789162a2010-01-11 03:32:00 +0000741 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
742 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000743 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner789162a2010-01-11 03:32:00 +0000744 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000745 // TODO: If important, we could handle the case when the BitsToClear
746 // are known zero in the disagreeing input.
Chris Lattner789162a2010-01-11 03:32:00 +0000747 Tmp != BitsToClear)
748 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000749 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000750 }
751 default:
752 // TODO: Can handle more cases here.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000753 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000754 }
755}
756
Chris Lattner80f43d32010-01-04 07:53:58 +0000757Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Nick Lewyckyeb3ac452013-01-14 20:56:10 +0000758 // If this zero extend is only used by a truncate, let the truncate be
Chris Lattner5324d802010-01-10 02:39:31 +0000759 // eliminated before we try to optimize this zext.
Stephen Hines36b56882014-04-23 16:57:46 -0700760 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Chris Lattner5324d802010-01-10 02:39:31 +0000761 return 0;
Craig Topperb57c2922013-01-24 05:22:40 +0000762
Chris Lattner80f43d32010-01-04 07:53:58 +0000763 // If one of the common conversion will work, do it.
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000764 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000765 return Result;
766
Craig Topperb57c2922013-01-24 05:22:40 +0000767 // See if we can simplify any instructions used by the input whose sole
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000768 // purpose is to compute bits we don't care about.
769 if (SimplifyDemandedInstructionBits(CI))
770 return &CI;
Craig Topperb57c2922013-01-24 05:22:40 +0000771
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000772 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000773 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Craig Topperb57c2922013-01-24 05:22:40 +0000774
Chris Lattner75215c92010-01-10 00:58:42 +0000775 // Attempt to extend the entire input expression tree to the destination
776 // type. Only do this if the dest type is a simple type, don't convert the
777 // expression tree to something weird like i93 unless the source is also
778 // strange.
Chris Lattner789162a2010-01-11 03:32:00 +0000779 unsigned BitsToClear;
Duncan Sands1df98592010-02-16 11:11:14 +0000780 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Craig Topperb57c2922013-01-24 05:22:40 +0000781 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
Chris Lattner789162a2010-01-11 03:32:00 +0000782 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
783 "Unreasonable BitsToClear");
Craig Topperb57c2922013-01-24 05:22:40 +0000784
Chris Lattner5324d802010-01-10 02:39:31 +0000785 // Okay, we can transform this! Insert the new expression now.
786 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
787 " to avoid zero extend: " << CI);
788 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
789 assert(Res->getType() == DestTy);
Craig Topperb57c2922013-01-24 05:22:40 +0000790
Chris Lattner789162a2010-01-11 03:32:00 +0000791 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
792 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topperb57c2922013-01-24 05:22:40 +0000793
Chris Lattner5324d802010-01-10 02:39:31 +0000794 // If the high bits are already filled with zeros, just replace this
795 // cast with the result.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000796 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
Chris Lattner789162a2010-01-11 03:32:00 +0000797 DestBitSize-SrcBitsKept)))
Chris Lattner5324d802010-01-10 02:39:31 +0000798 return ReplaceInstUsesWith(CI, Res);
Craig Topperb57c2922013-01-24 05:22:40 +0000799
Chris Lattner5324d802010-01-10 02:39:31 +0000800 // We need to emit an AND to clear the high bits.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000801 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner789162a2010-01-11 03:32:00 +0000802 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner5324d802010-01-10 02:39:31 +0000803 return BinaryOperator::CreateAnd(Res, C);
Chris Lattner75215c92010-01-10 00:58:42 +0000804 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000805
806 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
807 // types and if the sizes are just right we can convert this into a logical
808 // 'and' which will be much cheaper than the pair of casts.
809 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000810 // TODO: Subsume this into EvaluateInDifferentType.
Craig Topperb57c2922013-01-24 05:22:40 +0000811
Chris Lattner80f43d32010-01-04 07:53:58 +0000812 // Get the sizes of the types involved. We know that the intermediate type
813 // will be smaller than A or C, but don't know the relation between A and C.
814 Value *A = CSrc->getOperand(0);
815 unsigned SrcSize = A->getType()->getScalarSizeInBits();
816 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
817 unsigned DstSize = CI.getType()->getScalarSizeInBits();
818 // If we're actually extending zero bits, then if
819 // SrcSize < DstSize: zext(a & mask)
820 // SrcSize == DstSize: a & mask
821 // SrcSize > DstSize: trunc(a) & mask
822 if (SrcSize < DstSize) {
823 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
824 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
825 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
826 return new ZExtInst(And, CI.getType());
827 }
Craig Topperb57c2922013-01-24 05:22:40 +0000828
Chris Lattner80f43d32010-01-04 07:53:58 +0000829 if (SrcSize == DstSize) {
830 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
831 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
832 AndValue));
833 }
834 if (SrcSize > DstSize) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000835 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
Chris Lattner80f43d32010-01-04 07:53:58 +0000836 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Craig Topperb57c2922013-01-24 05:22:40 +0000837 return BinaryOperator::CreateAnd(Trunc,
Chris Lattner80f43d32010-01-04 07:53:58 +0000838 ConstantInt::get(Trunc->getType(),
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000839 AndValue));
Chris Lattner80f43d32010-01-04 07:53:58 +0000840 }
841 }
842
843 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
844 return transformZExtICmp(ICI, CI);
845
846 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
847 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
848 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
849 // of the (zext icmp) will be transformed.
850 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
851 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
852 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
853 (transformZExtICmp(LHS, CI, false) ||
854 transformZExtICmp(RHS, CI, false))) {
855 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
856 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
857 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
858 }
859 }
860
Stephen Hines36b56882014-04-23 16:57:46 -0700861 // zext(trunc(X) & C) -> (X & zext(C)).
862 Constant *C;
863 Value *X;
864 if (SrcI &&
865 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
866 X->getType() == CI.getType())
867 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
Chris Lattner80f43d32010-01-04 07:53:58 +0000868
Stephen Hines36b56882014-04-23 16:57:46 -0700869 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
870 Value *And;
871 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
872 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
873 X->getType() == CI.getType()) {
874 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
875 return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
876 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000877
Chris Lattner718bf3f2010-01-05 21:04:47 +0000878 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
Stephen Hines36b56882014-04-23 16:57:46 -0700879 if (SrcI && SrcI->hasOneUse() &&
880 SrcI->getType()->getScalarType()->isIntegerTy(1) &&
881 match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) {
Chris Lattner718bf3f2010-01-05 21:04:47 +0000882 Value *New = Builder->CreateZExt(X, CI.getType());
883 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
884 }
Craig Topperb57c2922013-01-24 05:22:40 +0000885
Chris Lattner80f43d32010-01-04 07:53:58 +0000886 return 0;
887}
888
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000889/// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
890/// in order to eliminate the icmp.
891Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
892 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
893 ICmpInst::Predicate Pred = ICI->getPredicate();
894
Stephen Hines36b56882014-04-23 16:57:46 -0700895 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Benjamin Kramer406a6502011-04-01 22:29:18 +0000896 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
897 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
Stephen Hines36b56882014-04-23 16:57:46 -0700898 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000899 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
900
901 Value *Sh = ConstantInt::get(Op0->getType(),
902 Op0->getType()->getScalarSizeInBits()-1);
903 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
904 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000905 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000906
907 if (Pred == ICmpInst::ICMP_SGT)
908 In = Builder->CreateNot(In, In->getName()+".not");
909 return ReplaceInstUsesWith(CI, In);
910 }
Stephen Hines36b56882014-04-23 16:57:46 -0700911 }
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000912
Stephen Hines36b56882014-04-23 16:57:46 -0700913 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000914 // If we know that only one bit of the LHS of the icmp can be set and we
915 // have an equality comparison with zero or a power of 2, we can transform
916 // the icmp and sext into bitwise/integer operations.
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000917 if (ICI->hasOneUse() &&
918 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000919 unsigned BitWidth = Op1C->getType()->getBitWidth();
920 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000921 ComputeMaskedBits(Op0, KnownZero, KnownOne);
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000922
Benjamin Kramerce1498b2011-04-01 20:15:16 +0000923 APInt KnownZeroMask(~KnownZero);
924 if (KnownZeroMask.isPowerOf2()) {
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000925 Value *In = ICI->getOperand(0);
926
Benjamin Kramerf5b75932011-04-02 18:50:58 +0000927 // If the icmp tests for a known zero bit we can constant fold it.
928 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
929 Value *V = Pred == ICmpInst::ICMP_NE ?
930 ConstantInt::getAllOnesValue(CI.getType()) :
931 ConstantInt::getNullValue(CI.getType());
932 return ReplaceInstUsesWith(CI, V);
933 }
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000934
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000935 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
936 // sext ((x & 2^n) == 0) -> (x >> n) - 1
937 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
938 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
939 // Perform a right shift to place the desired bit in the LSB.
940 if (ShiftAmt)
941 In = Builder->CreateLShr(In,
942 ConstantInt::get(In->getType(), ShiftAmt));
943
944 // At this point "In" is either 1 or 0. Subtract 1 to turn
945 // {1, 0} -> {0, -1}.
946 In = Builder->CreateAdd(In,
947 ConstantInt::getAllOnesValue(In->getType()),
948 "sext");
949 } else {
950 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000951 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000952 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
953 // Perform a left shift to place the desired bit in the MSB.
954 if (ShiftAmt)
955 In = Builder->CreateShl(In,
956 ConstantInt::get(In->getType(), ShiftAmt));
957
958 // Distribute the bit over the whole bit width.
959 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
960 BitWidth - 1), "sext");
961 }
962
963 if (CI.getType() == In->getType())
964 return ReplaceInstUsesWith(CI, In);
965 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
966 }
967 }
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000968 }
969
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000970 return 0;
971}
972
Chris Lattner75215c92010-01-10 00:58:42 +0000973/// CanEvaluateSExtd - Return true if we can take the specified value
974/// and return it as type Ty without inserting any new casts and without
975/// changing the value of the common low bits. This is used by code that tries
976/// to promote integer operations to a wider types will allow us to eliminate
977/// the extension.
978///
Chris Lattneraa9c8942010-01-10 07:57:20 +0000979/// This function works on both vectors and scalars.
Chris Lattner75215c92010-01-10 00:58:42 +0000980///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000981static bool CanEvaluateSExtd(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000982 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
983 "Can't sign extend type to a smaller type");
Chris Lattneraa9c8942010-01-10 07:57:20 +0000984 // If this is a constant, it can be trivially promoted.
985 if (isa<Constant>(V))
986 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000987
Chris Lattner75215c92010-01-10 00:58:42 +0000988 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattneraa9c8942010-01-10 07:57:20 +0000989 if (!I) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000990
Jakob Stoklund Olesen7ee3ca12012-06-22 16:36:43 +0000991 // If this is a truncate from the dest type, we can trivially eliminate it.
992 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattneraa9c8942010-01-10 07:57:20 +0000993 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000994
Chris Lattner75215c92010-01-10 00:58:42 +0000995 // We can't extend or shrink something that has multiple uses: doing so would
996 // require duplicating the instruction in general, which isn't profitable.
Chris Lattneraa9c8942010-01-10 07:57:20 +0000997 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000998
Chris Lattneraa9c8942010-01-10 07:57:20 +0000999 switch (I->getOpcode()) {
Chris Lattner11ea8122010-01-10 20:30:41 +00001000 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1001 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1002 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1003 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001004 case Instruction::And:
1005 case Instruction::Or:
1006 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +00001007 case Instruction::Add:
1008 case Instruction::Sub:
Chris Lattner75215c92010-01-10 00:58:42 +00001009 case Instruction::Mul:
Chris Lattneraa9c8942010-01-10 07:57:20 +00001010 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001011 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1012 CanEvaluateSExtd(I->getOperand(1), Ty);
Craig Topperb57c2922013-01-24 05:22:40 +00001013
Chris Lattner75215c92010-01-10 00:58:42 +00001014 //case Instruction::Shl: TODO
1015 //case Instruction::LShr: TODO
Craig Topperb57c2922013-01-24 05:22:40 +00001016
Chris Lattneraa9c8942010-01-10 07:57:20 +00001017 case Instruction::Select:
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001018 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1019 CanEvaluateSExtd(I->getOperand(2), Ty);
Craig Topperb57c2922013-01-24 05:22:40 +00001020
Chris Lattner75215c92010-01-10 00:58:42 +00001021 case Instruction::PHI: {
1022 // We can change a phi if we can change all operands. Note that we never
1023 // get into trouble with cyclic PHIs here because we only consider
1024 // instructions with a single use.
1025 PHINode *PN = cast<PHINode>(I);
Chris Lattner9ee947c2010-01-10 20:25:54 +00001026 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001027 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattneraa9c8942010-01-10 07:57:20 +00001028 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001029 }
1030 default:
1031 // TODO: Can handle more cases here.
1032 break;
1033 }
Craig Topperb57c2922013-01-24 05:22:40 +00001034
Chris Lattneraa9c8942010-01-10 07:57:20 +00001035 return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001036}
1037
Chris Lattner80f43d32010-01-04 07:53:58 +00001038Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Arnaud A. de Grandmaison66bff1e2013-02-13 00:19:19 +00001039 // If this sign extend is only used by a truncate, let the truncate be
1040 // eliminated before we try to optimize this sext.
Stephen Hines36b56882014-04-23 16:57:46 -07001041 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Chris Lattner5324d802010-01-10 02:39:31 +00001042 return 0;
Craig Topperb57c2922013-01-24 05:22:40 +00001043
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001044 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +00001045 return I;
Craig Topperb57c2922013-01-24 05:22:40 +00001046
1047 // See if we can simplify any instructions used by the input whose sole
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001048 // purpose is to compute bits we don't care about.
1049 if (SimplifyDemandedInstructionBits(CI))
1050 return &CI;
Craig Topperb57c2922013-01-24 05:22:40 +00001051
Chris Lattner80f43d32010-01-04 07:53:58 +00001052 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001053 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattner75215c92010-01-10 00:58:42 +00001054
Chris Lattner75215c92010-01-10 00:58:42 +00001055 // Attempt to extend the entire input expression tree to the destination
1056 // type. Only do this if the dest type is a simple type, don't convert the
1057 // expression tree to something weird like i93 unless the source is also
1058 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +00001059 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001060 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001061 // Okay, we can transform this! Insert the new expression now.
1062 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1063 " to avoid sign extend: " << CI);
1064 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1065 assert(Res->getType() == DestTy);
1066
Chris Lattner75215c92010-01-10 00:58:42 +00001067 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1068 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001069
1070 // If the high bits are already filled with sign bit, just replace this
1071 // cast with the result.
Chris Lattneraa9c8942010-01-10 07:57:20 +00001072 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001073 return ReplaceInstUsesWith(CI, Res);
Craig Topperb57c2922013-01-24 05:22:40 +00001074
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001075 // We need to emit a shl + ashr to do the sign extend.
1076 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1077 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1078 ShAmt);
Chris Lattner75215c92010-01-10 00:58:42 +00001079 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001080
Chris Lattnercd5adbb2010-01-18 22:19:16 +00001081 // If this input is a trunc from our destination, then turn sext(trunc(x))
1082 // into shifts.
1083 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1084 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1085 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1086 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topperb57c2922013-01-24 05:22:40 +00001087
Chris Lattnercd5adbb2010-01-18 22:19:16 +00001088 // We need to emit a shl + ashr to do the sign extend.
1089 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1090 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1091 return BinaryOperator::CreateAShr(Res, ShAmt);
1092 }
Nate Begeman9a3dc552010-12-17 23:12:19 +00001093
Benjamin Kramer0a30c422011-04-01 20:09:03 +00001094 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1095 return transformSExtICmp(ICI, CI);
Bill Wendling2d0537c2010-12-17 23:27:41 +00001096
Chris Lattner80f43d32010-01-04 07:53:58 +00001097 // If the input is a shl/ashr pair of a same constant, then this is a sign
1098 // extension from a smaller value. If we could trust arbitrary bitwidth
1099 // integers, we could turn this into a truncate to the smaller bit and then
1100 // use a sext for the whole extension. Since we don't, look deeper and check
1101 // for a truncate. If the source and dest are the same type, eliminate the
1102 // trunc and extend and just do shifts. For example, turn:
1103 // %a = trunc i32 %i to i8
1104 // %b = shl i8 %a, 6
1105 // %c = ashr i8 %b, 6
1106 // %d = sext i8 %c to i32
1107 // into:
1108 // %a = shl i32 %i, 30
1109 // %d = ashr i32 %a, 30
1110 Value *A = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001111 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Chris Lattner80f43d32010-01-04 07:53:58 +00001112 ConstantInt *BA = 0, *CA = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001113 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner80f43d32010-01-04 07:53:58 +00001114 m_ConstantInt(CA))) &&
Chris Lattner4f379782010-01-10 01:04:31 +00001115 BA == CA && A->getType() == CI.getType()) {
1116 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1117 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1118 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1119 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1120 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1121 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner80f43d32010-01-04 07:53:58 +00001122 }
Craig Topperb57c2922013-01-24 05:22:40 +00001123
Chris Lattner80f43d32010-01-04 07:53:58 +00001124 return 0;
1125}
1126
1127
1128/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1129/// in the specified FP type without changing its value.
1130static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1131 bool losesInfo;
1132 APFloat F = CFP->getValueAPF();
1133 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1134 if (!losesInfo)
1135 return ConstantFP::get(CFP->getContext(), F);
1136 return 0;
1137}
1138
1139/// LookThroughFPExtensions - If this is an fp extension instruction, look
1140/// through it until we get the source value.
1141static Value *LookThroughFPExtensions(Value *V) {
1142 if (Instruction *I = dyn_cast<Instruction>(V))
1143 if (I->getOpcode() == Instruction::FPExt)
1144 return LookThroughFPExtensions(I->getOperand(0));
Craig Topperb57c2922013-01-24 05:22:40 +00001145
Chris Lattner80f43d32010-01-04 07:53:58 +00001146 // If this value is a constant, return the constant in the smallest FP type
1147 // that can accurately represent it. This allows us to turn
1148 // (float)((double)X+2.0) into x+2.0f.
1149 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1150 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1151 return V; // No constant folding of this.
Dan Gohmance163392011-12-17 00:04:22 +00001152 // See if the value can be truncated to half and then reextended.
1153 if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
1154 return V;
Chris Lattner80f43d32010-01-04 07:53:58 +00001155 // See if the value can be truncated to float and then reextended.
1156 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1157 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001158 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001159 return V; // Won't shrink.
1160 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1161 return V;
1162 // Don't try to shrink to various long double types.
1163 }
Craig Topperb57c2922013-01-24 05:22:40 +00001164
Chris Lattner80f43d32010-01-04 07:53:58 +00001165 return V;
1166}
1167
1168Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1169 if (Instruction *I = commonCastTransforms(CI))
1170 return I;
Stephen Hines36b56882014-04-23 16:57:46 -07001171 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1172 // simpilify this expression to avoid one or more of the trunc/extend
1173 // operations if we can do so without changing the numerical results.
1174 //
1175 // The exact manner in which the widths of the operands interact to limit
1176 // what we can and cannot do safely varies from operation to operation, and
1177 // is explained below in the various case statements.
Chris Lattner80f43d32010-01-04 07:53:58 +00001178 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1179 if (OpI && OpI->hasOneUse()) {
Stephen Hines36b56882014-04-23 16:57:46 -07001180 Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0));
1181 Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1));
1182 unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1183 unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
1184 unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
1185 unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1186 unsigned DstWidth = CI.getType()->getFPMantissaWidth();
Chris Lattner80f43d32010-01-04 07:53:58 +00001187 switch (OpI->getOpcode()) {
Stephen Hines36b56882014-04-23 16:57:46 -07001188 default: break;
1189 case Instruction::FAdd:
1190 case Instruction::FSub:
1191 // For addition and subtraction, the infinitely precise result can
1192 // essentially be arbitrarily wide; proving that double rounding
1193 // will not occur because the result of OpI is exact (as we will for
1194 // FMul, for example) is hopeless. However, we *can* nonetheless
1195 // frequently know that double rounding cannot occur (or that it is
1196 // innocuous) by taking advantage of the specific structure of
1197 // infinitely-precise results that admit double rounding.
1198 //
1199 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
1200 // to represent both sources, we can guarantee that the double
1201 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1202 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1203 // for proof of this fact).
1204 //
1205 // Note: Figueroa does not consider the case where DstFormat !=
1206 // SrcFormat. It's possible (likely even!) that this analysis
1207 // could be tightened for those cases, but they are rare (the main
1208 // case of interest here is (float)((double)float + float)).
1209 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1210 if (LHSOrig->getType() != CI.getType())
1211 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1212 if (RHSOrig->getType() != CI.getType())
1213 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1214 Instruction *RI =
1215 BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
1216 RI->copyFastMathFlags(OpI);
1217 return RI;
Chris Lattner80f43d32010-01-04 07:53:58 +00001218 }
Stephen Hines36b56882014-04-23 16:57:46 -07001219 break;
1220 case Instruction::FMul:
1221 // For multiplication, the infinitely precise result has at most
1222 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1223 // that such a value can be exactly represented, then no double
1224 // rounding can possibly occur; we can safely perform the operation
1225 // in the destination format if it can represent both sources.
1226 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1227 if (LHSOrig->getType() != CI.getType())
1228 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1229 if (RHSOrig->getType() != CI.getType())
1230 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1231 Instruction *RI =
1232 BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
1233 RI->copyFastMathFlags(OpI);
1234 return RI;
1235 }
1236 break;
1237 case Instruction::FDiv:
1238 // For division, we use again use the bound from Figueroa's
1239 // dissertation. I am entirely certain that this bound can be
1240 // tightened in the unbalanced operand case by an analysis based on
1241 // the diophantine rational approximation bound, but the well-known
1242 // condition used here is a good conservative first pass.
1243 // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1244 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1245 if (LHSOrig->getType() != CI.getType())
1246 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1247 if (RHSOrig->getType() != CI.getType())
1248 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1249 Instruction *RI =
1250 BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
1251 RI->copyFastMathFlags(OpI);
1252 return RI;
1253 }
1254 break;
1255 case Instruction::FRem:
1256 // Remainder is straightforward. Remainder is always exact, so the
1257 // type of OpI doesn't enter into things at all. We simply evaluate
1258 // in whichever source type is larger, then convert to the
1259 // destination type.
1260 if (LHSWidth < SrcWidth)
1261 LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
1262 else if (RHSWidth <= SrcWidth)
1263 RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
1264 Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
1265 if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
1266 RI->copyFastMathFlags(OpI);
1267 return CastInst::CreateFPCast(ExactResult, CI.getType());
Chris Lattner80f43d32010-01-04 07:53:58 +00001268 }
Owen Andersone9d4eba2013-01-10 22:06:52 +00001269
1270 // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1271 if (BinaryOperator::isFNeg(OpI)) {
1272 Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
1273 CI.getType());
Stephen Hines36b56882014-04-23 16:57:46 -07001274 Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
1275 RI->copyFastMathFlags(OpI);
1276 return RI;
Owen Andersone9d4eba2013-01-10 22:06:52 +00001277 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001278 }
Owen Andersone9d4eba2013-01-10 22:06:52 +00001279
Owen Anderson03e84c92013-10-03 21:08:05 +00001280 // (fptrunc (select cond, R1, Cst)) -->
1281 // (select cond, (fptrunc R1), (fptrunc Cst))
1282 SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
1283 if (SI &&
1284 (isa<ConstantFP>(SI->getOperand(1)) ||
1285 isa<ConstantFP>(SI->getOperand(2)))) {
1286 Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
1287 CI.getType());
1288 Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
1289 CI.getType());
1290 return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
1291 }
1292
Owen Andersone9d4eba2013-01-10 22:06:52 +00001293 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
1294 if (II) {
1295 switch (II->getIntrinsicID()) {
1296 default: break;
1297 case Intrinsic::fabs: {
1298 // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1299 Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
1300 CI.getType());
1301 Type *IntrinsicType[] = { CI.getType() };
1302 Function *Overload =
1303 Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
1304 II->getIntrinsicID(), IntrinsicType);
1305
1306 Value *Args[] = { InnerTrunc };
1307 return CallInst::Create(Overload, Args, II->getName());
1308 }
1309 }
1310 }
1311
Owen Andersond9029012010-07-19 08:09:34 +00001312 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
Hal Finkel64fa5012013-11-16 21:29:08 +00001313 // Note that we restrict this transformation based on
1314 // TLI->has(LibFunc::sqrtf), even for the sqrt intrinsic, because
1315 // TLI->has(LibFunc::sqrtf) is sufficient to guarantee that the
1316 // single-precision intrinsic can be expanded in the backend.
Owen Andersond9029012010-07-19 08:09:34 +00001317 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
Chad Rosier00737bd2011-12-01 21:29:16 +00001318 if (Call && Call->getCalledFunction() && TLI->has(LibFunc::sqrtf) &&
Hal Finkel64fa5012013-11-16 21:29:08 +00001319 (Call->getCalledFunction()->getName() == TLI->getName(LibFunc::sqrt) ||
1320 Call->getCalledFunction()->getIntrinsicID() == Intrinsic::sqrt) &&
Evan Cheng93a635c2011-07-13 19:08:16 +00001321 Call->getNumArgOperands() == 1 &&
1322 Call->hasOneUse()) {
Owen Andersond9029012010-07-19 08:09:34 +00001323 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1324 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
Owen Anderson5f23a932010-07-19 19:23:32 +00001325 CI.getType()->isFloatTy() &&
1326 Call->getType()->isDoubleTy() &&
1327 Arg->getType()->isDoubleTy() &&
1328 Arg->getOperand(0)->getType()->isFloatTy()) {
1329 Function *Callee = Call->getCalledFunction();
1330 Module *M = CI.getParent()->getParent()->getParent();
Hal Finkel64fa5012013-11-16 21:29:08 +00001331 Constant *SqrtfFunc = (Callee->getIntrinsicID() == Intrinsic::sqrt) ?
1332 Intrinsic::getDeclaration(M, Intrinsic::sqrt, Builder->getFloatTy()) :
1333 M->getOrInsertFunction("sqrtf", Callee->getAttributes(),
1334 Builder->getFloatTy(), Builder->getFloatTy(),
1335 NULL);
Owen Andersond9029012010-07-19 08:09:34 +00001336 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1337 "sqrtfcall");
Owen Anderson5f23a932010-07-19 19:23:32 +00001338 ret->setAttributes(Callee->getAttributes());
Craig Topperb57c2922013-01-24 05:22:40 +00001339
1340
Chris Lattner979ed442010-09-07 20:01:38 +00001341 // Remove the old Call. With -fmath-errno, it won't get marked readnone.
Eli Friedman3e22cb92011-05-18 00:32:01 +00001342 ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
Chris Lattner979ed442010-09-07 20:01:38 +00001343 EraseInstFromFunction(*Call);
Owen Andersond9029012010-07-19 08:09:34 +00001344 return ret;
1345 }
1346 }
Craig Topperb57c2922013-01-24 05:22:40 +00001347
Chris Lattner80f43d32010-01-04 07:53:58 +00001348 return 0;
1349}
1350
1351Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1352 return commonCastTransforms(CI);
1353}
1354
1355Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1356 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1357 if (OpI == 0)
1358 return commonCastTransforms(FI);
1359
1360 // fptoui(uitofp(X)) --> X
1361 // fptoui(sitofp(X)) --> X
1362 // This is safe if the intermediate type has enough bits in its mantissa to
1363 // accurately represent all values of X. For example, do not do this with
1364 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topperb57c2922013-01-24 05:22:40 +00001365 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner80f43d32010-01-04 07:53:58 +00001366 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1367 OpI->getOperand(0)->getType() == FI.getType() &&
1368 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1369 OpI->getType()->getFPMantissaWidth())
1370 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1371
1372 return commonCastTransforms(FI);
1373}
1374
1375Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1376 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1377 if (OpI == 0)
1378 return commonCastTransforms(FI);
Craig Topperb57c2922013-01-24 05:22:40 +00001379
Chris Lattner80f43d32010-01-04 07:53:58 +00001380 // fptosi(sitofp(X)) --> X
1381 // fptosi(uitofp(X)) --> X
1382 // This is safe if the intermediate type has enough bits in its mantissa to
1383 // accurately represent all values of X. For example, do not do this with
1384 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topperb57c2922013-01-24 05:22:40 +00001385 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner80f43d32010-01-04 07:53:58 +00001386 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1387 OpI->getOperand(0)->getType() == FI.getType() &&
1388 (int)FI.getType()->getScalarSizeInBits() <=
1389 OpI->getType()->getFPMantissaWidth())
1390 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Craig Topperb57c2922013-01-24 05:22:40 +00001391
Chris Lattner80f43d32010-01-04 07:53:58 +00001392 return commonCastTransforms(FI);
1393}
1394
1395Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1396 return commonCastTransforms(CI);
1397}
1398
1399Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1400 return commonCastTransforms(CI);
1401}
1402
Chris Lattner80f43d32010-01-04 07:53:58 +00001403Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001404 // If the source integer type is not the intptr_t type for this target, do a
1405 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1406 // cast to be exposed to other transforms.
Benjamin Kramer39b5f122013-02-05 20:22:40 +00001407
Stephen Hines36b56882014-04-23 16:57:46 -07001408 if (DL) {
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001409 unsigned AS = CI.getAddressSpace();
1410 if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
Stephen Hines36b56882014-04-23 16:57:46 -07001411 DL->getPointerSizeInBits(AS)) {
1412 Type *Ty = DL->getIntPtrType(CI.getContext(), AS);
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001413 if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1414 Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
1415
1416 Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
1417 return new IntToPtrInst(P, CI.getType());
1418 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001419 }
Craig Topperb57c2922013-01-24 05:22:40 +00001420
Chris Lattner80f43d32010-01-04 07:53:58 +00001421 if (Instruction *I = commonCastTransforms(CI))
1422 return I;
1423
1424 return 0;
1425}
1426
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001427/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1428Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1429 Value *Src = CI.getOperand(0);
Craig Topperb57c2922013-01-24 05:22:40 +00001430
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001431 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1432 // If casting the result of a getelementptr instruction with no offset, turn
1433 // this into a cast of the original pointer!
1434 if (GEP->hasAllZeroIndices()) {
1435 // Changing the cast operand is usually not a good idea but it is safe
Craig Topperb57c2922013-01-24 05:22:40 +00001436 // here because the pointer operand is being replaced with another
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001437 // pointer operand so the opcode doesn't need to change.
1438 Worklist.Add(GEP);
1439 CI.setOperand(0, GEP->getOperand(0));
1440 return &CI;
1441 }
Craig Topperb57c2922013-01-24 05:22:40 +00001442
Stephen Hines36b56882014-04-23 16:57:46 -07001443 if (!DL)
Matt Arsenault5c40cc22013-08-19 22:17:18 +00001444 return commonCastTransforms(CI);
1445
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001446 // If the GEP has a single use, and the base pointer is a bitcast, and the
1447 // GEP computes a constant offset, see if we can convert these three
1448 // instructions into fewer. This typically happens with unions and other
1449 // non-type-safe code.
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001450 unsigned AS = GEP->getPointerAddressSpace();
Stephen Hines36b56882014-04-23 16:57:46 -07001451 unsigned OffsetBits = DL->getPointerSizeInBits(AS);
Matt Arsenault5c40cc22013-08-19 22:17:18 +00001452 APInt Offset(OffsetBits, 0);
1453 BitCastInst *BCI = dyn_cast<BitCastInst>(GEP->getOperand(0));
1454 if (GEP->hasOneUse() &&
1455 BCI &&
Stephen Hines36b56882014-04-23 16:57:46 -07001456 GEP->accumulateConstantOffset(*DL, Offset)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001457 // Get the base pointer input of the bitcast, and the type it points to.
Matt Arsenault5c40cc22013-08-19 22:17:18 +00001458 Value *OrigBase = BCI->getOperand(0);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001459 SmallVector<Value*, 8> NewIndices;
Matt Arsenault8e3367e2013-08-19 22:17:40 +00001460 if (FindElementAtOffset(OrigBase->getType(),
1461 Offset.getSExtValue(),
1462 NewIndices)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001463 // If we were able to index down into an element, create the GEP
1464 // and bitcast the result. This eliminates one bitcast, potentially
1465 // two.
1466 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
Matt Arsenault5c40cc22013-08-19 22:17:18 +00001467 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1468 Builder->CreateGEP(OrigBase, NewIndices);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001469 NGEP->takeName(GEP);
Craig Topperb57c2922013-01-24 05:22:40 +00001470
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001471 if (isa<BitCastInst>(CI))
1472 return new BitCastInst(NGEP, CI.getType());
1473 assert(isa<PtrToIntInst>(CI));
1474 return new PtrToIntInst(NGEP, CI.getType());
Craig Topperb57c2922013-01-24 05:22:40 +00001475 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001476 }
1477 }
Craig Topperb57c2922013-01-24 05:22:40 +00001478
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001479 return commonCastTransforms(CI);
1480}
1481
1482Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001483 // If the destination integer type is not the intptr_t type for this target,
1484 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1485 // to be exposed to other transforms.
Benjamin Kramer1018fa22013-02-05 19:21:56 +00001486
Stephen Hines36b56882014-04-23 16:57:46 -07001487 if (!DL)
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001488 return commonPointerCastTransforms(CI);
Craig Topperb57c2922013-01-24 05:22:40 +00001489
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001490 Type *Ty = CI.getType();
1491 unsigned AS = CI.getPointerAddressSpace();
1492
Stephen Hines36b56882014-04-23 16:57:46 -07001493 if (Ty->getScalarSizeInBits() == DL->getPointerSizeInBits(AS))
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001494 return commonPointerCastTransforms(CI);
1495
Stephen Hines36b56882014-04-23 16:57:46 -07001496 Type *PtrTy = DL->getIntPtrType(CI.getContext(), AS);
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001497 if (Ty->isVectorTy()) // Handle vectors of pointers.
1498 PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1499
1500 Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
1501 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001502}
1503
Chris Lattner67451912010-05-08 21:50:26 +00001504/// OptimizeVectorResize - This input value (which is known to have vector type)
1505/// is being zero extended or truncated to the specified vector type. Try to
1506/// replace it with a shuffle (and vector/vector bitcast) if possible.
1507///
1508/// The source and destination vector types may have different element types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001509static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
Chris Lattner67451912010-05-08 21:50:26 +00001510 InstCombiner &IC) {
1511 // We can only do this optimization if the output is a multiple of the input
1512 // element size, or the input is a multiple of the output element size.
1513 // Convert the input type to have the same element type as the output.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001514 VectorType *SrcTy = cast<VectorType>(InVal->getType());
Craig Topperb57c2922013-01-24 05:22:40 +00001515
Chris Lattner67451912010-05-08 21:50:26 +00001516 if (SrcTy->getElementType() != DestTy->getElementType()) {
1517 // The input types don't need to be identical, but for now they must be the
1518 // same size. There is no specific reason we couldn't handle things like
1519 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
Craig Topperb57c2922013-01-24 05:22:40 +00001520 // there yet.
Chris Lattner67451912010-05-08 21:50:26 +00001521 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1522 DestTy->getElementType()->getPrimitiveSizeInBits())
1523 return 0;
Craig Topperb57c2922013-01-24 05:22:40 +00001524
Chris Lattner67451912010-05-08 21:50:26 +00001525 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1526 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1527 }
Craig Topperb57c2922013-01-24 05:22:40 +00001528
Chris Lattner67451912010-05-08 21:50:26 +00001529 // Now that the element types match, get the shuffle mask and RHS of the
1530 // shuffle to use, which depends on whether we're increasing or decreasing the
1531 // size of the input.
Chris Lattner7302d802012-02-06 21:56:39 +00001532 SmallVector<uint32_t, 16> ShuffleMask;
Chris Lattner67451912010-05-08 21:50:26 +00001533 Value *V2;
Craig Topperb57c2922013-01-24 05:22:40 +00001534
Chris Lattner67451912010-05-08 21:50:26 +00001535 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1536 // If we're shrinking the number of elements, just shuffle in the low
1537 // elements from the input and use undef as the second shuffle input.
1538 V2 = UndefValue::get(SrcTy);
1539 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
Chris Lattner7302d802012-02-06 21:56:39 +00001540 ShuffleMask.push_back(i);
Craig Topperb57c2922013-01-24 05:22:40 +00001541
Chris Lattner67451912010-05-08 21:50:26 +00001542 } else {
1543 // If we're increasing the number of elements, shuffle in all of the
1544 // elements from InVal and fill the rest of the result elements with zeros
1545 // from a constant zero.
1546 V2 = Constant::getNullValue(SrcTy);
1547 unsigned SrcElts = SrcTy->getNumElements();
1548 for (unsigned i = 0, e = SrcElts; i != e; ++i)
Chris Lattner7302d802012-02-06 21:56:39 +00001549 ShuffleMask.push_back(i);
Chris Lattner67451912010-05-08 21:50:26 +00001550
1551 // The excess elements reference the first element of the zero input.
Chris Lattner7302d802012-02-06 21:56:39 +00001552 for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1553 ShuffleMask.push_back(SrcElts);
Chris Lattner67451912010-05-08 21:50:26 +00001554 }
Craig Topperb57c2922013-01-24 05:22:40 +00001555
Chris Lattner7302d802012-02-06 21:56:39 +00001556 return new ShuffleVectorInst(InVal, V2,
1557 ConstantDataVector::get(V2->getContext(),
1558 ShuffleMask));
Chris Lattner67451912010-05-08 21:50:26 +00001559}
1560
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001561static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001562 return Value % Ty->getPrimitiveSizeInBits() == 0;
1563}
1564
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001565static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001566 return Value / Ty->getPrimitiveSizeInBits();
1567}
1568
1569/// CollectInsertionElements - V is a value which is inserted into a vector of
1570/// VecEltTy. Look through the value to see if we can decompose it into
1571/// insertions into the vector. See the example in the comment for
1572/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1573/// The type of V is always a non-zero multiple of VecEltTy's size.
Richard Sandiford23331c32013-08-12 07:26:09 +00001574/// Shift is the number of bits between the lsb of V and the lsb of
1575/// the vector.
Chris Lattner3dd08732010-08-28 01:20:38 +00001576///
1577/// This returns false if the pattern can't be matched or true if it can,
1578/// filling in Elements with the elements found here.
Richard Sandiford23331c32013-08-12 07:26:09 +00001579static bool CollectInsertionElements(Value *V, unsigned Shift,
Chris Lattner3dd08732010-08-28 01:20:38 +00001580 SmallVectorImpl<Value*> &Elements,
Richard Sandiford23331c32013-08-12 07:26:09 +00001581 Type *VecEltTy, InstCombiner &IC) {
1582 assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1583 "Shift should be a multiple of the element type size");
1584
Chris Lattner157d4ea2010-08-28 03:36:51 +00001585 // Undef values never contribute useful bits to the result.
1586 if (isa<UndefValue>(V)) return true;
Craig Topperb57c2922013-01-24 05:22:40 +00001587
Chris Lattner3dd08732010-08-28 01:20:38 +00001588 // If we got down to a value of the right type, we win, try inserting into the
1589 // right element.
1590 if (V->getType() == VecEltTy) {
Chris Lattner79007792010-08-28 01:50:57 +00001591 // Inserting null doesn't actually insert any elements.
1592 if (Constant *C = dyn_cast<Constant>(V))
1593 if (C->isNullValue())
1594 return true;
Craig Topperb57c2922013-01-24 05:22:40 +00001595
Richard Sandiford23331c32013-08-12 07:26:09 +00001596 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
1597 if (IC.getDataLayout()->isBigEndian())
1598 ElementIndex = Elements.size() - ElementIndex - 1;
1599
Chris Lattner3dd08732010-08-28 01:20:38 +00001600 // Fail if multiple elements are inserted into this slot.
Richard Sandiford23331c32013-08-12 07:26:09 +00001601 if (Elements[ElementIndex] != 0)
Chris Lattner3dd08732010-08-28 01:20:38 +00001602 return false;
Craig Topperb57c2922013-01-24 05:22:40 +00001603
Chris Lattner3dd08732010-08-28 01:20:38 +00001604 Elements[ElementIndex] = V;
1605 return true;
1606 }
Craig Topperb57c2922013-01-24 05:22:40 +00001607
Chris Lattner79007792010-08-28 01:50:57 +00001608 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001609 // Figure out the # elements this provides, and bitcast it or slice it up
1610 // as required.
Chris Lattner79007792010-08-28 01:50:57 +00001611 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1612 VecEltTy);
1613 // If the constant is the size of a vector element, we just need to bitcast
1614 // it to the right type so it gets properly inserted.
1615 if (NumElts == 1)
1616 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
Richard Sandiford23331c32013-08-12 07:26:09 +00001617 Shift, Elements, VecEltTy, IC);
Craig Topperb57c2922013-01-24 05:22:40 +00001618
Chris Lattner79007792010-08-28 01:50:57 +00001619 // Okay, this is a constant that covers multiple elements. Slice it up into
1620 // pieces and insert each element-sized piece into the vector.
1621 if (!isa<IntegerType>(C->getType()))
1622 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1623 C->getType()->getPrimitiveSizeInBits()));
1624 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001625 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
Craig Topperb57c2922013-01-24 05:22:40 +00001626
Chris Lattner79007792010-08-28 01:50:57 +00001627 for (unsigned i = 0; i != NumElts; ++i) {
Richard Sandiford23331c32013-08-12 07:26:09 +00001628 unsigned ShiftI = Shift+i*ElementSize;
Chris Lattner79007792010-08-28 01:50:57 +00001629 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
Richard Sandiford23331c32013-08-12 07:26:09 +00001630 ShiftI));
Chris Lattner79007792010-08-28 01:50:57 +00001631 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
Richard Sandiford23331c32013-08-12 07:26:09 +00001632 if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy, IC))
Chris Lattner79007792010-08-28 01:50:57 +00001633 return false;
1634 }
1635 return true;
1636 }
Craig Topperb57c2922013-01-24 05:22:40 +00001637
Chris Lattner3dd08732010-08-28 01:20:38 +00001638 if (!V->hasOneUse()) return false;
Craig Topperb57c2922013-01-24 05:22:40 +00001639
Chris Lattner3dd08732010-08-28 01:20:38 +00001640 Instruction *I = dyn_cast<Instruction>(V);
1641 if (I == 0) return false;
1642 switch (I->getOpcode()) {
1643 default: return false; // Unhandled case.
1644 case Instruction::BitCast:
Richard Sandiford23331c32013-08-12 07:26:09 +00001645 return CollectInsertionElements(I->getOperand(0), Shift,
1646 Elements, VecEltTy, IC);
Chris Lattner3dd08732010-08-28 01:20:38 +00001647 case Instruction::ZExt:
1648 if (!isMultipleOfTypeSize(
1649 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1650 VecEltTy))
1651 return false;
Richard Sandiford23331c32013-08-12 07:26:09 +00001652 return CollectInsertionElements(I->getOperand(0), Shift,
1653 Elements, VecEltTy, IC);
Chris Lattner3dd08732010-08-28 01:20:38 +00001654 case Instruction::Or:
Richard Sandiford23331c32013-08-12 07:26:09 +00001655 return CollectInsertionElements(I->getOperand(0), Shift,
1656 Elements, VecEltTy, IC) &&
1657 CollectInsertionElements(I->getOperand(1), Shift,
1658 Elements, VecEltTy, IC);
Chris Lattner3dd08732010-08-28 01:20:38 +00001659 case Instruction::Shl: {
1660 // Must be shifting by a constant that is a multiple of the element size.
1661 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1662 if (CI == 0) return false;
Richard Sandiford23331c32013-08-12 07:26:09 +00001663 Shift += CI->getZExtValue();
1664 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
1665 return CollectInsertionElements(I->getOperand(0), Shift,
1666 Elements, VecEltTy, IC);
Chris Lattner3dd08732010-08-28 01:20:38 +00001667 }
Craig Topperb57c2922013-01-24 05:22:40 +00001668
Chris Lattner3dd08732010-08-28 01:20:38 +00001669 }
1670}
1671
1672
1673/// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1674/// may be doing shifts and ors to assemble the elements of the vector manually.
1675/// Try to rip the code out and replace it with insertelements. This is to
1676/// optimize code like this:
1677///
1678/// %tmp37 = bitcast float %inc to i32
1679/// %tmp38 = zext i32 %tmp37 to i64
1680/// %tmp31 = bitcast float %inc5 to i32
1681/// %tmp32 = zext i32 %tmp31 to i64
1682/// %tmp33 = shl i64 %tmp32, 32
1683/// %ins35 = or i64 %tmp33, %tmp38
1684/// %tmp43 = bitcast i64 %ins35 to <2 x float>
1685///
1686/// Into two insertelements that do "buildvector{%inc, %inc5}".
1687static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1688 InstCombiner &IC) {
Richard Sandiford23331c32013-08-12 07:26:09 +00001689 // We need to know the target byte order to perform this optimization.
1690 if (!IC.getDataLayout()) return 0;
1691
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001692 VectorType *DestVecTy = cast<VectorType>(CI.getType());
Chris Lattner3dd08732010-08-28 01:20:38 +00001693 Value *IntInput = CI.getOperand(0);
1694
1695 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1696 if (!CollectInsertionElements(IntInput, 0, Elements,
Richard Sandiford23331c32013-08-12 07:26:09 +00001697 DestVecTy->getElementType(), IC))
Chris Lattner3dd08732010-08-28 01:20:38 +00001698 return 0;
1699
1700 // If we succeeded, we know that all of the element are specified by Elements
1701 // or are zero if Elements has a null entry. Recast this as a set of
1702 // insertions.
1703 Value *Result = Constant::getNullValue(CI.getType());
1704 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1705 if (Elements[i] == 0) continue; // Unset element.
Craig Topperb57c2922013-01-24 05:22:40 +00001706
Chris Lattner3dd08732010-08-28 01:20:38 +00001707 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1708 IC.Builder->getInt32(i));
1709 }
Craig Topperb57c2922013-01-24 05:22:40 +00001710
Chris Lattner3dd08732010-08-28 01:20:38 +00001711 return Result;
1712}
1713
1714
Chris Lattnere5a14262010-08-26 21:55:42 +00001715/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1716/// bitcast. The various long double bitcasts can't get in here.
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001717static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
Ulrich Weigandfdc61772013-03-26 15:36:14 +00001718 // We need to know the target byte order to perform this optimization.
1719 if (!IC.getDataLayout()) return 0;
1720
Chris Lattnere5a14262010-08-26 21:55:42 +00001721 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001722 Type *DestTy = CI.getType();
Chris Lattnere5a14262010-08-26 21:55:42 +00001723
1724 // If this is a bitcast from int to float, check to see if the int is an
1725 // extraction from a vector.
1726 Value *VecInput = 0;
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001727 // bitcast(trunc(bitcast(somevector)))
Chris Lattnere5a14262010-08-26 21:55:42 +00001728 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1729 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001730 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001731 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1732
1733 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1734 // If the element type of the vector doesn't match the result type,
1735 // bitcast it to be a vector type we can extract from.
1736 if (VecTy->getElementType() != DestTy) {
1737 VecTy = VectorType::get(DestTy,
1738 VecTy->getPrimitiveSizeInBits() / DestWidth);
1739 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1740 }
Craig Topperb57c2922013-01-24 05:22:40 +00001741
Ulrich Weigandfdc61772013-03-26 15:36:14 +00001742 unsigned Elt = 0;
1743 if (IC.getDataLayout()->isBigEndian())
1744 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1;
1745 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001746 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001747 }
Craig Topperb57c2922013-01-24 05:22:40 +00001748
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001749 // bitcast(trunc(lshr(bitcast(somevector), cst))
1750 ConstantInt *ShAmt = 0;
1751 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1752 m_ConstantInt(ShAmt)))) &&
1753 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001754 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001755 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1756 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1757 ShAmt->getZExtValue() % DestWidth == 0) {
1758 // If the element type of the vector doesn't match the result type,
1759 // bitcast it to be a vector type we can extract from.
1760 if (VecTy->getElementType() != DestTy) {
1761 VecTy = VectorType::get(DestTy,
1762 VecTy->getPrimitiveSizeInBits() / DestWidth);
1763 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1764 }
Craig Topperb57c2922013-01-24 05:22:40 +00001765
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001766 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
Ulrich Weigandfdc61772013-03-26 15:36:14 +00001767 if (IC.getDataLayout()->isBigEndian())
1768 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt;
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001769 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1770 }
1771 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001772 return 0;
1773}
Chris Lattner67451912010-05-08 21:50:26 +00001774
Chris Lattner80f43d32010-01-04 07:53:58 +00001775Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1776 // If the operands are integer typed then apply the integer transforms,
1777 // otherwise just apply the common ones.
1778 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001779 Type *SrcTy = Src->getType();
1780 Type *DestTy = CI.getType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001781
Chris Lattner80f43d32010-01-04 07:53:58 +00001782 // Get rid of casts from one type to the same type. These are useless and can
1783 // be replaced by the operand.
1784 if (DestTy == Src->getType())
1785 return ReplaceInstUsesWith(CI, Src);
1786
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001787 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1788 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1789 Type *DstElTy = DstPTy->getElementType();
1790 Type *SrcElTy = SrcPTy->getElementType();
Craig Topperb57c2922013-01-24 05:22:40 +00001791
Chris Lattner80f43d32010-01-04 07:53:58 +00001792 // If we are casting a alloca to a pointer to a type of the same
1793 // size, rewrite the allocation instruction to allocate the "right" type.
1794 // There is no need to modify malloc calls because it is their bitcast that
1795 // needs to be cleaned up.
1796 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1797 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1798 return V;
Craig Topperb57c2922013-01-24 05:22:40 +00001799
Chris Lattner80f43d32010-01-04 07:53:58 +00001800 // If the source and destination are pointers, and this cast is equivalent
1801 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1802 // This can enhance SROA and other transforms that want type-safe pointers.
1803 Constant *ZeroUInt =
1804 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1805 unsigned NumZeros = 0;
Craig Topperb57c2922013-01-24 05:22:40 +00001806 while (SrcElTy != DstElTy &&
Duncan Sands1df98592010-02-16 11:11:14 +00001807 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner80f43d32010-01-04 07:53:58 +00001808 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1809 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1810 ++NumZeros;
1811 }
1812
1813 // If we found a path from the src to dest, create the getelementptr now.
1814 if (SrcElTy == DstElTy) {
1815 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Jay Foada9203102011-07-25 09:48:08 +00001816 return GetElementPtrInst::CreateInBounds(Src, Idxs);
Chris Lattner80f43d32010-01-04 07:53:58 +00001817 }
1818 }
Craig Topperb57c2922013-01-24 05:22:40 +00001819
Chris Lattnere5a14262010-08-26 21:55:42 +00001820 // Try to optimize int -> float bitcasts.
1821 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1822 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1823 return I;
Chris Lattner80f43d32010-01-04 07:53:58 +00001824
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001825 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001826 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001827 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1828 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001829 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001830 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1831 }
Craig Topperb57c2922013-01-24 05:22:40 +00001832
Chris Lattner3dd08732010-08-28 01:20:38 +00001833 if (isa<IntegerType>(SrcTy)) {
1834 // If this is a cast from an integer to vector, check to see if the input
1835 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1836 // the casts with a shuffle and (potentially) a bitcast.
1837 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1838 CastInst *SrcCast = cast<CastInst>(Src);
1839 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1840 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1841 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
Chris Lattner67451912010-05-08 21:50:26 +00001842 cast<VectorType>(DestTy), *this))
Chris Lattner3dd08732010-08-28 01:20:38 +00001843 return I;
1844 }
Craig Topperb57c2922013-01-24 05:22:40 +00001845
Chris Lattner3dd08732010-08-28 01:20:38 +00001846 // If the input is an 'or' instruction, we may be doing shifts and ors to
1847 // assemble the elements of the vector manually. Try to rip the code out
1848 // and replace it with insertelements.
1849 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1850 return ReplaceInstUsesWith(CI, V);
Chris Lattner67451912010-05-08 21:50:26 +00001851 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001852 }
1853
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001854 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Michael Ilseman9c213cc2013-02-11 21:41:44 +00001855 if (SrcVTy->getNumElements() == 1) {
1856 // If our destination is not a vector, then make this a straight
1857 // scalar-scalar cast.
1858 if (!DestTy->isVectorTy()) {
1859 Value *Elem =
1860 Builder->CreateExtractElement(Src,
1861 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1862 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1863 }
1864
1865 // Otherwise, see if our source is an insert. If so, then use the scalar
1866 // component directly.
1867 if (InsertElementInst *IEI =
1868 dyn_cast<InsertElementInst>(CI.getOperand(0)))
1869 return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
1870 DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001871 }
1872 }
1873
1874 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001875 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmana5ced592010-04-07 23:22:42 +00001876 // a bitcast to a vector with the same # elts.
Craig Topperb57c2922013-01-24 05:22:40 +00001877 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Matt Arsenault3ea117e2013-08-14 00:24:34 +00001878 DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001879 SVI->getType()->getNumElements() ==
Matt Arsenault3ea117e2013-08-14 00:24:34 +00001880 SVI->getOperand(0)->getType()->getVectorNumElements()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001881 BitCastInst *Tmp;
1882 // If either of the operands is a cast from CI.getType(), then
1883 // evaluating the shuffle in the casted destination's type will allow
1884 // us to eliminate at least one cast.
Craig Topperb57c2922013-01-24 05:22:40 +00001885 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001886 Tmp->getOperand(0)->getType() == DestTy) ||
Craig Topperb57c2922013-01-24 05:22:40 +00001887 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001888 Tmp->getOperand(0)->getType() == DestTy)) {
1889 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1890 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1891 // Return a new shuffle vector. Use the same element ID's, as we
1892 // know the vector types match #elts.
1893 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001894 }
1895 }
1896 }
Craig Topperb57c2922013-01-24 05:22:40 +00001897
Duncan Sands1df98592010-02-16 11:11:14 +00001898 if (SrcTy->isPointerTy())
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001899 return commonPointerCastTransforms(CI);
1900 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001901}
Matt Arsenault6dd44d32013-11-15 05:45:08 +00001902
1903Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
Stephen Hines36b56882014-04-23 16:57:46 -07001904 return commonPointerCastTransforms(CI);
Matt Arsenault6dd44d32013-11-15 05:45:08 +00001905}