blob: 9db4e7d2a4bb833800f4b1ad1190548182c8d60f [file] [log] [blame]
Chris Lattner2b295a02010-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
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/DataLayout.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000017#include "llvm/IR/PatternMatch.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattner2b295a02010-01-04 07:53:58 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattner59d95742010-01-04 07:59:07 +000024/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
25/// expression. If so, decompose it, returning some value X, such that Val is
26/// X*Scale+Offset.
27///
28static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Dan Gohman05a65552010-05-28 04:33:04 +000029 uint64_t &Offset) {
Chris Lattner59d95742010-01-04 07:59:07 +000030 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
31 Offset = CI->getZExtValue();
32 Scale = 0;
Dan Gohman05a65552010-05-28 04:33:04 +000033 return ConstantInt::get(Val->getType(), 0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000034 }
Craig Topper3529aa52013-01-24 05:22:40 +000035
Chris Lattneraaccc8d2010-01-05 20:57:30 +000036 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Bob Wilson3c68b622011-07-08 22:09:33 +000037 // Cannot look past anything that might overflow.
38 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
Stepan Dyatkovskiycb2a1a32012-05-05 07:09:40 +000039 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
Bob Wilson3c68b622011-07-08 22:09:33 +000040 Scale = 1;
41 Offset = 0;
42 return Val;
43 }
44
Chris Lattner59d95742010-01-04 07:59:07 +000045 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
46 if (I->getOpcode() == Instruction::Shl) {
47 // This is a value scaled by '1 << the shift amt'.
Dan Gohman05a65552010-05-28 04:33:04 +000048 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattner59d95742010-01-04 07:59:07 +000049 Offset = 0;
50 return I->getOperand(0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000051 }
Craig Topper3529aa52013-01-24 05:22:40 +000052
Chris Lattneraaccc8d2010-01-05 20:57:30 +000053 if (I->getOpcode() == Instruction::Mul) {
Chris Lattner59d95742010-01-04 07:59:07 +000054 // This value is scaled by 'RHS'.
55 Scale = RHS->getZExtValue();
56 Offset = 0;
57 return I->getOperand(0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000058 }
Craig Topper3529aa52013-01-24 05:22:40 +000059
Chris Lattneraaccc8d2010-01-05 20:57:30 +000060 if (I->getOpcode() == Instruction::Add) {
Craig Topper3529aa52013-01-24 05:22:40 +000061 // We have X+C. Check to see if we really have (X*C2)+C1,
Chris Lattner59d95742010-01-04 07:59:07 +000062 // where C1 is divisible by C2.
63 unsigned SubScale;
Craig Topper3529aa52013-01-24 05:22:40 +000064 Value *SubVal =
Chris Lattner59d95742010-01-04 07:59:07 +000065 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
66 Offset += RHS->getZExtValue();
67 Scale = SubScale;
68 return SubVal;
69 }
70 }
71 }
72
73 // Otherwise, we can't look past this.
74 Scale = 1;
75 Offset = 0;
76 return Val;
77}
78
79/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
80/// try to eliminate the cast by moving the type information into the alloc.
81Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
82 AllocaInst &AI) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +000083 // This requires DataLayout to get the alloca alignment and size information.
Craig Topperf40110f2014-04-25 05:29:35 +000084 if (!DL) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +000085
Chris Lattner229907c2011-07-18 04:54:35 +000086 PointerType *PTy = cast<PointerType>(CI.getType());
Craig Topper3529aa52013-01-24 05:22:40 +000087
Chris Lattner59d95742010-01-04 07:59:07 +000088 BuilderTy AllocaBuilder(*Builder);
89 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
90
91 // Get the type really allocated and the type casted to.
Chris Lattner229907c2011-07-18 04:54:35 +000092 Type *AllocElTy = AI.getAllocatedType();
93 Type *CastElTy = PTy->getElementType();
Craig Topperf40110f2014-04-25 05:29:35 +000094 if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +000095
Rafael Espindola37dc9e12014-02-21 00:06:31 +000096 unsigned AllocElTyAlign = DL->getABITypeAlignment(AllocElTy);
97 unsigned CastElTyAlign = DL->getABITypeAlignment(CastElTy);
Craig Topperf40110f2014-04-25 05:29:35 +000098 if (CastElTyAlign < AllocElTyAlign) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +000099
100 // If the allocation has multiple uses, only promote it if we are strictly
101 // increasing the alignment of the resultant allocation. If we keep it the
Devang Patelfbb482b2011-03-08 22:12:11 +0000102 // same, we open the door to infinite loops of various kinds.
Craig Topperf40110f2014-04-25 05:29:35 +0000103 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000104
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000105 uint64_t AllocElTySize = DL->getTypeAllocSize(AllocElTy);
106 uint64_t CastElTySize = DL->getTypeAllocSize(CastElTy);
Craig Topperf40110f2014-04-25 05:29:35 +0000107 if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000108
Jim Grosbach95d2eb92013-03-06 05:44:53 +0000109 // If the allocation has multiple uses, only promote it if we're not
110 // shrinking the amount of memory being allocated.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000111 uint64_t AllocElTyStoreSize = DL->getTypeStoreSize(AllocElTy);
112 uint64_t CastElTyStoreSize = DL->getTypeStoreSize(CastElTy);
Craig Topperf40110f2014-04-25 05:29:35 +0000113 if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
Jim Grosbach95d2eb92013-03-06 05:44:53 +0000114
Chris Lattner59d95742010-01-04 07:59:07 +0000115 // See if we can satisfy the modulus by pulling a scale out of the array
116 // size argument.
117 unsigned ArraySizeScale;
Dan Gohman05a65552010-05-28 04:33:04 +0000118 uint64_t ArrayOffset;
Chris Lattner59d95742010-01-04 07:59:07 +0000119 Value *NumElements = // See if the array size is a decomposable linear expr.
120 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Craig Topper3529aa52013-01-24 05:22:40 +0000121
Chris Lattner59d95742010-01-04 07:59:07 +0000122 // If we can now satisfy the modulus, by using a non-1 scale, we really can
123 // do the xform.
124 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000125 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000126
127 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
Craig Topperf40110f2014-04-25 05:29:35 +0000128 Value *Amt = nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000129 if (Scale == 1) {
130 Amt = NumElements;
131 } else {
Dan Gohman05a65552010-05-28 04:33:04 +0000132 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattner59d95742010-01-04 07:59:07 +0000133 // Insert before the alloca, not before the cast.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000134 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
Chris Lattner59d95742010-01-04 07:59:07 +0000135 }
Craig Topper3529aa52013-01-24 05:22:40 +0000136
Dan Gohman05a65552010-05-28 04:33:04 +0000137 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
138 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattner59d95742010-01-04 07:59:07 +0000139 Offset, true);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000140 Amt = AllocaBuilder.CreateAdd(Amt, Off);
Chris Lattner59d95742010-01-04 07:59:07 +0000141 }
Craig Topper3529aa52013-01-24 05:22:40 +0000142
Chris Lattner59d95742010-01-04 07:59:07 +0000143 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
144 New->setAlignment(AI.getAlignment());
145 New->takeName(&AI);
Hans Wennborge36e1162014-04-28 17:40:03 +0000146 New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
Craig Topper3529aa52013-01-24 05:22:40 +0000147
Chris Lattner59d95742010-01-04 07:59:07 +0000148 // If the allocation has multiple real uses, insert a cast and change all
149 // things that used it to use the new cast. This will also hack on CI, but it
150 // will die soon.
Devang Patelfbb482b2011-03-08 22:12:11 +0000151 if (!AI.hasOneUse()) {
Chris Lattner59d95742010-01-04 07:59:07 +0000152 // New is the allocation instruction, pointer typed. AI is the original
153 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
154 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Eli Friedmanb9ed18f2011-05-18 00:32:01 +0000155 ReplaceInstUsesWith(AI, NewCast);
Chris Lattner59d95742010-01-04 07:59:07 +0000156 }
157 return ReplaceInstUsesWith(CI, New);
158}
159
Craig Topper3529aa52013-01-24 05:22:40 +0000160/// EvaluateInDifferentType - Given an expression that
Chris Lattner10840e92010-01-08 19:19:23 +0000161/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattner98748c02010-01-06 01:56:21 +0000162/// insert the code to evaluate the expression.
Craig Topper3529aa52013-01-24 05:22:40 +0000163Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
Chris Lattner92be2ad2010-01-04 07:54:59 +0000164 bool isSigned) {
Chris Lattner9242ae02010-01-08 19:28:47 +0000165 if (Constant *C = dyn_cast<Constant>(V)) {
166 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000167 // If we got a constantexpr back, try to simplify it with DL info.
Chris Lattner9242ae02010-01-08 19:28:47 +0000168 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000169 C = ConstantFoldConstantExpression(CE, DL, TLI);
Chris Lattner9242ae02010-01-08 19:28:47 +0000170 return C;
171 }
Chris Lattner92be2ad2010-01-04 07:54:59 +0000172
173 // Otherwise, it must be an instruction.
174 Instruction *I = cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000175 Instruction *Res = nullptr;
Chris Lattner92be2ad2010-01-04 07:54:59 +0000176 unsigned Opc = I->getOpcode();
177 switch (Opc) {
178 case Instruction::Add:
179 case Instruction::Sub:
180 case Instruction::Mul:
181 case Instruction::And:
182 case Instruction::Or:
183 case Instruction::Xor:
184 case Instruction::AShr:
185 case Instruction::LShr:
186 case Instruction::Shl:
187 case Instruction::UDiv:
188 case Instruction::URem: {
189 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
190 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
191 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
192 break;
Craig Topper3529aa52013-01-24 05:22:40 +0000193 }
Chris Lattner92be2ad2010-01-04 07:54:59 +0000194 case Instruction::Trunc:
195 case Instruction::ZExt:
196 case Instruction::SExt:
197 // If the source type of the cast is the type we're trying for then we can
198 // just return the source. There's no need to insert it because it is not
199 // new.
200 if (I->getOperand(0)->getType() == Ty)
201 return I->getOperand(0);
Craig Topper3529aa52013-01-24 05:22:40 +0000202
Chris Lattner92be2ad2010-01-04 07:54:59 +0000203 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner39d2daa2010-01-10 20:25:54 +0000204 // This also handles the case of zext(trunc(x)) -> zext(x).
205 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
206 Opc == Instruction::SExt);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000207 break;
208 case Instruction::Select: {
209 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
210 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
211 Res = SelectInst::Create(I->getOperand(0), True, False);
212 break;
213 }
214 case Instruction::PHI: {
215 PHINode *OPN = cast<PHINode>(I);
Jay Foad52131342011-03-30 11:28:46 +0000216 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
Chris Lattner92be2ad2010-01-04 07:54:59 +0000217 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
218 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
219 NPN->addIncoming(V, OPN->getIncomingBlock(i));
220 }
221 Res = NPN;
222 break;
223 }
Craig Topper3529aa52013-01-24 05:22:40 +0000224 default:
Chris Lattner92be2ad2010-01-04 07:54:59 +0000225 // TODO: Can handle more cases here.
226 llvm_unreachable("Unreachable!");
Chris Lattner92be2ad2010-01-04 07:54:59 +0000227 }
Craig Topper3529aa52013-01-24 05:22:40 +0000228
Chris Lattner92be2ad2010-01-04 07:54:59 +0000229 Res->takeName(I);
Eli Friedman35211c62011-05-27 00:19:40 +0000230 return InsertNewInstWith(Res, *I);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000231}
Chris Lattner2b295a02010-01-04 07:53:58 +0000232
233
234/// This function is a wrapper around CastInst::isEliminableCastPair. It
235/// simply extracts arguments and returns what that function returns.
Craig Topper3529aa52013-01-24 05:22:40 +0000236static Instruction::CastOps
Chris Lattner2b295a02010-01-04 07:53:58 +0000237isEliminableCastPair(
238 const CastInst *CI, ///< The first cast instruction
239 unsigned opcode, ///< The opcode of the second cast instruction
Chris Lattner229907c2011-07-18 04:54:35 +0000240 Type *DstTy, ///< The target type for the second cast instruction
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000241 const DataLayout *DL ///< The target data for pointer size
Chris Lattner2b295a02010-01-04 07:53:58 +0000242) {
243
Chris Lattner229907c2011-07-18 04:54:35 +0000244 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
245 Type *MidTy = CI->getType(); // B from above
Chris Lattner2b295a02010-01-04 07:53:58 +0000246
247 // Get the opcodes of the two Cast instructions
248 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
249 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000250 Type *SrcIntPtrTy = DL && SrcTy->isPtrOrPtrVectorTy() ?
Craig Topperf40110f2014-04-25 05:29:35 +0000251 DL->getIntPtrType(SrcTy) : nullptr;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000252 Type *MidIntPtrTy = DL && MidTy->isPtrOrPtrVectorTy() ?
Craig Topperf40110f2014-04-25 05:29:35 +0000253 DL->getIntPtrType(MidTy) : nullptr;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000254 Type *DstIntPtrTy = DL && DstTy->isPtrOrPtrVectorTy() ?
Craig Topperf40110f2014-04-25 05:29:35 +0000255 DL->getIntPtrType(DstTy) : nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000256 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Duncan Sandse2395dc2012-10-30 16:03:32 +0000257 DstTy, SrcIntPtrTy, MidIntPtrTy,
258 DstIntPtrTy);
Micah Villmow12d91272012-10-24 15:52:52 +0000259
Chris Lattner2b295a02010-01-04 07:53:58 +0000260 // We don't want to form an inttoptr or ptrtoint that converts to an integer
261 // type that differs from the pointer size.
Duncan Sandse2395dc2012-10-30 16:03:32 +0000262 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
263 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
Chris Lattner2b295a02010-01-04 07:53:58 +0000264 Res = 0;
Craig Topper3529aa52013-01-24 05:22:40 +0000265
Chris Lattner2b295a02010-01-04 07:53:58 +0000266 return Instruction::CastOps(Res);
267}
268
Chris Lattner4e8137d2010-02-11 06:26:33 +0000269/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
270/// results in any code being generated and is interesting to optimize out. If
271/// the cast can be eliminated by some other simple transformation, we prefer
272/// to do the simplification first.
273bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
Chris Lattner229907c2011-07-18 04:54:35 +0000274 Type *Ty) {
Chris Lattner4e8137d2010-02-11 06:26:33 +0000275 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner2b295a02010-01-04 07:53:58 +0000276 if (V->getType() == Ty || isa<Constant>(V)) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000277
Chris Lattner4e8137d2010-02-11 06:26:33 +0000278 // If this is another cast that can be eliminated, we prefer to have it
279 // eliminated.
Chris Lattner2b295a02010-01-04 07:53:58 +0000280 if (const CastInst *CI = dyn_cast<CastInst>(V))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000281 if (isEliminableCastPair(CI, opc, Ty, DL))
Chris Lattner2b295a02010-01-04 07:53:58 +0000282 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000283
Chris Lattner4e8137d2010-02-11 06:26:33 +0000284 // If this is a vector sext from a compare, then we don't want to break the
285 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands19d0b472010-02-16 11:11:14 +0000286 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner4e8137d2010-02-11 06:26:33 +0000287 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000288
Chris Lattner2b295a02010-01-04 07:53:58 +0000289 return true;
290}
291
292
293/// @brief Implement the transforms common to all CastInst visitors.
294Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
295 Value *Src = CI.getOperand(0);
296
297 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
298 // eliminate it now.
299 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Craig Topper3529aa52013-01-24 05:22:40 +0000300 if (Instruction::CastOps opc =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000301 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000302 // The first cast (CSrc) is eliminable so we need to fix up or replace
303 // the second cast (CI). CSrc will then have a good chance of being dead.
304 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
305 }
306 }
307
308 // If we are casting a select then fold the cast into the select
309 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
310 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
311 return NV;
312
313 // If we are casting a PHI then fold the cast into the PHI
314 if (isa<PHINode>(Src)) {
315 // We don't do this if this would create a PHI node with an illegal type if
316 // it is currently legal.
Duncan Sands19d0b472010-02-16 11:11:14 +0000317 if (!Src->getType()->isIntegerTy() ||
318 !CI.getType()->isIntegerTy() ||
Chris Lattner2b295a02010-01-04 07:53:58 +0000319 ShouldChangeType(CI.getType(), Src->getType()))
320 if (Instruction *NV = FoldOpIntoPhi(CI))
321 return NV;
322 }
Craig Topper3529aa52013-01-24 05:22:40 +0000323
Craig Topperf40110f2014-04-25 05:29:35 +0000324 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000325}
326
Chris Lattnerc3aca382010-01-10 00:58:42 +0000327/// CanEvaluateTruncated - Return true if we can evaluate the specified
328/// expression tree as type Ty instead of its larger type, and arrive with the
329/// same value. This is used by code that tries to eliminate truncates.
330///
331/// Ty will always be a type smaller than V. We should return true if trunc(V)
332/// can be computed by computing V in the smaller type. If V is an instruction,
333/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
334/// makes sense if x and y can be efficiently truncated.
335///
Chris Lattner172630a2010-01-11 02:43:35 +0000336/// This function works on both vectors and scalars.
337///
Hal Finkel60db0582014-09-07 18:57:58 +0000338static bool CanEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC,
339 Instruction *CxtI) {
Chris Lattnerc3aca382010-01-10 00:58:42 +0000340 // We can always evaluate constants in another type.
341 if (isa<Constant>(V))
342 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000343
Chris Lattnerc3aca382010-01-10 00:58:42 +0000344 Instruction *I = dyn_cast<Instruction>(V);
345 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000346
Chris Lattner229907c2011-07-18 04:54:35 +0000347 Type *OrigTy = V->getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000348
Chris Lattnera6b13562010-01-11 22:45:25 +0000349 // If this is an extension from the dest type, we can eliminate it, even if it
350 // has multiple uses.
Craig Topper3529aa52013-01-24 05:22:40 +0000351 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattnerc3aca382010-01-10 00:58:42 +0000352 I->getOperand(0)->getType() == Ty)
353 return true;
354
355 // We can't extend or shrink something that has multiple uses: doing so would
356 // require duplicating the instruction in general, which isn't profitable.
357 if (!I->hasOneUse()) return false;
358
359 unsigned Opc = I->getOpcode();
360 switch (Opc) {
361 case Instruction::Add:
362 case Instruction::Sub:
363 case Instruction::Mul:
364 case Instruction::And:
365 case Instruction::Or:
366 case Instruction::Xor:
367 // These operators can all arbitrarily be extended or truncated.
Hal Finkel60db0582014-09-07 18:57:58 +0000368 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
369 CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000370
371 case Instruction::UDiv:
372 case Instruction::URem: {
373 // UDiv and URem can be truncated if all the truncated bits are zero.
374 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
375 uint32_t BitWidth = Ty->getScalarSizeInBits();
376 if (BitWidth < OrigBitWidth) {
377 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
Hal Finkel60db0582014-09-07 18:57:58 +0000378 if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
379 IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
380 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
381 CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000382 }
383 }
384 break;
385 }
386 case Instruction::Shl:
387 // If we are truncating the result of this SHL, and if it's a shift of a
388 // constant amount, we can always perform a SHL in a smaller type.
389 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
390 uint32_t BitWidth = Ty->getScalarSizeInBits();
391 if (CI->getLimitedValue(BitWidth) < BitWidth)
Hal Finkel60db0582014-09-07 18:57:58 +0000392 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000393 }
394 break;
395 case Instruction::LShr:
396 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000397 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattnerc3aca382010-01-10 00:58:42 +0000398 // already zeros.
399 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
400 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
401 uint32_t BitWidth = Ty->getScalarSizeInBits();
Hal Finkel60db0582014-09-07 18:57:58 +0000402 if (IC.MaskedValueIsZero(I->getOperand(0),
403 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth), 0, CxtI) &&
Chris Lattnerc3aca382010-01-10 00:58:42 +0000404 CI->getLimitedValue(BitWidth) < BitWidth) {
Hal Finkel60db0582014-09-07 18:57:58 +0000405 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000406 }
407 }
408 break;
409 case Instruction::Trunc:
410 // trunc(trunc(x)) -> trunc(x)
411 return true;
Chris Lattner73984342010-08-27 20:32:06 +0000412 case Instruction::ZExt:
413 case Instruction::SExt:
414 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
415 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
416 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000417 case Instruction::Select: {
418 SelectInst *SI = cast<SelectInst>(I);
Hal Finkel60db0582014-09-07 18:57:58 +0000419 return CanEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
420 CanEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000421 }
422 case Instruction::PHI: {
423 // We can change a phi if we can change all operands. Note that we never
424 // get into trouble with cyclic PHIs here because we only consider
425 // instructions with a single use.
426 PHINode *PN = cast<PHINode>(I);
427 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Hal Finkel60db0582014-09-07 18:57:58 +0000428 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty, IC, CxtI))
Chris Lattnerc3aca382010-01-10 00:58:42 +0000429 return false;
430 return true;
431 }
432 default:
433 // TODO: Can handle more cases here.
434 break;
435 }
Craig Topper3529aa52013-01-24 05:22:40 +0000436
Chris Lattnerc3aca382010-01-10 00:58:42 +0000437 return false;
438}
439
440Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner883550a2010-01-10 01:00:46 +0000441 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattnerc3aca382010-01-10 00:58:42 +0000442 return Result;
Craig Topper3529aa52013-01-24 05:22:40 +0000443
444 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +0000445 // purpose is to compute bits we don't care about.
446 if (SimplifyDemandedInstructionBits(CI))
447 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +0000448
Chris Lattnerc3aca382010-01-10 00:58:42 +0000449 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000450 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000451
Chris Lattnerc3aca382010-01-10 00:58:42 +0000452 // Attempt to truncate the entire input expression tree to the destination
453 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner2b295a02010-01-04 07:53:58 +0000454 // expression tree to something weird like i93 unless the source is also
455 // strange.
Duncan Sands19d0b472010-02-16 11:11:14 +0000456 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Hal Finkel60db0582014-09-07 18:57:58 +0000457 CanEvaluateTruncated(Src, DestTy, *this, &CI)) {
Craig Topper3529aa52013-01-24 05:22:40 +0000458
Chris Lattner2b295a02010-01-04 07:53:58 +0000459 // If this cast is a truncate, evaluting in a different type always
Chris Lattner8600dd32010-01-05 23:00:30 +0000460 // eliminates the cast, so it is always a win.
Chris Lattner3057c372010-01-07 23:41:00 +0000461 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohmana4abd032010-05-25 21:50:35 +0000462 " to avoid cast: " << CI << '\n');
Chris Lattner3057c372010-01-07 23:41:00 +0000463 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
464 assert(Res->getType() == DestTy);
465 return ReplaceInstUsesWith(CI, Res);
466 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000467
Chris Lattnera93c63c2010-01-05 22:21:18 +0000468 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
469 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000470 Constant *One = ConstantInt::get(Src->getType(), 1);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000471 Src = Builder->CreateAnd(Src, One);
Chris Lattner2b295a02010-01-04 07:53:58 +0000472 Value *Zero = Constant::getNullValue(Src->getType());
473 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
474 }
Craig Topper3529aa52013-01-24 05:22:40 +0000475
Chris Lattner90cd7462010-08-27 18:31:05 +0000476 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
Craig Topperf40110f2014-04-25 05:29:35 +0000477 Value *A = nullptr; ConstantInt *Cst = nullptr;
Chris Lattner9c10d582011-01-15 06:32:33 +0000478 if (Src->hasOneUse() &&
479 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
Chris Lattner90cd7462010-08-27 18:31:05 +0000480 // We have three types to worry about here, the type of A, the source of
481 // the truncate (MidSize), and the destination of the truncate. We know that
482 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
483 // between ASize and ResultSize.
484 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +0000485
Chris Lattner90cd7462010-08-27 18:31:05 +0000486 // If the shift amount is larger than the size of A, then the result is
487 // known to be zero because all the input bits got shifted out.
488 if (Cst->getZExtValue() >= ASize)
489 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
490
491 // Since we're doing an lshr and a zero extend, and know that the shift
492 // amount is smaller than ASize, it is always safe to do the shift in A's
493 // type, then zero extend or truncate to the result.
494 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
495 Shift->takeName(Src);
496 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
497 }
Craig Topper3529aa52013-01-24 05:22:40 +0000498
Chris Lattner9c10d582011-01-15 06:32:33 +0000499 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
500 // type isn't non-native.
501 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
502 ShouldChangeType(Src->getType(), CI.getType()) &&
503 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
504 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
505 return BinaryOperator::CreateAnd(NewTrunc,
506 ConstantExpr::getTrunc(Cst, CI.getType()));
507 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000508
Craig Topperf40110f2014-04-25 05:29:35 +0000509 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000510}
511
512/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
513/// in order to eliminate the icmp.
514Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
515 bool DoXform) {
516 // If we are just checking for a icmp eq of a single bit and zext'ing it
517 // to an integer, then shift the bit to the appropriate place and then
518 // cast to integer to avoid the comparison.
519 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
520 const APInt &Op1CV = Op1C->getValue();
Craig Topper3529aa52013-01-24 05:22:40 +0000521
Chris Lattner2b295a02010-01-04 07:53:58 +0000522 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
523 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
524 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
525 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
526 if (!DoXform) return ICI;
527
528 Value *In = ICI->getOperand(0);
529 Value *Sh = ConstantInt::get(In->getType(),
530 In->getType()->getScalarSizeInBits()-1);
531 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
532 if (In->getType() != CI.getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000533 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner2b295a02010-01-04 07:53:58 +0000534
535 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
536 Constant *One = ConstantInt::get(In->getType(), 1);
537 In = Builder->CreateXor(In, One, In->getName()+".not");
538 }
539
540 return ReplaceInstUsesWith(CI, In);
541 }
Chad Rosier385d9f62011-11-30 01:59:59 +0000542
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000543 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
544 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
545 // zext (X == 1) to i32 --> X iff X has only the low bit set.
546 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
547 // zext (X != 0) to i32 --> X iff X has only the low bit set.
548 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
549 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
550 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Craig Topper3529aa52013-01-24 05:22:40 +0000551 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
Chris Lattner2b295a02010-01-04 07:53:58 +0000552 // This only works for EQ and NE
553 ICI->isEquality()) {
554 // If Op1C some other power of two, convert:
555 uint32_t BitWidth = Op1C->getType()->getBitWidth();
556 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +0000557 computeKnownBits(ICI->getOperand(0), KnownZero, KnownOne, 0, &CI);
Craig Topper3529aa52013-01-24 05:22:40 +0000558
Chris Lattner2b295a02010-01-04 07:53:58 +0000559 APInt KnownZeroMask(~KnownZero);
560 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
561 if (!DoXform) return ICI;
562
563 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
564 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
565 // (X&4) == 2 --> false
566 // (X&4) != 2 --> true
567 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
568 isNE);
569 Res = ConstantExpr::getZExt(Res, CI.getType());
570 return ReplaceInstUsesWith(CI, Res);
571 }
Craig Topper3529aa52013-01-24 05:22:40 +0000572
Chris Lattner2b295a02010-01-04 07:53:58 +0000573 uint32_t ShiftAmt = KnownZeroMask.logBase2();
574 Value *In = ICI->getOperand(0);
575 if (ShiftAmt) {
576 // Perform a logical shr by shiftamt.
577 // Insert the shift to put the result in the low bit.
578 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
579 In->getName()+".lobit");
580 }
Craig Topper3529aa52013-01-24 05:22:40 +0000581
Chris Lattner2b295a02010-01-04 07:53:58 +0000582 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
583 Constant *One = ConstantInt::get(In->getType(), 1);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000584 In = Builder->CreateXor(In, One);
Chris Lattner2b295a02010-01-04 07:53:58 +0000585 }
Craig Topper3529aa52013-01-24 05:22:40 +0000586
Chris Lattner2b295a02010-01-04 07:53:58 +0000587 if (CI.getType() == In->getType())
588 return ReplaceInstUsesWith(CI, In);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000589 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner2b295a02010-01-04 07:53:58 +0000590 }
591 }
592 }
593
594 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
595 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
596 // may lead to additional simplifications.
597 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000598 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000599 uint32_t BitWidth = ITy->getBitWidth();
600 Value *LHS = ICI->getOperand(0);
601 Value *RHS = ICI->getOperand(1);
602
603 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
604 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +0000605 computeKnownBits(LHS, KnownZeroLHS, KnownOneLHS, 0, &CI);
606 computeKnownBits(RHS, KnownZeroRHS, KnownOneRHS, 0, &CI);
Chris Lattner2b295a02010-01-04 07:53:58 +0000607
608 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
609 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
610 APInt UnknownBit = ~KnownBits;
611 if (UnknownBit.countPopulation() == 1) {
612 if (!DoXform) return ICI;
613
614 Value *Result = Builder->CreateXor(LHS, RHS);
615
616 // Mask off any bits that are set and won't be shifted away.
617 if (KnownOneLHS.uge(UnknownBit))
618 Result = Builder->CreateAnd(Result,
619 ConstantInt::get(ITy, UnknownBit));
620
621 // Shift the bit we're testing down to the lsb.
622 Result = Builder->CreateLShr(
623 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
624
625 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
626 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
627 Result->takeName(ICI);
628 return ReplaceInstUsesWith(CI, Result);
629 }
630 }
631 }
632 }
633
Craig Topperf40110f2014-04-25 05:29:35 +0000634 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000635}
636
Chris Lattnerc3aca382010-01-10 00:58:42 +0000637/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner172630a2010-01-11 02:43:35 +0000638/// specified wider type and produce the same low bits. If not, return false.
639///
Chris Lattner12bd8992010-01-11 03:32:00 +0000640/// If this function returns true, it can also return a non-zero number of bits
641/// (in BitsToClear) which indicates that the value it computes is correct for
642/// the zero extend, but that the additional BitsToClear bits need to be zero'd
643/// out. For example, to promote something like:
644///
645/// %B = trunc i64 %A to i32
646/// %C = lshr i32 %B, 8
647/// %E = zext i32 %C to i64
648///
649/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
650/// set to 8 to indicate that the promoted value needs to have bits 24-31
651/// cleared in addition to bits 32-63. Since an 'and' will be generated to
652/// clear the top bits anyway, doing this has no extra cost.
653///
Chris Lattner172630a2010-01-11 02:43:35 +0000654/// This function works on both vectors and scalars.
Hal Finkel60db0582014-09-07 18:57:58 +0000655static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
656 InstCombiner &IC, Instruction *CxtI) {
Chris Lattner12bd8992010-01-11 03:32:00 +0000657 BitsToClear = 0;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000658 if (isa<Constant>(V))
659 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000660
Chris Lattnerc3aca382010-01-10 00:58:42 +0000661 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000662 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000663
Chris Lattnerc3aca382010-01-10 00:58:42 +0000664 // If the input is a truncate from the destination type, we can trivially
Jakob Stoklund Olesenc5c4e962012-06-22 16:36:43 +0000665 // eliminate it.
666 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000667 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000668
Chris Lattnerc3aca382010-01-10 00:58:42 +0000669 // We can't extend or shrink something that has multiple uses: doing so would
670 // require duplicating the instruction in general, which isn't profitable.
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000671 if (!I->hasOneUse()) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000672
Chris Lattner12bd8992010-01-11 03:32:00 +0000673 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000674 switch (Opc) {
Chris Lattner39d2daa2010-01-10 20:25:54 +0000675 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
676 case Instruction::SExt: // zext(sext(x)) -> sext(x).
677 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
678 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000679 case Instruction::And:
Chris Lattnerc3aca382010-01-10 00:58:42 +0000680 case Instruction::Or:
681 case Instruction::Xor:
Chris Lattnerc3aca382010-01-10 00:58:42 +0000682 case Instruction::Add:
683 case Instruction::Sub:
684 case Instruction::Mul:
Hal Finkel60db0582014-09-07 18:57:58 +0000685 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
686 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
Chris Lattner12bd8992010-01-11 03:32:00 +0000687 return false;
688 // These can all be promoted if neither operand has 'bits to clear'.
689 if (BitsToClear == 0 && Tmp == 0)
690 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000691
Chris Lattner0a854202010-01-11 04:05:13 +0000692 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
693 // other side, BitsToClear is ok.
694 if (Tmp == 0 &&
695 (Opc == Instruction::And || Opc == Instruction::Or ||
696 Opc == Instruction::Xor)) {
697 // We use MaskedValueIsZero here for generality, but the case we care
698 // about the most is constant RHS.
699 unsigned VSize = V->getType()->getScalarSizeInBits();
Hal Finkel60db0582014-09-07 18:57:58 +0000700 if (IC.MaskedValueIsZero(I->getOperand(1),
701 APInt::getHighBitsSet(VSize, BitsToClear),
702 0, CxtI))
Chris Lattner0a854202010-01-11 04:05:13 +0000703 return true;
704 }
Craig Topper3529aa52013-01-24 05:22:40 +0000705
Chris Lattner0a854202010-01-11 04:05:13 +0000706 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner12bd8992010-01-11 03:32:00 +0000707 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000708
Benjamin Kramer14e915f2013-05-10 16:26:37 +0000709 case Instruction::Shl:
710 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the
711 // upper bits we can reduce BitsToClear by the shift amount.
712 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
Hal Finkel60db0582014-09-07 18:57:58 +0000713 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
Benjamin Kramer14e915f2013-05-10 16:26:37 +0000714 return false;
715 uint64_t ShiftAmt = Amt->getZExtValue();
716 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
717 return true;
718 }
719 return false;
Chris Lattner12bd8992010-01-11 03:32:00 +0000720 case Instruction::LShr:
721 // We can promote lshr(x, cst) if we can promote x. This requires the
722 // ultimate 'and' to clear out the high zero bits we're clearing out though.
723 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
Hal Finkel60db0582014-09-07 18:57:58 +0000724 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
Chris Lattner12bd8992010-01-11 03:32:00 +0000725 return false;
726 BitsToClear += Amt->getZExtValue();
727 if (BitsToClear > V->getType()->getScalarSizeInBits())
728 BitsToClear = V->getType()->getScalarSizeInBits();
729 return true;
730 }
731 // Cannot promote variable LSHR.
732 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000733 case Instruction::Select:
Hal Finkel60db0582014-09-07 18:57:58 +0000734 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
735 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
Chris Lattner0a854202010-01-11 04:05:13 +0000736 // TODO: If important, we could handle the case when the BitsToClear are
737 // known zero in the disagreeing side.
Chris Lattner12bd8992010-01-11 03:32:00 +0000738 Tmp != BitsToClear)
739 return false;
740 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000741
Chris Lattnerc3aca382010-01-10 00:58:42 +0000742 case Instruction::PHI: {
743 // We can change a phi if we can change all operands. Note that we never
744 // get into trouble with cyclic PHIs here because we only consider
745 // instructions with a single use.
746 PHINode *PN = cast<PHINode>(I);
Hal Finkel60db0582014-09-07 18:57:58 +0000747 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
Chris Lattner12bd8992010-01-11 03:32:00 +0000748 return false;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000749 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Hal Finkel60db0582014-09-07 18:57:58 +0000750 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
Chris Lattner0a854202010-01-11 04:05:13 +0000751 // TODO: If important, we could handle the case when the BitsToClear
752 // are known zero in the disagreeing input.
Chris Lattner12bd8992010-01-11 03:32:00 +0000753 Tmp != BitsToClear)
754 return false;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000755 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000756 }
757 default:
758 // TODO: Can handle more cases here.
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000759 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000760 }
761}
762
Chris Lattner2b295a02010-01-04 07:53:58 +0000763Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Nick Lewycky80ea0032013-01-14 20:56:10 +0000764 // If this zero extend is only used by a truncate, let the truncate be
Chris Lattner49d2c972010-01-10 02:39:31 +0000765 // eliminated before we try to optimize this zext.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000766 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Craig Topperf40110f2014-04-25 05:29:35 +0000767 return nullptr;
Craig Topper3529aa52013-01-24 05:22:40 +0000768
Chris Lattner2b295a02010-01-04 07:53:58 +0000769 // If one of the common conversion will work, do it.
Chris Lattner883550a2010-01-10 01:00:46 +0000770 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner2b295a02010-01-04 07:53:58 +0000771 return Result;
772
Craig Topper3529aa52013-01-24 05:22:40 +0000773 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +0000774 // purpose is to compute bits we don't care about.
775 if (SimplifyDemandedInstructionBits(CI))
776 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +0000777
Chris Lattner883550a2010-01-10 01:00:46 +0000778 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000779 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000780
Chris Lattnerc3aca382010-01-10 00:58:42 +0000781 // Attempt to extend the entire input expression tree to the destination
782 // type. Only do this if the dest type is a simple type, don't convert the
783 // expression tree to something weird like i93 unless the source is also
784 // strange.
Chris Lattner12bd8992010-01-11 03:32:00 +0000785 unsigned BitsToClear;
Duncan Sands19d0b472010-02-16 11:11:14 +0000786 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Hal Finkel60db0582014-09-07 18:57:58 +0000787 CanEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
Chris Lattner12bd8992010-01-11 03:32:00 +0000788 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
789 "Unreasonable BitsToClear");
Craig Topper3529aa52013-01-24 05:22:40 +0000790
Chris Lattner49d2c972010-01-10 02:39:31 +0000791 // Okay, we can transform this! Insert the new expression now.
792 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
793 " to avoid zero extend: " << CI);
794 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
795 assert(Res->getType() == DestTy);
Craig Topper3529aa52013-01-24 05:22:40 +0000796
Chris Lattner12bd8992010-01-11 03:32:00 +0000797 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
798 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +0000799
Chris Lattner49d2c972010-01-10 02:39:31 +0000800 // If the high bits are already filled with zeros, just replace this
801 // cast with the result.
Hal Finkel60db0582014-09-07 18:57:58 +0000802 if (MaskedValueIsZero(Res,
803 APInt::getHighBitsSet(DestBitSize,
804 DestBitSize-SrcBitsKept),
805 0, &CI))
Chris Lattner49d2c972010-01-10 02:39:31 +0000806 return ReplaceInstUsesWith(CI, Res);
Craig Topper3529aa52013-01-24 05:22:40 +0000807
Chris Lattner49d2c972010-01-10 02:39:31 +0000808 // We need to emit an AND to clear the high bits.
Chris Lattner39d2daa2010-01-10 20:25:54 +0000809 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner12bd8992010-01-11 03:32:00 +0000810 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner49d2c972010-01-10 02:39:31 +0000811 return BinaryOperator::CreateAnd(Res, C);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000812 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000813
814 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
815 // types and if the sizes are just right we can convert this into a logical
816 // 'and' which will be much cheaper than the pair of casts.
817 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerd8509422010-01-10 07:08:30 +0000818 // TODO: Subsume this into EvaluateInDifferentType.
Craig Topper3529aa52013-01-24 05:22:40 +0000819
Chris Lattner2b295a02010-01-04 07:53:58 +0000820 // Get the sizes of the types involved. We know that the intermediate type
821 // will be smaller than A or C, but don't know the relation between A and C.
822 Value *A = CSrc->getOperand(0);
823 unsigned SrcSize = A->getType()->getScalarSizeInBits();
824 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
825 unsigned DstSize = CI.getType()->getScalarSizeInBits();
826 // If we're actually extending zero bits, then if
827 // SrcSize < DstSize: zext(a & mask)
828 // SrcSize == DstSize: a & mask
829 // SrcSize > DstSize: trunc(a) & mask
830 if (SrcSize < DstSize) {
831 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
832 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
833 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
834 return new ZExtInst(And, CI.getType());
835 }
Craig Topper3529aa52013-01-24 05:22:40 +0000836
Chris Lattner2b295a02010-01-04 07:53:58 +0000837 if (SrcSize == DstSize) {
838 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
839 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
840 AndValue));
841 }
842 if (SrcSize > DstSize) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000843 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
Chris Lattner2b295a02010-01-04 07:53:58 +0000844 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Craig Topper3529aa52013-01-24 05:22:40 +0000845 return BinaryOperator::CreateAnd(Trunc,
Chris Lattner2b295a02010-01-04 07:53:58 +0000846 ConstantInt::get(Trunc->getType(),
Chris Lattnerd8509422010-01-10 07:08:30 +0000847 AndValue));
Chris Lattner2b295a02010-01-04 07:53:58 +0000848 }
849 }
850
851 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
852 return transformZExtICmp(ICI, CI);
853
854 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
855 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
856 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
857 // of the (zext icmp) will be transformed.
858 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
859 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
860 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
861 (transformZExtICmp(LHS, CI, false) ||
862 transformZExtICmp(RHS, CI, false))) {
863 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
864 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
865 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
866 }
867 }
868
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000869 // zext(trunc(X) & C) -> (X & zext(C)).
870 Constant *C;
871 Value *X;
872 if (SrcI &&
873 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
874 X->getType() == CI.getType())
875 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
Chris Lattner2b295a02010-01-04 07:53:58 +0000876
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000877 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
878 Value *And;
879 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
880 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
881 X->getType() == CI.getType()) {
882 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
883 return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
884 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000885
Chris Lattnerfd7e42b2010-01-05 21:04:47 +0000886 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000887 if (SrcI && SrcI->hasOneUse() &&
888 SrcI->getType()->getScalarType()->isIntegerTy(1) &&
889 match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) {
Chris Lattnerfd7e42b2010-01-05 21:04:47 +0000890 Value *New = Builder->CreateZExt(X, CI.getType());
891 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
892 }
Craig Topper3529aa52013-01-24 05:22:40 +0000893
Craig Topperf40110f2014-04-25 05:29:35 +0000894 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000895}
896
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000897/// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
898/// in order to eliminate the icmp.
899Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
900 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
901 ICmpInst::Predicate Pred = ICI->getPredicate();
902
David Majnemerc8bdd232014-10-27 05:47:49 +0000903 // Don't bother if Op1 isn't of vector or integer type.
904 if (!Op1->getType()->isIntOrIntVectorTy())
905 return nullptr;
906
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000907 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Benjamin Kramer8b94c292011-04-01 22:29:18 +0000908 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
909 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000910 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000911 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
912
913 Value *Sh = ConstantInt::get(Op0->getType(),
914 Op0->getType()->getScalarSizeInBits()-1);
915 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
916 if (In->getType() != CI.getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000917 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000918
919 if (Pred == ICmpInst::ICMP_SGT)
920 In = Builder->CreateNot(In, In->getName()+".not");
921 return ReplaceInstUsesWith(CI, In);
922 }
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000923 }
Benjamin Kramerd1217652011-04-01 20:09:10 +0000924
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000925 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramerd1217652011-04-01 20:09:10 +0000926 // If we know that only one bit of the LHS of the icmp can be set and we
927 // have an equality comparison with zero or a power of 2, we can transform
928 // the icmp and sext into bitwise/integer operations.
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000929 if (ICI->hasOneUse() &&
930 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
Benjamin Kramerd1217652011-04-01 20:09:10 +0000931 unsigned BitWidth = Op1C->getType()->getBitWidth();
932 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +0000933 computeKnownBits(Op0, KnownZero, KnownOne, 0, &CI);
Benjamin Kramerd1217652011-04-01 20:09:10 +0000934
Benjamin Kramerac2d5652011-04-01 20:15:16 +0000935 APInt KnownZeroMask(~KnownZero);
936 if (KnownZeroMask.isPowerOf2()) {
Benjamin Kramerd1217652011-04-01 20:09:10 +0000937 Value *In = ICI->getOperand(0);
938
Benjamin Kramer50a281a2011-04-02 18:50:58 +0000939 // If the icmp tests for a known zero bit we can constant fold it.
940 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
941 Value *V = Pred == ICmpInst::ICMP_NE ?
942 ConstantInt::getAllOnesValue(CI.getType()) :
943 ConstantInt::getNullValue(CI.getType());
944 return ReplaceInstUsesWith(CI, V);
945 }
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000946
Benjamin Kramerd1217652011-04-01 20:09:10 +0000947 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
948 // sext ((x & 2^n) == 0) -> (x >> n) - 1
949 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
950 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
951 // Perform a right shift to place the desired bit in the LSB.
952 if (ShiftAmt)
953 In = Builder->CreateLShr(In,
954 ConstantInt::get(In->getType(), ShiftAmt));
955
956 // At this point "In" is either 1 or 0. Subtract 1 to turn
957 // {1, 0} -> {0, -1}.
958 In = Builder->CreateAdd(In,
959 ConstantInt::getAllOnesValue(In->getType()),
960 "sext");
961 } else {
962 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000963 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramerd1217652011-04-01 20:09:10 +0000964 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
965 // Perform a left shift to place the desired bit in the MSB.
966 if (ShiftAmt)
967 In = Builder->CreateShl(In,
968 ConstantInt::get(In->getType(), ShiftAmt));
969
970 // Distribute the bit over the whole bit width.
971 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
972 BitWidth - 1), "sext");
973 }
974
975 if (CI.getType() == In->getType())
976 return ReplaceInstUsesWith(CI, In);
977 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
978 }
979 }
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000980 }
981
Craig Topperf40110f2014-04-25 05:29:35 +0000982 return nullptr;
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000983}
984
Chris Lattnerc3aca382010-01-10 00:58:42 +0000985/// CanEvaluateSExtd - Return true if we can take the specified value
986/// and return it as type Ty without inserting any new casts and without
987/// changing the value of the common low bits. This is used by code that tries
988/// to promote integer operations to a wider types will allow us to eliminate
989/// the extension.
990///
Chris Lattner1a05fdd2010-01-10 07:57:20 +0000991/// This function works on both vectors and scalars.
Chris Lattnerc3aca382010-01-10 00:58:42 +0000992///
Chris Lattner229907c2011-07-18 04:54:35 +0000993static bool CanEvaluateSExtd(Value *V, Type *Ty) {
Chris Lattnerc3aca382010-01-10 00:58:42 +0000994 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
995 "Can't sign extend type to a smaller type");
Chris Lattner1a05fdd2010-01-10 07:57:20 +0000996 // If this is a constant, it can be trivially promoted.
997 if (isa<Constant>(V))
998 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000999
Chris Lattnerc3aca382010-01-10 00:58:42 +00001000 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001001 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001002
Jakob Stoklund Olesenc5c4e962012-06-22 16:36:43 +00001003 // If this is a truncate from the dest type, we can trivially eliminate it.
1004 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001005 return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001006
Chris Lattnerc3aca382010-01-10 00:58:42 +00001007 // We can't extend or shrink something that has multiple uses: doing so would
1008 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001009 if (!I->hasOneUse()) return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001010
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001011 switch (I->getOpcode()) {
Chris Lattner7dd540e2010-01-10 20:30:41 +00001012 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1013 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1014 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1015 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001016 case Instruction::And:
1017 case Instruction::Or:
1018 case Instruction::Xor:
Chris Lattnerc3aca382010-01-10 00:58:42 +00001019 case Instruction::Add:
1020 case Instruction::Sub:
Chris Lattnerc3aca382010-01-10 00:58:42 +00001021 case Instruction::Mul:
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001022 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner172630a2010-01-11 02:43:35 +00001023 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1024 CanEvaluateSExtd(I->getOperand(1), Ty);
Craig Topper3529aa52013-01-24 05:22:40 +00001025
Chris Lattnerc3aca382010-01-10 00:58:42 +00001026 //case Instruction::Shl: TODO
1027 //case Instruction::LShr: TODO
Craig Topper3529aa52013-01-24 05:22:40 +00001028
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001029 case Instruction::Select:
Chris Lattner172630a2010-01-11 02:43:35 +00001030 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1031 CanEvaluateSExtd(I->getOperand(2), Ty);
Craig Topper3529aa52013-01-24 05:22:40 +00001032
Chris Lattnerc3aca382010-01-10 00:58:42 +00001033 case Instruction::PHI: {
1034 // We can change a phi if we can change all operands. Note that we never
1035 // get into trouble with cyclic PHIs here because we only consider
1036 // instructions with a single use.
1037 PHINode *PN = cast<PHINode>(I);
Chris Lattner39d2daa2010-01-10 20:25:54 +00001038 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner172630a2010-01-11 02:43:35 +00001039 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001040 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001041 }
1042 default:
1043 // TODO: Can handle more cases here.
1044 break;
1045 }
Craig Topper3529aa52013-01-24 05:22:40 +00001046
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001047 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001048}
1049
Chris Lattner2b295a02010-01-04 07:53:58 +00001050Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Arnaud A. de Grandmaison2e4df4f2013-02-13 00:19:19 +00001051 // If this sign extend is only used by a truncate, let the truncate be
1052 // eliminated before we try to optimize this sext.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001053 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Craig Topperf40110f2014-04-25 05:29:35 +00001054 return nullptr;
Craig Topper3529aa52013-01-24 05:22:40 +00001055
Chris Lattner883550a2010-01-10 01:00:46 +00001056 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner2b295a02010-01-04 07:53:58 +00001057 return I;
Craig Topper3529aa52013-01-24 05:22:40 +00001058
1059 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +00001060 // purpose is to compute bits we don't care about.
1061 if (SimplifyDemandedInstructionBits(CI))
1062 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +00001063
Chris Lattner2b295a02010-01-04 07:53:58 +00001064 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001065 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattnerc3aca382010-01-10 00:58:42 +00001066
Philip Reames9ae15202015-02-14 00:05:36 +00001067 // If we know that the value being extended is positive, we can use a zext
1068 // instead.
1069 bool KnownZero, KnownOne;
1070 ComputeSignBit(Src, KnownZero, KnownOne, 0, &CI);
1071 if (KnownZero) {
1072 Value *ZExt = Builder->CreateZExt(Src, DestTy);
1073 return ReplaceInstUsesWith(CI, ZExt);
1074 }
1075
Chris Lattnerc3aca382010-01-10 00:58:42 +00001076 // Attempt to extend the entire input expression tree to the destination
1077 // type. Only do this if the dest type is a simple type, don't convert the
1078 // expression tree to something weird like i93 unless the source is also
1079 // strange.
Duncan Sands19d0b472010-02-16 11:11:14 +00001080 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner172630a2010-01-11 02:43:35 +00001081 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattner2fff10c2010-01-10 07:40:50 +00001082 // Okay, we can transform this! Insert the new expression now.
1083 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1084 " to avoid sign extend: " << CI);
1085 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1086 assert(Res->getType() == DestTy);
1087
Chris Lattnerc3aca382010-01-10 00:58:42 +00001088 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1089 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattner2fff10c2010-01-10 07:40:50 +00001090
1091 // If the high bits are already filled with sign bit, just replace this
1092 // cast with the result.
Hal Finkel60db0582014-09-07 18:57:58 +00001093 if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
Chris Lattner2fff10c2010-01-10 07:40:50 +00001094 return ReplaceInstUsesWith(CI, Res);
Craig Topper3529aa52013-01-24 05:22:40 +00001095
Chris Lattner2fff10c2010-01-10 07:40:50 +00001096 // We need to emit a shl + ashr to do the sign extend.
1097 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1098 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1099 ShAmt);
Chris Lattnerc3aca382010-01-10 00:58:42 +00001100 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001101
Chris Lattner43f2fa62010-01-18 22:19:16 +00001102 // If this input is a trunc from our destination, then turn sext(trunc(x))
1103 // into shifts.
1104 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1105 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1106 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1107 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +00001108
Chris Lattner43f2fa62010-01-18 22:19:16 +00001109 // We need to emit a shl + ashr to do the sign extend.
1110 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1111 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1112 return BinaryOperator::CreateAShr(Res, ShAmt);
1113 }
Nate Begeman7aa18bf2010-12-17 23:12:19 +00001114
Benjamin Kramer398b8c52011-04-01 20:09:03 +00001115 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1116 return transformSExtICmp(ICI, CI);
Bill Wendling5e360552010-12-17 23:27:41 +00001117
Chris Lattner2b295a02010-01-04 07:53:58 +00001118 // If the input is a shl/ashr pair of a same constant, then this is a sign
1119 // extension from a smaller value. If we could trust arbitrary bitwidth
1120 // integers, we could turn this into a truncate to the smaller bit and then
1121 // use a sext for the whole extension. Since we don't, look deeper and check
1122 // for a truncate. If the source and dest are the same type, eliminate the
1123 // trunc and extend and just do shifts. For example, turn:
1124 // %a = trunc i32 %i to i8
1125 // %b = shl i8 %a, 6
1126 // %c = ashr i8 %b, 6
1127 // %d = sext i8 %c to i32
1128 // into:
1129 // %a = shl i32 %i, 30
1130 // %d = ashr i32 %a, 30
Craig Topperf40110f2014-04-25 05:29:35 +00001131 Value *A = nullptr;
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001132 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Craig Topperf40110f2014-04-25 05:29:35 +00001133 ConstantInt *BA = nullptr, *CA = nullptr;
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001134 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner2b295a02010-01-04 07:53:58 +00001135 m_ConstantInt(CA))) &&
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001136 BA == CA && A->getType() == CI.getType()) {
1137 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1138 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1139 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1140 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1141 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1142 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner2b295a02010-01-04 07:53:58 +00001143 }
Craig Topper3529aa52013-01-24 05:22:40 +00001144
Craig Topperf40110f2014-04-25 05:29:35 +00001145 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001146}
1147
1148
1149/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1150/// in the specified FP type without changing its value.
1151static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1152 bool losesInfo;
1153 APFloat F = CFP->getValueAPF();
1154 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1155 if (!losesInfo)
1156 return ConstantFP::get(CFP->getContext(), F);
Craig Topperf40110f2014-04-25 05:29:35 +00001157 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001158}
1159
1160/// LookThroughFPExtensions - If this is an fp extension instruction, look
1161/// through it until we get the source value.
1162static Value *LookThroughFPExtensions(Value *V) {
1163 if (Instruction *I = dyn_cast<Instruction>(V))
1164 if (I->getOpcode() == Instruction::FPExt)
1165 return LookThroughFPExtensions(I->getOperand(0));
Craig Topper3529aa52013-01-24 05:22:40 +00001166
Chris Lattner2b295a02010-01-04 07:53:58 +00001167 // If this value is a constant, return the constant in the smallest FP type
1168 // that can accurately represent it. This allows us to turn
1169 // (float)((double)X+2.0) into x+2.0f.
1170 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1171 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1172 return V; // No constant folding of this.
Dan Gohman518cda42011-12-17 00:04:22 +00001173 // See if the value can be truncated to half and then reextended.
1174 if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
1175 return V;
Chris Lattner2b295a02010-01-04 07:53:58 +00001176 // See if the value can be truncated to float and then reextended.
1177 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1178 return V;
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001179 if (CFP->getType()->isDoubleTy())
Chris Lattner2b295a02010-01-04 07:53:58 +00001180 return V; // Won't shrink.
1181 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1182 return V;
1183 // Don't try to shrink to various long double types.
1184 }
Craig Topper3529aa52013-01-24 05:22:40 +00001185
Chris Lattner2b295a02010-01-04 07:53:58 +00001186 return V;
1187}
1188
1189Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1190 if (Instruction *I = commonCastTransforms(CI))
1191 return I;
Stephen Canonc4549642013-11-28 21:38:05 +00001192 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1193 // simpilify this expression to avoid one or more of the trunc/extend
1194 // operations if we can do so without changing the numerical results.
1195 //
1196 // The exact manner in which the widths of the operands interact to limit
1197 // what we can and cannot do safely varies from operation to operation, and
1198 // is explained below in the various case statements.
Chris Lattner2b295a02010-01-04 07:53:58 +00001199 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1200 if (OpI && OpI->hasOneUse()) {
Stephen Canonc4549642013-11-28 21:38:05 +00001201 Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0));
1202 Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1));
1203 unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1204 unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
1205 unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
1206 unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1207 unsigned DstWidth = CI.getType()->getFPMantissaWidth();
Chris Lattner2b295a02010-01-04 07:53:58 +00001208 switch (OpI->getOpcode()) {
Stephen Canonc4549642013-11-28 21:38:05 +00001209 default: break;
1210 case Instruction::FAdd:
1211 case Instruction::FSub:
1212 // For addition and subtraction, the infinitely precise result can
1213 // essentially be arbitrarily wide; proving that double rounding
1214 // will not occur because the result of OpI is exact (as we will for
1215 // FMul, for example) is hopeless. However, we *can* nonetheless
1216 // frequently know that double rounding cannot occur (or that it is
Alp Tokercb402912014-01-24 17:20:08 +00001217 // innocuous) by taking advantage of the specific structure of
Stephen Canonc4549642013-11-28 21:38:05 +00001218 // infinitely-precise results that admit double rounding.
1219 //
Alp Tokercb402912014-01-24 17:20:08 +00001220 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
Stephen Canonc4549642013-11-28 21:38:05 +00001221 // to represent both sources, we can guarantee that the double
1222 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1223 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1224 // for proof of this fact).
1225 //
1226 // Note: Figueroa does not consider the case where DstFormat !=
1227 // SrcFormat. It's possible (likely even!) that this analysis
1228 // could be tightened for those cases, but they are rare (the main
1229 // case of interest here is (float)((double)float + float)).
1230 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1231 if (LHSOrig->getType() != CI.getType())
1232 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1233 if (RHSOrig->getType() != CI.getType())
1234 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001235 Instruction *RI =
1236 BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
1237 RI->copyFastMathFlags(OpI);
1238 return RI;
Chris Lattner2b295a02010-01-04 07:53:58 +00001239 }
Stephen Canonc4549642013-11-28 21:38:05 +00001240 break;
1241 case Instruction::FMul:
1242 // For multiplication, the infinitely precise result has at most
1243 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1244 // that such a value can be exactly represented, then no double
1245 // rounding can possibly occur; we can safely perform the operation
1246 // in the destination format if it can represent both sources.
1247 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1248 if (LHSOrig->getType() != CI.getType())
1249 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1250 if (RHSOrig->getType() != CI.getType())
1251 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001252 Instruction *RI =
1253 BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
1254 RI->copyFastMathFlags(OpI);
1255 return RI;
Stephen Canonc4549642013-11-28 21:38:05 +00001256 }
1257 break;
1258 case Instruction::FDiv:
1259 // For division, we use again use the bound from Figueroa's
1260 // dissertation. I am entirely certain that this bound can be
1261 // tightened in the unbalanced operand case by an analysis based on
1262 // the diophantine rational approximation bound, but the well-known
1263 // condition used here is a good conservative first pass.
1264 // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1265 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1266 if (LHSOrig->getType() != CI.getType())
1267 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1268 if (RHSOrig->getType() != CI.getType())
1269 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001270 Instruction *RI =
1271 BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
1272 RI->copyFastMathFlags(OpI);
1273 return RI;
Stephen Canonc4549642013-11-28 21:38:05 +00001274 }
1275 break;
1276 case Instruction::FRem:
1277 // Remainder is straightforward. Remainder is always exact, so the
1278 // type of OpI doesn't enter into things at all. We simply evaluate
1279 // in whichever source type is larger, then convert to the
1280 // destination type.
Steven Wuf179d122014-12-12 18:48:37 +00001281 if (SrcWidth == OpWidth)
Steven Wu1f7402a2014-12-12 17:21:54 +00001282 break;
Steven Wu1f7402a2014-12-12 17:21:54 +00001283 if (LHSWidth < SrcWidth)
1284 LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
1285 else if (RHSWidth <= SrcWidth)
1286 RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
1287 if (LHSOrig != OpI->getOperand(0) || RHSOrig != OpI->getOperand(1)) {
1288 Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
1289 if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
1290 RI->copyFastMathFlags(OpI);
1291 return CastInst::CreateFPCast(ExactResult, CI.getType());
1292 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001293 }
Owen Andersondbf0ca52013-01-10 22:06:52 +00001294
1295 // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1296 if (BinaryOperator::isFNeg(OpI)) {
1297 Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
1298 CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001299 Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
1300 RI->copyFastMathFlags(OpI);
1301 return RI;
Owen Andersondbf0ca52013-01-10 22:06:52 +00001302 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001303 }
Owen Andersondbf0ca52013-01-10 22:06:52 +00001304
Owen Anderson5797bfd2013-10-03 21:08:05 +00001305 // (fptrunc (select cond, R1, Cst)) -->
1306 // (select cond, (fptrunc R1), (fptrunc Cst))
1307 SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
1308 if (SI &&
1309 (isa<ConstantFP>(SI->getOperand(1)) ||
1310 isa<ConstantFP>(SI->getOperand(2)))) {
1311 Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
1312 CI.getType());
1313 Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
1314 CI.getType());
1315 return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
1316 }
1317
Owen Andersondbf0ca52013-01-10 22:06:52 +00001318 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
1319 if (II) {
1320 switch (II->getIntrinsicID()) {
1321 default: break;
1322 case Intrinsic::fabs: {
1323 // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1324 Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
1325 CI.getType());
1326 Type *IntrinsicType[] = { CI.getType() };
1327 Function *Overload =
1328 Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
1329 II->getIntrinsicID(), IntrinsicType);
1330
1331 Value *Args[] = { InnerTrunc };
1332 return CallInst::Create(Overload, Args, II->getName());
1333 }
1334 }
1335 }
1336
Craig Topperf40110f2014-04-25 05:29:35 +00001337 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001338}
1339
1340Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1341 return commonCastTransforms(CI);
1342}
1343
1344Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1345 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001346 if (!OpI)
Chris Lattner2b295a02010-01-04 07:53:58 +00001347 return commonCastTransforms(FI);
1348
1349 // fptoui(uitofp(X)) --> X
1350 // fptoui(sitofp(X)) --> X
1351 // This is safe if the intermediate type has enough bits in its mantissa to
1352 // accurately represent all values of X. For example, do not do this with
1353 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topper3529aa52013-01-24 05:22:40 +00001354 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner2b295a02010-01-04 07:53:58 +00001355 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1356 OpI->getOperand(0)->getType() == FI.getType() &&
1357 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1358 OpI->getType()->getFPMantissaWidth())
1359 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1360
1361 return commonCastTransforms(FI);
1362}
1363
1364Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1365 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001366 if (!OpI)
Chris Lattner2b295a02010-01-04 07:53:58 +00001367 return commonCastTransforms(FI);
Craig Topper3529aa52013-01-24 05:22:40 +00001368
Chris Lattner2b295a02010-01-04 07:53:58 +00001369 // fptosi(sitofp(X)) --> X
1370 // fptosi(uitofp(X)) --> X
1371 // This is safe if the intermediate type has enough bits in its mantissa to
1372 // accurately represent all values of X. For example, do not do this with
1373 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topper3529aa52013-01-24 05:22:40 +00001374 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner2b295a02010-01-04 07:53:58 +00001375 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1376 OpI->getOperand(0)->getType() == FI.getType() &&
1377 (int)FI.getType()->getScalarSizeInBits() <=
1378 OpI->getType()->getFPMantissaWidth())
1379 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Craig Topper3529aa52013-01-24 05:22:40 +00001380
Chris Lattner2b295a02010-01-04 07:53:58 +00001381 return commonCastTransforms(FI);
1382}
1383
1384Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1385 return commonCastTransforms(CI);
1386}
1387
1388Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1389 return commonCastTransforms(CI);
1390}
1391
Chris Lattner2b295a02010-01-04 07:53:58 +00001392Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman949458d2010-02-02 01:44:02 +00001393 // If the source integer type is not the intptr_t type for this target, do a
1394 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1395 // cast to be exposed to other transforms.
Benjamin Kramer944e0ab2013-02-05 20:22:40 +00001396
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001397 if (DL) {
Matt Arsenault745101d2013-08-21 19:53:10 +00001398 unsigned AS = CI.getAddressSpace();
1399 if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001400 DL->getPointerSizeInBits(AS)) {
1401 Type *Ty = DL->getIntPtrType(CI.getContext(), AS);
Matt Arsenault745101d2013-08-21 19:53:10 +00001402 if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1403 Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
1404
1405 Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
1406 return new IntToPtrInst(P, CI.getType());
1407 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001408 }
Craig Topper3529aa52013-01-24 05:22:40 +00001409
Chris Lattner2b295a02010-01-04 07:53:58 +00001410 if (Instruction *I = commonCastTransforms(CI))
1411 return I;
1412
Craig Topperf40110f2014-04-25 05:29:35 +00001413 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001414}
1415
Chris Lattnera93c63c2010-01-05 22:21:18 +00001416/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1417Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1418 Value *Src = CI.getOperand(0);
Craig Topper3529aa52013-01-24 05:22:40 +00001419
Chris Lattnera93c63c2010-01-05 22:21:18 +00001420 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1421 // If casting the result of a getelementptr instruction with no offset, turn
1422 // this into a cast of the original pointer!
Jingyue Wu77145d92014-06-06 21:52:55 +00001423 if (GEP->hasAllZeroIndices() &&
1424 // If CI is an addrspacecast and GEP changes the poiner type, merging
1425 // GEP into CI would undo canonicalizing addrspacecast with different
1426 // pointer types, causing infinite loops.
1427 (!isa<AddrSpaceCastInst>(CI) ||
1428 GEP->getType() == GEP->getPointerOperand()->getType())) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001429 // Changing the cast operand is usually not a good idea but it is safe
Craig Topper3529aa52013-01-24 05:22:40 +00001430 // here because the pointer operand is being replaced with another
Chris Lattnera93c63c2010-01-05 22:21:18 +00001431 // pointer operand so the opcode doesn't need to change.
1432 Worklist.Add(GEP);
1433 CI.setOperand(0, GEP->getOperand(0));
1434 return &CI;
1435 }
Craig Topper3529aa52013-01-24 05:22:40 +00001436
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001437 if (!DL)
Matt Arsenault94a028a2013-08-19 22:17:18 +00001438 return commonCastTransforms(CI);
1439
Chris Lattnera93c63c2010-01-05 22:21:18 +00001440 // If the GEP has a single use, and the base pointer is a bitcast, and the
1441 // GEP computes a constant offset, see if we can convert these three
1442 // instructions into fewer. This typically happens with unions and other
1443 // non-type-safe code.
Matt Arsenault745101d2013-08-21 19:53:10 +00001444 unsigned AS = GEP->getPointerAddressSpace();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001445 unsigned OffsetBits = DL->getPointerSizeInBits(AS);
Matt Arsenault94a028a2013-08-19 22:17:18 +00001446 APInt Offset(OffsetBits, 0);
1447 BitCastInst *BCI = dyn_cast<BitCastInst>(GEP->getOperand(0));
1448 if (GEP->hasOneUse() &&
1449 BCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001450 GEP->accumulateConstantOffset(*DL, Offset)) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001451 // Get the base pointer input of the bitcast, and the type it points to.
Matt Arsenault94a028a2013-08-19 22:17:18 +00001452 Value *OrigBase = BCI->getOperand(0);
Chris Lattnera93c63c2010-01-05 22:21:18 +00001453 SmallVector<Value*, 8> NewIndices;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +00001454 if (FindElementAtOffset(OrigBase->getType(),
1455 Offset.getSExtValue(),
1456 NewIndices)) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001457 // If we were able to index down into an element, create the GEP
1458 // and bitcast the result. This eliminates one bitcast, potentially
1459 // two.
1460 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
Matt Arsenault94a028a2013-08-19 22:17:18 +00001461 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1462 Builder->CreateGEP(OrigBase, NewIndices);
Chris Lattnera93c63c2010-01-05 22:21:18 +00001463 NGEP->takeName(GEP);
Craig Topper3529aa52013-01-24 05:22:40 +00001464
Chris Lattnera93c63c2010-01-05 22:21:18 +00001465 if (isa<BitCastInst>(CI))
1466 return new BitCastInst(NGEP, CI.getType());
1467 assert(isa<PtrToIntInst>(CI));
1468 return new PtrToIntInst(NGEP, CI.getType());
Craig Topper3529aa52013-01-24 05:22:40 +00001469 }
Chris Lattnera93c63c2010-01-05 22:21:18 +00001470 }
1471 }
Craig Topper3529aa52013-01-24 05:22:40 +00001472
Chris Lattnera93c63c2010-01-05 22:21:18 +00001473 return commonCastTransforms(CI);
1474}
1475
1476Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman949458d2010-02-02 01:44:02 +00001477 // If the destination integer type is not the intptr_t type for this target,
1478 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1479 // to be exposed to other transforms.
Benjamin Kramere4778752013-02-05 19:21:56 +00001480
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001481 if (!DL)
Matt Arsenault745101d2013-08-21 19:53:10 +00001482 return commonPointerCastTransforms(CI);
Craig Topper3529aa52013-01-24 05:22:40 +00001483
Matt Arsenault745101d2013-08-21 19:53:10 +00001484 Type *Ty = CI.getType();
1485 unsigned AS = CI.getPointerAddressSpace();
1486
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001487 if (Ty->getScalarSizeInBits() == DL->getPointerSizeInBits(AS))
Matt Arsenault745101d2013-08-21 19:53:10 +00001488 return commonPointerCastTransforms(CI);
1489
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001490 Type *PtrTy = DL->getIntPtrType(CI.getContext(), AS);
Matt Arsenault745101d2013-08-21 19:53:10 +00001491 if (Ty->isVectorTy()) // Handle vectors of pointers.
1492 PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1493
1494 Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
1495 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
Chris Lattnera93c63c2010-01-05 22:21:18 +00001496}
1497
Chris Lattner02b0df52010-05-08 21:50:26 +00001498/// OptimizeVectorResize - This input value (which is known to have vector type)
1499/// is being zero extended or truncated to the specified vector type. Try to
1500/// replace it with a shuffle (and vector/vector bitcast) if possible.
1501///
1502/// The source and destination vector types may have different element types.
Chris Lattner229907c2011-07-18 04:54:35 +00001503static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
Chris Lattner02b0df52010-05-08 21:50:26 +00001504 InstCombiner &IC) {
1505 // We can only do this optimization if the output is a multiple of the input
1506 // element size, or the input is a multiple of the output element size.
1507 // Convert the input type to have the same element type as the output.
Chris Lattner229907c2011-07-18 04:54:35 +00001508 VectorType *SrcTy = cast<VectorType>(InVal->getType());
Craig Topper3529aa52013-01-24 05:22:40 +00001509
Chris Lattner02b0df52010-05-08 21:50:26 +00001510 if (SrcTy->getElementType() != DestTy->getElementType()) {
1511 // The input types don't need to be identical, but for now they must be the
1512 // same size. There is no specific reason we couldn't handle things like
1513 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
Craig Topper3529aa52013-01-24 05:22:40 +00001514 // there yet.
Chris Lattner02b0df52010-05-08 21:50:26 +00001515 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1516 DestTy->getElementType()->getPrimitiveSizeInBits())
Craig Topperf40110f2014-04-25 05:29:35 +00001517 return nullptr;
Craig Topper3529aa52013-01-24 05:22:40 +00001518
Chris Lattner02b0df52010-05-08 21:50:26 +00001519 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1520 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1521 }
Craig Topper3529aa52013-01-24 05:22:40 +00001522
Chris Lattner02b0df52010-05-08 21:50:26 +00001523 // Now that the element types match, get the shuffle mask and RHS of the
1524 // shuffle to use, which depends on whether we're increasing or decreasing the
1525 // size of the input.
Chris Lattner8213c8a2012-02-06 21:56:39 +00001526 SmallVector<uint32_t, 16> ShuffleMask;
Chris Lattner02b0df52010-05-08 21:50:26 +00001527 Value *V2;
Craig Topper3529aa52013-01-24 05:22:40 +00001528
Chris Lattner02b0df52010-05-08 21:50:26 +00001529 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1530 // If we're shrinking the number of elements, just shuffle in the low
1531 // elements from the input and use undef as the second shuffle input.
1532 V2 = UndefValue::get(SrcTy);
1533 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
Chris Lattner8213c8a2012-02-06 21:56:39 +00001534 ShuffleMask.push_back(i);
Craig Topper3529aa52013-01-24 05:22:40 +00001535
Chris Lattner02b0df52010-05-08 21:50:26 +00001536 } else {
1537 // If we're increasing the number of elements, shuffle in all of the
1538 // elements from InVal and fill the rest of the result elements with zeros
1539 // from a constant zero.
1540 V2 = Constant::getNullValue(SrcTy);
1541 unsigned SrcElts = SrcTy->getNumElements();
1542 for (unsigned i = 0, e = SrcElts; i != e; ++i)
Chris Lattner8213c8a2012-02-06 21:56:39 +00001543 ShuffleMask.push_back(i);
Chris Lattner02b0df52010-05-08 21:50:26 +00001544
1545 // The excess elements reference the first element of the zero input.
Chris Lattner8213c8a2012-02-06 21:56:39 +00001546 for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1547 ShuffleMask.push_back(SrcElts);
Chris Lattner02b0df52010-05-08 21:50:26 +00001548 }
Craig Topper3529aa52013-01-24 05:22:40 +00001549
Chris Lattner8213c8a2012-02-06 21:56:39 +00001550 return new ShuffleVectorInst(InVal, V2,
1551 ConstantDataVector::get(V2->getContext(),
1552 ShuffleMask));
Chris Lattner02b0df52010-05-08 21:50:26 +00001553}
1554
Chris Lattner229907c2011-07-18 04:54:35 +00001555static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001556 return Value % Ty->getPrimitiveSizeInBits() == 0;
1557}
1558
Chris Lattner229907c2011-07-18 04:54:35 +00001559static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001560 return Value / Ty->getPrimitiveSizeInBits();
1561}
1562
1563/// CollectInsertionElements - V is a value which is inserted into a vector of
1564/// VecEltTy. Look through the value to see if we can decompose it into
1565/// insertions into the vector. See the example in the comment for
1566/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1567/// The type of V is always a non-zero multiple of VecEltTy's size.
Richard Sandifordfeb34712013-08-12 07:26:09 +00001568/// Shift is the number of bits between the lsb of V and the lsb of
1569/// the vector.
Chris Lattnerdd660102010-08-28 01:20:38 +00001570///
1571/// This returns false if the pattern can't be matched or true if it can,
1572/// filling in Elements with the elements found here.
Richard Sandifordfeb34712013-08-12 07:26:09 +00001573static bool CollectInsertionElements(Value *V, unsigned Shift,
Chris Lattnerdd660102010-08-28 01:20:38 +00001574 SmallVectorImpl<Value*> &Elements,
Richard Sandifordfeb34712013-08-12 07:26:09 +00001575 Type *VecEltTy, InstCombiner &IC) {
1576 assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1577 "Shift should be a multiple of the element type size");
1578
Chris Lattner50df36a2010-08-28 03:36:51 +00001579 // Undef values never contribute useful bits to the result.
1580 if (isa<UndefValue>(V)) return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001581
Chris Lattnerdd660102010-08-28 01:20:38 +00001582 // If we got down to a value of the right type, we win, try inserting into the
1583 // right element.
1584 if (V->getType() == VecEltTy) {
Chris Lattnerd0214f32010-08-28 01:50:57 +00001585 // Inserting null doesn't actually insert any elements.
1586 if (Constant *C = dyn_cast<Constant>(V))
1587 if (C->isNullValue())
1588 return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001589
Richard Sandifordfeb34712013-08-12 07:26:09 +00001590 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
1591 if (IC.getDataLayout()->isBigEndian())
1592 ElementIndex = Elements.size() - ElementIndex - 1;
1593
Chris Lattnerdd660102010-08-28 01:20:38 +00001594 // Fail if multiple elements are inserted into this slot.
Craig Topperf40110f2014-04-25 05:29:35 +00001595 if (Elements[ElementIndex])
Chris Lattnerdd660102010-08-28 01:20:38 +00001596 return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001597
Chris Lattnerdd660102010-08-28 01:20:38 +00001598 Elements[ElementIndex] = V;
1599 return true;
1600 }
Craig Topper3529aa52013-01-24 05:22:40 +00001601
Chris Lattnerd0214f32010-08-28 01:50:57 +00001602 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001603 // Figure out the # elements this provides, and bitcast it or slice it up
1604 // as required.
Chris Lattnerd0214f32010-08-28 01:50:57 +00001605 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1606 VecEltTy);
1607 // If the constant is the size of a vector element, we just need to bitcast
1608 // it to the right type so it gets properly inserted.
1609 if (NumElts == 1)
1610 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
Richard Sandifordfeb34712013-08-12 07:26:09 +00001611 Shift, Elements, VecEltTy, IC);
Craig Topper3529aa52013-01-24 05:22:40 +00001612
Chris Lattnerd0214f32010-08-28 01:50:57 +00001613 // Okay, this is a constant that covers multiple elements. Slice it up into
1614 // pieces and insert each element-sized piece into the vector.
1615 if (!isa<IntegerType>(C->getType()))
1616 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1617 C->getType()->getPrimitiveSizeInBits()));
1618 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +00001619 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
Craig Topper3529aa52013-01-24 05:22:40 +00001620
Chris Lattnerd0214f32010-08-28 01:50:57 +00001621 for (unsigned i = 0; i != NumElts; ++i) {
Richard Sandifordfeb34712013-08-12 07:26:09 +00001622 unsigned ShiftI = Shift+i*ElementSize;
Chris Lattnerd0214f32010-08-28 01:50:57 +00001623 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
Richard Sandifordfeb34712013-08-12 07:26:09 +00001624 ShiftI));
Chris Lattnerd0214f32010-08-28 01:50:57 +00001625 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
Richard Sandifordfeb34712013-08-12 07:26:09 +00001626 if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy, IC))
Chris Lattnerd0214f32010-08-28 01:50:57 +00001627 return false;
1628 }
1629 return true;
1630 }
Craig Topper3529aa52013-01-24 05:22:40 +00001631
Chris Lattnerdd660102010-08-28 01:20:38 +00001632 if (!V->hasOneUse()) return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001633
Chris Lattnerdd660102010-08-28 01:20:38 +00001634 Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001635 if (!I) return false;
Chris Lattnerdd660102010-08-28 01:20:38 +00001636 switch (I->getOpcode()) {
1637 default: return false; // Unhandled case.
1638 case Instruction::BitCast:
Richard Sandifordfeb34712013-08-12 07:26:09 +00001639 return CollectInsertionElements(I->getOperand(0), Shift,
1640 Elements, VecEltTy, IC);
Chris Lattnerdd660102010-08-28 01:20:38 +00001641 case Instruction::ZExt:
1642 if (!isMultipleOfTypeSize(
1643 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1644 VecEltTy))
1645 return false;
Richard Sandifordfeb34712013-08-12 07:26:09 +00001646 return CollectInsertionElements(I->getOperand(0), Shift,
1647 Elements, VecEltTy, IC);
Chris Lattnerdd660102010-08-28 01:20:38 +00001648 case Instruction::Or:
Richard Sandifordfeb34712013-08-12 07:26:09 +00001649 return CollectInsertionElements(I->getOperand(0), Shift,
1650 Elements, VecEltTy, IC) &&
1651 CollectInsertionElements(I->getOperand(1), Shift,
1652 Elements, VecEltTy, IC);
Chris Lattnerdd660102010-08-28 01:20:38 +00001653 case Instruction::Shl: {
1654 // Must be shifting by a constant that is a multiple of the element size.
1655 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +00001656 if (!CI) return false;
Richard Sandifordfeb34712013-08-12 07:26:09 +00001657 Shift += CI->getZExtValue();
1658 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
1659 return CollectInsertionElements(I->getOperand(0), Shift,
1660 Elements, VecEltTy, IC);
Chris Lattnerdd660102010-08-28 01:20:38 +00001661 }
Craig Topper3529aa52013-01-24 05:22:40 +00001662
Chris Lattnerdd660102010-08-28 01:20:38 +00001663 }
1664}
1665
1666
1667/// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1668/// may be doing shifts and ors to assemble the elements of the vector manually.
1669/// Try to rip the code out and replace it with insertelements. This is to
1670/// optimize code like this:
1671///
1672/// %tmp37 = bitcast float %inc to i32
1673/// %tmp38 = zext i32 %tmp37 to i64
1674/// %tmp31 = bitcast float %inc5 to i32
1675/// %tmp32 = zext i32 %tmp31 to i64
1676/// %tmp33 = shl i64 %tmp32, 32
1677/// %ins35 = or i64 %tmp33, %tmp38
1678/// %tmp43 = bitcast i64 %ins35 to <2 x float>
1679///
1680/// Into two insertelements that do "buildvector{%inc, %inc5}".
1681static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1682 InstCombiner &IC) {
Richard Sandifordfeb34712013-08-12 07:26:09 +00001683 // We need to know the target byte order to perform this optimization.
Craig Topperf40110f2014-04-25 05:29:35 +00001684 if (!IC.getDataLayout()) return nullptr;
Richard Sandifordfeb34712013-08-12 07:26:09 +00001685
Chris Lattner229907c2011-07-18 04:54:35 +00001686 VectorType *DestVecTy = cast<VectorType>(CI.getType());
Chris Lattnerdd660102010-08-28 01:20:38 +00001687 Value *IntInput = CI.getOperand(0);
1688
1689 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1690 if (!CollectInsertionElements(IntInput, 0, Elements,
Richard Sandifordfeb34712013-08-12 07:26:09 +00001691 DestVecTy->getElementType(), IC))
Craig Topperf40110f2014-04-25 05:29:35 +00001692 return nullptr;
Chris Lattnerdd660102010-08-28 01:20:38 +00001693
1694 // If we succeeded, we know that all of the element are specified by Elements
1695 // or are zero if Elements has a null entry. Recast this as a set of
1696 // insertions.
1697 Value *Result = Constant::getNullValue(CI.getType());
1698 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +00001699 if (!Elements[i]) continue; // Unset element.
Craig Topper3529aa52013-01-24 05:22:40 +00001700
Chris Lattnerdd660102010-08-28 01:20:38 +00001701 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1702 IC.Builder->getInt32(i));
1703 }
Craig Topper3529aa52013-01-24 05:22:40 +00001704
Chris Lattnerdd660102010-08-28 01:20:38 +00001705 return Result;
1706}
1707
1708
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001709/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1710/// bitcast. The various long double bitcasts can't get in here.
Chris Lattnerbfd22282010-08-26 22:14:59 +00001711static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001712 // We need to know the target byte order to perform this optimization.
Craig Topperf40110f2014-04-25 05:29:35 +00001713 if (!IC.getDataLayout()) return nullptr;
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001714
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001715 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001716 Type *DestTy = CI.getType();
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001717
1718 // If this is a bitcast from int to float, check to see if the int is an
1719 // extraction from a vector.
Craig Topperf40110f2014-04-25 05:29:35 +00001720 Value *VecInput = nullptr;
Chris Lattnerbfd22282010-08-26 22:14:59 +00001721 // bitcast(trunc(bitcast(somevector)))
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001722 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1723 isa<VectorType>(VecInput->getType())) {
Chris Lattner229907c2011-07-18 04:54:35 +00001724 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattnerbfd22282010-08-26 22:14:59 +00001725 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1726
1727 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1728 // If the element type of the vector doesn't match the result type,
1729 // bitcast it to be a vector type we can extract from.
1730 if (VecTy->getElementType() != DestTy) {
1731 VecTy = VectorType::get(DestTy,
1732 VecTy->getPrimitiveSizeInBits() / DestWidth);
1733 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1734 }
Craig Topper3529aa52013-01-24 05:22:40 +00001735
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001736 unsigned Elt = 0;
1737 if (IC.getDataLayout()->isBigEndian())
1738 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1;
1739 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
Chris Lattnerbfd22282010-08-26 22:14:59 +00001740 }
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001741 }
Craig Topper3529aa52013-01-24 05:22:40 +00001742
Chris Lattnerbfd22282010-08-26 22:14:59 +00001743 // bitcast(trunc(lshr(bitcast(somevector), cst))
Craig Topperf40110f2014-04-25 05:29:35 +00001744 ConstantInt *ShAmt = nullptr;
Chris Lattnerbfd22282010-08-26 22:14:59 +00001745 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1746 m_ConstantInt(ShAmt)))) &&
1747 isa<VectorType>(VecInput->getType())) {
Chris Lattner229907c2011-07-18 04:54:35 +00001748 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattnerbfd22282010-08-26 22:14:59 +00001749 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1750 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1751 ShAmt->getZExtValue() % DestWidth == 0) {
1752 // If the element type of the vector doesn't match the result type,
1753 // bitcast it to be a vector type we can extract from.
1754 if (VecTy->getElementType() != DestTy) {
1755 VecTy = VectorType::get(DestTy,
1756 VecTy->getPrimitiveSizeInBits() / DestWidth);
1757 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1758 }
Craig Topper3529aa52013-01-24 05:22:40 +00001759
Chris Lattnerbfd22282010-08-26 22:14:59 +00001760 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001761 if (IC.getDataLayout()->isBigEndian())
1762 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt;
Chris Lattnerbfd22282010-08-26 22:14:59 +00001763 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1764 }
1765 }
Craig Topperf40110f2014-04-25 05:29:35 +00001766 return nullptr;
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001767}
Chris Lattner02b0df52010-05-08 21:50:26 +00001768
Chris Lattner2b295a02010-01-04 07:53:58 +00001769Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1770 // If the operands are integer typed then apply the integer transforms,
1771 // otherwise just apply the common ones.
1772 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001773 Type *SrcTy = Src->getType();
1774 Type *DestTy = CI.getType();
Chris Lattner2b295a02010-01-04 07:53:58 +00001775
Chris Lattner2b295a02010-01-04 07:53:58 +00001776 // Get rid of casts from one type to the same type. These are useless and can
1777 // be replaced by the operand.
1778 if (DestTy == Src->getType())
1779 return ReplaceInstUsesWith(CI, Src);
1780
Chris Lattner229907c2011-07-18 04:54:35 +00001781 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1782 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1783 Type *DstElTy = DstPTy->getElementType();
1784 Type *SrcElTy = SrcPTy->getElementType();
Craig Topper3529aa52013-01-24 05:22:40 +00001785
Chris Lattner2b295a02010-01-04 07:53:58 +00001786 // If we are casting a alloca to a pointer to a type of the same
1787 // size, rewrite the allocation instruction to allocate the "right" type.
1788 // There is no need to modify malloc calls because it is their bitcast that
1789 // needs to be cleaned up.
1790 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1791 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1792 return V;
Craig Topper3529aa52013-01-24 05:22:40 +00001793
Chris Lattner2b295a02010-01-04 07:53:58 +00001794 // If the source and destination are pointers, and this cast is equivalent
1795 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1796 // This can enhance SROA and other transforms that want type-safe pointers.
1797 Constant *ZeroUInt =
1798 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1799 unsigned NumZeros = 0;
Craig Topper3529aa52013-01-24 05:22:40 +00001800 while (SrcElTy != DstElTy &&
Duncan Sands19d0b472010-02-16 11:11:14 +00001801 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner2b295a02010-01-04 07:53:58 +00001802 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1803 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1804 ++NumZeros;
1805 }
1806
1807 // If we found a path from the src to dest, create the getelementptr now.
1808 if (SrcElTy == DstElTy) {
1809 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Jay Foadd1b78492011-07-25 09:48:08 +00001810 return GetElementPtrInst::CreateInBounds(Src, Idxs);
Chris Lattner2b295a02010-01-04 07:53:58 +00001811 }
1812 }
Craig Topper3529aa52013-01-24 05:22:40 +00001813
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001814 // Try to optimize int -> float bitcasts.
1815 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1816 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1817 return I;
Chris Lattner2b295a02010-01-04 07:53:58 +00001818
Chris Lattner229907c2011-07-18 04:54:35 +00001819 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001820 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001821 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1822 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2b295a02010-01-04 07:53:58 +00001823 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner2b295a02010-01-04 07:53:58 +00001824 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1825 }
Craig Topper3529aa52013-01-24 05:22:40 +00001826
Chris Lattnerdd660102010-08-28 01:20:38 +00001827 if (isa<IntegerType>(SrcTy)) {
1828 // If this is a cast from an integer to vector, check to see if the input
1829 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1830 // the casts with a shuffle and (potentially) a bitcast.
1831 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1832 CastInst *SrcCast = cast<CastInst>(Src);
1833 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1834 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1835 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
Chris Lattner02b0df52010-05-08 21:50:26 +00001836 cast<VectorType>(DestTy), *this))
Chris Lattnerdd660102010-08-28 01:20:38 +00001837 return I;
1838 }
Craig Topper3529aa52013-01-24 05:22:40 +00001839
Chris Lattnerdd660102010-08-28 01:20:38 +00001840 // If the input is an 'or' instruction, we may be doing shifts and ors to
1841 // assemble the elements of the vector manually. Try to rip the code out
1842 // and replace it with insertelements.
1843 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1844 return ReplaceInstUsesWith(CI, V);
Chris Lattner02b0df52010-05-08 21:50:26 +00001845 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001846 }
1847
Chris Lattner229907c2011-07-18 04:54:35 +00001848 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Michael Ilseman74a6da92013-02-11 21:41:44 +00001849 if (SrcVTy->getNumElements() == 1) {
1850 // If our destination is not a vector, then make this a straight
1851 // scalar-scalar cast.
1852 if (!DestTy->isVectorTy()) {
1853 Value *Elem =
1854 Builder->CreateExtractElement(Src,
1855 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1856 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1857 }
1858
1859 // Otherwise, see if our source is an insert. If so, then use the scalar
1860 // component directly.
1861 if (InsertElementInst *IEI =
1862 dyn_cast<InsertElementInst>(CI.getOperand(0)))
1863 return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
1864 DestTy);
Chris Lattner2b295a02010-01-04 07:53:58 +00001865 }
1866 }
1867
1868 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001869 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmaneb7111b2010-04-07 23:22:42 +00001870 // a bitcast to a vector with the same # elts.
Craig Topper3529aa52013-01-24 05:22:40 +00001871 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001872 DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001873 SVI->getType()->getNumElements() ==
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001874 SVI->getOperand(0)->getType()->getVectorNumElements()) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001875 BitCastInst *Tmp;
1876 // If either of the operands is a cast from CI.getType(), then
1877 // evaluating the shuffle in the casted destination's type will allow
1878 // us to eliminate at least one cast.
Craig Topper3529aa52013-01-24 05:22:40 +00001879 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001880 Tmp->getOperand(0)->getType() == DestTy) ||
Craig Topper3529aa52013-01-24 05:22:40 +00001881 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001882 Tmp->getOperand(0)->getType() == DestTy)) {
1883 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1884 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1885 // Return a new shuffle vector. Use the same element ID's, as we
1886 // know the vector types match #elts.
1887 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner2b295a02010-01-04 07:53:58 +00001888 }
1889 }
1890 }
Craig Topper3529aa52013-01-24 05:22:40 +00001891
Duncan Sands19d0b472010-02-16 11:11:14 +00001892 if (SrcTy->isPointerTy())
Chris Lattnera93c63c2010-01-05 22:21:18 +00001893 return commonPointerCastTransforms(CI);
1894 return commonCastTransforms(CI);
Chris Lattner2b295a02010-01-04 07:53:58 +00001895}
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +00001896
1897Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
Manuel Jacobb4db99c2014-07-16 01:34:21 +00001898 // If the destination pointer element type is not the same as the source's
1899 // first do a bitcast to the destination type, and then the addrspacecast.
1900 // This allows the cast to be exposed to other transforms.
Jingyue Wu77145d92014-06-06 21:52:55 +00001901 Value *Src = CI.getOperand(0);
1902 PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
1903 PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
1904
1905 Type *DestElemTy = DestTy->getElementType();
1906 if (SrcTy->getElementType() != DestElemTy) {
1907 Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
Jingyue Wubaabe502014-06-15 21:40:57 +00001908 if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
1909 // Handle vectors of pointers.
1910 MidTy = VectorType::get(MidTy, VT->getNumElements());
1911 }
Jingyue Wu77145d92014-06-06 21:52:55 +00001912
1913 Value *NewBitCast = Builder->CreateBitCast(Src, MidTy);
1914 return new AddrSpaceCastInst(NewBitCast, CI.getType());
1915 }
1916
Matt Arsenault2d353d12014-01-14 20:00:45 +00001917 return commonPointerCastTransforms(CI);
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +00001918}