LLVM API Documentation

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