blob: f10e48abf108824a5725d4b959d9d365afd9ac82 [file] [log] [blame]
Chris Lattner80f43d32010-01-04 07:53:58 +00001//===- InstCombineCasts.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for cast operations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Eli Friedman74703252011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner80f43d32010-01-04 07:53:58 +000016#include "llvm/Target/TargetData.h"
17#include "llvm/Support/PatternMatch.h"
18using namespace llvm;
19using namespace PatternMatch;
20
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000021/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
22/// expression. If so, decompose it, returning some value X, such that Val is
23/// X*Scale+Offset.
24///
25static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Dan Gohman28d2e0a2010-05-28 04:33:04 +000026 uint64_t &Offset) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000027 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28 Offset = CI->getZExtValue();
29 Scale = 0;
Dan Gohman28d2e0a2010-05-28 04:33:04 +000030 return ConstantInt::get(Val->getType(), 0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000031 }
32
33 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Bob Wilsone2e86f62011-07-08 22:09:33 +000034 // Cannot look past anything that might overflow.
35 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
36 if (OBI && !OBI->hasNoUnsignedWrap()) {
37 Scale = 1;
38 Offset = 0;
39 return Val;
40 }
41
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000042 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
43 if (I->getOpcode() == Instruction::Shl) {
44 // This is a value scaled by '1 << the shift amt'.
Dan Gohman28d2e0a2010-05-28 04:33:04 +000045 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000046 Offset = 0;
47 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000048 }
49
50 if (I->getOpcode() == Instruction::Mul) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000051 // This value is scaled by 'RHS'.
52 Scale = RHS->getZExtValue();
53 Offset = 0;
54 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000055 }
56
57 if (I->getOpcode() == Instruction::Add) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000058 // We have X+C. Check to see if we really have (X*C2)+C1,
59 // where C1 is divisible by C2.
60 unsigned SubScale;
61 Value *SubVal =
62 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
63 Offset += RHS->getZExtValue();
64 Scale = SubScale;
65 return SubVal;
66 }
67 }
68 }
69
70 // Otherwise, we can't look past this.
71 Scale = 1;
72 Offset = 0;
73 return Val;
74}
75
76/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
77/// try to eliminate the cast by moving the type information into the alloc.
78Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
79 AllocaInst &AI) {
80 // This requires TargetData to get the alloca alignment and size information.
81 if (!TD) return 0;
82
Chris Lattnerdb125cf2011-07-18 04:54:35 +000083 PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000084
85 BuilderTy AllocaBuilder(*Builder);
86 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
87
88 // Get the type really allocated and the type casted to.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000089 Type *AllocElTy = AI.getAllocatedType();
90 Type *CastElTy = PTy->getElementType();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000091 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
92
93 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
94 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
95 if (CastElTyAlign < AllocElTyAlign) return 0;
96
97 // If the allocation has multiple uses, only promote it if we are strictly
98 // increasing the alignment of the resultant allocation. If we keep it the
Devang Patel5aa3fa62011-03-08 22:12:11 +000099 // same, we open the door to infinite loops of various kinds.
100 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000101
102 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
103 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
104 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
105
106 // See if we can satisfy the modulus by pulling a scale out of the array
107 // size argument.
108 unsigned ArraySizeScale;
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000109 uint64_t ArrayOffset;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000110 Value *NumElements = // See if the array size is a decomposable linear expr.
111 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
112
113 // If we can now satisfy the modulus, by using a non-1 scale, we really can
114 // do the xform.
115 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
116 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
117
118 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
119 Value *Amt = 0;
120 if (Scale == 1) {
121 Amt = NumElements;
122 } else {
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000123 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000124 // Insert before the alloca, not before the cast.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000125 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000126 }
127
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000128 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
129 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000130 Offset, true);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000131 Amt = AllocaBuilder.CreateAdd(Amt, Off);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000132 }
133
134 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
135 New->setAlignment(AI.getAlignment());
136 New->takeName(&AI);
137
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000138 // If the allocation has multiple real uses, insert a cast and change all
139 // things that used it to use the new cast. This will also hack on CI, but it
140 // will die soon.
Devang Patel5aa3fa62011-03-08 22:12:11 +0000141 if (!AI.hasOneUse()) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000142 // New is the allocation instruction, pointer typed. AI is the original
143 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
144 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Eli Friedman3e22cb92011-05-18 00:32:01 +0000145 ReplaceInstUsesWith(AI, NewCast);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000146 }
147 return ReplaceInstUsesWith(CI, New);
148}
149
150
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000151
Chris Lattner5f0290e2010-01-04 07:54:59 +0000152/// EvaluateInDifferentType - Given an expression that
Chris Lattner14bf8f02010-01-08 19:19:23 +0000153/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000154/// insert the code to evaluate the expression.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000155Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
Chris Lattner5f0290e2010-01-04 07:54:59 +0000156 bool isSigned) {
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000157 if (Constant *C = dyn_cast<Constant>(V)) {
158 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
159 // If we got a constantexpr back, try to simplify it with TD info.
160 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
161 C = ConstantFoldConstantExpression(CE, TD);
162 return C;
163 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000164
165 // Otherwise, it must be an instruction.
166 Instruction *I = cast<Instruction>(V);
167 Instruction *Res = 0;
168 unsigned Opc = I->getOpcode();
169 switch (Opc) {
170 case Instruction::Add:
171 case Instruction::Sub:
172 case Instruction::Mul:
173 case Instruction::And:
174 case Instruction::Or:
175 case Instruction::Xor:
176 case Instruction::AShr:
177 case Instruction::LShr:
178 case Instruction::Shl:
179 case Instruction::UDiv:
180 case Instruction::URem: {
181 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
182 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
183 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
184 break;
185 }
186 case Instruction::Trunc:
187 case Instruction::ZExt:
188 case Instruction::SExt:
189 // If the source type of the cast is the type we're trying for then we can
190 // just return the source. There's no need to insert it because it is not
191 // new.
192 if (I->getOperand(0)->getType() == Ty)
193 return I->getOperand(0);
194
195 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000196 // This also handles the case of zext(trunc(x)) -> zext(x).
197 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
198 Opc == Instruction::SExt);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000199 break;
200 case Instruction::Select: {
201 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
202 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
203 Res = SelectInst::Create(I->getOperand(0), True, False);
204 break;
205 }
206 case Instruction::PHI: {
207 PHINode *OPN = cast<PHINode>(I);
Jay Foad3ecfc862011-03-30 11:28:46 +0000208 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
Chris Lattner5f0290e2010-01-04 07:54:59 +0000209 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
210 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
211 NPN->addIncoming(V, OPN->getIncomingBlock(i));
212 }
213 Res = NPN;
214 break;
215 }
216 default:
217 // TODO: Can handle more cases here.
218 llvm_unreachable("Unreachable!");
219 break;
220 }
221
222 Res->takeName(I);
Eli Friedmana311c342011-05-27 00:19:40 +0000223 return InsertNewInstWith(Res, *I);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000224}
Chris Lattner80f43d32010-01-04 07:53:58 +0000225
226
227/// This function is a wrapper around CastInst::isEliminableCastPair. It
228/// simply extracts arguments and returns what that function returns.
229static Instruction::CastOps
230isEliminableCastPair(
231 const CastInst *CI, ///< The first cast instruction
232 unsigned opcode, ///< The opcode of the second cast instruction
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000233 Type *DstTy, ///< The target type for the second cast instruction
Chris Lattner80f43d32010-01-04 07:53:58 +0000234 TargetData *TD ///< The target data for pointer size
235) {
236
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
238 Type *MidTy = CI->getType(); // B from above
Chris Lattner80f43d32010-01-04 07:53:58 +0000239
240 // Get the opcodes of the two Cast instructions
241 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
242 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
243
244 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
245 DstTy,
246 TD ? TD->getIntPtrType(CI->getContext()) : 0);
247
248 // We don't want to form an inttoptr or ptrtoint that converts to an integer
249 // type that differs from the pointer size.
250 if ((Res == Instruction::IntToPtr &&
251 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
252 (Res == Instruction::PtrToInt &&
253 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
254 Res = 0;
255
256 return Instruction::CastOps(Res);
257}
258
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000259/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
260/// results in any code being generated and is interesting to optimize out. If
261/// the cast can be eliminated by some other simple transformation, we prefer
262/// to do the simplification first.
263bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000264 Type *Ty) {
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000265 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner80f43d32010-01-04 07:53:58 +0000266 if (V->getType() == Ty || isa<Constant>(V)) return false;
267
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000268 // If this is another cast that can be eliminated, we prefer to have it
269 // eliminated.
Chris Lattner80f43d32010-01-04 07:53:58 +0000270 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000271 if (isEliminableCastPair(CI, opc, Ty, TD))
Chris Lattner80f43d32010-01-04 07:53:58 +0000272 return false;
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000273
274 // If this is a vector sext from a compare, then we don't want to break the
275 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands1df98592010-02-16 11:11:14 +0000276 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000277 return false;
278
Chris Lattner80f43d32010-01-04 07:53:58 +0000279 return true;
280}
281
282
283/// @brief Implement the transforms common to all CastInst visitors.
284Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
285 Value *Src = CI.getOperand(0);
286
287 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
288 // eliminate it now.
289 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
290 if (Instruction::CastOps opc =
291 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
292 // The first cast (CSrc) is eliminable so we need to fix up or replace
293 // the second cast (CI). CSrc will then have a good chance of being dead.
294 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
295 }
296 }
297
298 // If we are casting a select then fold the cast into the select
299 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
300 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
301 return NV;
302
303 // If we are casting a PHI then fold the cast into the PHI
304 if (isa<PHINode>(Src)) {
305 // We don't do this if this would create a PHI node with an illegal type if
306 // it is currently legal.
Duncan Sands1df98592010-02-16 11:11:14 +0000307 if (!Src->getType()->isIntegerTy() ||
308 !CI.getType()->isIntegerTy() ||
Chris Lattner80f43d32010-01-04 07:53:58 +0000309 ShouldChangeType(CI.getType(), Src->getType()))
310 if (Instruction *NV = FoldOpIntoPhi(CI))
311 return NV;
312 }
313
314 return 0;
315}
316
Chris Lattner75215c92010-01-10 00:58:42 +0000317/// CanEvaluateTruncated - Return true if we can evaluate the specified
318/// expression tree as type Ty instead of its larger type, and arrive with the
319/// same value. This is used by code that tries to eliminate truncates.
320///
321/// Ty will always be a type smaller than V. We should return true if trunc(V)
322/// can be computed by computing V in the smaller type. If V is an instruction,
323/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
324/// makes sense if x and y can be efficiently truncated.
325///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000326/// This function works on both vectors and scalars.
327///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000328static bool CanEvaluateTruncated(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000329 // We can always evaluate constants in another type.
330 if (isa<Constant>(V))
331 return true;
Chris Lattner68c6e892010-01-05 23:00:30 +0000332
Chris Lattner75215c92010-01-10 00:58:42 +0000333 Instruction *I = dyn_cast<Instruction>(V);
334 if (!I) return false;
335
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000336 Type *OrigTy = V->getType();
Chris Lattner75215c92010-01-10 00:58:42 +0000337
Chris Lattnera958cbf2010-01-11 22:45:25 +0000338 // If this is an extension from the dest type, we can eliminate it, even if it
339 // has multiple uses.
Chris Lattner53af2d12010-01-11 22:49:40 +0000340 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000341 I->getOperand(0)->getType() == Ty)
342 return true;
343
344 // We can't extend or shrink something that has multiple uses: doing so would
345 // require duplicating the instruction in general, which isn't profitable.
346 if (!I->hasOneUse()) return false;
347
348 unsigned Opc = I->getOpcode();
349 switch (Opc) {
350 case Instruction::Add:
351 case Instruction::Sub:
352 case Instruction::Mul:
353 case Instruction::And:
354 case Instruction::Or:
355 case Instruction::Xor:
356 // These operators can all arbitrarily be extended or truncated.
357 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
358 CanEvaluateTruncated(I->getOperand(1), Ty);
359
360 case Instruction::UDiv:
361 case Instruction::URem: {
362 // UDiv and URem can be truncated if all the truncated bits are zero.
363 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
364 uint32_t BitWidth = Ty->getScalarSizeInBits();
365 if (BitWidth < OrigBitWidth) {
366 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
367 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
368 MaskedValueIsZero(I->getOperand(1), Mask)) {
369 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
370 CanEvaluateTruncated(I->getOperand(1), Ty);
371 }
372 }
373 break;
374 }
375 case Instruction::Shl:
376 // If we are truncating the result of this SHL, and if it's a shift of a
377 // constant amount, we can always perform a SHL in a smaller type.
378 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
379 uint32_t BitWidth = Ty->getScalarSizeInBits();
380 if (CI->getLimitedValue(BitWidth) < BitWidth)
381 return CanEvaluateTruncated(I->getOperand(0), Ty);
382 }
383 break;
384 case Instruction::LShr:
385 // If this is a truncate of a logical shr, we can truncate it to a smaller
386 // lshr iff we know that the bits we would otherwise be shifting in are
387 // already zeros.
388 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
389 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
390 uint32_t BitWidth = Ty->getScalarSizeInBits();
391 if (MaskedValueIsZero(I->getOperand(0),
392 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
393 CI->getLimitedValue(BitWidth) < BitWidth) {
394 return CanEvaluateTruncated(I->getOperand(0), Ty);
395 }
396 }
397 break;
398 case Instruction::Trunc:
399 // trunc(trunc(x)) -> trunc(x)
400 return true;
Chris Lattnerf9d05ab2010-08-27 20:32:06 +0000401 case Instruction::ZExt:
402 case Instruction::SExt:
403 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
404 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
405 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000406 case Instruction::Select: {
407 SelectInst *SI = cast<SelectInst>(I);
408 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
409 CanEvaluateTruncated(SI->getFalseValue(), Ty);
410 }
411 case Instruction::PHI: {
412 // We can change a phi if we can change all operands. Note that we never
413 // get into trouble with cyclic PHIs here because we only consider
414 // instructions with a single use.
415 PHINode *PN = cast<PHINode>(I);
416 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
417 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
418 return false;
419 return true;
420 }
421 default:
422 // TODO: Can handle more cases here.
423 break;
424 }
425
426 return false;
427}
428
429Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000430 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner75215c92010-01-10 00:58:42 +0000431 return Result;
432
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000433 // See if we can simplify any instructions used by the input whose sole
434 // purpose is to compute bits we don't care about.
435 if (SimplifyDemandedInstructionBits(CI))
436 return &CI;
437
Chris Lattner75215c92010-01-10 00:58:42 +0000438 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000439 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
Chris Lattner75215c92010-01-10 00:58:42 +0000440
441 // Attempt to truncate the entire input expression tree to the destination
442 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner80f43d32010-01-04 07:53:58 +0000443 // expression tree to something weird like i93 unless the source is also
444 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +0000445 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000446 CanEvaluateTruncated(Src, DestTy)) {
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000447
Chris Lattner80f43d32010-01-04 07:53:58 +0000448 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000449 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000450 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohman5b71dce2010-05-25 21:50:35 +0000451 " to avoid cast: " << CI << '\n');
Chris Lattner075f6922010-01-07 23:41:00 +0000452 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
453 assert(Res->getType() == DestTy);
454 return ReplaceInstUsesWith(CI, Res);
455 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000456
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000457 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
458 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000459 Constant *One = ConstantInt::get(Src->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000460 Src = Builder->CreateAnd(Src, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000461 Value *Zero = Constant::getNullValue(Src->getType());
462 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
463 }
Chris Lattner784f3332010-08-27 18:31:05 +0000464
465 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
466 Value *A = 0; ConstantInt *Cst = 0;
Chris Lattner62fe4062011-01-15 06:32:33 +0000467 if (Src->hasOneUse() &&
468 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
Chris Lattner784f3332010-08-27 18:31:05 +0000469 // We have three types to worry about here, the type of A, the source of
470 // the truncate (MidSize), and the destination of the truncate. We know that
471 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
472 // between ASize and ResultSize.
473 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
474
475 // If the shift amount is larger than the size of A, then the result is
476 // known to be zero because all the input bits got shifted out.
477 if (Cst->getZExtValue() >= ASize)
478 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
479
480 // Since we're doing an lshr and a zero extend, and know that the shift
481 // amount is smaller than ASize, it is always safe to do the shift in A's
482 // type, then zero extend or truncate to the result.
483 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
484 Shift->takeName(Src);
485 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
486 }
Chris Lattner62fe4062011-01-15 06:32:33 +0000487
488 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
489 // type isn't non-native.
490 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
491 ShouldChangeType(Src->getType(), CI.getType()) &&
492 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
493 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
494 return BinaryOperator::CreateAnd(NewTrunc,
495 ConstantExpr::getTrunc(Cst, CI.getType()));
496 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000497
Chris Lattner80f43d32010-01-04 07:53:58 +0000498 return 0;
499}
500
501/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
502/// in order to eliminate the icmp.
503Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
504 bool DoXform) {
505 // If we are just checking for a icmp eq of a single bit and zext'ing it
506 // to an integer, then shift the bit to the appropriate place and then
507 // cast to integer to avoid the comparison.
508 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
509 const APInt &Op1CV = Op1C->getValue();
510
511 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
512 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
513 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
514 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
515 if (!DoXform) return ICI;
516
517 Value *In = ICI->getOperand(0);
518 Value *Sh = ConstantInt::get(In->getType(),
519 In->getType()->getScalarSizeInBits()-1);
520 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
521 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000522 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000523
524 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
525 Constant *One = ConstantInt::get(In->getType(), 1);
526 In = Builder->CreateXor(In, One, In->getName()+".not");
527 }
528
529 return ReplaceInstUsesWith(CI, In);
530 }
531
532
533
534 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
535 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
536 // zext (X == 1) to i32 --> X iff X has only the low bit set.
537 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
538 // zext (X != 0) to i32 --> X iff X has only the low bit set.
539 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
540 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
541 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
542 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
543 // This only works for EQ and NE
544 ICI->isEquality()) {
545 // If Op1C some other power of two, convert:
546 uint32_t BitWidth = Op1C->getType()->getBitWidth();
547 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
548 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
549 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
550
551 APInt KnownZeroMask(~KnownZero);
552 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
553 if (!DoXform) return ICI;
554
555 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
556 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
557 // (X&4) == 2 --> false
558 // (X&4) != 2 --> true
559 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
560 isNE);
561 Res = ConstantExpr::getZExt(Res, CI.getType());
562 return ReplaceInstUsesWith(CI, Res);
563 }
564
565 uint32_t ShiftAmt = KnownZeroMask.logBase2();
566 Value *In = ICI->getOperand(0);
567 if (ShiftAmt) {
568 // Perform a logical shr by shiftamt.
569 // Insert the shift to put the result in the low bit.
570 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
571 In->getName()+".lobit");
572 }
573
574 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
575 Constant *One = ConstantInt::get(In->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000576 In = Builder->CreateXor(In, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000577 }
578
579 if (CI.getType() == In->getType())
580 return ReplaceInstUsesWith(CI, In);
Chris Lattner29cc0b32010-08-27 22:24:38 +0000581 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000582 }
583 }
584 }
585
586 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
587 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
588 // may lead to additional simplifications.
589 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000590 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000591 uint32_t BitWidth = ITy->getBitWidth();
592 Value *LHS = ICI->getOperand(0);
593 Value *RHS = ICI->getOperand(1);
594
595 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
596 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
597 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
598 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
599 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
600
601 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
602 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
603 APInt UnknownBit = ~KnownBits;
604 if (UnknownBit.countPopulation() == 1) {
605 if (!DoXform) return ICI;
606
607 Value *Result = Builder->CreateXor(LHS, RHS);
608
609 // Mask off any bits that are set and won't be shifted away.
610 if (KnownOneLHS.uge(UnknownBit))
611 Result = Builder->CreateAnd(Result,
612 ConstantInt::get(ITy, UnknownBit));
613
614 // Shift the bit we're testing down to the lsb.
615 Result = Builder->CreateLShr(
616 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
617
618 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
619 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
620 Result->takeName(ICI);
621 return ReplaceInstUsesWith(CI, Result);
622 }
623 }
624 }
625 }
626
627 return 0;
628}
629
Chris Lattner75215c92010-01-10 00:58:42 +0000630/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000631/// specified wider type and produce the same low bits. If not, return false.
632///
Chris Lattner789162a2010-01-11 03:32:00 +0000633/// If this function returns true, it can also return a non-zero number of bits
634/// (in BitsToClear) which indicates that the value it computes is correct for
635/// the zero extend, but that the additional BitsToClear bits need to be zero'd
636/// out. For example, to promote something like:
637///
638/// %B = trunc i64 %A to i32
639/// %C = lshr i32 %B, 8
640/// %E = zext i32 %C to i64
641///
642/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
643/// set to 8 to indicate that the promoted value needs to have bits 24-31
644/// cleared in addition to bits 32-63. Since an 'and' will be generated to
645/// clear the top bits anyway, doing this has no extra cost.
646///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000647/// This function works on both vectors and scalars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000648static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
Chris Lattner789162a2010-01-11 03:32:00 +0000649 BitsToClear = 0;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000650 if (isa<Constant>(V))
651 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000652
653 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner9e390dd2010-01-10 02:50:04 +0000654 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000655
656 // If the input is a truncate from the destination type, we can trivially
Chris Lattnera958cbf2010-01-11 22:45:25 +0000657 // eliminate it, even if it has multiple uses.
658 // FIXME: This is currently disabled until codegen can handle this without
659 // pessimizing code, PR5997.
660 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner9e390dd2010-01-10 02:50:04 +0000661 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000662
663 // We can't extend or shrink something that has multiple uses: doing so would
664 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000665 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000666
Chris Lattner789162a2010-01-11 03:32:00 +0000667 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattner75215c92010-01-10 00:58:42 +0000668 switch (Opc) {
Chris Lattner9ee947c2010-01-10 20:25:54 +0000669 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
670 case Instruction::SExt: // zext(sext(x)) -> sext(x).
671 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
672 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000673 case Instruction::And:
Chris Lattner75215c92010-01-10 00:58:42 +0000674 case Instruction::Or:
675 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000676 case Instruction::Add:
677 case Instruction::Sub:
678 case Instruction::Mul:
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000679 case Instruction::Shl:
Chris Lattner789162a2010-01-11 03:32:00 +0000680 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
681 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
682 return false;
683 // These can all be promoted if neither operand has 'bits to clear'.
684 if (BitsToClear == 0 && Tmp == 0)
685 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000686
Chris Lattner7acc4b12010-01-11 04:05:13 +0000687 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
688 // other side, BitsToClear is ok.
689 if (Tmp == 0 &&
690 (Opc == Instruction::And || Opc == Instruction::Or ||
691 Opc == Instruction::Xor)) {
692 // We use MaskedValueIsZero here for generality, but the case we care
693 // about the most is constant RHS.
694 unsigned VSize = V->getType()->getScalarSizeInBits();
695 if (MaskedValueIsZero(I->getOperand(1),
696 APInt::getHighBitsSet(VSize, BitsToClear)))
697 return true;
698 }
699
700 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner789162a2010-01-11 03:32:00 +0000701 return false;
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000702
Chris Lattner789162a2010-01-11 03:32:00 +0000703 case Instruction::LShr:
704 // We can promote lshr(x, cst) if we can promote x. This requires the
705 // ultimate 'and' to clear out the high zero bits we're clearing out though.
706 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
707 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
708 return false;
709 BitsToClear += Amt->getZExtValue();
710 if (BitsToClear > V->getType()->getScalarSizeInBits())
711 BitsToClear = V->getType()->getScalarSizeInBits();
712 return true;
713 }
714 // Cannot promote variable LSHR.
715 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000716 case Instruction::Select:
Chris Lattner789162a2010-01-11 03:32:00 +0000717 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
718 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000719 // TODO: If important, we could handle the case when the BitsToClear are
720 // known zero in the disagreeing side.
Chris Lattner789162a2010-01-11 03:32:00 +0000721 Tmp != BitsToClear)
722 return false;
723 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000724
725 case Instruction::PHI: {
726 // We can change a phi if we can change all operands. Note that we never
727 // get into trouble with cyclic PHIs here because we only consider
728 // instructions with a single use.
729 PHINode *PN = cast<PHINode>(I);
Chris Lattner789162a2010-01-11 03:32:00 +0000730 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
731 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000732 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner789162a2010-01-11 03:32:00 +0000733 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000734 // TODO: If important, we could handle the case when the BitsToClear
735 // are known zero in the disagreeing input.
Chris Lattner789162a2010-01-11 03:32:00 +0000736 Tmp != BitsToClear)
737 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000738 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000739 }
740 default:
741 // TODO: Can handle more cases here.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000742 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000743 }
744}
745
Chris Lattner80f43d32010-01-04 07:53:58 +0000746Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +0000747 // If this zero extend is only used by a truncate, let the truncate by
748 // eliminated before we try to optimize this zext.
749 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
750 return 0;
751
Chris Lattner80f43d32010-01-04 07:53:58 +0000752 // If one of the common conversion will work, do it.
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000753 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000754 return Result;
755
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000756 // See if we can simplify any instructions used by the input whose sole
757 // purpose is to compute bits we don't care about.
758 if (SimplifyDemandedInstructionBits(CI))
759 return &CI;
Chris Lattner75215c92010-01-10 00:58:42 +0000760
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000761 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000762 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattner75215c92010-01-10 00:58:42 +0000763
764 // Attempt to extend the entire input expression tree to the destination
765 // type. Only do this if the dest type is a simple type, don't convert the
766 // expression tree to something weird like i93 unless the source is also
767 // strange.
Chris Lattner789162a2010-01-11 03:32:00 +0000768 unsigned BitsToClear;
Duncan Sands1df98592010-02-16 11:11:14 +0000769 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner789162a2010-01-11 03:32:00 +0000770 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
771 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
772 "Unreasonable BitsToClear");
773
Chris Lattner5324d802010-01-10 02:39:31 +0000774 // Okay, we can transform this! Insert the new expression now.
775 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
776 " to avoid zero extend: " << CI);
777 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
778 assert(Res->getType() == DestTy);
779
Chris Lattner789162a2010-01-11 03:32:00 +0000780 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
781 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
782
Chris Lattner5324d802010-01-10 02:39:31 +0000783 // If the high bits are already filled with zeros, just replace this
784 // cast with the result.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000785 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
Chris Lattner789162a2010-01-11 03:32:00 +0000786 DestBitSize-SrcBitsKept)))
Chris Lattner5324d802010-01-10 02:39:31 +0000787 return ReplaceInstUsesWith(CI, Res);
788
789 // We need to emit an AND to clear the high bits.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000790 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner789162a2010-01-11 03:32:00 +0000791 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner5324d802010-01-10 02:39:31 +0000792 return BinaryOperator::CreateAnd(Res, C);
Chris Lattner75215c92010-01-10 00:58:42 +0000793 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000794
795 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
796 // types and if the sizes are just right we can convert this into a logical
797 // 'and' which will be much cheaper than the pair of casts.
798 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000799 // TODO: Subsume this into EvaluateInDifferentType.
800
Chris Lattner80f43d32010-01-04 07:53:58 +0000801 // Get the sizes of the types involved. We know that the intermediate type
802 // will be smaller than A or C, but don't know the relation between A and C.
803 Value *A = CSrc->getOperand(0);
804 unsigned SrcSize = A->getType()->getScalarSizeInBits();
805 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
806 unsigned DstSize = CI.getType()->getScalarSizeInBits();
807 // If we're actually extending zero bits, then if
808 // SrcSize < DstSize: zext(a & mask)
809 // SrcSize == DstSize: a & mask
810 // SrcSize > DstSize: trunc(a) & mask
811 if (SrcSize < DstSize) {
812 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
813 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
814 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
815 return new ZExtInst(And, CI.getType());
816 }
817
818 if (SrcSize == DstSize) {
819 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
820 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
821 AndValue));
822 }
823 if (SrcSize > DstSize) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000824 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
Chris Lattner80f43d32010-01-04 07:53:58 +0000825 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
826 return BinaryOperator::CreateAnd(Trunc,
827 ConstantInt::get(Trunc->getType(),
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000828 AndValue));
Chris Lattner80f43d32010-01-04 07:53:58 +0000829 }
830 }
831
832 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
833 return transformZExtICmp(ICI, CI);
834
835 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
836 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
837 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
838 // of the (zext icmp) will be transformed.
839 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
840 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
841 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
842 (transformZExtICmp(LHS, CI, false) ||
843 transformZExtICmp(RHS, CI, false))) {
844 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
845 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
846 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
847 }
848 }
849
850 // zext(trunc(t) & C) -> (t & zext(C)).
851 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
852 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
853 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
854 Value *TI0 = TI->getOperand(0);
855 if (TI0->getType() == CI.getType())
856 return
857 BinaryOperator::CreateAnd(TI0,
858 ConstantExpr::getZExt(C, CI.getType()));
859 }
860
861 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
862 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
863 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
864 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
865 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
866 And->getOperand(1) == C)
867 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
868 Value *TI0 = TI->getOperand(0);
869 if (TI0->getType() == CI.getType()) {
870 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000871 Value *NewAnd = Builder->CreateAnd(TI0, ZC);
Chris Lattner80f43d32010-01-04 07:53:58 +0000872 return BinaryOperator::CreateXor(NewAnd, ZC);
873 }
874 }
875
Chris Lattner718bf3f2010-01-05 21:04:47 +0000876 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
877 Value *X;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000878 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
Chris Lattner49bdfef2010-01-05 21:11:17 +0000879 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +0000880 (!X->hasOneUse() || !isa<CmpInst>(X))) {
881 Value *New = Builder->CreateZExt(X, CI.getType());
882 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
883 }
884
Chris Lattner80f43d32010-01-04 07:53:58 +0000885 return 0;
886}
887
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000888/// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
889/// in order to eliminate the icmp.
890Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
891 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
892 ICmpInst::Predicate Pred = ICI->getPredicate();
893
894 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramer406a6502011-04-01 22:29:18 +0000895 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
896 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000897 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isZero()) ||
898 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
899
900 Value *Sh = ConstantInt::get(Op0->getType(),
901 Op0->getType()->getScalarSizeInBits()-1);
902 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
903 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000904 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000905
906 if (Pred == ICmpInst::ICMP_SGT)
907 In = Builder->CreateNot(In, In->getName()+".not");
908 return ReplaceInstUsesWith(CI, In);
909 }
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000910
911 // If we know that only one bit of the LHS of the icmp can be set and we
912 // have an equality comparison with zero or a power of 2, we can transform
913 // the icmp and sext into bitwise/integer operations.
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000914 if (ICI->hasOneUse() &&
915 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000916 unsigned BitWidth = Op1C->getType()->getBitWidth();
917 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
918 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
919 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
920
Benjamin Kramerce1498b2011-04-01 20:15:16 +0000921 APInt KnownZeroMask(~KnownZero);
922 if (KnownZeroMask.isPowerOf2()) {
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000923 Value *In = ICI->getOperand(0);
924
Benjamin Kramerf5b75932011-04-02 18:50:58 +0000925 // If the icmp tests for a known zero bit we can constant fold it.
926 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
927 Value *V = Pred == ICmpInst::ICMP_NE ?
928 ConstantInt::getAllOnesValue(CI.getType()) :
929 ConstantInt::getNullValue(CI.getType());
930 return ReplaceInstUsesWith(CI, V);
931 }
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000932
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000933 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
934 // sext ((x & 2^n) == 0) -> (x >> n) - 1
935 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
936 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
937 // Perform a right shift to place the desired bit in the LSB.
938 if (ShiftAmt)
939 In = Builder->CreateLShr(In,
940 ConstantInt::get(In->getType(), ShiftAmt));
941
942 // At this point "In" is either 1 or 0. Subtract 1 to turn
943 // {1, 0} -> {0, -1}.
944 In = Builder->CreateAdd(In,
945 ConstantInt::getAllOnesValue(In->getType()),
946 "sext");
947 } else {
948 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000949 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000950 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
951 // Perform a left shift to place the desired bit in the MSB.
952 if (ShiftAmt)
953 In = Builder->CreateShl(In,
954 ConstantInt::get(In->getType(), ShiftAmt));
955
956 // Distribute the bit over the whole bit width.
957 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
958 BitWidth - 1), "sext");
959 }
960
961 if (CI.getType() == In->getType())
962 return ReplaceInstUsesWith(CI, In);
963 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
964 }
965 }
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000966 }
967
968 // vector (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000969 if (VectorType *VTy = dyn_cast<VectorType>(CI.getType())) {
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000970 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_Zero()) &&
971 Op0->getType() == CI.getType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000972 Type *EltTy = VTy->getElementType();
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000973
974 // splat the shift constant to a constant vector.
975 Constant *VSh = ConstantInt::get(VTy, EltTy->getScalarSizeInBits()-1);
976 Value *In = Builder->CreateAShr(Op0, VSh, Op0->getName()+".lobit");
977 return ReplaceInstUsesWith(CI, In);
978 }
979 }
980
981 return 0;
982}
983
Chris Lattner75215c92010-01-10 00:58:42 +0000984/// CanEvaluateSExtd - Return true if we can take the specified value
985/// and return it as type Ty without inserting any new casts and without
986/// changing the value of the common low bits. This is used by code that tries
987/// to promote integer operations to a wider types will allow us to eliminate
988/// the extension.
989///
Chris Lattneraa9c8942010-01-10 07:57:20 +0000990/// This function works on both vectors and scalars.
Chris Lattner75215c92010-01-10 00:58:42 +0000991///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000992static bool CanEvaluateSExtd(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000993 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
994 "Can't sign extend type to a smaller type");
Chris Lattneraa9c8942010-01-10 07:57:20 +0000995 // If this is a constant, it can be trivially promoted.
996 if (isa<Constant>(V))
997 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000998
999 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattneraa9c8942010-01-10 07:57:20 +00001000 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001001
Chris Lattnera958cbf2010-01-11 22:45:25 +00001002 // If this is a truncate from the dest type, we can trivially eliminate it,
1003 // even if it has multiple uses.
1004 // FIXME: This is currently disabled until codegen can handle this without
1005 // pessimizing code, PR5997.
1006 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattneraa9c8942010-01-10 07:57:20 +00001007 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001008
1009 // We can't extend or shrink something that has multiple uses: doing so would
1010 // require duplicating the instruction in general, which isn't profitable.
Chris Lattneraa9c8942010-01-10 07:57:20 +00001011 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001012
Chris Lattneraa9c8942010-01-10 07:57:20 +00001013 switch (I->getOpcode()) {
Chris Lattner11ea8122010-01-10 20:30:41 +00001014 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1015 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1016 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1017 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001018 case Instruction::And:
1019 case Instruction::Or:
1020 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +00001021 case Instruction::Add:
1022 case Instruction::Sub:
Chris Lattner75215c92010-01-10 00:58:42 +00001023 case Instruction::Mul:
Chris Lattneraa9c8942010-01-10 07:57:20 +00001024 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001025 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1026 CanEvaluateSExtd(I->getOperand(1), Ty);
Chris Lattner75215c92010-01-10 00:58:42 +00001027
1028 //case Instruction::Shl: TODO
1029 //case Instruction::LShr: TODO
Chris Lattner75215c92010-01-10 00:58:42 +00001030
Chris Lattneraa9c8942010-01-10 07:57:20 +00001031 case Instruction::Select:
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001032 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1033 CanEvaluateSExtd(I->getOperand(2), Ty);
Chris Lattner9ee947c2010-01-10 20:25:54 +00001034
Chris Lattner75215c92010-01-10 00:58:42 +00001035 case Instruction::PHI: {
1036 // We can change a phi if we can change all operands. Note that we never
1037 // get into trouble with cyclic PHIs here because we only consider
1038 // instructions with a single use.
1039 PHINode *PN = cast<PHINode>(I);
Chris Lattner9ee947c2010-01-10 20:25:54 +00001040 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001041 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattneraa9c8942010-01-10 07:57:20 +00001042 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001043 }
1044 default:
1045 // TODO: Can handle more cases here.
1046 break;
1047 }
1048
Chris Lattneraa9c8942010-01-10 07:57:20 +00001049 return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001050}
1051
Chris Lattner80f43d32010-01-04 07:53:58 +00001052Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +00001053 // If this sign extend is only used by a truncate, let the truncate by
1054 // eliminated before we try to optimize this zext.
1055 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
1056 return 0;
1057
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001058 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +00001059 return I;
1060
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001061 // See if we can simplify any instructions used by the input whose sole
1062 // purpose is to compute bits we don't care about.
1063 if (SimplifyDemandedInstructionBits(CI))
1064 return &CI;
1065
Chris Lattner80f43d32010-01-04 07:53:58 +00001066 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001067 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattner75215c92010-01-10 00:58:42 +00001068
Chris Lattner75215c92010-01-10 00:58:42 +00001069 // Attempt to extend the entire input expression tree to the destination
1070 // type. Only do this if the dest type is a simple type, don't convert the
1071 // expression tree to something weird like i93 unless the source is also
1072 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +00001073 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001074 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001075 // Okay, we can transform this! Insert the new expression now.
1076 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1077 " to avoid sign extend: " << CI);
1078 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1079 assert(Res->getType() == DestTy);
1080
Chris Lattner75215c92010-01-10 00:58:42 +00001081 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1082 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001083
1084 // If the high bits are already filled with sign bit, just replace this
1085 // cast with the result.
Chris Lattneraa9c8942010-01-10 07:57:20 +00001086 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001087 return ReplaceInstUsesWith(CI, Res);
Chris Lattner75215c92010-01-10 00:58:42 +00001088
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001089 // We need to emit a shl + ashr to do the sign extend.
1090 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1091 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1092 ShAmt);
Chris Lattner75215c92010-01-10 00:58:42 +00001093 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001094
Chris Lattnercd5adbb2010-01-18 22:19:16 +00001095 // If this input is a trunc from our destination, then turn sext(trunc(x))
1096 // into shifts.
1097 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1098 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1099 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1100 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1101
1102 // We need to emit a shl + ashr to do the sign extend.
1103 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1104 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1105 return BinaryOperator::CreateAShr(Res, ShAmt);
1106 }
Nate Begeman9a3dc552010-12-17 23:12:19 +00001107
Benjamin Kramer0a30c422011-04-01 20:09:03 +00001108 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1109 return transformSExtICmp(ICI, CI);
Bill Wendling2d0537c2010-12-17 23:27:41 +00001110
Chris Lattner80f43d32010-01-04 07:53:58 +00001111 // If the input is a shl/ashr pair of a same constant, then this is a sign
1112 // extension from a smaller value. If we could trust arbitrary bitwidth
1113 // integers, we could turn this into a truncate to the smaller bit and then
1114 // use a sext for the whole extension. Since we don't, look deeper and check
1115 // for a truncate. If the source and dest are the same type, eliminate the
1116 // trunc and extend and just do shifts. For example, turn:
1117 // %a = trunc i32 %i to i8
1118 // %b = shl i8 %a, 6
1119 // %c = ashr i8 %b, 6
1120 // %d = sext i8 %c to i32
1121 // into:
1122 // %a = shl i32 %i, 30
1123 // %d = ashr i32 %a, 30
1124 Value *A = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001125 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Chris Lattner80f43d32010-01-04 07:53:58 +00001126 ConstantInt *BA = 0, *CA = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001127 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner80f43d32010-01-04 07:53:58 +00001128 m_ConstantInt(CA))) &&
Chris Lattner4f379782010-01-10 01:04:31 +00001129 BA == CA && A->getType() == CI.getType()) {
1130 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1131 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1132 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1133 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1134 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1135 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner80f43d32010-01-04 07:53:58 +00001136 }
1137
1138 return 0;
1139}
1140
1141
1142/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1143/// in the specified FP type without changing its value.
1144static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1145 bool losesInfo;
1146 APFloat F = CFP->getValueAPF();
1147 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1148 if (!losesInfo)
1149 return ConstantFP::get(CFP->getContext(), F);
1150 return 0;
1151}
1152
1153/// LookThroughFPExtensions - If this is an fp extension instruction, look
1154/// through it until we get the source value.
1155static Value *LookThroughFPExtensions(Value *V) {
1156 if (Instruction *I = dyn_cast<Instruction>(V))
1157 if (I->getOpcode() == Instruction::FPExt)
1158 return LookThroughFPExtensions(I->getOperand(0));
1159
1160 // If this value is a constant, return the constant in the smallest FP type
1161 // that can accurately represent it. This allows us to turn
1162 // (float)((double)X+2.0) into x+2.0f.
1163 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1164 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1165 return V; // No constant folding of this.
1166 // See if the value can be truncated to float and then reextended.
1167 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1168 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001169 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001170 return V; // Won't shrink.
1171 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1172 return V;
1173 // Don't try to shrink to various long double types.
1174 }
1175
1176 return V;
1177}
1178
1179Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1180 if (Instruction *I = commonCastTransforms(CI))
1181 return I;
1182
1183 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1184 // smaller than the destination type, we can eliminate the truncate by doing
1185 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1186 // as many builtins (sqrt, etc).
1187 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1188 if (OpI && OpI->hasOneUse()) {
1189 switch (OpI->getOpcode()) {
1190 default: break;
1191 case Instruction::FAdd:
1192 case Instruction::FSub:
1193 case Instruction::FMul:
1194 case Instruction::FDiv:
1195 case Instruction::FRem:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001196 Type *SrcTy = OpI->getType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001197 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1198 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1199 if (LHSTrunc->getType() != SrcTy &&
1200 RHSTrunc->getType() != SrcTy) {
1201 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1202 // If the source types were both smaller than the destination type of
1203 // the cast, do this xform.
1204 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1205 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1206 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1207 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1208 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1209 }
1210 }
1211 break;
1212 }
1213 }
Owen Andersond9029012010-07-19 08:09:34 +00001214
1215 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
1216 // NOTE: This should be disabled by -fno-builtin-sqrt if we ever support it.
1217 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
1218 if (Call && Call->getCalledFunction() &&
1219 Call->getCalledFunction()->getName() == "sqrt" &&
Evan Cheng93a635c2011-07-13 19:08:16 +00001220 Call->getNumArgOperands() == 1 &&
1221 Call->hasOneUse()) {
Owen Andersond9029012010-07-19 08:09:34 +00001222 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1223 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
Owen Anderson5f23a932010-07-19 19:23:32 +00001224 CI.getType()->isFloatTy() &&
1225 Call->getType()->isDoubleTy() &&
1226 Arg->getType()->isDoubleTy() &&
1227 Arg->getOperand(0)->getType()->isFloatTy()) {
1228 Function *Callee = Call->getCalledFunction();
1229 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner979ed442010-09-07 20:01:38 +00001230 Constant *SqrtfFunc = M->getOrInsertFunction("sqrtf",
Owen Anderson5f23a932010-07-19 19:23:32 +00001231 Callee->getAttributes(),
Owen Andersond9029012010-07-19 08:09:34 +00001232 Builder->getFloatTy(),
1233 Builder->getFloatTy(),
1234 NULL);
1235 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1236 "sqrtfcall");
Owen Anderson5f23a932010-07-19 19:23:32 +00001237 ret->setAttributes(Callee->getAttributes());
Chris Lattner979ed442010-09-07 20:01:38 +00001238
1239
1240 // Remove the old Call. With -fmath-errno, it won't get marked readnone.
Eli Friedman3e22cb92011-05-18 00:32:01 +00001241 ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
Chris Lattner979ed442010-09-07 20:01:38 +00001242 EraseInstFromFunction(*Call);
Owen Andersond9029012010-07-19 08:09:34 +00001243 return ret;
1244 }
1245 }
1246
Chris Lattner80f43d32010-01-04 07:53:58 +00001247 return 0;
1248}
1249
1250Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1251 return commonCastTransforms(CI);
1252}
1253
1254Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1255 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1256 if (OpI == 0)
1257 return commonCastTransforms(FI);
1258
1259 // fptoui(uitofp(X)) --> X
1260 // fptoui(sitofp(X)) --> X
1261 // This is safe if the intermediate type has enough bits in its mantissa to
1262 // accurately represent all values of X. For example, do not do this with
1263 // i64->float->i64. This is also safe for sitofp case, because any negative
1264 // 'X' value would cause an undefined result for the fptoui.
1265 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1266 OpI->getOperand(0)->getType() == FI.getType() &&
1267 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1268 OpI->getType()->getFPMantissaWidth())
1269 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1270
1271 return commonCastTransforms(FI);
1272}
1273
1274Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1275 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1276 if (OpI == 0)
1277 return commonCastTransforms(FI);
1278
1279 // fptosi(sitofp(X)) --> X
1280 // fptosi(uitofp(X)) --> X
1281 // This is safe if the intermediate type has enough bits in its mantissa to
1282 // accurately represent all values of X. For example, do not do this with
1283 // i64->float->i64. This is also safe for sitofp case, because any negative
1284 // 'X' value would cause an undefined result for the fptoui.
1285 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1286 OpI->getOperand(0)->getType() == FI.getType() &&
1287 (int)FI.getType()->getScalarSizeInBits() <=
1288 OpI->getType()->getFPMantissaWidth())
1289 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1290
1291 return commonCastTransforms(FI);
1292}
1293
1294Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1295 return commonCastTransforms(CI);
1296}
1297
1298Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1299 return commonCastTransforms(CI);
1300}
1301
Chris Lattner80f43d32010-01-04 07:53:58 +00001302Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001303 // If the source integer type is not the intptr_t type for this target, do a
1304 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1305 // cast to be exposed to other transforms.
1306 if (TD) {
1307 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1308 TD->getPointerSizeInBits()) {
1309 Value *P = Builder->CreateTrunc(CI.getOperand(0),
Benjamin Kramera9390a42011-09-27 20:39:19 +00001310 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001311 return new IntToPtrInst(P, CI.getType());
1312 }
1313 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1314 TD->getPointerSizeInBits()) {
1315 Value *P = Builder->CreateZExt(CI.getOperand(0),
Benjamin Kramera9390a42011-09-27 20:39:19 +00001316 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001317 return new IntToPtrInst(P, CI.getType());
1318 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001319 }
1320
1321 if (Instruction *I = commonCastTransforms(CI))
1322 return I;
1323
1324 return 0;
1325}
1326
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001327/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1328Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1329 Value *Src = CI.getOperand(0);
1330
1331 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1332 // If casting the result of a getelementptr instruction with no offset, turn
1333 // this into a cast of the original pointer!
1334 if (GEP->hasAllZeroIndices()) {
1335 // Changing the cast operand is usually not a good idea but it is safe
1336 // here because the pointer operand is being replaced with another
1337 // pointer operand so the opcode doesn't need to change.
1338 Worklist.Add(GEP);
1339 CI.setOperand(0, GEP->getOperand(0));
1340 return &CI;
1341 }
1342
1343 // If the GEP has a single use, and the base pointer is a bitcast, and the
1344 // GEP computes a constant offset, see if we can convert these three
1345 // instructions into fewer. This typically happens with unions and other
1346 // non-type-safe code.
1347 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1348 GEP->hasAllConstantIndices()) {
1349 // We are guaranteed to get a constant from EmitGEPOffset.
1350 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1351 int64_t Offset = OffsetV->getSExtValue();
1352
1353 // Get the base pointer input of the bitcast, and the type it points to.
1354 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001355 Type *GEPIdxTy =
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001356 cast<PointerType>(OrigBase->getType())->getElementType();
1357 SmallVector<Value*, 8> NewIndices;
1358 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1359 // If we were able to index down into an element, create the GEP
1360 // and bitcast the result. This eliminates one bitcast, potentially
1361 // two.
1362 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001363 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1364 Builder->CreateGEP(OrigBase, NewIndices);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001365 NGEP->takeName(GEP);
1366
1367 if (isa<BitCastInst>(CI))
1368 return new BitCastInst(NGEP, CI.getType());
1369 assert(isa<PtrToIntInst>(CI));
1370 return new PtrToIntInst(NGEP, CI.getType());
1371 }
1372 }
1373 }
1374
1375 return commonCastTransforms(CI);
1376}
1377
1378Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001379 // If the destination integer type is not the intptr_t type for this target,
1380 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1381 // to be exposed to other transforms.
1382 if (TD) {
1383 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1384 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
Benjamin Kramera9390a42011-09-27 20:39:19 +00001385 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001386 return new TruncInst(P, CI.getType());
1387 }
1388 if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1389 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
Benjamin Kramera9390a42011-09-27 20:39:19 +00001390 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001391 return new ZExtInst(P, CI.getType());
1392 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001393 }
1394
1395 return commonPointerCastTransforms(CI);
1396}
1397
Chris Lattner67451912010-05-08 21:50:26 +00001398/// OptimizeVectorResize - This input value (which is known to have vector type)
1399/// is being zero extended or truncated to the specified vector type. Try to
1400/// replace it with a shuffle (and vector/vector bitcast) if possible.
1401///
1402/// The source and destination vector types may have different element types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001403static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
Chris Lattner67451912010-05-08 21:50:26 +00001404 InstCombiner &IC) {
1405 // We can only do this optimization if the output is a multiple of the input
1406 // element size, or the input is a multiple of the output element size.
1407 // Convert the input type to have the same element type as the output.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001408 VectorType *SrcTy = cast<VectorType>(InVal->getType());
Chris Lattner67451912010-05-08 21:50:26 +00001409
1410 if (SrcTy->getElementType() != DestTy->getElementType()) {
1411 // The input types don't need to be identical, but for now they must be the
1412 // same size. There is no specific reason we couldn't handle things like
1413 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1414 // there yet.
1415 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1416 DestTy->getElementType()->getPrimitiveSizeInBits())
1417 return 0;
1418
1419 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1420 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1421 }
1422
1423 // Now that the element types match, get the shuffle mask and RHS of the
1424 // shuffle to use, which depends on whether we're increasing or decreasing the
1425 // size of the input.
1426 SmallVector<Constant*, 16> ShuffleMask;
1427 Value *V2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001428 IntegerType *Int32Ty = Type::getInt32Ty(SrcTy->getContext());
Chris Lattner67451912010-05-08 21:50:26 +00001429
1430 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1431 // If we're shrinking the number of elements, just shuffle in the low
1432 // elements from the input and use undef as the second shuffle input.
1433 V2 = UndefValue::get(SrcTy);
1434 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1435 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1436
1437 } else {
1438 // If we're increasing the number of elements, shuffle in all of the
1439 // elements from InVal and fill the rest of the result elements with zeros
1440 // from a constant zero.
1441 V2 = Constant::getNullValue(SrcTy);
1442 unsigned SrcElts = SrcTy->getNumElements();
1443 for (unsigned i = 0, e = SrcElts; i != e; ++i)
1444 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1445
1446 // The excess elements reference the first element of the zero input.
1447 ShuffleMask.append(DestTy->getNumElements()-SrcElts,
1448 ConstantInt::get(Int32Ty, SrcElts));
1449 }
1450
Chris Lattner2ca5c862011-02-15 00:14:00 +00001451 return new ShuffleVectorInst(InVal, V2, ConstantVector::get(ShuffleMask));
Chris Lattner67451912010-05-08 21:50:26 +00001452}
1453
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001454static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001455 return Value % Ty->getPrimitiveSizeInBits() == 0;
1456}
1457
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001458static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001459 return Value / Ty->getPrimitiveSizeInBits();
1460}
1461
1462/// CollectInsertionElements - V is a value which is inserted into a vector of
1463/// VecEltTy. Look through the value to see if we can decompose it into
1464/// insertions into the vector. See the example in the comment for
1465/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1466/// The type of V is always a non-zero multiple of VecEltTy's size.
1467///
1468/// This returns false if the pattern can't be matched or true if it can,
1469/// filling in Elements with the elements found here.
1470static bool CollectInsertionElements(Value *V, unsigned ElementIndex,
1471 SmallVectorImpl<Value*> &Elements,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001472 Type *VecEltTy) {
Chris Lattner157d4ea2010-08-28 03:36:51 +00001473 // Undef values never contribute useful bits to the result.
1474 if (isa<UndefValue>(V)) return true;
1475
Chris Lattner3dd08732010-08-28 01:20:38 +00001476 // If we got down to a value of the right type, we win, try inserting into the
1477 // right element.
1478 if (V->getType() == VecEltTy) {
Chris Lattner79007792010-08-28 01:50:57 +00001479 // Inserting null doesn't actually insert any elements.
1480 if (Constant *C = dyn_cast<Constant>(V))
1481 if (C->isNullValue())
1482 return true;
1483
Chris Lattner3dd08732010-08-28 01:20:38 +00001484 // Fail if multiple elements are inserted into this slot.
1485 if (ElementIndex >= Elements.size() || Elements[ElementIndex] != 0)
1486 return false;
1487
1488 Elements[ElementIndex] = V;
1489 return true;
1490 }
1491
Chris Lattner79007792010-08-28 01:50:57 +00001492 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001493 // Figure out the # elements this provides, and bitcast it or slice it up
1494 // as required.
Chris Lattner79007792010-08-28 01:50:57 +00001495 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1496 VecEltTy);
1497 // If the constant is the size of a vector element, we just need to bitcast
1498 // it to the right type so it gets properly inserted.
1499 if (NumElts == 1)
1500 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1501 ElementIndex, Elements, VecEltTy);
1502
1503 // Okay, this is a constant that covers multiple elements. Slice it up into
1504 // pieces and insert each element-sized piece into the vector.
1505 if (!isa<IntegerType>(C->getType()))
1506 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1507 C->getType()->getPrimitiveSizeInBits()));
1508 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001509 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
Chris Lattner79007792010-08-28 01:50:57 +00001510
1511 for (unsigned i = 0; i != NumElts; ++i) {
1512 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1513 i*ElementSize));
1514 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1515 if (!CollectInsertionElements(Piece, ElementIndex+i, Elements, VecEltTy))
1516 return false;
1517 }
1518 return true;
1519 }
Chris Lattner3dd08732010-08-28 01:20:38 +00001520
1521 if (!V->hasOneUse()) return false;
1522
1523 Instruction *I = dyn_cast<Instruction>(V);
1524 if (I == 0) return false;
1525 switch (I->getOpcode()) {
1526 default: return false; // Unhandled case.
1527 case Instruction::BitCast:
1528 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1529 Elements, VecEltTy);
1530 case Instruction::ZExt:
1531 if (!isMultipleOfTypeSize(
1532 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1533 VecEltTy))
1534 return false;
1535 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1536 Elements, VecEltTy);
1537 case Instruction::Or:
1538 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1539 Elements, VecEltTy) &&
1540 CollectInsertionElements(I->getOperand(1), ElementIndex,
1541 Elements, VecEltTy);
1542 case Instruction::Shl: {
1543 // Must be shifting by a constant that is a multiple of the element size.
1544 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1545 if (CI == 0) return false;
1546 if (!isMultipleOfTypeSize(CI->getZExtValue(), VecEltTy)) return false;
1547 unsigned IndexShift = getTypeSizeIndex(CI->getZExtValue(), VecEltTy);
1548
1549 return CollectInsertionElements(I->getOperand(0), ElementIndex+IndexShift,
1550 Elements, VecEltTy);
1551 }
1552
1553 }
1554}
1555
1556
1557/// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1558/// may be doing shifts and ors to assemble the elements of the vector manually.
1559/// Try to rip the code out and replace it with insertelements. This is to
1560/// optimize code like this:
1561///
1562/// %tmp37 = bitcast float %inc to i32
1563/// %tmp38 = zext i32 %tmp37 to i64
1564/// %tmp31 = bitcast float %inc5 to i32
1565/// %tmp32 = zext i32 %tmp31 to i64
1566/// %tmp33 = shl i64 %tmp32, 32
1567/// %ins35 = or i64 %tmp33, %tmp38
1568/// %tmp43 = bitcast i64 %ins35 to <2 x float>
1569///
1570/// Into two insertelements that do "buildvector{%inc, %inc5}".
1571static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1572 InstCombiner &IC) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001573 VectorType *DestVecTy = cast<VectorType>(CI.getType());
Chris Lattner3dd08732010-08-28 01:20:38 +00001574 Value *IntInput = CI.getOperand(0);
1575
1576 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1577 if (!CollectInsertionElements(IntInput, 0, Elements,
1578 DestVecTy->getElementType()))
1579 return 0;
1580
1581 // If we succeeded, we know that all of the element are specified by Elements
1582 // or are zero if Elements has a null entry. Recast this as a set of
1583 // insertions.
1584 Value *Result = Constant::getNullValue(CI.getType());
1585 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1586 if (Elements[i] == 0) continue; // Unset element.
1587
1588 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1589 IC.Builder->getInt32(i));
1590 }
1591
1592 return Result;
1593}
1594
1595
Chris Lattnere5a14262010-08-26 21:55:42 +00001596/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1597/// bitcast. The various long double bitcasts can't get in here.
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001598static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
Chris Lattnere5a14262010-08-26 21:55:42 +00001599 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001600 Type *DestTy = CI.getType();
Chris Lattnere5a14262010-08-26 21:55:42 +00001601
1602 // If this is a bitcast from int to float, check to see if the int is an
1603 // extraction from a vector.
1604 Value *VecInput = 0;
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001605 // bitcast(trunc(bitcast(somevector)))
Chris Lattnere5a14262010-08-26 21:55:42 +00001606 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1607 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001608 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001609 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1610
1611 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1612 // If the element type of the vector doesn't match the result type,
1613 // bitcast it to be a vector type we can extract from.
1614 if (VecTy->getElementType() != DestTy) {
1615 VecTy = VectorType::get(DestTy,
1616 VecTy->getPrimitiveSizeInBits() / DestWidth);
1617 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1618 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001619
Chris Lattnere5a14262010-08-26 21:55:42 +00001620 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001621 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001622 }
1623
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001624 // bitcast(trunc(lshr(bitcast(somevector), cst))
1625 ConstantInt *ShAmt = 0;
1626 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1627 m_ConstantInt(ShAmt)))) &&
1628 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001629 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001630 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1631 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1632 ShAmt->getZExtValue() % DestWidth == 0) {
1633 // If the element type of the vector doesn't match the result type,
1634 // bitcast it to be a vector type we can extract from.
1635 if (VecTy->getElementType() != DestTy) {
1636 VecTy = VectorType::get(DestTy,
1637 VecTy->getPrimitiveSizeInBits() / DestWidth);
1638 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1639 }
1640
1641 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1642 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1643 }
1644 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001645 return 0;
1646}
Chris Lattner67451912010-05-08 21:50:26 +00001647
Chris Lattner80f43d32010-01-04 07:53:58 +00001648Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1649 // If the operands are integer typed then apply the integer transforms,
1650 // otherwise just apply the common ones.
1651 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001652 Type *SrcTy = Src->getType();
1653 Type *DestTy = CI.getType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001654
Chris Lattner80f43d32010-01-04 07:53:58 +00001655 // Get rid of casts from one type to the same type. These are useless and can
1656 // be replaced by the operand.
1657 if (DestTy == Src->getType())
1658 return ReplaceInstUsesWith(CI, Src);
1659
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001660 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1661 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1662 Type *DstElTy = DstPTy->getElementType();
1663 Type *SrcElTy = SrcPTy->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001664
1665 // If the address spaces don't match, don't eliminate the bitcast, which is
1666 // required for changing types.
1667 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1668 return 0;
1669
1670 // If we are casting a alloca to a pointer to a type of the same
1671 // size, rewrite the allocation instruction to allocate the "right" type.
1672 // There is no need to modify malloc calls because it is their bitcast that
1673 // needs to be cleaned up.
1674 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1675 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1676 return V;
1677
1678 // If the source and destination are pointers, and this cast is equivalent
1679 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1680 // This can enhance SROA and other transforms that want type-safe pointers.
1681 Constant *ZeroUInt =
1682 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1683 unsigned NumZeros = 0;
1684 while (SrcElTy != DstElTy &&
Duncan Sands1df98592010-02-16 11:11:14 +00001685 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner80f43d32010-01-04 07:53:58 +00001686 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1687 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1688 ++NumZeros;
1689 }
1690
1691 // If we found a path from the src to dest, create the getelementptr now.
1692 if (SrcElTy == DstElTy) {
1693 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Jay Foada9203102011-07-25 09:48:08 +00001694 return GetElementPtrInst::CreateInBounds(Src, Idxs);
Chris Lattner80f43d32010-01-04 07:53:58 +00001695 }
1696 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001697
1698 // Try to optimize int -> float bitcasts.
1699 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1700 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1701 return I;
Chris Lattner80f43d32010-01-04 07:53:58 +00001702
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001703 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001704 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001705 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1706 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001707 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001708 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1709 }
Chris Lattner67451912010-05-08 21:50:26 +00001710
Chris Lattner3dd08732010-08-28 01:20:38 +00001711 if (isa<IntegerType>(SrcTy)) {
1712 // If this is a cast from an integer to vector, check to see if the input
1713 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1714 // the casts with a shuffle and (potentially) a bitcast.
1715 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1716 CastInst *SrcCast = cast<CastInst>(Src);
1717 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1718 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1719 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
Chris Lattner67451912010-05-08 21:50:26 +00001720 cast<VectorType>(DestTy), *this))
Chris Lattner3dd08732010-08-28 01:20:38 +00001721 return I;
1722 }
1723
1724 // If the input is an 'or' instruction, we may be doing shifts and ors to
1725 // assemble the elements of the vector manually. Try to rip the code out
1726 // and replace it with insertelements.
1727 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1728 return ReplaceInstUsesWith(CI, V);
Chris Lattner67451912010-05-08 21:50:26 +00001729 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001730 }
1731
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001732 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001733 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001734 Value *Elem =
1735 Builder->CreateExtractElement(Src,
1736 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1737 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001738 }
1739 }
1740
1741 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001742 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmana5ced592010-04-07 23:22:42 +00001743 // a bitcast to a vector with the same # elts.
Duncan Sands1df98592010-02-16 11:11:14 +00001744 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001745 cast<VectorType>(DestTy)->getNumElements() ==
1746 SVI->getType()->getNumElements() &&
1747 SVI->getType()->getNumElements() ==
1748 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1749 BitCastInst *Tmp;
1750 // If either of the operands is a cast from CI.getType(), then
1751 // evaluating the shuffle in the casted destination's type will allow
1752 // us to eliminate at least one cast.
1753 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1754 Tmp->getOperand(0)->getType() == DestTy) ||
1755 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1756 Tmp->getOperand(0)->getType() == DestTy)) {
1757 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1758 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1759 // Return a new shuffle vector. Use the same element ID's, as we
1760 // know the vector types match #elts.
1761 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001762 }
1763 }
1764 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001765
Duncan Sands1df98592010-02-16 11:11:14 +00001766 if (SrcTy->isPointerTy())
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001767 return commonPointerCastTransforms(CI);
1768 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001769}