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