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/ADT/SetVector.h" 16 #include "llvm/Analysis/ConstantFolding.h" 17 #include "llvm/Analysis/TargetLibraryInfo.h" 18 #include "llvm/IR/DataLayout.h" 19 #include "llvm/IR/DIBuilder.h" 20 #include "llvm/IR/PatternMatch.h" 21 #include "llvm/Support/KnownBits.h" 22 using namespace llvm; 23 using namespace PatternMatch; 24 25 #define DEBUG_TYPE "instcombine" 26 27 /// Analyze 'Val', seeing if it is a simple linear expression. 28 /// If so, decompose it, returning some value X, such that Val is 29 /// X*Scale+Offset. 30 /// 31 static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale, 32 uint64_t &Offset) { 33 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { 34 Offset = CI->getZExtValue(); 35 Scale = 0; 36 return ConstantInt::get(Val->getType(), 0); 37 } 38 39 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) { 40 // Cannot look past anything that might overflow. 41 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val); 42 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) { 43 Scale = 1; 44 Offset = 0; 45 return Val; 46 } 47 48 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) { 49 if (I->getOpcode() == Instruction::Shl) { 50 // This is a value scaled by '1 << the shift amt'. 51 Scale = UINT64_C(1) << RHS->getZExtValue(); 52 Offset = 0; 53 return I->getOperand(0); 54 } 55 56 if (I->getOpcode() == Instruction::Mul) { 57 // This value is scaled by 'RHS'. 58 Scale = RHS->getZExtValue(); 59 Offset = 0; 60 return I->getOperand(0); 61 } 62 63 if (I->getOpcode() == Instruction::Add) { 64 // We have X+C. Check to see if we really have (X*C2)+C1, 65 // where C1 is divisible by C2. 66 unsigned SubScale; 67 Value *SubVal = 68 decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset); 69 Offset += RHS->getZExtValue(); 70 Scale = SubScale; 71 return SubVal; 72 } 73 } 74 } 75 76 // Otherwise, we can't look past this. 77 Scale = 1; 78 Offset = 0; 79 return Val; 80 } 81 82 /// If we find a cast of an allocation instruction, try to eliminate the cast by 83 /// moving the type information into the alloc. 84 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI, 85 AllocaInst &AI) { 86 PointerType *PTy = cast<PointerType>(CI.getType()); 87 88 BuilderTy AllocaBuilder(Builder); 89 AllocaBuilder.SetInsertPoint(&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 /// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns 161 /// true for, actually insert the code to evaluate the expression. 162 Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty, 163 bool isSigned) { 164 if (Constant *C = dyn_cast<Constant>(V)) { 165 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/); 166 // If we got a constantexpr back, try to simplify it with DL info. 167 if (Constant *FoldedC = ConstantFoldConstant(C, DL, &TLI)) 168 C = FoldedC; 169 return C; 170 } 171 172 // Otherwise, it must be an instruction. 173 Instruction *I = cast<Instruction>(V); 174 Instruction *Res = nullptr; 175 unsigned Opc = I->getOpcode(); 176 switch (Opc) { 177 case Instruction::Add: 178 case Instruction::Sub: 179 case Instruction::Mul: 180 case Instruction::And: 181 case Instruction::Or: 182 case Instruction::Xor: 183 case Instruction::AShr: 184 case Instruction::LShr: 185 case Instruction::Shl: 186 case Instruction::UDiv: 187 case Instruction::URem: { 188 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned); 189 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned); 190 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 191 break; 192 } 193 case Instruction::Trunc: 194 case Instruction::ZExt: 195 case Instruction::SExt: 196 // If the source type of the cast is the type we're trying for then we can 197 // just return the source. There's no need to insert it because it is not 198 // new. 199 if (I->getOperand(0)->getType() == Ty) 200 return I->getOperand(0); 201 202 // Otherwise, must be the same type of cast, so just reinsert a new one. 203 // This also handles the case of zext(trunc(x)) -> zext(x). 204 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty, 205 Opc == Instruction::SExt); 206 break; 207 case Instruction::Select: { 208 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned); 209 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned); 210 Res = SelectInst::Create(I->getOperand(0), True, False); 211 break; 212 } 213 case Instruction::PHI: { 214 PHINode *OPN = cast<PHINode>(I); 215 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues()); 216 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) { 217 Value *V = 218 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 Instruction::CastOps InstCombiner::isEliminableCastPair(const CastInst *CI1, 234 const CastInst *CI2) { 235 Type *SrcTy = CI1->getSrcTy(); 236 Type *MidTy = CI1->getDestTy(); 237 Type *DstTy = CI2->getDestTy(); 238 239 Instruction::CastOps firstOp = CI1->getOpcode(); 240 Instruction::CastOps secondOp = CI2->getOpcode(); 241 Type *SrcIntPtrTy = 242 SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr; 243 Type *MidIntPtrTy = 244 MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr; 245 Type *DstIntPtrTy = 246 DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr; 247 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, 248 DstTy, SrcIntPtrTy, MidIntPtrTy, 249 DstIntPtrTy); 250 251 // We don't want to form an inttoptr or ptrtoint that converts to an integer 252 // type that differs from the pointer size. 253 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) || 254 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy)) 255 Res = 0; 256 257 return Instruction::CastOps(Res); 258 } 259 260 /// Implement the transforms common to all CastInst visitors. 261 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) { 262 Value *Src = CI.getOperand(0); 263 264 // Try to eliminate a cast of a cast. 265 if (auto *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast 266 if (Instruction::CastOps NewOpc = isEliminableCastPair(CSrc, &CI)) { 267 // The first cast (CSrc) is eliminable so we need to fix up or replace 268 // the second cast (CI). CSrc will then have a good chance of being dead. 269 auto *Res = CastInst::Create(NewOpc, CSrc->getOperand(0), CI.getType()); 270 271 // If the eliminable cast has debug users, insert a debug value after the 272 // cast pointing to the new Value. 273 SmallVector<DbgInfoIntrinsic *, 1> CSrcDbgInsts; 274 findDbgUsers(CSrcDbgInsts, CSrc); 275 if (CSrcDbgInsts.size()) { 276 DIBuilder DIB(*CI.getModule()); 277 for (auto *DII : CSrcDbgInsts) 278 DIB.insertDbgValueIntrinsic( 279 Res, DII->getVariable(), DII->getExpression(), 280 DII->getDebugLoc().get(), &*std::next(CI.getIterator())); 281 } 282 return Res; 283 } 284 } 285 286 if (auto *Sel = dyn_cast<SelectInst>(Src)) { 287 // We are casting a select. Try to fold the cast into the select, but only 288 // if the select does not have a compare instruction with matching operand 289 // types. Creating a select with operands that are different sizes than its 290 // condition may inhibit other folds and lead to worse codegen. 291 auto *Cmp = dyn_cast<CmpInst>(Sel->getCondition()); 292 if (!Cmp || Cmp->getOperand(0)->getType() != Sel->getType()) 293 if (Instruction *NV = FoldOpIntoSelect(CI, Sel)) 294 return NV; 295 } 296 297 // If we are casting a PHI, then fold the cast into the PHI. 298 if (auto *PN = dyn_cast<PHINode>(Src)) { 299 // Don't do this if it would create a PHI node with an illegal type from a 300 // legal type. 301 if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() || 302 shouldChangeType(CI.getType(), Src->getType())) 303 if (Instruction *NV = foldOpIntoPhi(CI, PN)) 304 return NV; 305 } 306 307 return nullptr; 308 } 309 310 /// Constants and extensions/truncates from the destination type are always 311 /// free to be evaluated in that type. This is a helper for canEvaluate*. 312 static bool canAlwaysEvaluateInType(Value *V, Type *Ty) { 313 if (isa<Constant>(V)) 314 return true; 315 Value *X; 316 if ((match(V, m_ZExtOrSExt(m_Value(X))) || match(V, m_Trunc(m_Value(X)))) && 317 X->getType() == Ty) 318 return true; 319 320 return false; 321 } 322 323 /// Filter out values that we can not evaluate in the destination type for free. 324 /// This is a helper for canEvaluate*. 325 static bool canNotEvaluateInType(Value *V, Type *Ty) { 326 assert(!isa<Constant>(V) && "Constant should already be handled."); 327 if (!isa<Instruction>(V)) 328 return true; 329 // We don't extend or shrink something that has multiple uses -- doing so 330 // would require duplicating the instruction which isn't profitable. 331 if (!V->hasOneUse()) 332 return true; 333 334 return false; 335 } 336 337 /// Return true if we can evaluate the specified expression tree as type Ty 338 /// instead of its larger type, and arrive with the same value. 339 /// This is used by code that tries to eliminate truncates. 340 /// 341 /// Ty will always be a type smaller than V. We should return true if trunc(V) 342 /// can be computed by computing V in the smaller type. If V is an instruction, 343 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only 344 /// makes sense if x and y can be efficiently truncated. 345 /// 346 /// This function works on both vectors and scalars. 347 /// 348 static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC, 349 Instruction *CxtI) { 350 if (canAlwaysEvaluateInType(V, Ty)) 351 return true; 352 if (canNotEvaluateInType(V, Ty)) 353 return false; 354 355 auto *I = cast<Instruction>(V); 356 Type *OrigTy = V->getType(); 357 switch (I->getOpcode()) { 358 case Instruction::Add: 359 case Instruction::Sub: 360 case Instruction::Mul: 361 case Instruction::And: 362 case Instruction::Or: 363 case Instruction::Xor: 364 // These operators can all arbitrarily be extended or truncated. 365 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 366 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 367 368 case Instruction::UDiv: 369 case Instruction::URem: { 370 // UDiv and URem can be truncated if all the truncated bits are zero. 371 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 372 uint32_t BitWidth = Ty->getScalarSizeInBits(); 373 assert(BitWidth < OrigBitWidth && "Unexpected bitwidths!"); 374 APInt Mask = APInt::getBitsSetFrom(OrigBitWidth, BitWidth); 375 if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) && 376 IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) { 377 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 378 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 379 } 380 break; 381 } 382 case Instruction::Shl: { 383 // If we are truncating the result of this SHL, and if it's a shift of a 384 // constant amount, we can always perform a SHL in a smaller type. 385 const APInt *Amt; 386 if (match(I->getOperand(1), m_APInt(Amt))) { 387 uint32_t BitWidth = Ty->getScalarSizeInBits(); 388 if (Amt->getLimitedValue(BitWidth) < BitWidth) 389 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI); 390 } 391 break; 392 } 393 case Instruction::LShr: { 394 // If this is a truncate of a logical shr, we can truncate it to a smaller 395 // lshr iff we know that the bits we would otherwise be shifting in are 396 // already zeros. 397 const APInt *Amt; 398 if (match(I->getOperand(1), m_APInt(Amt))) { 399 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 400 uint32_t BitWidth = Ty->getScalarSizeInBits(); 401 if (Amt->getLimitedValue(BitWidth) < BitWidth && 402 IC.MaskedValueIsZero(I->getOperand(0), 403 APInt::getBitsSetFrom(OrigBitWidth, BitWidth), 0, CxtI)) { 404 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI); 405 } 406 } 407 break; 408 } 409 case Instruction::AShr: { 410 // If this is a truncate of an arithmetic shr, we can truncate it to a 411 // smaller ashr iff we know that all the bits from the sign bit of the 412 // original type and the sign bit of the truncate type are similar. 413 // TODO: It is enough to check that the bits we would be shifting in are 414 // similar to sign bit of the truncate type. 415 const APInt *Amt; 416 if (match(I->getOperand(1), m_APInt(Amt))) { 417 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 418 uint32_t BitWidth = Ty->getScalarSizeInBits(); 419 if (Amt->getLimitedValue(BitWidth) < BitWidth && 420 OrigBitWidth - BitWidth < 421 IC.ComputeNumSignBits(I->getOperand(0), 0, CxtI)) 422 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI); 423 } 424 break; 425 } 426 case Instruction::Trunc: 427 // trunc(trunc(x)) -> trunc(x) 428 return true; 429 case Instruction::ZExt: 430 case Instruction::SExt: 431 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest 432 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest 433 return true; 434 case Instruction::Select: { 435 SelectInst *SI = cast<SelectInst>(I); 436 return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) && 437 canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI); 438 } 439 case Instruction::PHI: { 440 // We can change a phi if we can change all operands. Note that we never 441 // get into trouble with cyclic PHIs here because we only consider 442 // instructions with a single use. 443 PHINode *PN = cast<PHINode>(I); 444 for (Value *IncValue : PN->incoming_values()) 445 if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI)) 446 return false; 447 return true; 448 } 449 default: 450 // TODO: Can handle more cases here. 451 break; 452 } 453 454 return false; 455 } 456 457 /// Given a vector that is bitcast to an integer, optionally logically 458 /// right-shifted, and truncated, convert it to an extractelement. 459 /// Example (big endian): 460 /// trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32 461 /// ---> 462 /// extractelement <4 x i32> %X, 1 463 static Instruction *foldVecTruncToExtElt(TruncInst &Trunc, InstCombiner &IC) { 464 Value *TruncOp = Trunc.getOperand(0); 465 Type *DestType = Trunc.getType(); 466 if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType)) 467 return nullptr; 468 469 Value *VecInput = nullptr; 470 ConstantInt *ShiftVal = nullptr; 471 if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)), 472 m_LShr(m_BitCast(m_Value(VecInput)), 473 m_ConstantInt(ShiftVal)))) || 474 !isa<VectorType>(VecInput->getType())) 475 return nullptr; 476 477 VectorType *VecType = cast<VectorType>(VecInput->getType()); 478 unsigned VecWidth = VecType->getPrimitiveSizeInBits(); 479 unsigned DestWidth = DestType->getPrimitiveSizeInBits(); 480 unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0; 481 482 if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0)) 483 return nullptr; 484 485 // If the element type of the vector doesn't match the result type, 486 // bitcast it to a vector type that we can extract from. 487 unsigned NumVecElts = VecWidth / DestWidth; 488 if (VecType->getElementType() != DestType) { 489 VecType = VectorType::get(DestType, NumVecElts); 490 VecInput = IC.Builder.CreateBitCast(VecInput, VecType, "bc"); 491 } 492 493 unsigned Elt = ShiftAmount / DestWidth; 494 if (IC.getDataLayout().isBigEndian()) 495 Elt = NumVecElts - 1 - Elt; 496 497 return ExtractElementInst::Create(VecInput, IC.Builder.getInt32(Elt)); 498 } 499 500 /// Rotate left/right may occur in a wider type than necessary because of type 501 /// promotion rules. Try to narrow all of the component instructions. 502 Instruction *InstCombiner::narrowRotate(TruncInst &Trunc) { 503 assert((isa<VectorType>(Trunc.getSrcTy()) || 504 shouldChangeType(Trunc.getSrcTy(), Trunc.getType())) && 505 "Don't narrow to an illegal scalar type"); 506 507 // First, find an or'd pair of opposite shifts with the same shifted operand: 508 // trunc (or (lshr ShVal, ShAmt0), (shl ShVal, ShAmt1)) 509 Value *Or0, *Or1; 510 if (!match(Trunc.getOperand(0), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1))))) 511 return nullptr; 512 513 Value *ShVal, *ShAmt0, *ShAmt1; 514 if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal), m_Value(ShAmt0)))) || 515 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(ShVal), m_Value(ShAmt1))))) 516 return nullptr; 517 518 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode(); 519 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode(); 520 if (ShiftOpcode0 == ShiftOpcode1) 521 return nullptr; 522 523 // The shift amounts must add up to the narrow bit width. 524 Value *ShAmt; 525 bool SubIsOnLHS; 526 Type *DestTy = Trunc.getType(); 527 unsigned NarrowWidth = DestTy->getScalarSizeInBits(); 528 if (match(ShAmt0, 529 m_OneUse(m_Sub(m_SpecificInt(NarrowWidth), m_Specific(ShAmt1))))) { 530 ShAmt = ShAmt1; 531 SubIsOnLHS = true; 532 } else if (match(ShAmt1, m_OneUse(m_Sub(m_SpecificInt(NarrowWidth), 533 m_Specific(ShAmt0))))) { 534 ShAmt = ShAmt0; 535 SubIsOnLHS = false; 536 } else { 537 return nullptr; 538 } 539 540 // The shifted value must have high zeros in the wide type. Typically, this 541 // will be a zext, but it could also be the result of an 'and' or 'shift'. 542 unsigned WideWidth = Trunc.getSrcTy()->getScalarSizeInBits(); 543 APInt HiBitMask = APInt::getHighBitsSet(WideWidth, WideWidth - NarrowWidth); 544 if (!MaskedValueIsZero(ShVal, HiBitMask, 0, &Trunc)) 545 return nullptr; 546 547 // We have an unnecessarily wide rotate! 548 // trunc (or (lshr ShVal, ShAmt), (shl ShVal, BitWidth - ShAmt)) 549 // Narrow it down to eliminate the zext/trunc: 550 // or (lshr trunc(ShVal), ShAmt0'), (shl trunc(ShVal), ShAmt1') 551 Value *NarrowShAmt = Builder.CreateTrunc(ShAmt, DestTy); 552 Value *NegShAmt = Builder.CreateNeg(NarrowShAmt); 553 554 // Mask both shift amounts to ensure there's no UB from oversized shifts. 555 Constant *MaskC = ConstantInt::get(DestTy, NarrowWidth - 1); 556 Value *MaskedShAmt = Builder.CreateAnd(NarrowShAmt, MaskC); 557 Value *MaskedNegShAmt = Builder.CreateAnd(NegShAmt, MaskC); 558 559 // Truncate the original value and use narrow ops. 560 Value *X = Builder.CreateTrunc(ShVal, DestTy); 561 Value *NarrowShAmt0 = SubIsOnLHS ? MaskedNegShAmt : MaskedShAmt; 562 Value *NarrowShAmt1 = SubIsOnLHS ? MaskedShAmt : MaskedNegShAmt; 563 Value *NarrowSh0 = Builder.CreateBinOp(ShiftOpcode0, X, NarrowShAmt0); 564 Value *NarrowSh1 = Builder.CreateBinOp(ShiftOpcode1, X, NarrowShAmt1); 565 return BinaryOperator::CreateOr(NarrowSh0, NarrowSh1); 566 } 567 568 /// Try to narrow the width of math or bitwise logic instructions by pulling a 569 /// truncate ahead of binary operators. 570 /// TODO: Transforms for truncated shifts should be moved into here. 571 Instruction *InstCombiner::narrowBinOp(TruncInst &Trunc) { 572 Type *SrcTy = Trunc.getSrcTy(); 573 Type *DestTy = Trunc.getType(); 574 if (!isa<VectorType>(SrcTy) && !shouldChangeType(SrcTy, DestTy)) 575 return nullptr; 576 577 BinaryOperator *BinOp; 578 if (!match(Trunc.getOperand(0), m_OneUse(m_BinOp(BinOp)))) 579 return nullptr; 580 581 Value *BinOp0 = BinOp->getOperand(0); 582 Value *BinOp1 = BinOp->getOperand(1); 583 switch (BinOp->getOpcode()) { 584 case Instruction::And: 585 case Instruction::Or: 586 case Instruction::Xor: 587 case Instruction::Add: 588 case Instruction::Sub: 589 case Instruction::Mul: { 590 Constant *C; 591 if (match(BinOp0, m_Constant(C))) { 592 // trunc (binop C, X) --> binop (trunc C', X) 593 Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy); 594 Value *TruncX = Builder.CreateTrunc(BinOp1, DestTy); 595 return BinaryOperator::Create(BinOp->getOpcode(), NarrowC, TruncX); 596 } 597 if (match(BinOp1, m_Constant(C))) { 598 // trunc (binop X, C) --> binop (trunc X, C') 599 Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy); 600 Value *TruncX = Builder.CreateTrunc(BinOp0, DestTy); 601 return BinaryOperator::Create(BinOp->getOpcode(), TruncX, NarrowC); 602 } 603 Value *X; 604 if (match(BinOp0, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) { 605 // trunc (binop (ext X), Y) --> binop X, (trunc Y) 606 Value *NarrowOp1 = Builder.CreateTrunc(BinOp1, DestTy); 607 return BinaryOperator::Create(BinOp->getOpcode(), X, NarrowOp1); 608 } 609 if (match(BinOp1, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) { 610 // trunc (binop Y, (ext X)) --> binop (trunc Y), X 611 Value *NarrowOp0 = Builder.CreateTrunc(BinOp0, DestTy); 612 return BinaryOperator::Create(BinOp->getOpcode(), NarrowOp0, X); 613 } 614 break; 615 } 616 617 default: break; 618 } 619 620 if (Instruction *NarrowOr = narrowRotate(Trunc)) 621 return NarrowOr; 622 623 return nullptr; 624 } 625 626 /// Try to narrow the width of a splat shuffle. This could be generalized to any 627 /// shuffle with a constant operand, but we limit the transform to avoid 628 /// creating a shuffle type that targets may not be able to lower effectively. 629 static Instruction *shrinkSplatShuffle(TruncInst &Trunc, 630 InstCombiner::BuilderTy &Builder) { 631 auto *Shuf = dyn_cast<ShuffleVectorInst>(Trunc.getOperand(0)); 632 if (Shuf && Shuf->hasOneUse() && isa<UndefValue>(Shuf->getOperand(1)) && 633 Shuf->getMask()->getSplatValue() && 634 Shuf->getType() == Shuf->getOperand(0)->getType()) { 635 // trunc (shuf X, Undef, SplatMask) --> shuf (trunc X), Undef, SplatMask 636 Constant *NarrowUndef = UndefValue::get(Trunc.getType()); 637 Value *NarrowOp = Builder.CreateTrunc(Shuf->getOperand(0), Trunc.getType()); 638 return new ShuffleVectorInst(NarrowOp, NarrowUndef, Shuf->getMask()); 639 } 640 641 return nullptr; 642 } 643 644 /// Try to narrow the width of an insert element. This could be generalized for 645 /// any vector constant, but we limit the transform to insertion into undef to 646 /// avoid potential backend problems from unsupported insertion widths. This 647 /// could also be extended to handle the case of inserting a scalar constant 648 /// into a vector variable. 649 static Instruction *shrinkInsertElt(CastInst &Trunc, 650 InstCombiner::BuilderTy &Builder) { 651 Instruction::CastOps Opcode = Trunc.getOpcode(); 652 assert((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) && 653 "Unexpected instruction for shrinking"); 654 655 auto *InsElt = dyn_cast<InsertElementInst>(Trunc.getOperand(0)); 656 if (!InsElt || !InsElt->hasOneUse()) 657 return nullptr; 658 659 Type *DestTy = Trunc.getType(); 660 Type *DestScalarTy = DestTy->getScalarType(); 661 Value *VecOp = InsElt->getOperand(0); 662 Value *ScalarOp = InsElt->getOperand(1); 663 Value *Index = InsElt->getOperand(2); 664 665 if (isa<UndefValue>(VecOp)) { 666 // trunc (inselt undef, X, Index) --> inselt undef, (trunc X), Index 667 // fptrunc (inselt undef, X, Index) --> inselt undef, (fptrunc X), Index 668 UndefValue *NarrowUndef = UndefValue::get(DestTy); 669 Value *NarrowOp = Builder.CreateCast(Opcode, ScalarOp, DestScalarTy); 670 return InsertElementInst::Create(NarrowUndef, NarrowOp, Index); 671 } 672 673 return nullptr; 674 } 675 676 Instruction *InstCombiner::visitTrunc(TruncInst &CI) { 677 if (Instruction *Result = commonCastTransforms(CI)) 678 return Result; 679 680 // Test if the trunc is the user of a select which is part of a 681 // minimum or maximum operation. If so, don't do any more simplification. 682 // Even simplifying demanded bits can break the canonical form of a 683 // min/max. 684 Value *LHS, *RHS; 685 if (SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0))) 686 if (matchSelectPattern(SI, LHS, RHS).Flavor != SPF_UNKNOWN) 687 return nullptr; 688 689 // See if we can simplify any instructions used by the input whose sole 690 // purpose is to compute bits we don't care about. 691 if (SimplifyDemandedInstructionBits(CI)) 692 return &CI; 693 694 Value *Src = CI.getOperand(0); 695 Type *DestTy = CI.getType(), *SrcTy = Src->getType(); 696 697 // Attempt to truncate the entire input expression tree to the destination 698 // type. Only do this if the dest type is a simple type, don't convert the 699 // expression tree to something weird like i93 unless the source is also 700 // strange. 701 if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) && 702 canEvaluateTruncated(Src, DestTy, *this, &CI)) { 703 704 // If this cast is a truncate, evaluting in a different type always 705 // eliminates the cast, so it is always a win. 706 LLVM_DEBUG( 707 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 708 " to avoid cast: " 709 << CI << '\n'); 710 Value *Res = EvaluateInDifferentType(Src, DestTy, false); 711 assert(Res->getType() == DestTy); 712 return replaceInstUsesWith(CI, Res); 713 } 714 715 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector. 716 if (DestTy->getScalarSizeInBits() == 1) { 717 Constant *One = ConstantInt::get(SrcTy, 1); 718 Src = Builder.CreateAnd(Src, One); 719 Value *Zero = Constant::getNullValue(Src->getType()); 720 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero); 721 } 722 723 // FIXME: Maybe combine the next two transforms to handle the no cast case 724 // more efficiently. Support vector types. Cleanup code by using m_OneUse. 725 726 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion. 727 Value *A = nullptr; ConstantInt *Cst = nullptr; 728 if (Src->hasOneUse() && 729 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) { 730 // We have three types to worry about here, the type of A, the source of 731 // the truncate (MidSize), and the destination of the truncate. We know that 732 // ASize < MidSize and MidSize > ResultSize, but don't know the relation 733 // between ASize and ResultSize. 734 unsigned ASize = A->getType()->getPrimitiveSizeInBits(); 735 736 // If the shift amount is larger than the size of A, then the result is 737 // known to be zero because all the input bits got shifted out. 738 if (Cst->getZExtValue() >= ASize) 739 return replaceInstUsesWith(CI, Constant::getNullValue(DestTy)); 740 741 // Since we're doing an lshr and a zero extend, and know that the shift 742 // amount is smaller than ASize, it is always safe to do the shift in A's 743 // type, then zero extend or truncate to the result. 744 Value *Shift = Builder.CreateLShr(A, Cst->getZExtValue()); 745 Shift->takeName(Src); 746 return CastInst::CreateIntegerCast(Shift, DestTy, false); 747 } 748 749 // FIXME: We should canonicalize to zext/trunc and remove this transform. 750 // Transform trunc(lshr (sext A), Cst) to ashr A, Cst to eliminate type 751 // conversion. 752 // It works because bits coming from sign extension have the same value as 753 // the sign bit of the original value; performing ashr instead of lshr 754 // generates bits of the same value as the sign bit. 755 if (Src->hasOneUse() && 756 match(Src, m_LShr(m_SExt(m_Value(A)), m_ConstantInt(Cst)))) { 757 Value *SExt = cast<Instruction>(Src)->getOperand(0); 758 const unsigned SExtSize = SExt->getType()->getPrimitiveSizeInBits(); 759 const unsigned ASize = A->getType()->getPrimitiveSizeInBits(); 760 const unsigned CISize = CI.getType()->getPrimitiveSizeInBits(); 761 const unsigned MaxAmt = SExtSize - std::max(CISize, ASize); 762 unsigned ShiftAmt = Cst->getZExtValue(); 763 764 // This optimization can be only performed when zero bits generated by 765 // the original lshr aren't pulled into the value after truncation, so we 766 // can only shift by values no larger than the number of extension bits. 767 // FIXME: Instead of bailing when the shift is too large, use and to clear 768 // the extra bits. 769 if (ShiftAmt <= MaxAmt) { 770 if (CISize == ASize) 771 return BinaryOperator::CreateAShr(A, ConstantInt::get(CI.getType(), 772 std::min(ShiftAmt, ASize - 1))); 773 if (SExt->hasOneUse()) { 774 Value *Shift = Builder.CreateAShr(A, std::min(ShiftAmt, ASize - 1)); 775 Shift->takeName(Src); 776 return CastInst::CreateIntegerCast(Shift, CI.getType(), true); 777 } 778 } 779 } 780 781 if (Instruction *I = narrowBinOp(CI)) 782 return I; 783 784 if (Instruction *I = shrinkSplatShuffle(CI, Builder)) 785 return I; 786 787 if (Instruction *I = shrinkInsertElt(CI, Builder)) 788 return I; 789 790 if (Src->hasOneUse() && isa<IntegerType>(SrcTy) && 791 shouldChangeType(SrcTy, DestTy)) { 792 // Transform "trunc (shl X, cst)" -> "shl (trunc X), cst" so long as the 793 // dest type is native and cst < dest size. 794 if (match(Src, m_Shl(m_Value(A), m_ConstantInt(Cst))) && 795 !match(A, m_Shr(m_Value(), m_Constant()))) { 796 // Skip shifts of shift by constants. It undoes a combine in 797 // FoldShiftByConstant and is the extend in reg pattern. 798 const unsigned DestSize = DestTy->getScalarSizeInBits(); 799 if (Cst->getValue().ult(DestSize)) { 800 Value *NewTrunc = Builder.CreateTrunc(A, DestTy, A->getName() + ".tr"); 801 802 return BinaryOperator::Create( 803 Instruction::Shl, NewTrunc, 804 ConstantInt::get(DestTy, Cst->getValue().trunc(DestSize))); 805 } 806 } 807 } 808 809 if (Instruction *I = foldVecTruncToExtElt(CI, *this)) 810 return I; 811 812 return nullptr; 813 } 814 815 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, ZExtInst &CI, 816 bool DoTransform) { 817 // If we are just checking for a icmp eq of a single bit and zext'ing it 818 // to an integer, then shift the bit to the appropriate place and then 819 // cast to integer to avoid the comparison. 820 const APInt *Op1CV; 821 if (match(ICI->getOperand(1), m_APInt(Op1CV))) { 822 823 // zext (x <s 0) to i32 --> x>>u31 true if signbit set. 824 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear. 825 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV->isNullValue()) || 826 (ICI->getPredicate() == ICmpInst::ICMP_SGT && Op1CV->isAllOnesValue())) { 827 if (!DoTransform) return ICI; 828 829 Value *In = ICI->getOperand(0); 830 Value *Sh = ConstantInt::get(In->getType(), 831 In->getType()->getScalarSizeInBits() - 1); 832 In = Builder.CreateLShr(In, Sh, In->getName() + ".lobit"); 833 if (In->getType() != CI.getType()) 834 In = Builder.CreateIntCast(In, CI.getType(), false /*ZExt*/); 835 836 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) { 837 Constant *One = ConstantInt::get(In->getType(), 1); 838 In = Builder.CreateXor(In, One, In->getName() + ".not"); 839 } 840 841 return replaceInstUsesWith(CI, In); 842 } 843 844 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set. 845 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. 846 // zext (X == 1) to i32 --> X iff X has only the low bit set. 847 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set. 848 // zext (X != 0) to i32 --> X iff X has only the low bit set. 849 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set. 850 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set. 851 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. 852 if ((Op1CV->isNullValue() || Op1CV->isPowerOf2()) && 853 // This only works for EQ and NE 854 ICI->isEquality()) { 855 // If Op1C some other power of two, convert: 856 KnownBits Known = computeKnownBits(ICI->getOperand(0), 0, &CI); 857 858 APInt KnownZeroMask(~Known.Zero); 859 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1? 860 if (!DoTransform) return ICI; 861 862 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE; 863 if (!Op1CV->isNullValue() && (*Op1CV != KnownZeroMask)) { 864 // (X&4) == 2 --> false 865 // (X&4) != 2 --> true 866 Constant *Res = ConstantInt::get(CI.getType(), isNE); 867 return replaceInstUsesWith(CI, Res); 868 } 869 870 uint32_t ShAmt = KnownZeroMask.logBase2(); 871 Value *In = ICI->getOperand(0); 872 if (ShAmt) { 873 // Perform a logical shr by shiftamt. 874 // Insert the shift to put the result in the low bit. 875 In = Builder.CreateLShr(In, ConstantInt::get(In->getType(), ShAmt), 876 In->getName() + ".lobit"); 877 } 878 879 if (!Op1CV->isNullValue() == isNE) { // Toggle the low bit. 880 Constant *One = ConstantInt::get(In->getType(), 1); 881 In = Builder.CreateXor(In, One); 882 } 883 884 if (CI.getType() == In->getType()) 885 return replaceInstUsesWith(CI, In); 886 887 Value *IntCast = Builder.CreateIntCast(In, CI.getType(), false); 888 return replaceInstUsesWith(CI, IntCast); 889 } 890 } 891 } 892 893 // icmp ne A, B is equal to xor A, B when A and B only really have one bit. 894 // It is also profitable to transform icmp eq into not(xor(A, B)) because that 895 // may lead to additional simplifications. 896 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) { 897 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) { 898 Value *LHS = ICI->getOperand(0); 899 Value *RHS = ICI->getOperand(1); 900 901 KnownBits KnownLHS = computeKnownBits(LHS, 0, &CI); 902 KnownBits KnownRHS = computeKnownBits(RHS, 0, &CI); 903 904 if (KnownLHS.Zero == KnownRHS.Zero && KnownLHS.One == KnownRHS.One) { 905 APInt KnownBits = KnownLHS.Zero | KnownLHS.One; 906 APInt UnknownBit = ~KnownBits; 907 if (UnknownBit.countPopulation() == 1) { 908 if (!DoTransform) return ICI; 909 910 Value *Result = Builder.CreateXor(LHS, RHS); 911 912 // Mask off any bits that are set and won't be shifted away. 913 if (KnownLHS.One.uge(UnknownBit)) 914 Result = Builder.CreateAnd(Result, 915 ConstantInt::get(ITy, UnknownBit)); 916 917 // Shift the bit we're testing down to the lsb. 918 Result = Builder.CreateLShr( 919 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros())); 920 921 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 922 Result = Builder.CreateXor(Result, ConstantInt::get(ITy, 1)); 923 Result->takeName(ICI); 924 return replaceInstUsesWith(CI, Result); 925 } 926 } 927 } 928 } 929 930 return nullptr; 931 } 932 933 /// Determine if the specified value can be computed in the specified wider type 934 /// and produce the same low bits. If not, return false. 935 /// 936 /// If this function returns true, it can also return a non-zero number of bits 937 /// (in BitsToClear) which indicates that the value it computes is correct for 938 /// the zero extend, but that the additional BitsToClear bits need to be zero'd 939 /// out. For example, to promote something like: 940 /// 941 /// %B = trunc i64 %A to i32 942 /// %C = lshr i32 %B, 8 943 /// %E = zext i32 %C to i64 944 /// 945 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be 946 /// set to 8 to indicate that the promoted value needs to have bits 24-31 947 /// cleared in addition to bits 32-63. Since an 'and' will be generated to 948 /// clear the top bits anyway, doing this has no extra cost. 949 /// 950 /// This function works on both vectors and scalars. 951 static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear, 952 InstCombiner &IC, Instruction *CxtI) { 953 BitsToClear = 0; 954 if (canAlwaysEvaluateInType(V, Ty)) 955 return true; 956 if (canNotEvaluateInType(V, Ty)) 957 return false; 958 959 auto *I = cast<Instruction>(V); 960 unsigned Tmp; 961 switch (I->getOpcode()) { 962 case Instruction::ZExt: // zext(zext(x)) -> zext(x). 963 case Instruction::SExt: // zext(sext(x)) -> sext(x). 964 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x) 965 return true; 966 case Instruction::And: 967 case Instruction::Or: 968 case Instruction::Xor: 969 case Instruction::Add: 970 case Instruction::Sub: 971 case Instruction::Mul: 972 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) || 973 !canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI)) 974 return false; 975 // These can all be promoted if neither operand has 'bits to clear'. 976 if (BitsToClear == 0 && Tmp == 0) 977 return true; 978 979 // If the operation is an AND/OR/XOR and the bits to clear are zero in the 980 // other side, BitsToClear is ok. 981 if (Tmp == 0 && I->isBitwiseLogicOp()) { 982 // We use MaskedValueIsZero here for generality, but the case we care 983 // about the most is constant RHS. 984 unsigned VSize = V->getType()->getScalarSizeInBits(); 985 if (IC.MaskedValueIsZero(I->getOperand(1), 986 APInt::getHighBitsSet(VSize, BitsToClear), 987 0, CxtI)) { 988 // If this is an And instruction and all of the BitsToClear are 989 // known to be zero we can reset BitsToClear. 990 if (I->getOpcode() == Instruction::And) 991 BitsToClear = 0; 992 return true; 993 } 994 } 995 996 // Otherwise, we don't know how to analyze this BitsToClear case yet. 997 return false; 998 999 case Instruction::Shl: { 1000 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the 1001 // upper bits we can reduce BitsToClear by the shift amount. 1002 const APInt *Amt; 1003 if (match(I->getOperand(1), m_APInt(Amt))) { 1004 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI)) 1005 return false; 1006 uint64_t ShiftAmt = Amt->getZExtValue(); 1007 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0; 1008 return true; 1009 } 1010 return false; 1011 } 1012 case Instruction::LShr: { 1013 // We can promote lshr(x, cst) if we can promote x. This requires the 1014 // ultimate 'and' to clear out the high zero bits we're clearing out though. 1015 const APInt *Amt; 1016 if (match(I->getOperand(1), m_APInt(Amt))) { 1017 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI)) 1018 return false; 1019 BitsToClear += Amt->getZExtValue(); 1020 if (BitsToClear > V->getType()->getScalarSizeInBits()) 1021 BitsToClear = V->getType()->getScalarSizeInBits(); 1022 return true; 1023 } 1024 // Cannot promote variable LSHR. 1025 return false; 1026 } 1027 case Instruction::Select: 1028 if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) || 1029 !canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) || 1030 // TODO: If important, we could handle the case when the BitsToClear are 1031 // known zero in the disagreeing side. 1032 Tmp != BitsToClear) 1033 return false; 1034 return true; 1035 1036 case Instruction::PHI: { 1037 // We can change a phi if we can change all operands. Note that we never 1038 // get into trouble with cyclic PHIs here because we only consider 1039 // instructions with a single use. 1040 PHINode *PN = cast<PHINode>(I); 1041 if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI)) 1042 return false; 1043 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) 1044 if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) || 1045 // TODO: If important, we could handle the case when the BitsToClear 1046 // are known zero in the disagreeing input. 1047 Tmp != BitsToClear) 1048 return false; 1049 return true; 1050 } 1051 default: 1052 // TODO: Can handle more cases here. 1053 return false; 1054 } 1055 } 1056 1057 Instruction *InstCombiner::visitZExt(ZExtInst &CI) { 1058 // If this zero extend is only used by a truncate, let the truncate be 1059 // eliminated before we try to optimize this zext. 1060 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back())) 1061 return nullptr; 1062 1063 // If one of the common conversion will work, do it. 1064 if (Instruction *Result = commonCastTransforms(CI)) 1065 return Result; 1066 1067 Value *Src = CI.getOperand(0); 1068 Type *SrcTy = Src->getType(), *DestTy = CI.getType(); 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 unsigned BitsToClear; 1075 if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) && 1076 canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) { 1077 assert(BitsToClear <= SrcTy->getScalarSizeInBits() && 1078 "Can't clear more bits than in SrcTy"); 1079 1080 // Okay, we can transform this! Insert the new expression now. 1081 LLVM_DEBUG( 1082 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 1083 " to avoid zero extend: " 1084 << CI << '\n'); 1085 Value *Res = EvaluateInDifferentType(Src, DestTy, false); 1086 assert(Res->getType() == DestTy); 1087 1088 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear; 1089 uint32_t DestBitSize = DestTy->getScalarSizeInBits(); 1090 1091 // If the high bits are already filled with zeros, just replace this 1092 // cast with the result. 1093 if (MaskedValueIsZero(Res, 1094 APInt::getHighBitsSet(DestBitSize, 1095 DestBitSize-SrcBitsKept), 1096 0, &CI)) 1097 return replaceInstUsesWith(CI, Res); 1098 1099 // We need to emit an AND to clear the high bits. 1100 Constant *C = ConstantInt::get(Res->getType(), 1101 APInt::getLowBitsSet(DestBitSize, SrcBitsKept)); 1102 return BinaryOperator::CreateAnd(Res, C); 1103 } 1104 1105 // If this is a TRUNC followed by a ZEXT then we are dealing with integral 1106 // types and if the sizes are just right we can convert this into a logical 1107 // 'and' which will be much cheaper than the pair of casts. 1108 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast 1109 // TODO: Subsume this into EvaluateInDifferentType. 1110 1111 // Get the sizes of the types involved. We know that the intermediate type 1112 // will be smaller than A or C, but don't know the relation between A and C. 1113 Value *A = CSrc->getOperand(0); 1114 unsigned SrcSize = A->getType()->getScalarSizeInBits(); 1115 unsigned MidSize = CSrc->getType()->getScalarSizeInBits(); 1116 unsigned DstSize = CI.getType()->getScalarSizeInBits(); 1117 // If we're actually extending zero bits, then if 1118 // SrcSize < DstSize: zext(a & mask) 1119 // SrcSize == DstSize: a & mask 1120 // SrcSize > DstSize: trunc(a) & mask 1121 if (SrcSize < DstSize) { 1122 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize)); 1123 Constant *AndConst = ConstantInt::get(A->getType(), AndValue); 1124 Value *And = Builder.CreateAnd(A, AndConst, CSrc->getName() + ".mask"); 1125 return new ZExtInst(And, CI.getType()); 1126 } 1127 1128 if (SrcSize == DstSize) { 1129 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize)); 1130 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(), 1131 AndValue)); 1132 } 1133 if (SrcSize > DstSize) { 1134 Value *Trunc = Builder.CreateTrunc(A, CI.getType()); 1135 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize)); 1136 return BinaryOperator::CreateAnd(Trunc, 1137 ConstantInt::get(Trunc->getType(), 1138 AndValue)); 1139 } 1140 } 1141 1142 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) 1143 return transformZExtICmp(ICI, CI); 1144 1145 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src); 1146 if (SrcI && SrcI->getOpcode() == Instruction::Or) { 1147 // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) if at least one 1148 // of the (zext icmp) can be eliminated. If so, immediately perform the 1149 // according elimination. 1150 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0)); 1151 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1)); 1152 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() && 1153 (transformZExtICmp(LHS, CI, false) || 1154 transformZExtICmp(RHS, CI, false))) { 1155 // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) 1156 Value *LCast = Builder.CreateZExt(LHS, CI.getType(), LHS->getName()); 1157 Value *RCast = Builder.CreateZExt(RHS, CI.getType(), RHS->getName()); 1158 BinaryOperator *Or = BinaryOperator::Create(Instruction::Or, LCast, RCast); 1159 1160 // Perform the elimination. 1161 if (auto *LZExt = dyn_cast<ZExtInst>(LCast)) 1162 transformZExtICmp(LHS, *LZExt); 1163 if (auto *RZExt = dyn_cast<ZExtInst>(RCast)) 1164 transformZExtICmp(RHS, *RZExt); 1165 1166 return Or; 1167 } 1168 } 1169 1170 // zext(trunc(X) & C) -> (X & zext(C)). 1171 Constant *C; 1172 Value *X; 1173 if (SrcI && 1174 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) && 1175 X->getType() == CI.getType()) 1176 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType())); 1177 1178 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)). 1179 Value *And; 1180 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) && 1181 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) && 1182 X->getType() == CI.getType()) { 1183 Constant *ZC = ConstantExpr::getZExt(C, CI.getType()); 1184 return BinaryOperator::CreateXor(Builder.CreateAnd(X, ZC), ZC); 1185 } 1186 1187 return nullptr; 1188 } 1189 1190 /// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp. 1191 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) { 1192 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1); 1193 ICmpInst::Predicate Pred = ICI->getPredicate(); 1194 1195 // Don't bother if Op1 isn't of vector or integer type. 1196 if (!Op1->getType()->isIntOrIntVectorTy()) 1197 return nullptr; 1198 1199 if (Constant *Op1C = dyn_cast<Constant>(Op1)) { 1200 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative 1201 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive 1202 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) || 1203 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) { 1204 1205 Value *Sh = ConstantInt::get(Op0->getType(), 1206 Op0->getType()->getScalarSizeInBits()-1); 1207 Value *In = Builder.CreateAShr(Op0, Sh, Op0->getName() + ".lobit"); 1208 if (In->getType() != CI.getType()) 1209 In = Builder.CreateIntCast(In, CI.getType(), true /*SExt*/); 1210 1211 if (Pred == ICmpInst::ICMP_SGT) 1212 In = Builder.CreateNot(In, In->getName() + ".not"); 1213 return replaceInstUsesWith(CI, In); 1214 } 1215 } 1216 1217 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 1218 // If we know that only one bit of the LHS of the icmp can be set and we 1219 // have an equality comparison with zero or a power of 2, we can transform 1220 // the icmp and sext into bitwise/integer operations. 1221 if (ICI->hasOneUse() && 1222 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){ 1223 KnownBits Known = computeKnownBits(Op0, 0, &CI); 1224 1225 APInt KnownZeroMask(~Known.Zero); 1226 if (KnownZeroMask.isPowerOf2()) { 1227 Value *In = ICI->getOperand(0); 1228 1229 // If the icmp tests for a known zero bit we can constant fold it. 1230 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) { 1231 Value *V = Pred == ICmpInst::ICMP_NE ? 1232 ConstantInt::getAllOnesValue(CI.getType()) : 1233 ConstantInt::getNullValue(CI.getType()); 1234 return replaceInstUsesWith(CI, V); 1235 } 1236 1237 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) { 1238 // sext ((x & 2^n) == 0) -> (x >> n) - 1 1239 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1 1240 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros(); 1241 // Perform a right shift to place the desired bit in the LSB. 1242 if (ShiftAmt) 1243 In = Builder.CreateLShr(In, 1244 ConstantInt::get(In->getType(), ShiftAmt)); 1245 1246 // At this point "In" is either 1 or 0. Subtract 1 to turn 1247 // {1, 0} -> {0, -1}. 1248 In = Builder.CreateAdd(In, 1249 ConstantInt::getAllOnesValue(In->getType()), 1250 "sext"); 1251 } else { 1252 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1 1253 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1 1254 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros(); 1255 // Perform a left shift to place the desired bit in the MSB. 1256 if (ShiftAmt) 1257 In = Builder.CreateShl(In, 1258 ConstantInt::get(In->getType(), ShiftAmt)); 1259 1260 // Distribute the bit over the whole bit width. 1261 In = Builder.CreateAShr(In, ConstantInt::get(In->getType(), 1262 KnownZeroMask.getBitWidth() - 1), "sext"); 1263 } 1264 1265 if (CI.getType() == In->getType()) 1266 return replaceInstUsesWith(CI, In); 1267 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/); 1268 } 1269 } 1270 } 1271 1272 return nullptr; 1273 } 1274 1275 /// Return true if we can take the specified value and return it as type Ty 1276 /// without inserting any new casts and without changing the value of the common 1277 /// low bits. This is used by code that tries to promote integer operations to 1278 /// a wider types will allow us to eliminate the extension. 1279 /// 1280 /// This function works on both vectors and scalars. 1281 /// 1282 static bool canEvaluateSExtd(Value *V, Type *Ty) { 1283 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() && 1284 "Can't sign extend type to a smaller type"); 1285 if (canAlwaysEvaluateInType(V, Ty)) 1286 return true; 1287 if (canNotEvaluateInType(V, Ty)) 1288 return false; 1289 1290 auto *I = cast<Instruction>(V); 1291 switch (I->getOpcode()) { 1292 case Instruction::SExt: // sext(sext(x)) -> sext(x) 1293 case Instruction::ZExt: // sext(zext(x)) -> zext(x) 1294 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x) 1295 return true; 1296 case Instruction::And: 1297 case Instruction::Or: 1298 case Instruction::Xor: 1299 case Instruction::Add: 1300 case Instruction::Sub: 1301 case Instruction::Mul: 1302 // These operators can all arbitrarily be extended if their inputs can. 1303 return canEvaluateSExtd(I->getOperand(0), Ty) && 1304 canEvaluateSExtd(I->getOperand(1), Ty); 1305 1306 //case Instruction::Shl: TODO 1307 //case Instruction::LShr: TODO 1308 1309 case Instruction::Select: 1310 return canEvaluateSExtd(I->getOperand(1), Ty) && 1311 canEvaluateSExtd(I->getOperand(2), Ty); 1312 1313 case Instruction::PHI: { 1314 // We can change a phi if we can change all operands. Note that we never 1315 // get into trouble with cyclic PHIs here because we only consider 1316 // instructions with a single use. 1317 PHINode *PN = cast<PHINode>(I); 1318 for (Value *IncValue : PN->incoming_values()) 1319 if (!canEvaluateSExtd(IncValue, Ty)) return false; 1320 return true; 1321 } 1322 default: 1323 // TODO: Can handle more cases here. 1324 break; 1325 } 1326 1327 return false; 1328 } 1329 1330 Instruction *InstCombiner::visitSExt(SExtInst &CI) { 1331 // If this sign extend is only used by a truncate, let the truncate be 1332 // eliminated before we try to optimize this sext. 1333 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back())) 1334 return nullptr; 1335 1336 if (Instruction *I = commonCastTransforms(CI)) 1337 return I; 1338 1339 Value *Src = CI.getOperand(0); 1340 Type *SrcTy = Src->getType(), *DestTy = CI.getType(); 1341 1342 // If we know that the value being extended is positive, we can use a zext 1343 // instead. 1344 KnownBits Known = computeKnownBits(Src, 0, &CI); 1345 if (Known.isNonNegative()) { 1346 Value *ZExt = Builder.CreateZExt(Src, DestTy); 1347 return replaceInstUsesWith(CI, ZExt); 1348 } 1349 1350 // Attempt to extend the entire input expression tree to the destination 1351 // type. Only do this if the dest type is a simple type, don't convert the 1352 // expression tree to something weird like i93 unless the source is also 1353 // strange. 1354 if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) && 1355 canEvaluateSExtd(Src, DestTy)) { 1356 // Okay, we can transform this! Insert the new expression now. 1357 LLVM_DEBUG( 1358 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 1359 " to avoid sign extend: " 1360 << CI << '\n'); 1361 Value *Res = EvaluateInDifferentType(Src, DestTy, true); 1362 assert(Res->getType() == DestTy); 1363 1364 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits(); 1365 uint32_t DestBitSize = DestTy->getScalarSizeInBits(); 1366 1367 // If the high bits are already filled with sign bit, just replace this 1368 // cast with the result. 1369 if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize) 1370 return replaceInstUsesWith(CI, Res); 1371 1372 // We need to emit a shl + ashr to do the sign extend. 1373 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize); 1374 return BinaryOperator::CreateAShr(Builder.CreateShl(Res, ShAmt, "sext"), 1375 ShAmt); 1376 } 1377 1378 // If the input is a trunc from the destination type, then turn sext(trunc(x)) 1379 // into shifts. 1380 Value *X; 1381 if (match(Src, m_OneUse(m_Trunc(m_Value(X)))) && X->getType() == DestTy) { 1382 // sext(trunc(X)) --> ashr(shl(X, C), C) 1383 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 1384 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 1385 Constant *ShAmt = ConstantInt::get(DestTy, DestBitSize - SrcBitSize); 1386 return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShAmt), ShAmt); 1387 } 1388 1389 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) 1390 return transformSExtICmp(ICI, CI); 1391 1392 // If the input is a shl/ashr pair of a same constant, then this is a sign 1393 // extension from a smaller value. If we could trust arbitrary bitwidth 1394 // integers, we could turn this into a truncate to the smaller bit and then 1395 // use a sext for the whole extension. Since we don't, look deeper and check 1396 // for a truncate. If the source and dest are the same type, eliminate the 1397 // trunc and extend and just do shifts. For example, turn: 1398 // %a = trunc i32 %i to i8 1399 // %b = shl i8 %a, 6 1400 // %c = ashr i8 %b, 6 1401 // %d = sext i8 %c to i32 1402 // into: 1403 // %a = shl i32 %i, 30 1404 // %d = ashr i32 %a, 30 1405 Value *A = nullptr; 1406 // TODO: Eventually this could be subsumed by EvaluateInDifferentType. 1407 ConstantInt *BA = nullptr, *CA = nullptr; 1408 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)), 1409 m_ConstantInt(CA))) && 1410 BA == CA && A->getType() == CI.getType()) { 1411 unsigned MidSize = Src->getType()->getScalarSizeInBits(); 1412 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits(); 1413 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize; 1414 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt); 1415 A = Builder.CreateShl(A, ShAmtV, CI.getName()); 1416 return BinaryOperator::CreateAShr(A, ShAmtV); 1417 } 1418 1419 return nullptr; 1420 } 1421 1422 1423 /// Return a Constant* for the specified floating-point constant if it fits 1424 /// in the specified FP type without changing its value. 1425 static bool fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) { 1426 bool losesInfo; 1427 APFloat F = CFP->getValueAPF(); 1428 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo); 1429 return !losesInfo; 1430 } 1431 1432 static Type *shrinkFPConstant(ConstantFP *CFP) { 1433 if (CFP->getType() == Type::getPPC_FP128Ty(CFP->getContext())) 1434 return nullptr; // No constant folding of this. 1435 // See if the value can be truncated to half and then reextended. 1436 if (fitsInFPType(CFP, APFloat::IEEEhalf())) 1437 return Type::getHalfTy(CFP->getContext()); 1438 // See if the value can be truncated to float and then reextended. 1439 if (fitsInFPType(CFP, APFloat::IEEEsingle())) 1440 return Type::getFloatTy(CFP->getContext()); 1441 if (CFP->getType()->isDoubleTy()) 1442 return nullptr; // Won't shrink. 1443 if (fitsInFPType(CFP, APFloat::IEEEdouble())) 1444 return Type::getDoubleTy(CFP->getContext()); 1445 // Don't try to shrink to various long double types. 1446 return nullptr; 1447 } 1448 1449 // Determine if this is a vector of ConstantFPs and if so, return the minimal 1450 // type we can safely truncate all elements to. 1451 // TODO: Make these support undef elements. 1452 static Type *shrinkFPConstantVector(Value *V) { 1453 auto *CV = dyn_cast<Constant>(V); 1454 if (!CV || !CV->getType()->isVectorTy()) 1455 return nullptr; 1456 1457 Type *MinType = nullptr; 1458 1459 unsigned NumElts = CV->getType()->getVectorNumElements(); 1460 for (unsigned i = 0; i != NumElts; ++i) { 1461 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i)); 1462 if (!CFP) 1463 return nullptr; 1464 1465 Type *T = shrinkFPConstant(CFP); 1466 if (!T) 1467 return nullptr; 1468 1469 // If we haven't found a type yet or this type has a larger mantissa than 1470 // our previous type, this is our new minimal type. 1471 if (!MinType || T->getFPMantissaWidth() > MinType->getFPMantissaWidth()) 1472 MinType = T; 1473 } 1474 1475 // Make a vector type from the minimal type. 1476 return VectorType::get(MinType, NumElts); 1477 } 1478 1479 /// Find the minimum FP type we can safely truncate to. 1480 static Type *getMinimumFPType(Value *V) { 1481 if (auto *FPExt = dyn_cast<FPExtInst>(V)) 1482 return FPExt->getOperand(0)->getType(); 1483 1484 // If this value is a constant, return the constant in the smallest FP type 1485 // that can accurately represent it. This allows us to turn 1486 // (float)((double)X+2.0) into x+2.0f. 1487 if (auto *CFP = dyn_cast<ConstantFP>(V)) 1488 if (Type *T = shrinkFPConstant(CFP)) 1489 return T; 1490 1491 // Try to shrink a vector of FP constants. 1492 if (Type *T = shrinkFPConstantVector(V)) 1493 return T; 1494 1495 return V->getType(); 1496 } 1497 1498 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &FPT) { 1499 if (Instruction *I = commonCastTransforms(FPT)) 1500 return I; 1501 1502 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to 1503 // simplify this expression to avoid one or more of the trunc/extend 1504 // operations if we can do so without changing the numerical results. 1505 // 1506 // The exact manner in which the widths of the operands interact to limit 1507 // what we can and cannot do safely varies from operation to operation, and 1508 // is explained below in the various case statements. 1509 Type *Ty = FPT.getType(); 1510 BinaryOperator *OpI = dyn_cast<BinaryOperator>(FPT.getOperand(0)); 1511 if (OpI && OpI->hasOneUse()) { 1512 Type *LHSMinType = getMinimumFPType(OpI->getOperand(0)); 1513 Type *RHSMinType = getMinimumFPType(OpI->getOperand(1)); 1514 unsigned OpWidth = OpI->getType()->getFPMantissaWidth(); 1515 unsigned LHSWidth = LHSMinType->getFPMantissaWidth(); 1516 unsigned RHSWidth = RHSMinType->getFPMantissaWidth(); 1517 unsigned SrcWidth = std::max(LHSWidth, RHSWidth); 1518 unsigned DstWidth = Ty->getFPMantissaWidth(); 1519 switch (OpI->getOpcode()) { 1520 default: break; 1521 case Instruction::FAdd: 1522 case Instruction::FSub: 1523 // For addition and subtraction, the infinitely precise result can 1524 // essentially be arbitrarily wide; proving that double rounding 1525 // will not occur because the result of OpI is exact (as we will for 1526 // FMul, for example) is hopeless. However, we *can* nonetheless 1527 // frequently know that double rounding cannot occur (or that it is 1528 // innocuous) by taking advantage of the specific structure of 1529 // infinitely-precise results that admit double rounding. 1530 // 1531 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient 1532 // to represent both sources, we can guarantee that the double 1533 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis, 1534 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..." 1535 // for proof of this fact). 1536 // 1537 // Note: Figueroa does not consider the case where DstFormat != 1538 // SrcFormat. It's possible (likely even!) that this analysis 1539 // could be tightened for those cases, but they are rare (the main 1540 // case of interest here is (float)((double)float + float)). 1541 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) { 1542 Value *LHS = Builder.CreateFPTrunc(OpI->getOperand(0), Ty); 1543 Value *RHS = Builder.CreateFPTrunc(OpI->getOperand(1), Ty); 1544 Instruction *RI = BinaryOperator::Create(OpI->getOpcode(), LHS, RHS); 1545 RI->copyFastMathFlags(OpI); 1546 return RI; 1547 } 1548 break; 1549 case Instruction::FMul: 1550 // For multiplication, the infinitely precise result has at most 1551 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient 1552 // that such a value can be exactly represented, then no double 1553 // rounding can possibly occur; we can safely perform the operation 1554 // in the destination format if it can represent both sources. 1555 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) { 1556 Value *LHS = Builder.CreateFPTrunc(OpI->getOperand(0), Ty); 1557 Value *RHS = Builder.CreateFPTrunc(OpI->getOperand(1), Ty); 1558 return BinaryOperator::CreateFMulFMF(LHS, RHS, OpI); 1559 } 1560 break; 1561 case Instruction::FDiv: 1562 // For division, we use again use the bound from Figueroa's 1563 // dissertation. I am entirely certain that this bound can be 1564 // tightened in the unbalanced operand case by an analysis based on 1565 // the diophantine rational approximation bound, but the well-known 1566 // condition used here is a good conservative first pass. 1567 // TODO: Tighten bound via rigorous analysis of the unbalanced case. 1568 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) { 1569 Value *LHS = Builder.CreateFPTrunc(OpI->getOperand(0), Ty); 1570 Value *RHS = Builder.CreateFPTrunc(OpI->getOperand(1), Ty); 1571 return BinaryOperator::CreateFDivFMF(LHS, RHS, OpI); 1572 } 1573 break; 1574 case Instruction::FRem: { 1575 // Remainder is straightforward. Remainder is always exact, so the 1576 // type of OpI doesn't enter into things at all. We simply evaluate 1577 // in whichever source type is larger, then convert to the 1578 // destination type. 1579 if (SrcWidth == OpWidth) 1580 break; 1581 Value *LHS, *RHS; 1582 if (LHSWidth == SrcWidth) { 1583 LHS = Builder.CreateFPTrunc(OpI->getOperand(0), LHSMinType); 1584 RHS = Builder.CreateFPTrunc(OpI->getOperand(1), LHSMinType); 1585 } else { 1586 LHS = Builder.CreateFPTrunc(OpI->getOperand(0), RHSMinType); 1587 RHS = Builder.CreateFPTrunc(OpI->getOperand(1), RHSMinType); 1588 } 1589 1590 Value *ExactResult = Builder.CreateFRemFMF(LHS, RHS, OpI); 1591 return CastInst::CreateFPCast(ExactResult, Ty); 1592 } 1593 } 1594 1595 // (fptrunc (fneg x)) -> (fneg (fptrunc x)) 1596 if (BinaryOperator::isFNeg(OpI)) { 1597 Value *InnerTrunc = Builder.CreateFPTrunc(OpI->getOperand(1), Ty); 1598 return BinaryOperator::CreateFNegFMF(InnerTrunc, OpI); 1599 } 1600 } 1601 1602 if (auto *II = dyn_cast<IntrinsicInst>(FPT.getOperand(0))) { 1603 switch (II->getIntrinsicID()) { 1604 default: break; 1605 case Intrinsic::ceil: 1606 case Intrinsic::fabs: 1607 case Intrinsic::floor: 1608 case Intrinsic::nearbyint: 1609 case Intrinsic::rint: 1610 case Intrinsic::round: 1611 case Intrinsic::trunc: { 1612 Value *Src = II->getArgOperand(0); 1613 if (!Src->hasOneUse()) 1614 break; 1615 1616 // Except for fabs, this transformation requires the input of the unary FP 1617 // operation to be itself an fpext from the type to which we're 1618 // truncating. 1619 if (II->getIntrinsicID() != Intrinsic::fabs) { 1620 FPExtInst *FPExtSrc = dyn_cast<FPExtInst>(Src); 1621 if (!FPExtSrc || FPExtSrc->getSrcTy() != Ty) 1622 break; 1623 } 1624 1625 // Do unary FP operation on smaller type. 1626 // (fptrunc (fabs x)) -> (fabs (fptrunc x)) 1627 Value *InnerTrunc = Builder.CreateFPTrunc(Src, Ty); 1628 Function *Overload = Intrinsic::getDeclaration(FPT.getModule(), 1629 II->getIntrinsicID(), Ty); 1630 SmallVector<OperandBundleDef, 1> OpBundles; 1631 II->getOperandBundlesAsDefs(OpBundles); 1632 CallInst *NewCI = CallInst::Create(Overload, { InnerTrunc }, OpBundles, 1633 II->getName()); 1634 NewCI->copyFastMathFlags(II); 1635 return NewCI; 1636 } 1637 } 1638 } 1639 1640 if (Instruction *I = shrinkInsertElt(FPT, Builder)) 1641 return I; 1642 1643 return nullptr; 1644 } 1645 1646 Instruction *InstCombiner::visitFPExt(CastInst &CI) { 1647 return commonCastTransforms(CI); 1648 } 1649 1650 // fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X) 1651 // This is safe if the intermediate type has enough bits in its mantissa to 1652 // accurately represent all values of X. For example, this won't work with 1653 // i64 -> float -> i64. 1654 Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) { 1655 if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0))) 1656 return nullptr; 1657 Instruction *OpI = cast<Instruction>(FI.getOperand(0)); 1658 1659 Value *SrcI = OpI->getOperand(0); 1660 Type *FITy = FI.getType(); 1661 Type *OpITy = OpI->getType(); 1662 Type *SrcTy = SrcI->getType(); 1663 bool IsInputSigned = isa<SIToFPInst>(OpI); 1664 bool IsOutputSigned = isa<FPToSIInst>(FI); 1665 1666 // We can safely assume the conversion won't overflow the output range, 1667 // because (for example) (uint8_t)18293.f is undefined behavior. 1668 1669 // Since we can assume the conversion won't overflow, our decision as to 1670 // whether the input will fit in the float should depend on the minimum 1671 // of the input range and output range. 1672 1673 // This means this is also safe for a signed input and unsigned output, since 1674 // a negative input would lead to undefined behavior. 1675 int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned; 1676 int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned; 1677 int ActualSize = std::min(InputSize, OutputSize); 1678 1679 if (ActualSize <= OpITy->getFPMantissaWidth()) { 1680 if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) { 1681 if (IsInputSigned && IsOutputSigned) 1682 return new SExtInst(SrcI, FITy); 1683 return new ZExtInst(SrcI, FITy); 1684 } 1685 if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits()) 1686 return new TruncInst(SrcI, FITy); 1687 if (SrcTy == FITy) 1688 return replaceInstUsesWith(FI, SrcI); 1689 return new BitCastInst(SrcI, FITy); 1690 } 1691 return nullptr; 1692 } 1693 1694 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) { 1695 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0)); 1696 if (!OpI) 1697 return commonCastTransforms(FI); 1698 1699 if (Instruction *I = FoldItoFPtoI(FI)) 1700 return I; 1701 1702 return commonCastTransforms(FI); 1703 } 1704 1705 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) { 1706 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0)); 1707 if (!OpI) 1708 return commonCastTransforms(FI); 1709 1710 if (Instruction *I = FoldItoFPtoI(FI)) 1711 return I; 1712 1713 return commonCastTransforms(FI); 1714 } 1715 1716 Instruction *InstCombiner::visitUIToFP(CastInst &CI) { 1717 return commonCastTransforms(CI); 1718 } 1719 1720 Instruction *InstCombiner::visitSIToFP(CastInst &CI) { 1721 return commonCastTransforms(CI); 1722 } 1723 1724 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) { 1725 // If the source integer type is not the intptr_t type for this target, do a 1726 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the 1727 // cast to be exposed to other transforms. 1728 unsigned AS = CI.getAddressSpace(); 1729 if (CI.getOperand(0)->getType()->getScalarSizeInBits() != 1730 DL.getPointerSizeInBits(AS)) { 1731 Type *Ty = DL.getIntPtrType(CI.getContext(), AS); 1732 if (CI.getType()->isVectorTy()) // Handle vectors of pointers. 1733 Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements()); 1734 1735 Value *P = Builder.CreateZExtOrTrunc(CI.getOperand(0), Ty); 1736 return new IntToPtrInst(P, CI.getType()); 1737 } 1738 1739 if (Instruction *I = commonCastTransforms(CI)) 1740 return I; 1741 1742 return nullptr; 1743 } 1744 1745 /// Implement the transforms for cast of pointer (bitcast/ptrtoint) 1746 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) { 1747 Value *Src = CI.getOperand(0); 1748 1749 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) { 1750 // If casting the result of a getelementptr instruction with no offset, turn 1751 // this into a cast of the original pointer! 1752 if (GEP->hasAllZeroIndices() && 1753 // If CI is an addrspacecast and GEP changes the poiner type, merging 1754 // GEP into CI would undo canonicalizing addrspacecast with different 1755 // pointer types, causing infinite loops. 1756 (!isa<AddrSpaceCastInst>(CI) || 1757 GEP->getType() == GEP->getPointerOperandType())) { 1758 // Changing the cast operand is usually not a good idea but it is safe 1759 // here because the pointer operand is being replaced with another 1760 // pointer operand so the opcode doesn't need to change. 1761 Worklist.Add(GEP); 1762 CI.setOperand(0, GEP->getOperand(0)); 1763 return &CI; 1764 } 1765 } 1766 1767 return commonCastTransforms(CI); 1768 } 1769 1770 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) { 1771 // If the destination integer type is not the intptr_t type for this target, 1772 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast 1773 // to be exposed to other transforms. 1774 1775 Type *Ty = CI.getType(); 1776 unsigned AS = CI.getPointerAddressSpace(); 1777 1778 if (Ty->getScalarSizeInBits() == DL.getIndexSizeInBits(AS)) 1779 return commonPointerCastTransforms(CI); 1780 1781 Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS); 1782 if (Ty->isVectorTy()) // Handle vectors of pointers. 1783 PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements()); 1784 1785 Value *P = Builder.CreatePtrToInt(CI.getOperand(0), PtrTy); 1786 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false); 1787 } 1788 1789 /// This input value (which is known to have vector type) is being zero extended 1790 /// or truncated to the specified vector type. 1791 /// Try to replace it with a shuffle (and vector/vector bitcast) if possible. 1792 /// 1793 /// The source and destination vector types may have different element types. 1794 static Instruction *optimizeVectorResize(Value *InVal, VectorType *DestTy, 1795 InstCombiner &IC) { 1796 // We can only do this optimization if the output is a multiple of the input 1797 // element size, or the input is a multiple of the output element size. 1798 // Convert the input type to have the same element type as the output. 1799 VectorType *SrcTy = cast<VectorType>(InVal->getType()); 1800 1801 if (SrcTy->getElementType() != DestTy->getElementType()) { 1802 // The input types don't need to be identical, but for now they must be the 1803 // same size. There is no specific reason we couldn't handle things like 1804 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten 1805 // there yet. 1806 if (SrcTy->getElementType()->getPrimitiveSizeInBits() != 1807 DestTy->getElementType()->getPrimitiveSizeInBits()) 1808 return nullptr; 1809 1810 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements()); 1811 InVal = IC.Builder.CreateBitCast(InVal, SrcTy); 1812 } 1813 1814 // Now that the element types match, get the shuffle mask and RHS of the 1815 // shuffle to use, which depends on whether we're increasing or decreasing the 1816 // size of the input. 1817 SmallVector<uint32_t, 16> ShuffleMask; 1818 Value *V2; 1819 1820 if (SrcTy->getNumElements() > DestTy->getNumElements()) { 1821 // If we're shrinking the number of elements, just shuffle in the low 1822 // elements from the input and use undef as the second shuffle input. 1823 V2 = UndefValue::get(SrcTy); 1824 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i) 1825 ShuffleMask.push_back(i); 1826 1827 } else { 1828 // If we're increasing the number of elements, shuffle in all of the 1829 // elements from InVal and fill the rest of the result elements with zeros 1830 // from a constant zero. 1831 V2 = Constant::getNullValue(SrcTy); 1832 unsigned SrcElts = SrcTy->getNumElements(); 1833 for (unsigned i = 0, e = SrcElts; i != e; ++i) 1834 ShuffleMask.push_back(i); 1835 1836 // The excess elements reference the first element of the zero input. 1837 for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i) 1838 ShuffleMask.push_back(SrcElts); 1839 } 1840 1841 return new ShuffleVectorInst(InVal, V2, 1842 ConstantDataVector::get(V2->getContext(), 1843 ShuffleMask)); 1844 } 1845 1846 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) { 1847 return Value % Ty->getPrimitiveSizeInBits() == 0; 1848 } 1849 1850 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) { 1851 return Value / Ty->getPrimitiveSizeInBits(); 1852 } 1853 1854 /// V is a value which is inserted into a vector of VecEltTy. 1855 /// Look through the value to see if we can decompose it into 1856 /// insertions into the vector. See the example in the comment for 1857 /// OptimizeIntegerToVectorInsertions for the pattern this handles. 1858 /// The type of V is always a non-zero multiple of VecEltTy's size. 1859 /// Shift is the number of bits between the lsb of V and the lsb of 1860 /// the vector. 1861 /// 1862 /// This returns false if the pattern can't be matched or true if it can, 1863 /// filling in Elements with the elements found here. 1864 static bool collectInsertionElements(Value *V, unsigned Shift, 1865 SmallVectorImpl<Value *> &Elements, 1866 Type *VecEltTy, bool isBigEndian) { 1867 assert(isMultipleOfTypeSize(Shift, VecEltTy) && 1868 "Shift should be a multiple of the element type size"); 1869 1870 // Undef values never contribute useful bits to the result. 1871 if (isa<UndefValue>(V)) return true; 1872 1873 // If we got down to a value of the right type, we win, try inserting into the 1874 // right element. 1875 if (V->getType() == VecEltTy) { 1876 // Inserting null doesn't actually insert any elements. 1877 if (Constant *C = dyn_cast<Constant>(V)) 1878 if (C->isNullValue()) 1879 return true; 1880 1881 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy); 1882 if (isBigEndian) 1883 ElementIndex = Elements.size() - ElementIndex - 1; 1884 1885 // Fail if multiple elements are inserted into this slot. 1886 if (Elements[ElementIndex]) 1887 return false; 1888 1889 Elements[ElementIndex] = V; 1890 return true; 1891 } 1892 1893 if (Constant *C = dyn_cast<Constant>(V)) { 1894 // Figure out the # elements this provides, and bitcast it or slice it up 1895 // as required. 1896 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(), 1897 VecEltTy); 1898 // If the constant is the size of a vector element, we just need to bitcast 1899 // it to the right type so it gets properly inserted. 1900 if (NumElts == 1) 1901 return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy), 1902 Shift, Elements, VecEltTy, isBigEndian); 1903 1904 // Okay, this is a constant that covers multiple elements. Slice it up into 1905 // pieces and insert each element-sized piece into the vector. 1906 if (!isa<IntegerType>(C->getType())) 1907 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(), 1908 C->getType()->getPrimitiveSizeInBits())); 1909 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits(); 1910 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize); 1911 1912 for (unsigned i = 0; i != NumElts; ++i) { 1913 unsigned ShiftI = Shift+i*ElementSize; 1914 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(), 1915 ShiftI)); 1916 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy); 1917 if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy, 1918 isBigEndian)) 1919 return false; 1920 } 1921 return true; 1922 } 1923 1924 if (!V->hasOneUse()) return false; 1925 1926 Instruction *I = dyn_cast<Instruction>(V); 1927 if (!I) return false; 1928 switch (I->getOpcode()) { 1929 default: return false; // Unhandled case. 1930 case Instruction::BitCast: 1931 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 1932 isBigEndian); 1933 case Instruction::ZExt: 1934 if (!isMultipleOfTypeSize( 1935 I->getOperand(0)->getType()->getPrimitiveSizeInBits(), 1936 VecEltTy)) 1937 return false; 1938 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 1939 isBigEndian); 1940 case Instruction::Or: 1941 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 1942 isBigEndian) && 1943 collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy, 1944 isBigEndian); 1945 case Instruction::Shl: { 1946 // Must be shifting by a constant that is a multiple of the element size. 1947 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1)); 1948 if (!CI) return false; 1949 Shift += CI->getZExtValue(); 1950 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false; 1951 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 1952 isBigEndian); 1953 } 1954 1955 } 1956 } 1957 1958 1959 /// If the input is an 'or' instruction, we may be doing shifts and ors to 1960 /// assemble the elements of the vector manually. 1961 /// Try to rip the code out and replace it with insertelements. This is to 1962 /// optimize code like this: 1963 /// 1964 /// %tmp37 = bitcast float %inc to i32 1965 /// %tmp38 = zext i32 %tmp37 to i64 1966 /// %tmp31 = bitcast float %inc5 to i32 1967 /// %tmp32 = zext i32 %tmp31 to i64 1968 /// %tmp33 = shl i64 %tmp32, 32 1969 /// %ins35 = or i64 %tmp33, %tmp38 1970 /// %tmp43 = bitcast i64 %ins35 to <2 x float> 1971 /// 1972 /// Into two insertelements that do "buildvector{%inc, %inc5}". 1973 static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI, 1974 InstCombiner &IC) { 1975 VectorType *DestVecTy = cast<VectorType>(CI.getType()); 1976 Value *IntInput = CI.getOperand(0); 1977 1978 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements()); 1979 if (!collectInsertionElements(IntInput, 0, Elements, 1980 DestVecTy->getElementType(), 1981 IC.getDataLayout().isBigEndian())) 1982 return nullptr; 1983 1984 // If we succeeded, we know that all of the element are specified by Elements 1985 // or are zero if Elements has a null entry. Recast this as a set of 1986 // insertions. 1987 Value *Result = Constant::getNullValue(CI.getType()); 1988 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 1989 if (!Elements[i]) continue; // Unset element. 1990 1991 Result = IC.Builder.CreateInsertElement(Result, Elements[i], 1992 IC.Builder.getInt32(i)); 1993 } 1994 1995 return Result; 1996 } 1997 1998 /// Canonicalize scalar bitcasts of extracted elements into a bitcast of the 1999 /// vector followed by extract element. The backend tends to handle bitcasts of 2000 /// vectors better than bitcasts of scalars because vector registers are 2001 /// usually not type-specific like scalar integer or scalar floating-point. 2002 static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast, 2003 InstCombiner &IC) { 2004 // TODO: Create and use a pattern matcher for ExtractElementInst. 2005 auto *ExtElt = dyn_cast<ExtractElementInst>(BitCast.getOperand(0)); 2006 if (!ExtElt || !ExtElt->hasOneUse()) 2007 return nullptr; 2008 2009 // The bitcast must be to a vectorizable type, otherwise we can't make a new 2010 // type to extract from. 2011 Type *DestType = BitCast.getType(); 2012 if (!VectorType::isValidElementType(DestType)) 2013 return nullptr; 2014 2015 unsigned NumElts = ExtElt->getVectorOperandType()->getNumElements(); 2016 auto *NewVecType = VectorType::get(DestType, NumElts); 2017 auto *NewBC = IC.Builder.CreateBitCast(ExtElt->getVectorOperand(), 2018 NewVecType, "bc"); 2019 return ExtractElementInst::Create(NewBC, ExtElt->getIndexOperand()); 2020 } 2021 2022 /// Change the type of a bitwise logic operation if we can eliminate a bitcast. 2023 static Instruction *foldBitCastBitwiseLogic(BitCastInst &BitCast, 2024 InstCombiner::BuilderTy &Builder) { 2025 Type *DestTy = BitCast.getType(); 2026 BinaryOperator *BO; 2027 if (!DestTy->isIntOrIntVectorTy() || 2028 !match(BitCast.getOperand(0), m_OneUse(m_BinOp(BO))) || 2029 !BO->isBitwiseLogicOp()) 2030 return nullptr; 2031 2032 // FIXME: This transform is restricted to vector types to avoid backend 2033 // problems caused by creating potentially illegal operations. If a fix-up is 2034 // added to handle that situation, we can remove this check. 2035 if (!DestTy->isVectorTy() || !BO->getType()->isVectorTy()) 2036 return nullptr; 2037 2038 Value *X; 2039 if (match(BO->getOperand(0), m_OneUse(m_BitCast(m_Value(X)))) && 2040 X->getType() == DestTy && !isa<Constant>(X)) { 2041 // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y)) 2042 Value *CastedOp1 = Builder.CreateBitCast(BO->getOperand(1), DestTy); 2043 return BinaryOperator::Create(BO->getOpcode(), X, CastedOp1); 2044 } 2045 2046 if (match(BO->getOperand(1), m_OneUse(m_BitCast(m_Value(X)))) && 2047 X->getType() == DestTy && !isa<Constant>(X)) { 2048 // bitcast(logic(Y, bitcast(X))) --> logic'(bitcast(Y), X) 2049 Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy); 2050 return BinaryOperator::Create(BO->getOpcode(), CastedOp0, X); 2051 } 2052 2053 // Canonicalize vector bitcasts to come before vector bitwise logic with a 2054 // constant. This eases recognition of special constants for later ops. 2055 // Example: 2056 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b 2057 Constant *C; 2058 if (match(BO->getOperand(1), m_Constant(C))) { 2059 // bitcast (logic X, C) --> logic (bitcast X, C') 2060 Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy); 2061 Value *CastedC = ConstantExpr::getBitCast(C, DestTy); 2062 return BinaryOperator::Create(BO->getOpcode(), CastedOp0, CastedC); 2063 } 2064 2065 return nullptr; 2066 } 2067 2068 /// Change the type of a select if we can eliminate a bitcast. 2069 static Instruction *foldBitCastSelect(BitCastInst &BitCast, 2070 InstCombiner::BuilderTy &Builder) { 2071 Value *Cond, *TVal, *FVal; 2072 if (!match(BitCast.getOperand(0), 2073 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) 2074 return nullptr; 2075 2076 // A vector select must maintain the same number of elements in its operands. 2077 Type *CondTy = Cond->getType(); 2078 Type *DestTy = BitCast.getType(); 2079 if (CondTy->isVectorTy()) { 2080 if (!DestTy->isVectorTy()) 2081 return nullptr; 2082 if (DestTy->getVectorNumElements() != CondTy->getVectorNumElements()) 2083 return nullptr; 2084 } 2085 2086 // FIXME: This transform is restricted from changing the select between 2087 // scalars and vectors to avoid backend problems caused by creating 2088 // potentially illegal operations. If a fix-up is added to handle that 2089 // situation, we can remove this check. 2090 if (DestTy->isVectorTy() != TVal->getType()->isVectorTy()) 2091 return nullptr; 2092 2093 auto *Sel = cast<Instruction>(BitCast.getOperand(0)); 2094 Value *X; 2095 if (match(TVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy && 2096 !isa<Constant>(X)) { 2097 // bitcast(select(Cond, bitcast(X), Y)) --> select'(Cond, X, bitcast(Y)) 2098 Value *CastedVal = Builder.CreateBitCast(FVal, DestTy); 2099 return SelectInst::Create(Cond, X, CastedVal, "", nullptr, Sel); 2100 } 2101 2102 if (match(FVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy && 2103 !isa<Constant>(X)) { 2104 // bitcast(select(Cond, Y, bitcast(X))) --> select'(Cond, bitcast(Y), X) 2105 Value *CastedVal = Builder.CreateBitCast(TVal, DestTy); 2106 return SelectInst::Create(Cond, CastedVal, X, "", nullptr, Sel); 2107 } 2108 2109 return nullptr; 2110 } 2111 2112 /// Check if all users of CI are StoreInsts. 2113 static bool hasStoreUsersOnly(CastInst &CI) { 2114 for (User *U : CI.users()) { 2115 if (!isa<StoreInst>(U)) 2116 return false; 2117 } 2118 return true; 2119 } 2120 2121 /// This function handles following case 2122 /// 2123 /// A -> B cast 2124 /// PHI 2125 /// B -> A cast 2126 /// 2127 /// All the related PHI nodes can be replaced by new PHI nodes with type A. 2128 /// The uses of \p CI can be changed to the new PHI node corresponding to \p PN. 2129 Instruction *InstCombiner::optimizeBitCastFromPhi(CastInst &CI, PHINode *PN) { 2130 // BitCast used by Store can be handled in InstCombineLoadStoreAlloca.cpp. 2131 if (hasStoreUsersOnly(CI)) 2132 return nullptr; 2133 2134 Value *Src = CI.getOperand(0); 2135 Type *SrcTy = Src->getType(); // Type B 2136 Type *DestTy = CI.getType(); // Type A 2137 2138 SmallVector<PHINode *, 4> PhiWorklist; 2139 SmallSetVector<PHINode *, 4> OldPhiNodes; 2140 2141 // Find all of the A->B casts and PHI nodes. 2142 // We need to inpect all related PHI nodes, but PHIs can be cyclic, so 2143 // OldPhiNodes is used to track all known PHI nodes, before adding a new 2144 // PHI to PhiWorklist, it is checked against and added to OldPhiNodes first. 2145 PhiWorklist.push_back(PN); 2146 OldPhiNodes.insert(PN); 2147 while (!PhiWorklist.empty()) { 2148 auto *OldPN = PhiWorklist.pop_back_val(); 2149 for (Value *IncValue : OldPN->incoming_values()) { 2150 if (isa<Constant>(IncValue)) 2151 continue; 2152 2153 if (auto *LI = dyn_cast<LoadInst>(IncValue)) { 2154 // If there is a sequence of one or more load instructions, each loaded 2155 // value is used as address of later load instruction, bitcast is 2156 // necessary to change the value type, don't optimize it. For 2157 // simplicity we give up if the load address comes from another load. 2158 Value *Addr = LI->getOperand(0); 2159 if (Addr == &CI || isa<LoadInst>(Addr)) 2160 return nullptr; 2161 if (LI->hasOneUse() && LI->isSimple()) 2162 continue; 2163 // If a LoadInst has more than one use, changing the type of loaded 2164 // value may create another bitcast. 2165 return nullptr; 2166 } 2167 2168 if (auto *PNode = dyn_cast<PHINode>(IncValue)) { 2169 if (OldPhiNodes.insert(PNode)) 2170 PhiWorklist.push_back(PNode); 2171 continue; 2172 } 2173 2174 auto *BCI = dyn_cast<BitCastInst>(IncValue); 2175 // We can't handle other instructions. 2176 if (!BCI) 2177 return nullptr; 2178 2179 // Verify it's a A->B cast. 2180 Type *TyA = BCI->getOperand(0)->getType(); 2181 Type *TyB = BCI->getType(); 2182 if (TyA != DestTy || TyB != SrcTy) 2183 return nullptr; 2184 } 2185 } 2186 2187 // For each old PHI node, create a corresponding new PHI node with a type A. 2188 SmallDenseMap<PHINode *, PHINode *> NewPNodes; 2189 for (auto *OldPN : OldPhiNodes) { 2190 Builder.SetInsertPoint(OldPN); 2191 PHINode *NewPN = Builder.CreatePHI(DestTy, OldPN->getNumOperands()); 2192 NewPNodes[OldPN] = NewPN; 2193 } 2194 2195 // Fill in the operands of new PHI nodes. 2196 for (auto *OldPN : OldPhiNodes) { 2197 PHINode *NewPN = NewPNodes[OldPN]; 2198 for (unsigned j = 0, e = OldPN->getNumOperands(); j != e; ++j) { 2199 Value *V = OldPN->getOperand(j); 2200 Value *NewV = nullptr; 2201 if (auto *C = dyn_cast<Constant>(V)) { 2202 NewV = ConstantExpr::getBitCast(C, DestTy); 2203 } else if (auto *LI = dyn_cast<LoadInst>(V)) { 2204 Builder.SetInsertPoint(LI->getNextNode()); 2205 NewV = Builder.CreateBitCast(LI, DestTy); 2206 Worklist.Add(LI); 2207 } else if (auto *BCI = dyn_cast<BitCastInst>(V)) { 2208 NewV = BCI->getOperand(0); 2209 } else if (auto *PrevPN = dyn_cast<PHINode>(V)) { 2210 NewV = NewPNodes[PrevPN]; 2211 } 2212 assert(NewV); 2213 NewPN->addIncoming(NewV, OldPN->getIncomingBlock(j)); 2214 } 2215 } 2216 2217 // If there is a store with type B, change it to type A. 2218 for (User *U : PN->users()) { 2219 auto *SI = dyn_cast<StoreInst>(U); 2220 if (SI && SI->isSimple() && SI->getOperand(0) == PN) { 2221 Builder.SetInsertPoint(SI); 2222 auto *NewBC = 2223 cast<BitCastInst>(Builder.CreateBitCast(NewPNodes[PN], SrcTy)); 2224 SI->setOperand(0, NewBC); 2225 Worklist.Add(SI); 2226 assert(hasStoreUsersOnly(*NewBC)); 2227 } 2228 } 2229 2230 return replaceInstUsesWith(CI, NewPNodes[PN]); 2231 } 2232 2233 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) { 2234 // If the operands are integer typed then apply the integer transforms, 2235 // otherwise just apply the common ones. 2236 Value *Src = CI.getOperand(0); 2237 Type *SrcTy = Src->getType(); 2238 Type *DestTy = CI.getType(); 2239 2240 // Get rid of casts from one type to the same type. These are useless and can 2241 // be replaced by the operand. 2242 if (DestTy == Src->getType()) 2243 return replaceInstUsesWith(CI, Src); 2244 2245 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) { 2246 PointerType *SrcPTy = cast<PointerType>(SrcTy); 2247 Type *DstElTy = DstPTy->getElementType(); 2248 Type *SrcElTy = SrcPTy->getElementType(); 2249 2250 // If we are casting a alloca to a pointer to a type of the same 2251 // size, rewrite the allocation instruction to allocate the "right" type. 2252 // There is no need to modify malloc calls because it is their bitcast that 2253 // needs to be cleaned up. 2254 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src)) 2255 if (Instruction *V = PromoteCastOfAllocation(CI, *AI)) 2256 return V; 2257 2258 // When the type pointed to is not sized the cast cannot be 2259 // turned into a gep. 2260 Type *PointeeType = 2261 cast<PointerType>(Src->getType()->getScalarType())->getElementType(); 2262 if (!PointeeType->isSized()) 2263 return nullptr; 2264 2265 // If the source and destination are pointers, and this cast is equivalent 2266 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep. 2267 // This can enhance SROA and other transforms that want type-safe pointers. 2268 unsigned NumZeros = 0; 2269 while (SrcElTy != DstElTy && 2270 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() && 2271 SrcElTy->getNumContainedTypes() /* not "{}" */) { 2272 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(0U); 2273 ++NumZeros; 2274 } 2275 2276 // If we found a path from the src to dest, create the getelementptr now. 2277 if (SrcElTy == DstElTy) { 2278 SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder.getInt32(0)); 2279 return GetElementPtrInst::CreateInBounds(Src, Idxs); 2280 } 2281 } 2282 2283 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) { 2284 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) { 2285 Value *Elem = Builder.CreateBitCast(Src, DestVTy->getElementType()); 2286 return InsertElementInst::Create(UndefValue::get(DestTy), Elem, 2287 Constant::getNullValue(Type::getInt32Ty(CI.getContext()))); 2288 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast) 2289 } 2290 2291 if (isa<IntegerType>(SrcTy)) { 2292 // If this is a cast from an integer to vector, check to see if the input 2293 // is a trunc or zext of a bitcast from vector. If so, we can replace all 2294 // the casts with a shuffle and (potentially) a bitcast. 2295 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) { 2296 CastInst *SrcCast = cast<CastInst>(Src); 2297 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0))) 2298 if (isa<VectorType>(BCIn->getOperand(0)->getType())) 2299 if (Instruction *I = optimizeVectorResize(BCIn->getOperand(0), 2300 cast<VectorType>(DestTy), *this)) 2301 return I; 2302 } 2303 2304 // If the input is an 'or' instruction, we may be doing shifts and ors to 2305 // assemble the elements of the vector manually. Try to rip the code out 2306 // and replace it with insertelements. 2307 if (Value *V = optimizeIntegerToVectorInsertions(CI, *this)) 2308 return replaceInstUsesWith(CI, V); 2309 } 2310 } 2311 2312 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) { 2313 if (SrcVTy->getNumElements() == 1) { 2314 // If our destination is not a vector, then make this a straight 2315 // scalar-scalar cast. 2316 if (!DestTy->isVectorTy()) { 2317 Value *Elem = 2318 Builder.CreateExtractElement(Src, 2319 Constant::getNullValue(Type::getInt32Ty(CI.getContext()))); 2320 return CastInst::Create(Instruction::BitCast, Elem, DestTy); 2321 } 2322 2323 // Otherwise, see if our source is an insert. If so, then use the scalar 2324 // component directly. 2325 if (InsertElementInst *IEI = 2326 dyn_cast<InsertElementInst>(CI.getOperand(0))) 2327 return CastInst::Create(Instruction::BitCast, IEI->getOperand(1), 2328 DestTy); 2329 } 2330 } 2331 2332 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) { 2333 // Okay, we have (bitcast (shuffle ..)). Check to see if this is 2334 // a bitcast to a vector with the same # elts. 2335 if (SVI->hasOneUse() && DestTy->isVectorTy() && 2336 DestTy->getVectorNumElements() == SVI->getType()->getNumElements() && 2337 SVI->getType()->getNumElements() == 2338 SVI->getOperand(0)->getType()->getVectorNumElements()) { 2339 BitCastInst *Tmp; 2340 // If either of the operands is a cast from CI.getType(), then 2341 // evaluating the shuffle in the casted destination's type will allow 2342 // us to eliminate at least one cast. 2343 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) && 2344 Tmp->getOperand(0)->getType() == DestTy) || 2345 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) && 2346 Tmp->getOperand(0)->getType() == DestTy)) { 2347 Value *LHS = Builder.CreateBitCast(SVI->getOperand(0), DestTy); 2348 Value *RHS = Builder.CreateBitCast(SVI->getOperand(1), DestTy); 2349 // Return a new shuffle vector. Use the same element ID's, as we 2350 // know the vector types match #elts. 2351 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2)); 2352 } 2353 } 2354 } 2355 2356 // Handle the A->B->A cast, and there is an intervening PHI node. 2357 if (PHINode *PN = dyn_cast<PHINode>(Src)) 2358 if (Instruction *I = optimizeBitCastFromPhi(CI, PN)) 2359 return I; 2360 2361 if (Instruction *I = canonicalizeBitCastExtElt(CI, *this)) 2362 return I; 2363 2364 if (Instruction *I = foldBitCastBitwiseLogic(CI, Builder)) 2365 return I; 2366 2367 if (Instruction *I = foldBitCastSelect(CI, Builder)) 2368 return I; 2369 2370 if (SrcTy->isPointerTy()) 2371 return commonPointerCastTransforms(CI); 2372 return commonCastTransforms(CI); 2373 } 2374 2375 Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) { 2376 // If the destination pointer element type is not the same as the source's 2377 // first do a bitcast to the destination type, and then the addrspacecast. 2378 // This allows the cast to be exposed to other transforms. 2379 Value *Src = CI.getOperand(0); 2380 PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType()); 2381 PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType()); 2382 2383 Type *DestElemTy = DestTy->getElementType(); 2384 if (SrcTy->getElementType() != DestElemTy) { 2385 Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace()); 2386 if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) { 2387 // Handle vectors of pointers. 2388 MidTy = VectorType::get(MidTy, VT->getNumElements()); 2389 } 2390 2391 Value *NewBitCast = Builder.CreateBitCast(Src, MidTy); 2392 return new AddrSpaceCastInst(NewBitCast, CI.getType()); 2393 } 2394 2395 return commonPointerCastTransforms(CI); 2396 } 2397