blob: a1d6d29ecd420ab4fab8c4770713c563948c0fb7 [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"
15#include "llvm/Target/TargetData.h"
16#include "llvm/Support/PatternMatch.h"
17using namespace llvm;
18using namespace PatternMatch;
19
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000020/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
21/// expression. If so, decompose it, returning some value X, such that Val is
22/// X*Scale+Offset.
23///
24static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
25 int &Offset) {
Benjamin Kramer11acaa32010-01-05 20:07:06 +000026 assert(Val->getType()->isInteger(32) && "Unexpected allocation size type!");
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000027 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28 Offset = CI->getZExtValue();
29 Scale = 0;
30 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000031 }
32
33 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000034 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
35 if (I->getOpcode() == Instruction::Shl) {
36 // This is a value scaled by '1 << the shift amt'.
37 Scale = 1U << RHS->getZExtValue();
38 Offset = 0;
39 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000040 }
41
42 if (I->getOpcode() == Instruction::Mul) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000043 // This value is scaled by 'RHS'.
44 Scale = RHS->getZExtValue();
45 Offset = 0;
46 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000047 }
48
49 if (I->getOpcode() == Instruction::Add) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000050 // We have X+C. Check to see if we really have (X*C2)+C1,
51 // where C1 is divisible by C2.
52 unsigned SubScale;
53 Value *SubVal =
54 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
55 Offset += RHS->getZExtValue();
56 Scale = SubScale;
57 return SubVal;
58 }
59 }
60 }
61
62 // Otherwise, we can't look past this.
63 Scale = 1;
64 Offset = 0;
65 return Val;
66}
67
68/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
69/// try to eliminate the cast by moving the type information into the alloc.
70Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
71 AllocaInst &AI) {
72 // This requires TargetData to get the alloca alignment and size information.
73 if (!TD) return 0;
74
75 const PointerType *PTy = cast<PointerType>(CI.getType());
76
77 BuilderTy AllocaBuilder(*Builder);
78 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
79
80 // Get the type really allocated and the type casted to.
81 const Type *AllocElTy = AI.getAllocatedType();
82 const Type *CastElTy = PTy->getElementType();
83 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
84
85 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
86 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
87 if (CastElTyAlign < AllocElTyAlign) return 0;
88
89 // If the allocation has multiple uses, only promote it if we are strictly
90 // increasing the alignment of the resultant allocation. If we keep it the
91 // same, we open the door to infinite loops of various kinds. (A reference
92 // from a dbg.declare doesn't count as a use for this purpose.)
93 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
94 CastElTyAlign == AllocElTyAlign) return 0;
95
96 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
97 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
98 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
99
100 // See if we can satisfy the modulus by pulling a scale out of the array
101 // size argument.
102 unsigned ArraySizeScale;
103 int ArrayOffset;
104 Value *NumElements = // See if the array size is a decomposable linear expr.
105 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
106
107 // If we can now satisfy the modulus, by using a non-1 scale, we really can
108 // do the xform.
109 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
110 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
111
112 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
113 Value *Amt = 0;
114 if (Scale == 1) {
115 Amt = NumElements;
116 } else {
117 Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
118 // Insert before the alloca, not before the cast.
119 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
120 }
121
122 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
123 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
124 Offset, true);
125 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
126 }
127
128 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
129 New->setAlignment(AI.getAlignment());
130 New->takeName(&AI);
131
132 // If the allocation has one real use plus a dbg.declare, just remove the
133 // declare.
134 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
135 EraseInstFromFunction(*(Instruction*)DI);
136 }
137 // If the allocation has multiple real uses, insert a cast and change all
138 // things that used it to use the new cast. This will also hack on CI, but it
139 // will die soon.
140 else if (!AI.hasOneUse()) {
141 // New is the allocation instruction, pointer typed. AI is the original
142 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
143 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
144 AI.replaceAllUsesWith(NewCast);
145 }
146 return ReplaceInstUsesWith(CI, New);
147}
148
149
Chris Lattner14bf8f02010-01-08 19:19:23 +0000150/// CanEvaluateTruncated - Return true if we can evaluate the specified
151/// expression tree as type Ty instead of its larger type, and arrive with the
152/// same value. This is used by code that tries to eliminate truncates.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000153///
Chris Lattner14bf8f02010-01-08 19:19:23 +0000154/// Ty will always be a type smaller than V. We should return true if trunc(V)
155/// can be computed by computing V in the smaller type. If V is an instruction,
156/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
157/// makes sense if x and y can be efficiently truncated.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000158///
Chris Lattner14bf8f02010-01-08 19:19:23 +0000159static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
Chris Lattner5f0290e2010-01-04 07:54:59 +0000160 // We can always evaluate constants in another type.
161 if (isa<Constant>(V))
162 return true;
163
164 Instruction *I = dyn_cast<Instruction>(V);
165 if (!I) return false;
166
167 const Type *OrigTy = V->getType();
168
Chris Lattner14bf8f02010-01-08 19:19:23 +0000169 // If this is an extension from the dest type, we can eliminate it.
170 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
171 I->getOperand(0)->getType() == Ty)
172 return true;
Chris Lattner5f0290e2010-01-04 07:54:59 +0000173
174 // We can't extend or shrink something that has multiple uses: doing so would
175 // require duplicating the instruction in general, which isn't profitable.
176 if (!I->hasOneUse()) return false;
177
178 unsigned Opc = I->getOpcode();
179 switch (Opc) {
180 case Instruction::Add:
181 case Instruction::Sub:
182 case Instruction::Mul:
183 case Instruction::And:
184 case Instruction::Or:
185 case Instruction::Xor:
186 // These operators can all arbitrarily be extended or truncated.
Chris Lattner14bf8f02010-01-08 19:19:23 +0000187 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
188 CanEvaluateTruncated(I->getOperand(1), Ty);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000189
190 case Instruction::UDiv:
191 case Instruction::URem: {
192 // UDiv and URem can be truncated if all the truncated bits are zero.
193 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
194 uint32_t BitWidth = Ty->getScalarSizeInBits();
195 if (BitWidth < OrigBitWidth) {
196 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
197 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
198 MaskedValueIsZero(I->getOperand(1), Mask)) {
Chris Lattner14bf8f02010-01-08 19:19:23 +0000199 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
200 CanEvaluateTruncated(I->getOperand(1), Ty);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000201 }
202 }
203 break;
204 }
205 case Instruction::Shl:
206 // If we are truncating the result of this SHL, and if it's a shift of a
207 // constant amount, we can always perform a SHL in a smaller type.
208 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
209 uint32_t BitWidth = Ty->getScalarSizeInBits();
Chris Lattner14bf8f02010-01-08 19:19:23 +0000210 if (CI->getLimitedValue(BitWidth) < BitWidth)
211 return CanEvaluateTruncated(I->getOperand(0), Ty);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000212 }
213 break;
214 case Instruction::LShr:
215 // If this is a truncate of a logical shr, we can truncate it to a smaller
216 // lshr iff we know that the bits we would otherwise be shifting in are
217 // already zeros.
218 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
219 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
220 uint32_t BitWidth = Ty->getScalarSizeInBits();
Chris Lattner14bf8f02010-01-08 19:19:23 +0000221 if (MaskedValueIsZero(I->getOperand(0),
Chris Lattner5f0290e2010-01-04 07:54:59 +0000222 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
223 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner14bf8f02010-01-08 19:19:23 +0000224 return CanEvaluateTruncated(I->getOperand(0), Ty);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000225 }
226 }
227 break;
Chris Lattner5f0290e2010-01-04 07:54:59 +0000228 case Instruction::Trunc:
Chris Lattner14bf8f02010-01-08 19:19:23 +0000229 // trunc(trunc(x)) -> trunc(x)
230 return true;
Chris Lattner5f0290e2010-01-04 07:54:59 +0000231 case Instruction::Select: {
232 SelectInst *SI = cast<SelectInst>(I);
Chris Lattner14bf8f02010-01-08 19:19:23 +0000233 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
234 CanEvaluateTruncated(SI->getFalseValue(), Ty);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000235 }
236 case Instruction::PHI: {
Chris Lattner94aab492010-01-05 22:30:42 +0000237 // We can change a phi if we can change all operands. Note that we never
238 // get into trouble with cyclic PHIs here because we only consider
239 // instructions with a single use.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000240 PHINode *PN = cast<PHINode>(I);
241 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner14bf8f02010-01-08 19:19:23 +0000242 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
Chris Lattner5f0290e2010-01-04 07:54:59 +0000243 return false;
244 return true;
245 }
246 default:
247 // TODO: Can handle more cases here.
248 break;
249 }
250
251 return false;
252}
253
Chris Lattner075f6922010-01-07 23:41:00 +0000254/// GetLeadingZeros - Compute the number of known-zero leading bits.
255static unsigned GetLeadingZeros(Value *V, const TargetData *TD) {
256 unsigned Bits = V->getType()->getScalarSizeInBits();
257 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
258 ComputeMaskedBits(V, APInt::getAllOnesValue(Bits), KnownZero, KnownOne, TD);
259 return KnownZero.countLeadingOnes();
260}
261
262/// CanEvaluateZExtd - Determine if the specified value can be computed in the
263/// specified wider type and produce the same low bits. If not, return -1. If
264/// it is possible, return the number of high bits that are known to be zero in
265/// the promoted value.
266static int CanEvaluateZExtd(Value *V, const Type *Ty,unsigned &NumCastsRemoved,
267 const TargetData *TD) {
268 const Type *OrigTy = V->getType();
269
270 if (isa<Constant>(V)) {
271 unsigned Extended = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
272
273 // Constants can always be zero ext'd, even if it requires a ConstantExpr.
274 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
275 return Extended + CI->getValue().countLeadingZeros();
276 return Extended;
277 }
278
279 Instruction *I = dyn_cast<Instruction>(V);
280 if (!I) return -1;
281
282 // If the input is a truncate from the destination type, we can trivially
283 // eliminate it, and this will remove a cast overall.
284 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty) {
285 // If the first operand is itself a cast, and is eliminable, do not count
286 // this as an eliminable cast. We would prefer to eliminate those two
287 // casts first.
288 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
289 ++NumCastsRemoved;
290
291 // Figure out the number of known-zero bits coming in.
292 return GetLeadingZeros(I->getOperand(0), TD);
293 }
294
295 // We can't extend or shrink something that has multiple uses: doing so would
296 // require duplicating the instruction in general, which isn't profitable.
297 if (!I->hasOneUse()) return -1;
298
299 int Tmp1, Tmp2;
300 unsigned Opc = I->getOpcode();
301 switch (Opc) {
302 case Instruction::And:
303 Tmp1 = CanEvaluateZExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
304 if (Tmp1 == -1) return -1;
305 Tmp2 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
306 if (Tmp2 == -1) return -1;
307 return std::max(Tmp1, Tmp2);
308 case Instruction::Or:
309 case Instruction::Xor:
310 Tmp1 = CanEvaluateZExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
311 if (Tmp1 == -1) return -1;
312 Tmp2 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
313 return std::min(Tmp1, Tmp2);
314
315 case Instruction::Add:
316 case Instruction::Sub:
317 case Instruction::Mul:
318 Tmp1 = CanEvaluateZExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
319 if (Tmp1 == -1) return -1;
320 Tmp2 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
321 if (Tmp2 == -1) return -1;
322 return 0;
323
324 //case Instruction::Shl:
325 //case Instruction::LShr:
326 case Instruction::ZExt:
327 // zext(zext(x)) -> zext(x). Since we're replacing it, it isn't eliminated.
328 Tmp1 = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
329 return GetLeadingZeros(I, TD)+Tmp1;
330
331 //case Instruction::SExt: zext(sext(x)) -> sext(x) with no upper bits known.
332 //case Instruction::Trunc:
333 case Instruction::Select:
334 Tmp1 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
335 if (Tmp1 == -1) return -1;
336 Tmp2 = CanEvaluateZExtd(I->getOperand(2), Ty, NumCastsRemoved, TD);
337 return std::min(Tmp1, Tmp2);
338
339 case Instruction::PHI: {
340 // We can change a phi if we can change all operands. Note that we never
341 // get into trouble with cyclic PHIs here because we only consider
342 // instructions with a single use.
343 PHINode *PN = cast<PHINode>(I);
344 int Result = CanEvaluateZExtd(PN->getIncomingValue(0), Ty,
345 NumCastsRemoved, TD);
346 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
347 if (Result == -1) return -1;
348 Tmp1 = CanEvaluateZExtd(PN->getIncomingValue(i), Ty, NumCastsRemoved, TD);
349 Result = std::min(Result, Tmp1);
350 }
351 return Result;
352 }
353 default:
354 // TODO: Can handle more cases here.
355 return -1;
356 }
357}
358
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000359/// CanEvaluateSExtd - Return true if we can take the specified value
360/// and return it as type Ty without inserting any new casts and without
Chris Lattner5c24a6d2010-01-06 05:32:15 +0000361/// changing the value of the common low bits. This is used by code that tries
362/// to promote integer operations to a wider types will allow us to eliminate
363/// the extension.
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000364///
365/// This returns 0 if we can't do this or the number of sign bits that would be
366/// set if we can. For example, CanEvaluateSExtd(i16 1, i64) would return 63,
367/// because the computation can be extended (to "i64 1") and the resulting
368/// computation has 63 equal sign bits.
369///
370/// This function works on both vectors and scalars. For vectors, the result is
371/// the number of bits known sign extended in each element.
372///
373static unsigned CanEvaluateSExtd(Value *V, const Type *Ty,
374 unsigned &NumCastsRemoved, TargetData *TD) {
375 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
376 "Can't sign extend type to a smaller type");
377 // If this is a constant, return the number of sign bits the extended version
378 // of it would have.
379 if (Constant *C = dyn_cast<Constant>(V))
380 return ComputeNumSignBits(ConstantExpr::getSExt(C, Ty), TD);
381
382 Instruction *I = dyn_cast<Instruction>(V);
383 if (!I) return 0;
384
385 // If this is a truncate from the destination type, we can trivially eliminate
386 // it, and this will remove a cast overall.
387 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty) {
388 // If the operand of the truncate is itself a cast, and is eliminable, do
389 // not count this as an eliminable cast. We would prefer to eliminate those
390 // two casts first.
391 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
392 ++NumCastsRemoved;
393 return ComputeNumSignBits(I->getOperand(0), TD);
394 }
395
396 // We can't extend or shrink something that has multiple uses: doing so would
397 // require duplicating the instruction in general, which isn't profitable.
398 if (!I->hasOneUse()) return 0;
399
400 const Type *OrigTy = V->getType();
401
402 unsigned Opc = I->getOpcode();
403 unsigned Tmp1, Tmp2;
404 switch (Opc) {
405 case Instruction::And:
406 case Instruction::Or:
407 case Instruction::Xor:
408 // These operators can all arbitrarily be extended or truncated.
409 Tmp1 = CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
410 if (Tmp1 == 0) return 0;
411 Tmp2 = CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
412 return std::min(Tmp1, Tmp2);
413 case Instruction::Add:
414 case Instruction::Sub:
415 // Add/Sub can have at most one carry/borrow bit.
416 Tmp1 = CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
417 if (Tmp1 == 0) return 0;
418 Tmp2 = CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
419 if (Tmp2 == 0) return 0;
420 return std::min(Tmp1, Tmp2)-1;
421 case Instruction::Mul:
422 // These operators can all arbitrarily be extended or truncated.
423 if (!CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD))
424 return 0;
425 if (!CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD))
426 return 0;
427 return 1; // IMPROVE?
428
429 //case Instruction::Shl: TODO
430 //case Instruction::LShr: TODO
431 //case Instruction::Trunc: TODO
432
433 case Instruction::SExt:
434 case Instruction::ZExt: {
435 // sext(sext(x)) -> sext(x)
436 // sext(zext(x)) -> zext(x)
437 // Note that replacing a cast does not reduce the number of casts in the
438 // input.
439 unsigned InSignBits = ComputeNumSignBits(I, TD);
440 unsigned ExtBits = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
441 // We'll end up extending it all the way out.
442 return InSignBits+ExtBits;
443 }
444 case Instruction::Select: {
445 SelectInst *SI = cast<SelectInst>(I);
446 Tmp1 = CanEvaluateSExtd(SI->getTrueValue(), Ty, NumCastsRemoved, TD);
447 if (Tmp1 == 0) return 0;
448 Tmp2 = CanEvaluateSExtd(SI->getFalseValue(), Ty, NumCastsRemoved,TD);
449 return std::min(Tmp1, Tmp2);
450 }
451 case Instruction::PHI: {
452 // We can change a phi if we can change all operands. Note that we never
453 // get into trouble with cyclic PHIs here because we only consider
454 // instructions with a single use.
455 PHINode *PN = cast<PHINode>(I);
456 unsigned Result = ~0U;
457 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
458 Result = std::min(Result,
459 CanEvaluateSExtd(PN->getIncomingValue(i), Ty,
460 NumCastsRemoved, TD));
461 if (Result == 0) return 0;
462 }
463 return Result;
464 }
465 default:
466 // TODO: Can handle more cases here.
467 break;
468 }
469
470 return 0;
471}
472
473
Chris Lattner5f0290e2010-01-04 07:54:59 +0000474/// EvaluateInDifferentType - Given an expression that
Chris Lattner14bf8f02010-01-08 19:19:23 +0000475/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000476/// insert the code to evaluate the expression.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000477Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
478 bool isSigned) {
Chris Lattner14bf8f02010-01-08 19:19:23 +0000479 // FIXME: use libanalysis constant folding.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000480 if (Constant *C = dyn_cast<Constant>(V))
481 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
482
483 // Otherwise, it must be an instruction.
484 Instruction *I = cast<Instruction>(V);
485 Instruction *Res = 0;
486 unsigned Opc = I->getOpcode();
487 switch (Opc) {
488 case Instruction::Add:
489 case Instruction::Sub:
490 case Instruction::Mul:
491 case Instruction::And:
492 case Instruction::Or:
493 case Instruction::Xor:
494 case Instruction::AShr:
495 case Instruction::LShr:
496 case Instruction::Shl:
497 case Instruction::UDiv:
498 case Instruction::URem: {
499 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
500 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
501 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
502 break;
503 }
504 case Instruction::Trunc:
505 case Instruction::ZExt:
506 case Instruction::SExt:
507 // If the source type of the cast is the type we're trying for then we can
508 // just return the source. There's no need to insert it because it is not
509 // new.
510 if (I->getOperand(0)->getType() == Ty)
511 return I->getOperand(0);
512
513 // Otherwise, must be the same type of cast, so just reinsert a new one.
514 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
515 break;
516 case Instruction::Select: {
517 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
518 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
519 Res = SelectInst::Create(I->getOperand(0), True, False);
520 break;
521 }
522 case Instruction::PHI: {
523 PHINode *OPN = cast<PHINode>(I);
524 PHINode *NPN = PHINode::Create(Ty);
525 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
526 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
527 NPN->addIncoming(V, OPN->getIncomingBlock(i));
528 }
529 Res = NPN;
530 break;
531 }
532 default:
533 // TODO: Can handle more cases here.
534 llvm_unreachable("Unreachable!");
535 break;
536 }
537
538 Res->takeName(I);
539 return InsertNewInstBefore(Res, *I);
540}
Chris Lattner80f43d32010-01-04 07:53:58 +0000541
542
543/// This function is a wrapper around CastInst::isEliminableCastPair. It
544/// simply extracts arguments and returns what that function returns.
545static Instruction::CastOps
546isEliminableCastPair(
547 const CastInst *CI, ///< The first cast instruction
548 unsigned opcode, ///< The opcode of the second cast instruction
549 const Type *DstTy, ///< The target type for the second cast instruction
550 TargetData *TD ///< The target data for pointer size
551) {
552
553 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
554 const Type *MidTy = CI->getType(); // B from above
555
556 // Get the opcodes of the two Cast instructions
557 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
558 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
559
560 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
561 DstTy,
562 TD ? TD->getIntPtrType(CI->getContext()) : 0);
563
564 // We don't want to form an inttoptr or ptrtoint that converts to an integer
565 // type that differs from the pointer size.
566 if ((Res == Instruction::IntToPtr &&
567 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
568 (Res == Instruction::PtrToInt &&
569 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
570 Res = 0;
571
572 return Instruction::CastOps(Res);
573}
574
575/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
576/// in any code being generated. It does not require codegen if V is simple
577/// enough or if the cast can be folded into other casts.
578bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
579 const Type *Ty) {
580 if (V->getType() == Ty || isa<Constant>(V)) return false;
581
582 // If this is another cast that can be eliminated, it isn't codegen either.
583 if (const CastInst *CI = dyn_cast<CastInst>(V))
584 if (isEliminableCastPair(CI, opcode, Ty, TD))
585 return false;
586 return true;
587}
588
589
590/// @brief Implement the transforms common to all CastInst visitors.
591Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
592 Value *Src = CI.getOperand(0);
593
594 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
595 // eliminate it now.
596 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
597 if (Instruction::CastOps opc =
598 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
599 // The first cast (CSrc) is eliminable so we need to fix up or replace
600 // the second cast (CI). CSrc will then have a good chance of being dead.
601 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
602 }
603 }
604
605 // If we are casting a select then fold the cast into the select
606 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
607 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
608 return NV;
609
610 // If we are casting a PHI then fold the cast into the PHI
611 if (isa<PHINode>(Src)) {
612 // We don't do this if this would create a PHI node with an illegal type if
613 // it is currently legal.
614 if (!isa<IntegerType>(Src->getType()) ||
615 !isa<IntegerType>(CI.getType()) ||
616 ShouldChangeType(CI.getType(), Src->getType()))
617 if (Instruction *NV = FoldOpIntoPhi(CI))
618 return NV;
619 }
620
621 return 0;
622}
623
Chris Lattner80f43d32010-01-04 07:53:58 +0000624/// commonIntCastTransforms - This function implements the common transforms
625/// for trunc, zext, and sext.
626Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
627 if (Instruction *Result = commonCastTransforms(CI))
628 return Result;
629
Chris Lattner80f43d32010-01-04 07:53:58 +0000630 // See if we can simplify any instructions used by the LHS whose sole
631 // purpose is to compute bits we don't care about.
632 if (SimplifyDemandedInstructionBits(CI))
633 return &CI;
Chris Lattner274ad682010-01-05 22:07:33 +0000634
Chris Lattner80f43d32010-01-04 07:53:58 +0000635 // If the source isn't an instruction or has more than one use then we
636 // can't do anything more.
Chris Lattner274ad682010-01-05 22:07:33 +0000637 Instruction *Src = dyn_cast<Instruction>(CI.getOperand(0));
638 if (!Src || !Src->hasOneUse())
Chris Lattner80f43d32010-01-04 07:53:58 +0000639 return 0;
Chris Lattner68c6e892010-01-05 23:00:30 +0000640
641 // Check to see if we can eliminate the cast by changing the entire
642 // computation chain to do the computation in the result type.
Chris Lattner274ad682010-01-05 22:07:33 +0000643 const Type *SrcTy = Src->getType();
644 const Type *DestTy = CI.getType();
Chris Lattner68c6e892010-01-05 23:00:30 +0000645
Chris Lattner80f43d32010-01-04 07:53:58 +0000646 // Only do this if the dest type is a simple type, don't convert the
647 // expression tree to something weird like i93 unless the source is also
648 // strange.
Chris Lattner68c6e892010-01-05 23:00:30 +0000649 if (!isa<VectorType>(DestTy) && !ShouldChangeType(SrcTy, DestTy))
650 return 0;
651
Chris Lattner075f6922010-01-07 23:41:00 +0000652 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
653 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
654
Chris Lattner68c6e892010-01-05 23:00:30 +0000655 // Attempt to propagate the cast into the instruction for int->int casts.
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000656 unsigned NumCastsRemoved = 0;
Chris Lattner68c6e892010-01-05 23:00:30 +0000657 switch (CI.getOpcode()) {
658 default: assert(0 && "not an integer cast");
Chris Lattner075f6922010-01-07 23:41:00 +0000659 case Instruction::Trunc: {
Chris Lattner14bf8f02010-01-08 19:19:23 +0000660 if (!CanEvaluateTruncated(Src, DestTy))
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000661 return 0;
662
Chris Lattner80f43d32010-01-04 07:53:58 +0000663 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000664 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000665 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
666 " to avoid cast: " << CI);
667 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
668 assert(Res->getType() == DestTy);
669 return ReplaceInstUsesWith(CI, Res);
670 }
671 case Instruction::ZExt: {
672 int BitsZExt = CanEvaluateZExtd(Src, DestTy, NumCastsRemoved, TD);
673 if (BitsZExt == -1) return 0;
674
Chris Lattner68c6e892010-01-05 23:00:30 +0000675 // If this is a zero-extension, we need to do an AND to maintain the clear
Chris Lattner075f6922010-01-07 23:41:00 +0000676 // top-part of the computation. If we know the result will be zero
677 // extended enough already, we don't need the and.
678 if (NumCastsRemoved < 1 &&
679 unsigned(BitsZExt) < DestBitSize-SrcBitSize)
Chris Lattner68c6e892010-01-05 23:00:30 +0000680 return 0;
Chris Lattner075f6922010-01-07 23:41:00 +0000681
682 // Okay, we can transform this! Insert the new expression now.
683 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
684 " to avoid zero extend: " << CI);
685 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
686 assert(Res->getType() == DestTy);
687
688 // If the high bits are already filled with zeros, just replace this
689 // cast with the result.
690 if (unsigned(BitsZExt) >= DestBitSize-SrcBitSize ||
691 MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
692 DestBitSize-SrcBitSize)))
693 return ReplaceInstUsesWith(CI, Res);
694
695 // We need to emit an AND to clear the high bits.
696 Constant *C = ConstantInt::get(CI.getContext(),
697 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
698 return BinaryOperator::CreateAnd(Res, C);
699 }
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000700 case Instruction::SExt: {
701 // Check to see if we can do this transformation, and if so, how many bits
702 // of the promoted expression will be known copies of the sign bit in the
703 // result.
704 unsigned NumBitsSExt = CanEvaluateSExtd(Src, DestTy, NumCastsRemoved, TD);
705 if (NumBitsSExt == 0)
Chris Lattner68c6e892010-01-05 23:00:30 +0000706 return 0;
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000707
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000708 // Because this is a sign extension, we can always transform it by inserting
709 // two new shifts (to do the extension). However, this is only profitable
710 // if we've eliminated two or more casts from the input. If we know the
Chris Lattner5c24a6d2010-01-06 05:32:15 +0000711 // result will be sign-extended enough to not require these shifts, we can
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000712 // always do the transformation.
713 if (NumCastsRemoved < 2 &&
714 NumBitsSExt <= DestBitSize-SrcBitSize)
715 return 0;
716
717 // Okay, we can transform this! Insert the new expression now.
Chris Lattner5c24a6d2010-01-06 05:32:15 +0000718 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000719 " to avoid sign extend: " << CI);
720 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
721 assert(Res->getType() == DestTy);
722
723 // If the high bits are already filled with sign bit, just replace this
724 // cast with the result.
725 if (NumBitsSExt > DestBitSize - SrcBitSize ||
726 ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
727 return ReplaceInstUsesWith(CI, Res);
728
729 // We need to emit a cast to truncate, then a cast to sext.
730 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
731 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000732 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000733}
734
Chris Lattner80f43d32010-01-04 07:53:58 +0000735Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
736 if (Instruction *Result = commonIntCastTransforms(CI))
737 return Result;
738
739 Value *Src = CI.getOperand(0);
Chris Lattner49bdfef2010-01-05 21:11:17 +0000740 const Type *DestTy = CI.getType();
Chris Lattner80f43d32010-01-04 07:53:58 +0000741
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000742 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
743 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000744 Constant *One = ConstantInt::get(Src->getType(), 1);
745 Src = Builder->CreateAnd(Src, One, "tmp");
746 Value *Zero = Constant::getNullValue(Src->getType());
747 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
748 }
749
Chris Lattner80f43d32010-01-04 07:53:58 +0000750 return 0;
751}
752
753/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
754/// in order to eliminate the icmp.
755Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
756 bool DoXform) {
757 // If we are just checking for a icmp eq of a single bit and zext'ing it
758 // to an integer, then shift the bit to the appropriate place and then
759 // cast to integer to avoid the comparison.
760 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
761 const APInt &Op1CV = Op1C->getValue();
762
763 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
764 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
765 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
766 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
767 if (!DoXform) return ICI;
768
769 Value *In = ICI->getOperand(0);
770 Value *Sh = ConstantInt::get(In->getType(),
771 In->getType()->getScalarSizeInBits()-1);
772 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
773 if (In->getType() != CI.getType())
774 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
775
776 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
777 Constant *One = ConstantInt::get(In->getType(), 1);
778 In = Builder->CreateXor(In, One, In->getName()+".not");
779 }
780
781 return ReplaceInstUsesWith(CI, In);
782 }
783
784
785
786 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
787 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
788 // zext (X == 1) to i32 --> X iff X has only the low bit set.
789 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
790 // zext (X != 0) to i32 --> X iff X has only the low bit set.
791 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
792 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
793 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
794 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
795 // This only works for EQ and NE
796 ICI->isEquality()) {
797 // If Op1C some other power of two, convert:
798 uint32_t BitWidth = Op1C->getType()->getBitWidth();
799 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
800 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
801 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
802
803 APInt KnownZeroMask(~KnownZero);
804 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
805 if (!DoXform) return ICI;
806
807 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
808 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
809 // (X&4) == 2 --> false
810 // (X&4) != 2 --> true
811 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
812 isNE);
813 Res = ConstantExpr::getZExt(Res, CI.getType());
814 return ReplaceInstUsesWith(CI, Res);
815 }
816
817 uint32_t ShiftAmt = KnownZeroMask.logBase2();
818 Value *In = ICI->getOperand(0);
819 if (ShiftAmt) {
820 // Perform a logical shr by shiftamt.
821 // Insert the shift to put the result in the low bit.
822 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
823 In->getName()+".lobit");
824 }
825
826 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
827 Constant *One = ConstantInt::get(In->getType(), 1);
828 In = Builder->CreateXor(In, One, "tmp");
829 }
830
831 if (CI.getType() == In->getType())
832 return ReplaceInstUsesWith(CI, In);
833 else
834 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
835 }
836 }
837 }
838
839 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
840 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
841 // may lead to additional simplifications.
842 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
843 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
844 uint32_t BitWidth = ITy->getBitWidth();
845 Value *LHS = ICI->getOperand(0);
846 Value *RHS = ICI->getOperand(1);
847
848 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
849 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
850 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
851 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
852 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
853
854 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
855 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
856 APInt UnknownBit = ~KnownBits;
857 if (UnknownBit.countPopulation() == 1) {
858 if (!DoXform) return ICI;
859
860 Value *Result = Builder->CreateXor(LHS, RHS);
861
862 // Mask off any bits that are set and won't be shifted away.
863 if (KnownOneLHS.uge(UnknownBit))
864 Result = Builder->CreateAnd(Result,
865 ConstantInt::get(ITy, UnknownBit));
866
867 // Shift the bit we're testing down to the lsb.
868 Result = Builder->CreateLShr(
869 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
870
871 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
872 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
873 Result->takeName(ICI);
874 return ReplaceInstUsesWith(CI, Result);
875 }
876 }
877 }
878 }
879
880 return 0;
881}
882
883Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
884 // If one of the common conversion will work, do it.
885 if (Instruction *Result = commonIntCastTransforms(CI))
886 return Result;
887
888 Value *Src = CI.getOperand(0);
889
890 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
891 // types and if the sizes are just right we can convert this into a logical
892 // 'and' which will be much cheaper than the pair of casts.
893 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
894 // Get the sizes of the types involved. We know that the intermediate type
895 // will be smaller than A or C, but don't know the relation between A and C.
896 Value *A = CSrc->getOperand(0);
897 unsigned SrcSize = A->getType()->getScalarSizeInBits();
898 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
899 unsigned DstSize = CI.getType()->getScalarSizeInBits();
900 // If we're actually extending zero bits, then if
901 // SrcSize < DstSize: zext(a & mask)
902 // SrcSize == DstSize: a & mask
903 // SrcSize > DstSize: trunc(a) & mask
904 if (SrcSize < DstSize) {
905 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
906 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
907 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
908 return new ZExtInst(And, CI.getType());
909 }
910
911 if (SrcSize == DstSize) {
912 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
913 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
914 AndValue));
915 }
916 if (SrcSize > DstSize) {
917 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
918 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
919 return BinaryOperator::CreateAnd(Trunc,
920 ConstantInt::get(Trunc->getType(),
921 AndValue));
922 }
923 }
924
925 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
926 return transformZExtICmp(ICI, CI);
927
928 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
929 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
930 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
931 // of the (zext icmp) will be transformed.
932 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
933 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
934 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
935 (transformZExtICmp(LHS, CI, false) ||
936 transformZExtICmp(RHS, CI, false))) {
937 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
938 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
939 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
940 }
941 }
942
943 // zext(trunc(t) & C) -> (t & zext(C)).
944 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
945 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
946 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
947 Value *TI0 = TI->getOperand(0);
948 if (TI0->getType() == CI.getType())
949 return
950 BinaryOperator::CreateAnd(TI0,
951 ConstantExpr::getZExt(C, CI.getType()));
952 }
953
954 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
955 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
956 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
957 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
958 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
959 And->getOperand(1) == C)
960 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
961 Value *TI0 = TI->getOperand(0);
962 if (TI0->getType() == CI.getType()) {
963 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
964 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
965 return BinaryOperator::CreateXor(NewAnd, ZC);
966 }
967 }
968
Chris Lattner718bf3f2010-01-05 21:04:47 +0000969 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
970 Value *X;
Chris Lattner49bdfef2010-01-05 21:11:17 +0000971 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isInteger(1) &&
972 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +0000973 (!X->hasOneUse() || !isa<CmpInst>(X))) {
974 Value *New = Builder->CreateZExt(X, CI.getType());
975 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
976 }
977
Chris Lattner80f43d32010-01-04 07:53:58 +0000978 return 0;
979}
980
981Instruction *InstCombiner::visitSExt(SExtInst &CI) {
982 if (Instruction *I = commonIntCastTransforms(CI))
983 return I;
984
985 Value *Src = CI.getOperand(0);
986
987 // Canonicalize sign-extend from i1 to a select.
Benjamin Kramer11acaa32010-01-05 20:07:06 +0000988 if (Src->getType()->isInteger(1))
Chris Lattner80f43d32010-01-04 07:53:58 +0000989 return SelectInst::Create(Src,
990 Constant::getAllOnesValue(CI.getType()),
991 Constant::getNullValue(CI.getType()));
992
993 // See if the value being truncated is already sign extended. If so, just
994 // eliminate the trunc/sext pair.
995 if (Operator::getOpcode(Src) == Instruction::Trunc) {
996 Value *Op = cast<User>(Src)->getOperand(0);
997 unsigned OpBits = Op->getType()->getScalarSizeInBits();
998 unsigned MidBits = Src->getType()->getScalarSizeInBits();
999 unsigned DestBits = CI.getType()->getScalarSizeInBits();
1000 unsigned NumSignBits = ComputeNumSignBits(Op);
1001
1002 if (OpBits == DestBits) {
1003 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
1004 // bits, it is already ready.
1005 if (NumSignBits > DestBits-MidBits)
1006 return ReplaceInstUsesWith(CI, Op);
1007 } else if (OpBits < DestBits) {
1008 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
1009 // bits, just sext from i32.
1010 if (NumSignBits > OpBits-MidBits)
1011 return new SExtInst(Op, CI.getType(), "tmp");
1012 } else {
1013 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
1014 // bits, just truncate to i32.
1015 if (NumSignBits > OpBits-MidBits)
1016 return new TruncInst(Op, CI.getType(), "tmp");
1017 }
1018 }
1019
1020 // If the input is a shl/ashr pair of a same constant, then this is a sign
1021 // extension from a smaller value. If we could trust arbitrary bitwidth
1022 // integers, we could turn this into a truncate to the smaller bit and then
1023 // use a sext for the whole extension. Since we don't, look deeper and check
1024 // for a truncate. If the source and dest are the same type, eliminate the
1025 // trunc and extend and just do shifts. For example, turn:
1026 // %a = trunc i32 %i to i8
1027 // %b = shl i8 %a, 6
1028 // %c = ashr i8 %b, 6
1029 // %d = sext i8 %c to i32
1030 // into:
1031 // %a = shl i32 %i, 30
1032 // %d = ashr i32 %a, 30
1033 Value *A = 0;
1034 ConstantInt *BA = 0, *CA = 0;
1035 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
1036 m_ConstantInt(CA))) &&
1037 BA == CA && isa<TruncInst>(A)) {
1038 Value *I = cast<TruncInst>(A)->getOperand(0);
1039 if (I->getType() == CI.getType()) {
1040 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1041 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1042 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1043 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1044 I = Builder->CreateShl(I, ShAmtV, CI.getName());
1045 return BinaryOperator::CreateAShr(I, ShAmtV);
1046 }
1047 }
1048
1049 return 0;
1050}
1051
1052
1053/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1054/// in the specified FP type without changing its value.
1055static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1056 bool losesInfo;
1057 APFloat F = CFP->getValueAPF();
1058 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1059 if (!losesInfo)
1060 return ConstantFP::get(CFP->getContext(), F);
1061 return 0;
1062}
1063
1064/// LookThroughFPExtensions - If this is an fp extension instruction, look
1065/// through it until we get the source value.
1066static Value *LookThroughFPExtensions(Value *V) {
1067 if (Instruction *I = dyn_cast<Instruction>(V))
1068 if (I->getOpcode() == Instruction::FPExt)
1069 return LookThroughFPExtensions(I->getOperand(0));
1070
1071 // If this value is a constant, return the constant in the smallest FP type
1072 // that can accurately represent it. This allows us to turn
1073 // (float)((double)X+2.0) into x+2.0f.
1074 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1075 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1076 return V; // No constant folding of this.
1077 // See if the value can be truncated to float and then reextended.
1078 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1079 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001080 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001081 return V; // Won't shrink.
1082 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1083 return V;
1084 // Don't try to shrink to various long double types.
1085 }
1086
1087 return V;
1088}
1089
1090Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1091 if (Instruction *I = commonCastTransforms(CI))
1092 return I;
1093
1094 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1095 // smaller than the destination type, we can eliminate the truncate by doing
1096 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1097 // as many builtins (sqrt, etc).
1098 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1099 if (OpI && OpI->hasOneUse()) {
1100 switch (OpI->getOpcode()) {
1101 default: break;
1102 case Instruction::FAdd:
1103 case Instruction::FSub:
1104 case Instruction::FMul:
1105 case Instruction::FDiv:
1106 case Instruction::FRem:
1107 const Type *SrcTy = OpI->getType();
1108 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1109 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1110 if (LHSTrunc->getType() != SrcTy &&
1111 RHSTrunc->getType() != SrcTy) {
1112 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1113 // If the source types were both smaller than the destination type of
1114 // the cast, do this xform.
1115 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1116 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1117 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1118 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1119 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1120 }
1121 }
1122 break;
1123 }
1124 }
1125 return 0;
1126}
1127
1128Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1129 return commonCastTransforms(CI);
1130}
1131
1132Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1133 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1134 if (OpI == 0)
1135 return commonCastTransforms(FI);
1136
1137 // fptoui(uitofp(X)) --> X
1138 // fptoui(sitofp(X)) --> X
1139 // This is safe if the intermediate type has enough bits in its mantissa to
1140 // accurately represent all values of X. For example, do not do this with
1141 // i64->float->i64. This is also safe for sitofp case, because any negative
1142 // 'X' value would cause an undefined result for the fptoui.
1143 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1144 OpI->getOperand(0)->getType() == FI.getType() &&
1145 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1146 OpI->getType()->getFPMantissaWidth())
1147 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1148
1149 return commonCastTransforms(FI);
1150}
1151
1152Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1153 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1154 if (OpI == 0)
1155 return commonCastTransforms(FI);
1156
1157 // fptosi(sitofp(X)) --> X
1158 // fptosi(uitofp(X)) --> X
1159 // This is safe if the intermediate type has enough bits in its mantissa to
1160 // accurately represent all values of X. For example, do not do this with
1161 // i64->float->i64. This is also safe for sitofp case, because any negative
1162 // 'X' value would cause an undefined result for the fptoui.
1163 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1164 OpI->getOperand(0)->getType() == FI.getType() &&
1165 (int)FI.getType()->getScalarSizeInBits() <=
1166 OpI->getType()->getFPMantissaWidth())
1167 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1168
1169 return commonCastTransforms(FI);
1170}
1171
1172Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1173 return commonCastTransforms(CI);
1174}
1175
1176Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1177 return commonCastTransforms(CI);
1178}
1179
Chris Lattner80f43d32010-01-04 07:53:58 +00001180Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1181 // If the source integer type is larger than the intptr_t type for
1182 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
1183 // allows the trunc to be exposed to other transforms. Don't do this for
1184 // extending inttoptr's, because we don't know if the target sign or zero
1185 // extends to pointers.
1186 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1187 TD->getPointerSizeInBits()) {
1188 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1189 TD->getIntPtrType(CI.getContext()), "tmp");
1190 return new IntToPtrInst(P, CI.getType());
1191 }
1192
1193 if (Instruction *I = commonCastTransforms(CI))
1194 return I;
1195
1196 return 0;
1197}
1198
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001199/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1200Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1201 Value *Src = CI.getOperand(0);
1202
1203 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1204 // If casting the result of a getelementptr instruction with no offset, turn
1205 // this into a cast of the original pointer!
1206 if (GEP->hasAllZeroIndices()) {
1207 // Changing the cast operand is usually not a good idea but it is safe
1208 // here because the pointer operand is being replaced with another
1209 // pointer operand so the opcode doesn't need to change.
1210 Worklist.Add(GEP);
1211 CI.setOperand(0, GEP->getOperand(0));
1212 return &CI;
1213 }
1214
1215 // If the GEP has a single use, and the base pointer is a bitcast, and the
1216 // GEP computes a constant offset, see if we can convert these three
1217 // instructions into fewer. This typically happens with unions and other
1218 // non-type-safe code.
1219 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1220 GEP->hasAllConstantIndices()) {
1221 // We are guaranteed to get a constant from EmitGEPOffset.
1222 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1223 int64_t Offset = OffsetV->getSExtValue();
1224
1225 // Get the base pointer input of the bitcast, and the type it points to.
1226 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1227 const Type *GEPIdxTy =
1228 cast<PointerType>(OrigBase->getType())->getElementType();
1229 SmallVector<Value*, 8> NewIndices;
1230 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1231 // If we were able to index down into an element, create the GEP
1232 // and bitcast the result. This eliminates one bitcast, potentially
1233 // two.
1234 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1235 Builder->CreateInBoundsGEP(OrigBase,
1236 NewIndices.begin(), NewIndices.end()) :
1237 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1238 NGEP->takeName(GEP);
1239
1240 if (isa<BitCastInst>(CI))
1241 return new BitCastInst(NGEP, CI.getType());
1242 assert(isa<PtrToIntInst>(CI));
1243 return new PtrToIntInst(NGEP, CI.getType());
1244 }
1245 }
1246 }
1247
1248 return commonCastTransforms(CI);
1249}
1250
1251Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1252 // If the destination integer type is smaller than the intptr_t type for
1253 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
1254 // trunc to be exposed to other transforms. Don't do this for extending
1255 // ptrtoint's, because we don't know if the target sign or zero extends its
1256 // pointers.
1257 if (TD &&
1258 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1259 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1260 TD->getIntPtrType(CI.getContext()),
1261 "tmp");
1262 return new TruncInst(P, CI.getType());
1263 }
1264
1265 return commonPointerCastTransforms(CI);
1266}
1267
Chris Lattner80f43d32010-01-04 07:53:58 +00001268Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1269 // If the operands are integer typed then apply the integer transforms,
1270 // otherwise just apply the common ones.
1271 Value *Src = CI.getOperand(0);
1272 const Type *SrcTy = Src->getType();
1273 const Type *DestTy = CI.getType();
1274
Chris Lattner80f43d32010-01-04 07:53:58 +00001275 // Get rid of casts from one type to the same type. These are useless and can
1276 // be replaced by the operand.
1277 if (DestTy == Src->getType())
1278 return ReplaceInstUsesWith(CI, Src);
1279
1280 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1281 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1282 const Type *DstElTy = DstPTy->getElementType();
1283 const Type *SrcElTy = SrcPTy->getElementType();
1284
1285 // If the address spaces don't match, don't eliminate the bitcast, which is
1286 // required for changing types.
1287 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1288 return 0;
1289
1290 // If we are casting a alloca to a pointer to a type of the same
1291 // size, rewrite the allocation instruction to allocate the "right" type.
1292 // There is no need to modify malloc calls because it is their bitcast that
1293 // needs to be cleaned up.
1294 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1295 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1296 return V;
1297
1298 // If the source and destination are pointers, and this cast is equivalent
1299 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1300 // This can enhance SROA and other transforms that want type-safe pointers.
1301 Constant *ZeroUInt =
1302 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1303 unsigned NumZeros = 0;
1304 while (SrcElTy != DstElTy &&
1305 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1306 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1307 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1308 ++NumZeros;
1309 }
1310
1311 // If we found a path from the src to dest, create the getelementptr now.
1312 if (SrcElTy == DstElTy) {
1313 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1314 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001315 ((Instruction*)NULL));
Chris Lattner80f43d32010-01-04 07:53:58 +00001316 }
1317 }
1318
1319 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001320 if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1321 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1322 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001323 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001324 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1325 }
1326 }
1327
1328 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001329 if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1330 Value *Elem =
1331 Builder->CreateExtractElement(Src,
1332 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1333 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001334 }
1335 }
1336
1337 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001338 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1339 // a bitconvert to a vector with the same # elts.
1340 if (SVI->hasOneUse() && isa<VectorType>(DestTy) &&
1341 cast<VectorType>(DestTy)->getNumElements() ==
1342 SVI->getType()->getNumElements() &&
1343 SVI->getType()->getNumElements() ==
1344 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1345 BitCastInst *Tmp;
1346 // If either of the operands is a cast from CI.getType(), then
1347 // evaluating the shuffle in the casted destination's type will allow
1348 // us to eliminate at least one cast.
1349 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1350 Tmp->getOperand(0)->getType() == DestTy) ||
1351 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1352 Tmp->getOperand(0)->getType() == DestTy)) {
1353 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1354 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1355 // Return a new shuffle vector. Use the same element ID's, as we
1356 // know the vector types match #elts.
1357 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001358 }
1359 }
1360 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001361
1362 if (isa<PointerType>(SrcTy))
1363 return commonPointerCastTransforms(CI);
1364 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001365}