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 "InstCombineInternal.h" 15 #include "llvm/Analysis/ConstantFolding.h" 16 #include "llvm/IR/DataLayout.h" 17 #include "llvm/IR/PatternMatch.h" 18 #include "llvm/Analysis/TargetLibraryInfo.h" 19 using namespace llvm; 20 using namespace PatternMatch; 21 22 #define DEBUG_TYPE "instcombine" 23 24 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear 25 /// expression. If so, decompose it, returning some value X, such that Val is 26 /// X*Scale+Offset. 27 /// 28 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale, 29 uint64_t &Offset) { 30 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { 31 Offset = CI->getZExtValue(); 32 Scale = 0; 33 return ConstantInt::get(Val->getType(), 0); 34 } 35 36 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) { 37 // Cannot look past anything that might overflow. 38 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val); 39 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) { 40 Scale = 1; 41 Offset = 0; 42 return Val; 43 } 44 45 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) { 46 if (I->getOpcode() == Instruction::Shl) { 47 // This is a value scaled by '1 << the shift amt'. 48 Scale = UINT64_C(1) << RHS->getZExtValue(); 49 Offset = 0; 50 return I->getOperand(0); 51 } 52 53 if (I->getOpcode() == Instruction::Mul) { 54 // This value is scaled by 'RHS'. 55 Scale = RHS->getZExtValue(); 56 Offset = 0; 57 return I->getOperand(0); 58 } 59 60 if (I->getOpcode() == Instruction::Add) { 61 // We have X+C. Check to see if we really have (X*C2)+C1, 62 // where C1 is divisible by C2. 63 unsigned SubScale; 64 Value *SubVal = 65 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset); 66 Offset += RHS->getZExtValue(); 67 Scale = SubScale; 68 return SubVal; 69 } 70 } 71 } 72 73 // Otherwise, we can't look past this. 74 Scale = 1; 75 Offset = 0; 76 return Val; 77 } 78 79 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction, 80 /// try to eliminate the cast by moving the type information into the alloc. 81 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI, 82 AllocaInst &AI) { 83 PointerType *PTy = cast<PointerType>(CI.getType()); 84 85 BuilderTy AllocaBuilder(*Builder); 86 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI); 87 88 // Get the type really allocated and the type casted to. 89 Type *AllocElTy = AI.getAllocatedType(); 90 Type *CastElTy = PTy->getElementType(); 91 if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr; 92 93 unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy); 94 unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy); 95 if (CastElTyAlign < AllocElTyAlign) return nullptr; 96 97 // If the allocation has multiple uses, only promote it if we are strictly 98 // increasing the alignment of the resultant allocation. If we keep it the 99 // same, we open the door to infinite loops of various kinds. 100 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr; 101 102 uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy); 103 uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy); 104 if (CastElTySize == 0 || AllocElTySize == 0) return nullptr; 105 106 // If the allocation has multiple uses, only promote it if we're not 107 // shrinking the amount of memory being allocated. 108 uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy); 109 uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy); 110 if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr; 111 112 // See if we can satisfy the modulus by pulling a scale out of the array 113 // size argument. 114 unsigned ArraySizeScale; 115 uint64_t ArrayOffset; 116 Value *NumElements = // See if the array size is a decomposable linear expr. 117 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset); 118 119 // If we can now satisfy the modulus, by using a non-1 scale, we really can 120 // do the xform. 121 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 || 122 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr; 123 124 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize; 125 Value *Amt = nullptr; 126 if (Scale == 1) { 127 Amt = NumElements; 128 } else { 129 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale); 130 // Insert before the alloca, not before the cast. 131 Amt = AllocaBuilder.CreateMul(Amt, NumElements); 132 } 133 134 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) { 135 Value *Off = ConstantInt::get(AI.getArraySize()->getType(), 136 Offset, true); 137 Amt = AllocaBuilder.CreateAdd(Amt, Off); 138 } 139 140 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt); 141 New->setAlignment(AI.getAlignment()); 142 New->takeName(&AI); 143 New->setUsedWithInAlloca(AI.isUsedWithInAlloca()); 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 DL info. 165 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) 166 C = ConstantFoldConstantExpression(CE, DL, TLI); 167 return C; 168 } 169 170 // Otherwise, it must be an instruction. 171 Instruction *I = cast<Instruction>(V); 172 Instruction *Res = nullptr; 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 = 216 EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned); 217 NPN->addIncoming(V, OPN->getIncomingBlock(i)); 218 } 219 Res = NPN; 220 break; 221 } 222 default: 223 // TODO: Can handle more cases here. 224 llvm_unreachable("Unreachable!"); 225 } 226 227 Res->takeName(I); 228 return InsertNewInstWith(Res, *I); 229 } 230 231 232 /// This function is a wrapper around CastInst::isEliminableCastPair. It 233 /// simply extracts arguments and returns what that function returns. 234 static Instruction::CastOps 235 isEliminableCastPair(const CastInst *CI, ///< First cast instruction 236 unsigned opcode, ///< Opcode for the second cast 237 Type *DstTy, ///< Target type for the second cast 238 const DataLayout &DL) { 239 Type *SrcTy = CI->getOperand(0)->getType(); // A from above 240 Type *MidTy = CI->getType(); // B from above 241 242 // Get the opcodes of the two Cast instructions 243 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode()); 244 Instruction::CastOps secondOp = Instruction::CastOps(opcode); 245 Type *SrcIntPtrTy = 246 SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr; 247 Type *MidIntPtrTy = 248 MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr; 249 Type *DstIntPtrTy = 250 DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr; 251 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, 252 DstTy, SrcIntPtrTy, MidIntPtrTy, 253 DstIntPtrTy); 254 255 // We don't want to form an inttoptr or ptrtoint that converts to an integer 256 // type that differs from the pointer size. 257 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) || 258 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy)) 259 Res = 0; 260 261 return Instruction::CastOps(Res); 262 } 263 264 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually 265 /// results in any code being generated and is interesting to optimize out. If 266 /// the cast can be eliminated by some other simple transformation, we prefer 267 /// to do the simplification first. 268 bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V, 269 Type *Ty) { 270 // Noop casts and casts of constants should be eliminated trivially. 271 if (V->getType() == Ty || isa<Constant>(V)) return false; 272 273 // If this is another cast that can be eliminated, we prefer to have it 274 // eliminated. 275 if (const CastInst *CI = dyn_cast<CastInst>(V)) 276 if (isEliminableCastPair(CI, opc, Ty, DL)) 277 return false; 278 279 // If this is a vector sext from a compare, then we don't want to break the 280 // idiom where each element of the extended vector is either zero or all ones. 281 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy()) 282 return false; 283 284 return true; 285 } 286 287 288 /// @brief Implement the transforms common to all CastInst visitors. 289 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) { 290 Value *Src = CI.getOperand(0); 291 292 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just 293 // eliminate it now. 294 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast 295 if (Instruction::CastOps opc = 296 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) { 297 // The first cast (CSrc) is eliminable so we need to fix up or replace 298 // the second cast (CI). CSrc will then have a good chance of being dead. 299 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType()); 300 } 301 } 302 303 // If we are casting a select then fold the cast into the select 304 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) 305 if (Instruction *NV = FoldOpIntoSelect(CI, SI)) 306 return NV; 307 308 // If we are casting a PHI then fold the cast into the PHI 309 if (isa<PHINode>(Src)) { 310 // We don't do this if this would create a PHI node with an illegal type if 311 // it is currently legal. 312 if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() || 313 ShouldChangeType(CI.getType(), Src->getType())) 314 if (Instruction *NV = FoldOpIntoPhi(CI)) 315 return NV; 316 } 317 318 return nullptr; 319 } 320 321 /// CanEvaluateTruncated - Return true if we can evaluate the specified 322 /// expression tree as type Ty instead of its larger type, and arrive with the 323 /// same value. This is used by code that tries to eliminate truncates. 324 /// 325 /// Ty will always be a type smaller than V. We should return true if trunc(V) 326 /// can be computed by computing V in the smaller type. If V is an instruction, 327 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only 328 /// makes sense if x and y can be efficiently truncated. 329 /// 330 /// This function works on both vectors and scalars. 331 /// 332 static bool CanEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC, 333 Instruction *CxtI) { 334 // We can always evaluate constants in another type. 335 if (isa<Constant>(V)) 336 return true; 337 338 Instruction *I = dyn_cast<Instruction>(V); 339 if (!I) return false; 340 341 Type *OrigTy = V->getType(); 342 343 // If this is an extension from the dest type, we can eliminate it, even if it 344 // has multiple uses. 345 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) && 346 I->getOperand(0)->getType() == Ty) 347 return true; 348 349 // We can't extend or shrink something that has multiple uses: doing so would 350 // require duplicating the instruction in general, which isn't profitable. 351 if (!I->hasOneUse()) return false; 352 353 unsigned Opc = I->getOpcode(); 354 switch (Opc) { 355 case Instruction::Add: 356 case Instruction::Sub: 357 case Instruction::Mul: 358 case Instruction::And: 359 case Instruction::Or: 360 case Instruction::Xor: 361 // These operators can all arbitrarily be extended or truncated. 362 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 363 CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 364 365 case Instruction::UDiv: 366 case Instruction::URem: { 367 // UDiv and URem can be truncated if all the truncated bits are zero. 368 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 369 uint32_t BitWidth = Ty->getScalarSizeInBits(); 370 if (BitWidth < OrigBitWidth) { 371 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth); 372 if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) && 373 IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) { 374 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 375 CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 376 } 377 } 378 break; 379 } 380 case Instruction::Shl: 381 // If we are truncating the result of this SHL, and if it's a shift of a 382 // constant amount, we can always perform a SHL in a smaller type. 383 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 384 uint32_t BitWidth = Ty->getScalarSizeInBits(); 385 if (CI->getLimitedValue(BitWidth) < BitWidth) 386 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI); 387 } 388 break; 389 case Instruction::LShr: 390 // If this is a truncate of a logical shr, we can truncate it to a smaller 391 // lshr iff we know that the bits we would otherwise be shifting in are 392 // already zeros. 393 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 394 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 395 uint32_t BitWidth = Ty->getScalarSizeInBits(); 396 if (IC.MaskedValueIsZero(I->getOperand(0), 397 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth), 0, CxtI) && 398 CI->getLimitedValue(BitWidth) < BitWidth) { 399 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI); 400 } 401 } 402 break; 403 case Instruction::Trunc: 404 // trunc(trunc(x)) -> trunc(x) 405 return true; 406 case Instruction::ZExt: 407 case Instruction::SExt: 408 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest 409 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest 410 return true; 411 case Instruction::Select: { 412 SelectInst *SI = cast<SelectInst>(I); 413 return CanEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) && 414 CanEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI); 415 } 416 case Instruction::PHI: { 417 // We can change a phi if we can change all operands. Note that we never 418 // get into trouble with cyclic PHIs here because we only consider 419 // instructions with a single use. 420 PHINode *PN = cast<PHINode>(I); 421 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 422 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty, IC, CxtI)) 423 return false; 424 return true; 425 } 426 default: 427 // TODO: Can handle more cases here. 428 break; 429 } 430 431 return false; 432 } 433 434 Instruction *InstCombiner::visitTrunc(TruncInst &CI) { 435 if (Instruction *Result = commonCastTransforms(CI)) 436 return Result; 437 438 // See if we can simplify any instructions used by the input whose sole 439 // purpose is to compute bits we don't care about. 440 if (SimplifyDemandedInstructionBits(CI)) 441 return &CI; 442 443 Value *Src = CI.getOperand(0); 444 Type *DestTy = CI.getType(), *SrcTy = Src->getType(); 445 446 // Attempt to truncate the entire input expression tree to the destination 447 // type. Only do this if the dest type is a simple type, don't convert the 448 // expression tree to something weird like i93 unless the source is also 449 // strange. 450 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) && 451 CanEvaluateTruncated(Src, DestTy, *this, &CI)) { 452 453 // If this cast is a truncate, evaluting in a different type always 454 // eliminates the cast, so it is always a win. 455 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type" 456 " to avoid cast: " << CI << '\n'); 457 Value *Res = EvaluateInDifferentType(Src, DestTy, false); 458 assert(Res->getType() == DestTy); 459 return ReplaceInstUsesWith(CI, Res); 460 } 461 462 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector. 463 if (DestTy->getScalarSizeInBits() == 1) { 464 Constant *One = ConstantInt::get(Src->getType(), 1); 465 Src = Builder->CreateAnd(Src, One); 466 Value *Zero = Constant::getNullValue(Src->getType()); 467 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero); 468 } 469 470 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion. 471 Value *A = nullptr; ConstantInt *Cst = nullptr; 472 if (Src->hasOneUse() && 473 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) { 474 // We have three types to worry about here, the type of A, the source of 475 // the truncate (MidSize), and the destination of the truncate. We know that 476 // ASize < MidSize and MidSize > ResultSize, but don't know the relation 477 // between ASize and ResultSize. 478 unsigned ASize = A->getType()->getPrimitiveSizeInBits(); 479 480 // If the shift amount is larger than the size of A, then the result is 481 // known to be zero because all the input bits got shifted out. 482 if (Cst->getZExtValue() >= ASize) 483 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType())); 484 485 // Since we're doing an lshr and a zero extend, and know that the shift 486 // amount is smaller than ASize, it is always safe to do the shift in A's 487 // type, then zero extend or truncate to the result. 488 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue()); 489 Shift->takeName(Src); 490 return CastInst::CreateIntegerCast(Shift, CI.getType(), false); 491 } 492 493 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest 494 // type isn't non-native. 495 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) && 496 ShouldChangeType(Src->getType(), CI.getType()) && 497 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) { 498 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr"); 499 return BinaryOperator::CreateAnd(NewTrunc, 500 ConstantExpr::getTrunc(Cst, CI.getType())); 501 } 502 503 return nullptr; 504 } 505 506 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations 507 /// in order to eliminate the icmp. 508 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI, 509 bool DoXform) { 510 // If we are just checking for a icmp eq of a single bit and zext'ing it 511 // to an integer, then shift the bit to the appropriate place and then 512 // cast to integer to avoid the comparison. 513 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) { 514 const APInt &Op1CV = Op1C->getValue(); 515 516 // zext (x <s 0) to i32 --> x>>u31 true if signbit set. 517 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear. 518 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) || 519 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) { 520 if (!DoXform) return ICI; 521 522 Value *In = ICI->getOperand(0); 523 Value *Sh = ConstantInt::get(In->getType(), 524 In->getType()->getScalarSizeInBits()-1); 525 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit"); 526 if (In->getType() != CI.getType()) 527 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/); 528 529 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) { 530 Constant *One = ConstantInt::get(In->getType(), 1); 531 In = Builder->CreateXor(In, One, In->getName()+".not"); 532 } 533 534 return ReplaceInstUsesWith(CI, In); 535 } 536 537 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set. 538 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. 539 // zext (X == 1) to i32 --> X iff X has only the low bit set. 540 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set. 541 // zext (X != 0) to i32 --> X iff X has only the low bit set. 542 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set. 543 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set. 544 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. 545 if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 546 // This only works for EQ and NE 547 ICI->isEquality()) { 548 // If Op1C some other power of two, convert: 549 uint32_t BitWidth = Op1C->getType()->getBitWidth(); 550 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 551 computeKnownBits(ICI->getOperand(0), KnownZero, KnownOne, 0, &CI); 552 553 APInt KnownZeroMask(~KnownZero); 554 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1? 555 if (!DoXform) return ICI; 556 557 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE; 558 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) { 559 // (X&4) == 2 --> false 560 // (X&4) != 2 --> true 561 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()), 562 isNE); 563 Res = ConstantExpr::getZExt(Res, CI.getType()); 564 return ReplaceInstUsesWith(CI, Res); 565 } 566 567 uint32_t ShiftAmt = KnownZeroMask.logBase2(); 568 Value *In = ICI->getOperand(0); 569 if (ShiftAmt) { 570 // Perform a logical shr by shiftamt. 571 // Insert the shift to put the result in the low bit. 572 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt), 573 In->getName()+".lobit"); 574 } 575 576 if ((Op1CV != 0) == isNE) { // Toggle the low bit. 577 Constant *One = ConstantInt::get(In->getType(), 1); 578 In = Builder->CreateXor(In, One); 579 } 580 581 if (CI.getType() == In->getType()) 582 return ReplaceInstUsesWith(CI, In); 583 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/); 584 } 585 } 586 } 587 588 // icmp ne A, B is equal to xor A, B when A and B only really have one bit. 589 // It is also profitable to transform icmp eq into not(xor(A, B)) because that 590 // may lead to additional simplifications. 591 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) { 592 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) { 593 uint32_t BitWidth = ITy->getBitWidth(); 594 Value *LHS = ICI->getOperand(0); 595 Value *RHS = ICI->getOperand(1); 596 597 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0); 598 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0); 599 computeKnownBits(LHS, KnownZeroLHS, KnownOneLHS, 0, &CI); 600 computeKnownBits(RHS, KnownZeroRHS, KnownOneRHS, 0, &CI); 601 602 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) { 603 APInt KnownBits = KnownZeroLHS | KnownOneLHS; 604 APInt UnknownBit = ~KnownBits; 605 if (UnknownBit.countPopulation() == 1) { 606 if (!DoXform) return ICI; 607 608 Value *Result = Builder->CreateXor(LHS, RHS); 609 610 // Mask off any bits that are set and won't be shifted away. 611 if (KnownOneLHS.uge(UnknownBit)) 612 Result = Builder->CreateAnd(Result, 613 ConstantInt::get(ITy, UnknownBit)); 614 615 // Shift the bit we're testing down to the lsb. 616 Result = Builder->CreateLShr( 617 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros())); 618 619 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 620 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1)); 621 Result->takeName(ICI); 622 return ReplaceInstUsesWith(CI, Result); 623 } 624 } 625 } 626 } 627 628 return nullptr; 629 } 630 631 /// CanEvaluateZExtd - Determine if the specified value can be computed in the 632 /// specified wider type and produce the same low bits. If not, return false. 633 /// 634 /// If this function returns true, it can also return a non-zero number of bits 635 /// (in BitsToClear) which indicates that the value it computes is correct for 636 /// the zero extend, but that the additional BitsToClear bits need to be zero'd 637 /// out. For example, to promote something like: 638 /// 639 /// %B = trunc i64 %A to i32 640 /// %C = lshr i32 %B, 8 641 /// %E = zext i32 %C to i64 642 /// 643 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be 644 /// set to 8 to indicate that the promoted value needs to have bits 24-31 645 /// cleared in addition to bits 32-63. Since an 'and' will be generated to 646 /// clear the top bits anyway, doing this has no extra cost. 647 /// 648 /// This function works on both vectors and scalars. 649 static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear, 650 InstCombiner &IC, Instruction *CxtI) { 651 BitsToClear = 0; 652 if (isa<Constant>(V)) 653 return true; 654 655 Instruction *I = dyn_cast<Instruction>(V); 656 if (!I) return false; 657 658 // If the input is a truncate from the destination type, we can trivially 659 // eliminate it. 660 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty) 661 return true; 662 663 // We can't extend or shrink something that has multiple uses: doing so would 664 // require duplicating the instruction in general, which isn't profitable. 665 if (!I->hasOneUse()) return false; 666 667 unsigned Opc = I->getOpcode(), Tmp; 668 switch (Opc) { 669 case Instruction::ZExt: // zext(zext(x)) -> zext(x). 670 case Instruction::SExt: // zext(sext(x)) -> sext(x). 671 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x) 672 return true; 673 case Instruction::And: 674 case Instruction::Or: 675 case Instruction::Xor: 676 case Instruction::Add: 677 case Instruction::Sub: 678 case Instruction::Mul: 679 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) || 680 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI)) 681 return false; 682 // These can all be promoted if neither operand has 'bits to clear'. 683 if (BitsToClear == 0 && Tmp == 0) 684 return true; 685 686 // If the operation is an AND/OR/XOR and the bits to clear are zero in the 687 // other side, BitsToClear is ok. 688 if (Tmp == 0 && 689 (Opc == Instruction::And || Opc == Instruction::Or || 690 Opc == Instruction::Xor)) { 691 // We use MaskedValueIsZero here for generality, but the case we care 692 // about the most is constant RHS. 693 unsigned VSize = V->getType()->getScalarSizeInBits(); 694 if (IC.MaskedValueIsZero(I->getOperand(1), 695 APInt::getHighBitsSet(VSize, BitsToClear), 696 0, CxtI)) 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, IC, CxtI)) 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, IC, CxtI)) 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, IC, CxtI) || 729 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) || 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, IC, CxtI)) 742 return false; 743 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) 744 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) || 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 757 Instruction *InstCombiner::visitZExt(ZExtInst &CI) { 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.user_back())) 761 return nullptr; 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, *this, &CI)) { 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, 797 APInt::getHighBitsSet(DestBitSize, 798 DestBitSize-SrcBitsKept), 799 0, &CI)) 800 return ReplaceInstUsesWith(CI, Res); 801 802 // We need to emit an AND to clear the high bits. 803 Constant *C = ConstantInt::get(Res->getType(), 804 APInt::getLowBitsSet(DestBitSize, SrcBitsKept)); 805 return BinaryOperator::CreateAnd(Res, C); 806 } 807 808 // If this is a TRUNC followed by a ZEXT then we are dealing with integral 809 // types and if the sizes are just right we can convert this into a logical 810 // 'and' which will be much cheaper than the pair of casts. 811 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast 812 // TODO: Subsume this into EvaluateInDifferentType. 813 814 // Get the sizes of the types involved. We know that the intermediate type 815 // will be smaller than A or C, but don't know the relation between A and C. 816 Value *A = CSrc->getOperand(0); 817 unsigned SrcSize = A->getType()->getScalarSizeInBits(); 818 unsigned MidSize = CSrc->getType()->getScalarSizeInBits(); 819 unsigned DstSize = CI.getType()->getScalarSizeInBits(); 820 // If we're actually extending zero bits, then if 821 // SrcSize < DstSize: zext(a & mask) 822 // SrcSize == DstSize: a & mask 823 // SrcSize > DstSize: trunc(a) & mask 824 if (SrcSize < DstSize) { 825 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize)); 826 Constant *AndConst = ConstantInt::get(A->getType(), AndValue); 827 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask"); 828 return new ZExtInst(And, CI.getType()); 829 } 830 831 if (SrcSize == DstSize) { 832 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize)); 833 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(), 834 AndValue)); 835 } 836 if (SrcSize > DstSize) { 837 Value *Trunc = Builder->CreateTrunc(A, CI.getType()); 838 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize)); 839 return BinaryOperator::CreateAnd(Trunc, 840 ConstantInt::get(Trunc->getType(), 841 AndValue)); 842 } 843 } 844 845 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) 846 return transformZExtICmp(ICI, CI); 847 848 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src); 849 if (SrcI && SrcI->getOpcode() == Instruction::Or) { 850 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one 851 // of the (zext icmp) will be transformed. 852 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0)); 853 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1)); 854 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() && 855 (transformZExtICmp(LHS, CI, false) || 856 transformZExtICmp(RHS, CI, false))) { 857 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName()); 858 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName()); 859 return BinaryOperator::Create(Instruction::Or, LCast, RCast); 860 } 861 } 862 863 // zext(trunc(X) & C) -> (X & zext(C)). 864 Constant *C; 865 Value *X; 866 if (SrcI && 867 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) && 868 X->getType() == CI.getType()) 869 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType())); 870 871 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)). 872 Value *And; 873 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) && 874 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) && 875 X->getType() == CI.getType()) { 876 Constant *ZC = ConstantExpr::getZExt(C, CI.getType()); 877 return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC); 878 } 879 880 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1 881 if (SrcI && SrcI->hasOneUse() && 882 SrcI->getType()->getScalarType()->isIntegerTy(1) && 883 match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) { 884 Value *New = Builder->CreateZExt(X, CI.getType()); 885 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1)); 886 } 887 888 return nullptr; 889 } 890 891 /// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations 892 /// in order to eliminate the icmp. 893 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) { 894 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1); 895 ICmpInst::Predicate Pred = ICI->getPredicate(); 896 897 // Don't bother if Op1 isn't of vector or integer type. 898 if (!Op1->getType()->isIntOrIntVectorTy()) 899 return nullptr; 900 901 if (Constant *Op1C = dyn_cast<Constant>(Op1)) { 902 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative 903 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive 904 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) || 905 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) { 906 907 Value *Sh = ConstantInt::get(Op0->getType(), 908 Op0->getType()->getScalarSizeInBits()-1); 909 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit"); 910 if (In->getType() != CI.getType()) 911 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/); 912 913 if (Pred == ICmpInst::ICMP_SGT) 914 In = Builder->CreateNot(In, In->getName()+".not"); 915 return ReplaceInstUsesWith(CI, In); 916 } 917 } 918 919 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 920 // If we know that only one bit of the LHS of the icmp can be set and we 921 // have an equality comparison with zero or a power of 2, we can transform 922 // the icmp and sext into bitwise/integer operations. 923 if (ICI->hasOneUse() && 924 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){ 925 unsigned BitWidth = Op1C->getType()->getBitWidth(); 926 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 927 computeKnownBits(Op0, KnownZero, KnownOne, 0, &CI); 928 929 APInt KnownZeroMask(~KnownZero); 930 if (KnownZeroMask.isPowerOf2()) { 931 Value *In = ICI->getOperand(0); 932 933 // If the icmp tests for a known zero bit we can constant fold it. 934 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) { 935 Value *V = Pred == ICmpInst::ICMP_NE ? 936 ConstantInt::getAllOnesValue(CI.getType()) : 937 ConstantInt::getNullValue(CI.getType()); 938 return ReplaceInstUsesWith(CI, V); 939 } 940 941 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) { 942 // sext ((x & 2^n) == 0) -> (x >> n) - 1 943 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1 944 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros(); 945 // Perform a right shift to place the desired bit in the LSB. 946 if (ShiftAmt) 947 In = Builder->CreateLShr(In, 948 ConstantInt::get(In->getType(), ShiftAmt)); 949 950 // At this point "In" is either 1 or 0. Subtract 1 to turn 951 // {1, 0} -> {0, -1}. 952 In = Builder->CreateAdd(In, 953 ConstantInt::getAllOnesValue(In->getType()), 954 "sext"); 955 } else { 956 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1 957 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1 958 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros(); 959 // Perform a left shift to place the desired bit in the MSB. 960 if (ShiftAmt) 961 In = Builder->CreateShl(In, 962 ConstantInt::get(In->getType(), ShiftAmt)); 963 964 // Distribute the bit over the whole bit width. 965 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(), 966 BitWidth - 1), "sext"); 967 } 968 969 if (CI.getType() == In->getType()) 970 return ReplaceInstUsesWith(CI, In); 971 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/); 972 } 973 } 974 } 975 976 return nullptr; 977 } 978 979 /// CanEvaluateSExtd - Return true if we can take the specified value 980 /// and return it as type Ty without inserting any new casts and without 981 /// changing the value of the common low bits. This is used by code that tries 982 /// to promote integer operations to a wider types will allow us to eliminate 983 /// the extension. 984 /// 985 /// This function works on both vectors and scalars. 986 /// 987 static bool CanEvaluateSExtd(Value *V, Type *Ty) { 988 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() && 989 "Can't sign extend type to a smaller type"); 990 // If this is a constant, it can be trivially promoted. 991 if (isa<Constant>(V)) 992 return true; 993 994 Instruction *I = dyn_cast<Instruction>(V); 995 if (!I) return false; 996 997 // If this is a truncate from the dest type, we can trivially eliminate it. 998 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty) 999 return true; 1000 1001 // We can't extend or shrink something that has multiple uses: doing so would 1002 // require duplicating the instruction in general, which isn't profitable. 1003 if (!I->hasOneUse()) return false; 1004 1005 switch (I->getOpcode()) { 1006 case Instruction::SExt: // sext(sext(x)) -> sext(x) 1007 case Instruction::ZExt: // sext(zext(x)) -> zext(x) 1008 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x) 1009 return true; 1010 case Instruction::And: 1011 case Instruction::Or: 1012 case Instruction::Xor: 1013 case Instruction::Add: 1014 case Instruction::Sub: 1015 case Instruction::Mul: 1016 // These operators can all arbitrarily be extended if their inputs can. 1017 return CanEvaluateSExtd(I->getOperand(0), Ty) && 1018 CanEvaluateSExtd(I->getOperand(1), Ty); 1019 1020 //case Instruction::Shl: TODO 1021 //case Instruction::LShr: TODO 1022 1023 case Instruction::Select: 1024 return CanEvaluateSExtd(I->getOperand(1), Ty) && 1025 CanEvaluateSExtd(I->getOperand(2), Ty); 1026 1027 case Instruction::PHI: { 1028 // We can change a phi if we can change all operands. Note that we never 1029 // get into trouble with cyclic PHIs here because we only consider 1030 // instructions with a single use. 1031 PHINode *PN = cast<PHINode>(I); 1032 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1033 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false; 1034 return true; 1035 } 1036 default: 1037 // TODO: Can handle more cases here. 1038 break; 1039 } 1040 1041 return false; 1042 } 1043 1044 Instruction *InstCombiner::visitSExt(SExtInst &CI) { 1045 // If this sign extend is only used by a truncate, let the truncate be 1046 // eliminated before we try to optimize this sext. 1047 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back())) 1048 return nullptr; 1049 1050 if (Instruction *I = commonCastTransforms(CI)) 1051 return I; 1052 1053 // See if we can simplify any instructions used by the input whose sole 1054 // purpose is to compute bits we don't care about. 1055 if (SimplifyDemandedInstructionBits(CI)) 1056 return &CI; 1057 1058 Value *Src = CI.getOperand(0); 1059 Type *SrcTy = Src->getType(), *DestTy = CI.getType(); 1060 1061 // If we know that the value being extended is positive, we can use a zext 1062 // instead. 1063 bool KnownZero, KnownOne; 1064 ComputeSignBit(Src, KnownZero, KnownOne, 0, &CI); 1065 if (KnownZero) { 1066 Value *ZExt = Builder->CreateZExt(Src, DestTy); 1067 return ReplaceInstUsesWith(CI, ZExt); 1068 } 1069 1070 // Attempt to extend the entire input expression tree to the destination 1071 // type. Only do this if the dest type is a simple type, don't convert the 1072 // expression tree to something weird like i93 unless the source is also 1073 // strange. 1074 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) && 1075 CanEvaluateSExtd(Src, DestTy)) { 1076 // Okay, we can transform this! Insert the new expression now. 1077 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type" 1078 " to avoid sign extend: " << CI); 1079 Value *Res = EvaluateInDifferentType(Src, DestTy, true); 1080 assert(Res->getType() == DestTy); 1081 1082 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits(); 1083 uint32_t DestBitSize = DestTy->getScalarSizeInBits(); 1084 1085 // If the high bits are already filled with sign bit, just replace this 1086 // cast with the result. 1087 if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize) 1088 return ReplaceInstUsesWith(CI, Res); 1089 1090 // We need to emit a shl + ashr to do the sign extend. 1091 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize); 1092 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"), 1093 ShAmt); 1094 } 1095 1096 // If this input is a trunc from our destination, then turn sext(trunc(x)) 1097 // into shifts. 1098 if (TruncInst *TI = dyn_cast<TruncInst>(Src)) 1099 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) { 1100 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits(); 1101 uint32_t DestBitSize = DestTy->getScalarSizeInBits(); 1102 1103 // We need to emit a shl + ashr to do the sign extend. 1104 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize); 1105 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext"); 1106 return BinaryOperator::CreateAShr(Res, ShAmt); 1107 } 1108 1109 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) 1110 return transformSExtICmp(ICI, CI); 1111 1112 // If the input is a shl/ashr pair of a same constant, then this is a sign 1113 // extension from a smaller value. If we could trust arbitrary bitwidth 1114 // integers, we could turn this into a truncate to the smaller bit and then 1115 // use a sext for the whole extension. Since we don't, look deeper and check 1116 // for a truncate. If the source and dest are the same type, eliminate the 1117 // trunc and extend and just do shifts. For example, turn: 1118 // %a = trunc i32 %i to i8 1119 // %b = shl i8 %a, 6 1120 // %c = ashr i8 %b, 6 1121 // %d = sext i8 %c to i32 1122 // into: 1123 // %a = shl i32 %i, 30 1124 // %d = ashr i32 %a, 30 1125 Value *A = nullptr; 1126 // TODO: Eventually this could be subsumed by EvaluateInDifferentType. 1127 ConstantInt *BA = nullptr, *CA = nullptr; 1128 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)), 1129 m_ConstantInt(CA))) && 1130 BA == CA && A->getType() == CI.getType()) { 1131 unsigned MidSize = Src->getType()->getScalarSizeInBits(); 1132 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits(); 1133 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize; 1134 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt); 1135 A = Builder->CreateShl(A, ShAmtV, CI.getName()); 1136 return BinaryOperator::CreateAShr(A, ShAmtV); 1137 } 1138 1139 return nullptr; 1140 } 1141 1142 1143 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits 1144 /// in the specified FP type without changing its value. 1145 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) { 1146 bool losesInfo; 1147 APFloat F = CFP->getValueAPF(); 1148 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo); 1149 if (!losesInfo) 1150 return ConstantFP::get(CFP->getContext(), F); 1151 return nullptr; 1152 } 1153 1154 /// LookThroughFPExtensions - If this is an fp extension instruction, look 1155 /// through it until we get the source value. 1156 static Value *LookThroughFPExtensions(Value *V) { 1157 if (Instruction *I = dyn_cast<Instruction>(V)) 1158 if (I->getOpcode() == Instruction::FPExt) 1159 return LookThroughFPExtensions(I->getOperand(0)); 1160 1161 // If this value is a constant, return the constant in the smallest FP type 1162 // that can accurately represent it. This allows us to turn 1163 // (float)((double)X+2.0) into x+2.0f. 1164 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { 1165 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext())) 1166 return V; // No constant folding of this. 1167 // See if the value can be truncated to half and then reextended. 1168 if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf)) 1169 return V; 1170 // See if the value can be truncated to float and then reextended. 1171 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle)) 1172 return V; 1173 if (CFP->getType()->isDoubleTy()) 1174 return V; // Won't shrink. 1175 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble)) 1176 return V; 1177 // Don't try to shrink to various long double types. 1178 } 1179 1180 return V; 1181 } 1182 1183 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) { 1184 if (Instruction *I = commonCastTransforms(CI)) 1185 return I; 1186 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to 1187 // simpilify this expression to avoid one or more of the trunc/extend 1188 // operations if we can do so without changing the numerical results. 1189 // 1190 // The exact manner in which the widths of the operands interact to limit 1191 // what we can and cannot do safely varies from operation to operation, and 1192 // is explained below in the various case statements. 1193 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0)); 1194 if (OpI && OpI->hasOneUse()) { 1195 Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0)); 1196 Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1)); 1197 unsigned OpWidth = OpI->getType()->getFPMantissaWidth(); 1198 unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth(); 1199 unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth(); 1200 unsigned SrcWidth = std::max(LHSWidth, RHSWidth); 1201 unsigned DstWidth = CI.getType()->getFPMantissaWidth(); 1202 switch (OpI->getOpcode()) { 1203 default: break; 1204 case Instruction::FAdd: 1205 case Instruction::FSub: 1206 // For addition and subtraction, the infinitely precise result can 1207 // essentially be arbitrarily wide; proving that double rounding 1208 // will not occur because the result of OpI is exact (as we will for 1209 // FMul, for example) is hopeless. However, we *can* nonetheless 1210 // frequently know that double rounding cannot occur (or that it is 1211 // innocuous) by taking advantage of the specific structure of 1212 // infinitely-precise results that admit double rounding. 1213 // 1214 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient 1215 // to represent both sources, we can guarantee that the double 1216 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis, 1217 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..." 1218 // for proof of this fact). 1219 // 1220 // Note: Figueroa does not consider the case where DstFormat != 1221 // SrcFormat. It's possible (likely even!) that this analysis 1222 // could be tightened for those cases, but they are rare (the main 1223 // case of interest here is (float)((double)float + float)). 1224 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) { 1225 if (LHSOrig->getType() != CI.getType()) 1226 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType()); 1227 if (RHSOrig->getType() != CI.getType()) 1228 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType()); 1229 Instruction *RI = 1230 BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig); 1231 RI->copyFastMathFlags(OpI); 1232 return RI; 1233 } 1234 break; 1235 case Instruction::FMul: 1236 // For multiplication, the infinitely precise result has at most 1237 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient 1238 // that such a value can be exactly represented, then no double 1239 // rounding can possibly occur; we can safely perform the operation 1240 // in the destination format if it can represent both sources. 1241 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) { 1242 if (LHSOrig->getType() != CI.getType()) 1243 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType()); 1244 if (RHSOrig->getType() != CI.getType()) 1245 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType()); 1246 Instruction *RI = 1247 BinaryOperator::CreateFMul(LHSOrig, RHSOrig); 1248 RI->copyFastMathFlags(OpI); 1249 return RI; 1250 } 1251 break; 1252 case Instruction::FDiv: 1253 // For division, we use again use the bound from Figueroa's 1254 // dissertation. I am entirely certain that this bound can be 1255 // tightened in the unbalanced operand case by an analysis based on 1256 // the diophantine rational approximation bound, but the well-known 1257 // condition used here is a good conservative first pass. 1258 // TODO: Tighten bound via rigorous analysis of the unbalanced case. 1259 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) { 1260 if (LHSOrig->getType() != CI.getType()) 1261 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType()); 1262 if (RHSOrig->getType() != CI.getType()) 1263 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType()); 1264 Instruction *RI = 1265 BinaryOperator::CreateFDiv(LHSOrig, RHSOrig); 1266 RI->copyFastMathFlags(OpI); 1267 return RI; 1268 } 1269 break; 1270 case Instruction::FRem: 1271 // Remainder is straightforward. Remainder is always exact, so the 1272 // type of OpI doesn't enter into things at all. We simply evaluate 1273 // in whichever source type is larger, then convert to the 1274 // destination type. 1275 if (SrcWidth == OpWidth) 1276 break; 1277 if (LHSWidth < SrcWidth) 1278 LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType()); 1279 else if (RHSWidth <= SrcWidth) 1280 RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType()); 1281 if (LHSOrig != OpI->getOperand(0) || RHSOrig != OpI->getOperand(1)) { 1282 Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig); 1283 if (Instruction *RI = dyn_cast<Instruction>(ExactResult)) 1284 RI->copyFastMathFlags(OpI); 1285 return CastInst::CreateFPCast(ExactResult, CI.getType()); 1286 } 1287 } 1288 1289 // (fptrunc (fneg x)) -> (fneg (fptrunc x)) 1290 if (BinaryOperator::isFNeg(OpI)) { 1291 Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1), 1292 CI.getType()); 1293 Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc); 1294 RI->copyFastMathFlags(OpI); 1295 return RI; 1296 } 1297 } 1298 1299 // (fptrunc (select cond, R1, Cst)) --> 1300 // (select cond, (fptrunc R1), (fptrunc Cst)) 1301 SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0)); 1302 if (SI && 1303 (isa<ConstantFP>(SI->getOperand(1)) || 1304 isa<ConstantFP>(SI->getOperand(2)))) { 1305 Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1), 1306 CI.getType()); 1307 Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2), 1308 CI.getType()); 1309 return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc); 1310 } 1311 1312 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0)); 1313 if (II) { 1314 switch (II->getIntrinsicID()) { 1315 default: break; 1316 case Intrinsic::fabs: { 1317 // (fptrunc (fabs x)) -> (fabs (fptrunc x)) 1318 Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0), 1319 CI.getType()); 1320 Type *IntrinsicType[] = { CI.getType() }; 1321 Function *Overload = 1322 Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(), 1323 II->getIntrinsicID(), IntrinsicType); 1324 1325 Value *Args[] = { InnerTrunc }; 1326 return CallInst::Create(Overload, Args, II->getName()); 1327 } 1328 } 1329 } 1330 1331 return nullptr; 1332 } 1333 1334 Instruction *InstCombiner::visitFPExt(CastInst &CI) { 1335 return commonCastTransforms(CI); 1336 } 1337 1338 // fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X) 1339 // This is safe if the intermediate type has enough bits in its mantissa to 1340 // accurately represent all values of X. For example, this won't work with 1341 // i64 -> float -> i64. 1342 Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) { 1343 if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0))) 1344 return nullptr; 1345 Instruction *OpI = cast<Instruction>(FI.getOperand(0)); 1346 1347 Value *SrcI = OpI->getOperand(0); 1348 Type *FITy = FI.getType(); 1349 Type *OpITy = OpI->getType(); 1350 Type *SrcTy = SrcI->getType(); 1351 bool IsInputSigned = isa<SIToFPInst>(OpI); 1352 bool IsOutputSigned = isa<FPToSIInst>(FI); 1353 1354 // We can safely assume the conversion won't overflow the output range, 1355 // because (for example) (uint8_t)18293.f is undefined behavior. 1356 1357 // Since we can assume the conversion won't overflow, our decision as to 1358 // whether the input will fit in the float should depend on the minimum 1359 // of the input range and output range. 1360 1361 // This means this is also safe for a signed input and unsigned output, since 1362 // a negative input would lead to undefined behavior. 1363 int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned; 1364 int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned; 1365 int ActualSize = std::min(InputSize, OutputSize); 1366 1367 if (ActualSize <= OpITy->getFPMantissaWidth()) { 1368 if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) { 1369 if (IsInputSigned && IsOutputSigned) 1370 return new SExtInst(SrcI, FITy); 1371 return new ZExtInst(SrcI, FITy); 1372 } 1373 if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits()) 1374 return new TruncInst(SrcI, FITy); 1375 if (SrcTy == FITy) 1376 return ReplaceInstUsesWith(FI, SrcI); 1377 return new BitCastInst(SrcI, FITy); 1378 } 1379 return nullptr; 1380 } 1381 1382 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) { 1383 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0)); 1384 if (!OpI) 1385 return commonCastTransforms(FI); 1386 1387 if (Instruction *I = FoldItoFPtoI(FI)) 1388 return I; 1389 1390 return commonCastTransforms(FI); 1391 } 1392 1393 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) { 1394 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0)); 1395 if (!OpI) 1396 return commonCastTransforms(FI); 1397 1398 if (Instruction *I = FoldItoFPtoI(FI)) 1399 return I; 1400 1401 return commonCastTransforms(FI); 1402 } 1403 1404 Instruction *InstCombiner::visitUIToFP(CastInst &CI) { 1405 return commonCastTransforms(CI); 1406 } 1407 1408 Instruction *InstCombiner::visitSIToFP(CastInst &CI) { 1409 return commonCastTransforms(CI); 1410 } 1411 1412 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) { 1413 // If the source integer type is not the intptr_t type for this target, do a 1414 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the 1415 // cast to be exposed to other transforms. 1416 unsigned AS = CI.getAddressSpace(); 1417 if (CI.getOperand(0)->getType()->getScalarSizeInBits() != 1418 DL.getPointerSizeInBits(AS)) { 1419 Type *Ty = DL.getIntPtrType(CI.getContext(), AS); 1420 if (CI.getType()->isVectorTy()) // Handle vectors of pointers. 1421 Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements()); 1422 1423 Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty); 1424 return new IntToPtrInst(P, CI.getType()); 1425 } 1426 1427 if (Instruction *I = commonCastTransforms(CI)) 1428 return I; 1429 1430 return nullptr; 1431 } 1432 1433 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint) 1434 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) { 1435 Value *Src = CI.getOperand(0); 1436 1437 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) { 1438 // If casting the result of a getelementptr instruction with no offset, turn 1439 // this into a cast of the original pointer! 1440 if (GEP->hasAllZeroIndices() && 1441 // If CI is an addrspacecast and GEP changes the poiner type, merging 1442 // GEP into CI would undo canonicalizing addrspacecast with different 1443 // pointer types, causing infinite loops. 1444 (!isa<AddrSpaceCastInst>(CI) || 1445 GEP->getType() == GEP->getPointerOperand()->getType())) { 1446 // Changing the cast operand is usually not a good idea but it is safe 1447 // here because the pointer operand is being replaced with another 1448 // pointer operand so the opcode doesn't need to change. 1449 Worklist.Add(GEP); 1450 CI.setOperand(0, GEP->getOperand(0)); 1451 return &CI; 1452 } 1453 1454 // If the GEP has a single use, and the base pointer is a bitcast, and the 1455 // GEP computes a constant offset, see if we can convert these three 1456 // instructions into fewer. This typically happens with unions and other 1457 // non-type-safe code. 1458 unsigned AS = GEP->getPointerAddressSpace(); 1459 unsigned OffsetBits = DL.getPointerSizeInBits(AS); 1460 APInt Offset(OffsetBits, 0); 1461 BitCastInst *BCI = dyn_cast<BitCastInst>(GEP->getOperand(0)); 1462 if (GEP->hasOneUse() && BCI && GEP->accumulateConstantOffset(DL, Offset)) { 1463 // FIXME: This is insufficiently tested - just a no-crash test 1464 // (test/Transforms/InstCombine/2007-05-14-Crash.ll) 1465 // 1466 // Get the base pointer input of the bitcast, and the type it points to. 1467 Value *OrigBase = BCI->getOperand(0); 1468 SmallVector<Value*, 8> NewIndices; 1469 if (FindElementAtOffset(OrigBase->getType(), Offset.getSExtValue(), 1470 NewIndices)) { 1471 // FIXME: This codepath is completely untested - could be unreachable 1472 // for all I know. 1473 // If we were able to index down into an element, create the GEP 1474 // and bitcast the result. This eliminates one bitcast, potentially 1475 // two. 1476 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ? 1477 Builder->CreateInBoundsGEP(OrigBase, NewIndices) : 1478 Builder->CreateGEP(OrigBase, NewIndices); 1479 NGEP->takeName(GEP); 1480 1481 if (isa<BitCastInst>(CI)) 1482 return new BitCastInst(NGEP, CI.getType()); 1483 assert(isa<PtrToIntInst>(CI)); 1484 return new PtrToIntInst(NGEP, CI.getType()); 1485 } 1486 } 1487 } 1488 1489 return commonCastTransforms(CI); 1490 } 1491 1492 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) { 1493 // If the destination integer type is not the intptr_t type for this target, 1494 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast 1495 // to be exposed to other transforms. 1496 1497 Type *Ty = CI.getType(); 1498 unsigned AS = CI.getPointerAddressSpace(); 1499 1500 if (Ty->getScalarSizeInBits() == DL.getPointerSizeInBits(AS)) 1501 return commonPointerCastTransforms(CI); 1502 1503 Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS); 1504 if (Ty->isVectorTy()) // Handle vectors of pointers. 1505 PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements()); 1506 1507 Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy); 1508 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false); 1509 } 1510 1511 /// OptimizeVectorResize - This input value (which is known to have vector type) 1512 /// is being zero extended or truncated to the specified vector type. Try to 1513 /// replace it with a shuffle (and vector/vector bitcast) if possible. 1514 /// 1515 /// The source and destination vector types may have different element types. 1516 static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy, 1517 InstCombiner &IC) { 1518 // We can only do this optimization if the output is a multiple of the input 1519 // element size, or the input is a multiple of the output element size. 1520 // Convert the input type to have the same element type as the output. 1521 VectorType *SrcTy = cast<VectorType>(InVal->getType()); 1522 1523 if (SrcTy->getElementType() != DestTy->getElementType()) { 1524 // The input types don't need to be identical, but for now they must be the 1525 // same size. There is no specific reason we couldn't handle things like 1526 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten 1527 // there yet. 1528 if (SrcTy->getElementType()->getPrimitiveSizeInBits() != 1529 DestTy->getElementType()->getPrimitiveSizeInBits()) 1530 return nullptr; 1531 1532 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements()); 1533 InVal = IC.Builder->CreateBitCast(InVal, SrcTy); 1534 } 1535 1536 // Now that the element types match, get the shuffle mask and RHS of the 1537 // shuffle to use, which depends on whether we're increasing or decreasing the 1538 // size of the input. 1539 SmallVector<uint32_t, 16> ShuffleMask; 1540 Value *V2; 1541 1542 if (SrcTy->getNumElements() > DestTy->getNumElements()) { 1543 // If we're shrinking the number of elements, just shuffle in the low 1544 // elements from the input and use undef as the second shuffle input. 1545 V2 = UndefValue::get(SrcTy); 1546 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i) 1547 ShuffleMask.push_back(i); 1548 1549 } else { 1550 // If we're increasing the number of elements, shuffle in all of the 1551 // elements from InVal and fill the rest of the result elements with zeros 1552 // from a constant zero. 1553 V2 = Constant::getNullValue(SrcTy); 1554 unsigned SrcElts = SrcTy->getNumElements(); 1555 for (unsigned i = 0, e = SrcElts; i != e; ++i) 1556 ShuffleMask.push_back(i); 1557 1558 // The excess elements reference the first element of the zero input. 1559 for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i) 1560 ShuffleMask.push_back(SrcElts); 1561 } 1562 1563 return new ShuffleVectorInst(InVal, V2, 1564 ConstantDataVector::get(V2->getContext(), 1565 ShuffleMask)); 1566 } 1567 1568 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) { 1569 return Value % Ty->getPrimitiveSizeInBits() == 0; 1570 } 1571 1572 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) { 1573 return Value / Ty->getPrimitiveSizeInBits(); 1574 } 1575 1576 /// CollectInsertionElements - V is a value which is inserted into a vector of 1577 /// VecEltTy. Look through the value to see if we can decompose it into 1578 /// insertions into the vector. See the example in the comment for 1579 /// OptimizeIntegerToVectorInsertions for the pattern this handles. 1580 /// The type of V is always a non-zero multiple of VecEltTy's size. 1581 /// Shift is the number of bits between the lsb of V and the lsb of 1582 /// the vector. 1583 /// 1584 /// This returns false if the pattern can't be matched or true if it can, 1585 /// filling in Elements with the elements found here. 1586 static bool CollectInsertionElements(Value *V, unsigned Shift, 1587 SmallVectorImpl<Value *> &Elements, 1588 Type *VecEltTy, bool isBigEndian) { 1589 assert(isMultipleOfTypeSize(Shift, VecEltTy) && 1590 "Shift should be a multiple of the element type size"); 1591 1592 // Undef values never contribute useful bits to the result. 1593 if (isa<UndefValue>(V)) return true; 1594 1595 // If we got down to a value of the right type, we win, try inserting into the 1596 // right element. 1597 if (V->getType() == VecEltTy) { 1598 // Inserting null doesn't actually insert any elements. 1599 if (Constant *C = dyn_cast<Constant>(V)) 1600 if (C->isNullValue()) 1601 return true; 1602 1603 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy); 1604 if (isBigEndian) 1605 ElementIndex = Elements.size() - ElementIndex - 1; 1606 1607 // Fail if multiple elements are inserted into this slot. 1608 if (Elements[ElementIndex]) 1609 return false; 1610 1611 Elements[ElementIndex] = V; 1612 return true; 1613 } 1614 1615 if (Constant *C = dyn_cast<Constant>(V)) { 1616 // Figure out the # elements this provides, and bitcast it or slice it up 1617 // as required. 1618 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(), 1619 VecEltTy); 1620 // If the constant is the size of a vector element, we just need to bitcast 1621 // it to the right type so it gets properly inserted. 1622 if (NumElts == 1) 1623 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy), 1624 Shift, Elements, VecEltTy, isBigEndian); 1625 1626 // Okay, this is a constant that covers multiple elements. Slice it up into 1627 // pieces and insert each element-sized piece into the vector. 1628 if (!isa<IntegerType>(C->getType())) 1629 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(), 1630 C->getType()->getPrimitiveSizeInBits())); 1631 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits(); 1632 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize); 1633 1634 for (unsigned i = 0; i != NumElts; ++i) { 1635 unsigned ShiftI = Shift+i*ElementSize; 1636 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(), 1637 ShiftI)); 1638 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy); 1639 if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy, 1640 isBigEndian)) 1641 return false; 1642 } 1643 return true; 1644 } 1645 1646 if (!V->hasOneUse()) return false; 1647 1648 Instruction *I = dyn_cast<Instruction>(V); 1649 if (!I) return false; 1650 switch (I->getOpcode()) { 1651 default: return false; // Unhandled case. 1652 case Instruction::BitCast: 1653 return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 1654 isBigEndian); 1655 case Instruction::ZExt: 1656 if (!isMultipleOfTypeSize( 1657 I->getOperand(0)->getType()->getPrimitiveSizeInBits(), 1658 VecEltTy)) 1659 return false; 1660 return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 1661 isBigEndian); 1662 case Instruction::Or: 1663 return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 1664 isBigEndian) && 1665 CollectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy, 1666 isBigEndian); 1667 case Instruction::Shl: { 1668 // Must be shifting by a constant that is a multiple of the element size. 1669 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1)); 1670 if (!CI) return false; 1671 Shift += CI->getZExtValue(); 1672 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false; 1673 return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 1674 isBigEndian); 1675 } 1676 1677 } 1678 } 1679 1680 1681 /// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we 1682 /// may be doing shifts and ors to assemble the elements of the vector manually. 1683 /// Try to rip the code out and replace it with insertelements. This is to 1684 /// optimize code like this: 1685 /// 1686 /// %tmp37 = bitcast float %inc to i32 1687 /// %tmp38 = zext i32 %tmp37 to i64 1688 /// %tmp31 = bitcast float %inc5 to i32 1689 /// %tmp32 = zext i32 %tmp31 to i64 1690 /// %tmp33 = shl i64 %tmp32, 32 1691 /// %ins35 = or i64 %tmp33, %tmp38 1692 /// %tmp43 = bitcast i64 %ins35 to <2 x float> 1693 /// 1694 /// Into two insertelements that do "buildvector{%inc, %inc5}". 1695 static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI, 1696 InstCombiner &IC) { 1697 VectorType *DestVecTy = cast<VectorType>(CI.getType()); 1698 Value *IntInput = CI.getOperand(0); 1699 1700 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements()); 1701 if (!CollectInsertionElements(IntInput, 0, Elements, 1702 DestVecTy->getElementType(), 1703 IC.getDataLayout().isBigEndian())) 1704 return nullptr; 1705 1706 // If we succeeded, we know that all of the element are specified by Elements 1707 // or are zero if Elements has a null entry. Recast this as a set of 1708 // insertions. 1709 Value *Result = Constant::getNullValue(CI.getType()); 1710 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 1711 if (!Elements[i]) continue; // Unset element. 1712 1713 Result = IC.Builder->CreateInsertElement(Result, Elements[i], 1714 IC.Builder->getInt32(i)); 1715 } 1716 1717 return Result; 1718 } 1719 1720 1721 /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double 1722 /// bitcast. The various long double bitcasts can't get in here. 1723 static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI, InstCombiner &IC, 1724 const DataLayout &DL) { 1725 Value *Src = CI.getOperand(0); 1726 Type *DestTy = CI.getType(); 1727 1728 // If this is a bitcast from int to float, check to see if the int is an 1729 // extraction from a vector. 1730 Value *VecInput = nullptr; 1731 // bitcast(trunc(bitcast(somevector))) 1732 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) && 1733 isa<VectorType>(VecInput->getType())) { 1734 VectorType *VecTy = cast<VectorType>(VecInput->getType()); 1735 unsigned DestWidth = DestTy->getPrimitiveSizeInBits(); 1736 1737 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) { 1738 // If the element type of the vector doesn't match the result type, 1739 // bitcast it to be a vector type we can extract from. 1740 if (VecTy->getElementType() != DestTy) { 1741 VecTy = VectorType::get(DestTy, 1742 VecTy->getPrimitiveSizeInBits() / DestWidth); 1743 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy); 1744 } 1745 1746 unsigned Elt = 0; 1747 if (DL.isBigEndian()) 1748 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1; 1749 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt)); 1750 } 1751 } 1752 1753 // bitcast(trunc(lshr(bitcast(somevector), cst)) 1754 ConstantInt *ShAmt = nullptr; 1755 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)), 1756 m_ConstantInt(ShAmt)))) && 1757 isa<VectorType>(VecInput->getType())) { 1758 VectorType *VecTy = cast<VectorType>(VecInput->getType()); 1759 unsigned DestWidth = DestTy->getPrimitiveSizeInBits(); 1760 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 && 1761 ShAmt->getZExtValue() % DestWidth == 0) { 1762 // If the element type of the vector doesn't match the result type, 1763 // bitcast it to be a vector type we can extract from. 1764 if (VecTy->getElementType() != DestTy) { 1765 VecTy = VectorType::get(DestTy, 1766 VecTy->getPrimitiveSizeInBits() / DestWidth); 1767 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy); 1768 } 1769 1770 unsigned Elt = ShAmt->getZExtValue() / DestWidth; 1771 if (DL.isBigEndian()) 1772 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt; 1773 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt)); 1774 } 1775 } 1776 return nullptr; 1777 } 1778 1779 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) { 1780 // If the operands are integer typed then apply the integer transforms, 1781 // otherwise just apply the common ones. 1782 Value *Src = CI.getOperand(0); 1783 Type *SrcTy = Src->getType(); 1784 Type *DestTy = CI.getType(); 1785 1786 // Get rid of casts from one type to the same type. These are useless and can 1787 // be replaced by the operand. 1788 if (DestTy == Src->getType()) 1789 return ReplaceInstUsesWith(CI, Src); 1790 1791 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) { 1792 PointerType *SrcPTy = cast<PointerType>(SrcTy); 1793 Type *DstElTy = DstPTy->getElementType(); 1794 Type *SrcElTy = SrcPTy->getElementType(); 1795 1796 // If we are casting a alloca to a pointer to a type of the same 1797 // size, rewrite the allocation instruction to allocate the "right" type. 1798 // There is no need to modify malloc calls because it is their bitcast that 1799 // needs to be cleaned up. 1800 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src)) 1801 if (Instruction *V = PromoteCastOfAllocation(CI, *AI)) 1802 return V; 1803 1804 // If the source and destination are pointers, and this cast is equivalent 1805 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep. 1806 // This can enhance SROA and other transforms that want type-safe pointers. 1807 Constant *ZeroUInt = 1808 Constant::getNullValue(Type::getInt32Ty(CI.getContext())); 1809 unsigned NumZeros = 0; 1810 while (SrcElTy != DstElTy && 1811 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() && 1812 SrcElTy->getNumContainedTypes() /* not "{}" */) { 1813 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt); 1814 ++NumZeros; 1815 } 1816 1817 // If we found a path from the src to dest, create the getelementptr now. 1818 if (SrcElTy == DstElTy) { 1819 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt); 1820 return GetElementPtrInst::CreateInBounds(Src, Idxs); 1821 } 1822 } 1823 1824 // Try to optimize int -> float bitcasts. 1825 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy)) 1826 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this, DL)) 1827 return I; 1828 1829 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) { 1830 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) { 1831 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType()); 1832 return InsertElementInst::Create(UndefValue::get(DestTy), Elem, 1833 Constant::getNullValue(Type::getInt32Ty(CI.getContext()))); 1834 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast) 1835 } 1836 1837 if (isa<IntegerType>(SrcTy)) { 1838 // If this is a cast from an integer to vector, check to see if the input 1839 // is a trunc or zext of a bitcast from vector. If so, we can replace all 1840 // the casts with a shuffle and (potentially) a bitcast. 1841 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) { 1842 CastInst *SrcCast = cast<CastInst>(Src); 1843 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0))) 1844 if (isa<VectorType>(BCIn->getOperand(0)->getType())) 1845 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0), 1846 cast<VectorType>(DestTy), *this)) 1847 return I; 1848 } 1849 1850 // If the input is an 'or' instruction, we may be doing shifts and ors to 1851 // assemble the elements of the vector manually. Try to rip the code out 1852 // and replace it with insertelements. 1853 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this)) 1854 return ReplaceInstUsesWith(CI, V); 1855 } 1856 } 1857 1858 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) { 1859 if (SrcVTy->getNumElements() == 1) { 1860 // If our destination is not a vector, then make this a straight 1861 // scalar-scalar cast. 1862 if (!DestTy->isVectorTy()) { 1863 Value *Elem = 1864 Builder->CreateExtractElement(Src, 1865 Constant::getNullValue(Type::getInt32Ty(CI.getContext()))); 1866 return CastInst::Create(Instruction::BitCast, Elem, DestTy); 1867 } 1868 1869 // Otherwise, see if our source is an insert. If so, then use the scalar 1870 // component directly. 1871 if (InsertElementInst *IEI = 1872 dyn_cast<InsertElementInst>(CI.getOperand(0))) 1873 return CastInst::Create(Instruction::BitCast, IEI->getOperand(1), 1874 DestTy); 1875 } 1876 } 1877 1878 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) { 1879 // Okay, we have (bitcast (shuffle ..)). Check to see if this is 1880 // a bitcast to a vector with the same # elts. 1881 if (SVI->hasOneUse() && DestTy->isVectorTy() && 1882 DestTy->getVectorNumElements() == SVI->getType()->getNumElements() && 1883 SVI->getType()->getNumElements() == 1884 SVI->getOperand(0)->getType()->getVectorNumElements()) { 1885 BitCastInst *Tmp; 1886 // If either of the operands is a cast from CI.getType(), then 1887 // evaluating the shuffle in the casted destination's type will allow 1888 // us to eliminate at least one cast. 1889 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) && 1890 Tmp->getOperand(0)->getType() == DestTy) || 1891 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) && 1892 Tmp->getOperand(0)->getType() == DestTy)) { 1893 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy); 1894 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy); 1895 // Return a new shuffle vector. Use the same element ID's, as we 1896 // know the vector types match #elts. 1897 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2)); 1898 } 1899 } 1900 } 1901 1902 if (SrcTy->isPointerTy()) 1903 return commonPointerCastTransforms(CI); 1904 return commonCastTransforms(CI); 1905 } 1906 1907 Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) { 1908 // If the destination pointer element type is not the same as the source's 1909 // first do a bitcast to the destination type, and then the addrspacecast. 1910 // This allows the cast to be exposed to other transforms. 1911 Value *Src = CI.getOperand(0); 1912 PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType()); 1913 PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType()); 1914 1915 Type *DestElemTy = DestTy->getElementType(); 1916 if (SrcTy->getElementType() != DestElemTy) { 1917 Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace()); 1918 if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) { 1919 // Handle vectors of pointers. 1920 MidTy = VectorType::get(MidTy, VT->getNumElements()); 1921 } 1922 1923 Value *NewBitCast = Builder->CreateBitCast(Src, MidTy); 1924 return new AddrSpaceCastInst(NewBitCast, CI.getType()); 1925 } 1926 1927 return commonPointerCastTransforms(CI); 1928 } 1929