1 //===- InstCombineCasts.cpp -----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visit functions for cast operations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/SetVector.h" 15 #include "llvm/Analysis/ConstantFolding.h" 16 #include "llvm/Analysis/TargetLibraryInfo.h" 17 #include "llvm/IR/DIBuilder.h" 18 #include "llvm/IR/DataLayout.h" 19 #include "llvm/IR/PatternMatch.h" 20 #include "llvm/Support/KnownBits.h" 21 #include "llvm/Transforms/InstCombine/InstCombiner.h" 22 #include <numeric> 23 using namespace llvm; 24 using namespace PatternMatch; 25 26 #define DEBUG_TYPE "instcombine" 27 28 /// Analyze 'Val', seeing if it is a simple linear expression. 29 /// If so, decompose it, returning some value X, such that Val is 30 /// X*Scale+Offset. 31 /// 32 static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale, 33 uint64_t &Offset) { 34 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { 35 Offset = CI->getZExtValue(); 36 Scale = 0; 37 return ConstantInt::get(Val->getType(), 0); 38 } 39 40 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) { 41 // Cannot look past anything that might overflow. 42 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val); 43 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) { 44 Scale = 1; 45 Offset = 0; 46 return Val; 47 } 48 49 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) { 50 if (I->getOpcode() == Instruction::Shl) { 51 // This is a value scaled by '1 << the shift amt'. 52 Scale = UINT64_C(1) << RHS->getZExtValue(); 53 Offset = 0; 54 return I->getOperand(0); 55 } 56 57 if (I->getOpcode() == Instruction::Mul) { 58 // This value is scaled by 'RHS'. 59 Scale = RHS->getZExtValue(); 60 Offset = 0; 61 return I->getOperand(0); 62 } 63 64 if (I->getOpcode() == Instruction::Add) { 65 // We have X+C. Check to see if we really have (X*C2)+C1, 66 // where C1 is divisible by C2. 67 unsigned SubScale; 68 Value *SubVal = 69 decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset); 70 Offset += RHS->getZExtValue(); 71 Scale = SubScale; 72 return SubVal; 73 } 74 } 75 } 76 77 // Otherwise, we can't look past this. 78 Scale = 1; 79 Offset = 0; 80 return Val; 81 } 82 83 /// If we find a cast of an allocation instruction, try to eliminate the cast by 84 /// moving the type information into the alloc. 85 Instruction *InstCombinerImpl::PromoteCastOfAllocation(BitCastInst &CI, 86 AllocaInst &AI) { 87 PointerType *PTy = cast<PointerType>(CI.getType()); 88 89 IRBuilderBase::InsertPointGuard Guard(Builder); 90 Builder.SetInsertPoint(&AI); 91 92 // Get the type really allocated and the type casted to. 93 Type *AllocElTy = AI.getAllocatedType(); 94 Type *CastElTy = PTy->getElementType(); 95 if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr; 96 97 // This optimisation does not work for cases where the cast type 98 // is scalable and the allocated type is not. This because we need to 99 // know how many times the casted type fits into the allocated type. 100 // For the opposite case where the allocated type is scalable and the 101 // cast type is not this leads to poor code quality due to the 102 // introduction of 'vscale' into the calculations. It seems better to 103 // bail out for this case too until we've done a proper cost-benefit 104 // analysis. 105 bool AllocIsScalable = isa<ScalableVectorType>(AllocElTy); 106 bool CastIsScalable = isa<ScalableVectorType>(CastElTy); 107 if (AllocIsScalable != CastIsScalable) return nullptr; 108 109 Align AllocElTyAlign = DL.getABITypeAlign(AllocElTy); 110 Align CastElTyAlign = DL.getABITypeAlign(CastElTy); 111 if (CastElTyAlign < AllocElTyAlign) return nullptr; 112 113 // If the allocation has multiple uses, only promote it if we are strictly 114 // increasing the alignment of the resultant allocation. If we keep it the 115 // same, we open the door to infinite loops of various kinds. 116 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr; 117 118 // The alloc and cast types should be either both fixed or both scalable. 119 uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy).getKnownMinSize(); 120 uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy).getKnownMinSize(); 121 if (CastElTySize == 0 || AllocElTySize == 0) return nullptr; 122 123 // If the allocation has multiple uses, only promote it if we're not 124 // shrinking the amount of memory being allocated. 125 uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy).getKnownMinSize(); 126 uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy).getKnownMinSize(); 127 if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr; 128 129 // See if we can satisfy the modulus by pulling a scale out of the array 130 // size argument. 131 unsigned ArraySizeScale; 132 uint64_t ArrayOffset; 133 Value *NumElements = // See if the array size is a decomposable linear expr. 134 decomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset); 135 136 // If we can now satisfy the modulus, by using a non-1 scale, we really can 137 // do the xform. 138 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 || 139 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr; 140 141 // We don't currently support arrays of scalable types. 142 assert(!AllocIsScalable || (ArrayOffset == 1 && ArraySizeScale == 0)); 143 144 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize; 145 Value *Amt = nullptr; 146 if (Scale == 1) { 147 Amt = NumElements; 148 } else { 149 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale); 150 // Insert before the alloca, not before the cast. 151 Amt = Builder.CreateMul(Amt, NumElements); 152 } 153 154 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) { 155 Value *Off = ConstantInt::get(AI.getArraySize()->getType(), 156 Offset, true); 157 Amt = Builder.CreateAdd(Amt, Off); 158 } 159 160 AllocaInst *New = Builder.CreateAlloca(CastElTy, Amt); 161 New->setAlignment(AI.getAlign()); 162 New->takeName(&AI); 163 New->setUsedWithInAlloca(AI.isUsedWithInAlloca()); 164 165 // If the allocation has multiple real uses, insert a cast and change all 166 // things that used it to use the new cast. This will also hack on CI, but it 167 // will die soon. 168 if (!AI.hasOneUse()) { 169 // New is the allocation instruction, pointer typed. AI is the original 170 // allocation instruction, also pointer typed. Thus, cast to use is BitCast. 171 Value *NewCast = Builder.CreateBitCast(New, AI.getType(), "tmpcast"); 172 replaceInstUsesWith(AI, NewCast); 173 eraseInstFromFunction(AI); 174 } 175 return replaceInstUsesWith(CI, New); 176 } 177 178 /// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns 179 /// true for, actually insert the code to evaluate the expression. 180 Value *InstCombinerImpl::EvaluateInDifferentType(Value *V, Type *Ty, 181 bool isSigned) { 182 if (Constant *C = dyn_cast<Constant>(V)) { 183 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/); 184 // If we got a constantexpr back, try to simplify it with DL info. 185 return ConstantFoldConstant(C, DL, &TLI); 186 } 187 188 // Otherwise, it must be an instruction. 189 Instruction *I = cast<Instruction>(V); 190 Instruction *Res = nullptr; 191 unsigned Opc = I->getOpcode(); 192 switch (Opc) { 193 case Instruction::Add: 194 case Instruction::Sub: 195 case Instruction::Mul: 196 case Instruction::And: 197 case Instruction::Or: 198 case Instruction::Xor: 199 case Instruction::AShr: 200 case Instruction::LShr: 201 case Instruction::Shl: 202 case Instruction::UDiv: 203 case Instruction::URem: { 204 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned); 205 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned); 206 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 207 break; 208 } 209 case Instruction::Trunc: 210 case Instruction::ZExt: 211 case Instruction::SExt: 212 // If the source type of the cast is the type we're trying for then we can 213 // just return the source. There's no need to insert it because it is not 214 // new. 215 if (I->getOperand(0)->getType() == Ty) 216 return I->getOperand(0); 217 218 // Otherwise, must be the same type of cast, so just reinsert a new one. 219 // This also handles the case of zext(trunc(x)) -> zext(x). 220 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty, 221 Opc == Instruction::SExt); 222 break; 223 case Instruction::Select: { 224 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned); 225 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned); 226 Res = SelectInst::Create(I->getOperand(0), True, False); 227 break; 228 } 229 case Instruction::PHI: { 230 PHINode *OPN = cast<PHINode>(I); 231 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues()); 232 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) { 233 Value *V = 234 EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned); 235 NPN->addIncoming(V, OPN->getIncomingBlock(i)); 236 } 237 Res = NPN; 238 break; 239 } 240 default: 241 // TODO: Can handle more cases here. 242 llvm_unreachable("Unreachable!"); 243 } 244 245 Res->takeName(I); 246 return InsertNewInstWith(Res, *I); 247 } 248 249 Instruction::CastOps 250 InstCombinerImpl::isEliminableCastPair(const CastInst *CI1, 251 const CastInst *CI2) { 252 Type *SrcTy = CI1->getSrcTy(); 253 Type *MidTy = CI1->getDestTy(); 254 Type *DstTy = CI2->getDestTy(); 255 256 Instruction::CastOps firstOp = CI1->getOpcode(); 257 Instruction::CastOps secondOp = CI2->getOpcode(); 258 Type *SrcIntPtrTy = 259 SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr; 260 Type *MidIntPtrTy = 261 MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr; 262 Type *DstIntPtrTy = 263 DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr; 264 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, 265 DstTy, SrcIntPtrTy, MidIntPtrTy, 266 DstIntPtrTy); 267 268 // We don't want to form an inttoptr or ptrtoint that converts to an integer 269 // type that differs from the pointer size. 270 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) || 271 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy)) 272 Res = 0; 273 274 return Instruction::CastOps(Res); 275 } 276 277 /// Implement the transforms common to all CastInst visitors. 278 Instruction *InstCombinerImpl::commonCastTransforms(CastInst &CI) { 279 Value *Src = CI.getOperand(0); 280 281 // Try to eliminate a cast of a cast. 282 if (auto *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast 283 if (Instruction::CastOps NewOpc = isEliminableCastPair(CSrc, &CI)) { 284 // The first cast (CSrc) is eliminable so we need to fix up or replace 285 // the second cast (CI). CSrc will then have a good chance of being dead. 286 auto *Ty = CI.getType(); 287 auto *Res = CastInst::Create(NewOpc, CSrc->getOperand(0), Ty); 288 // Point debug users of the dying cast to the new one. 289 if (CSrc->hasOneUse()) 290 replaceAllDbgUsesWith(*CSrc, *Res, CI, DT); 291 return Res; 292 } 293 } 294 295 if (auto *Sel = dyn_cast<SelectInst>(Src)) { 296 // We are casting a select. Try to fold the cast into the select if the 297 // select does not have a compare instruction with matching operand types 298 // or the select is likely better done in a narrow type. 299 // Creating a select with operands that are different sizes than its 300 // condition may inhibit other folds and lead to worse codegen. 301 auto *Cmp = dyn_cast<CmpInst>(Sel->getCondition()); 302 if (!Cmp || Cmp->getOperand(0)->getType() != Sel->getType() || 303 (CI.getOpcode() == Instruction::Trunc && 304 shouldChangeType(CI.getSrcTy(), CI.getType()))) { 305 if (Instruction *NV = FoldOpIntoSelect(CI, Sel)) { 306 replaceAllDbgUsesWith(*Sel, *NV, CI, DT); 307 return NV; 308 } 309 } 310 } 311 312 // If we are casting a PHI, then fold the cast into the PHI. 313 if (auto *PN = dyn_cast<PHINode>(Src)) { 314 // Don't do this if it would create a PHI node with an illegal type from a 315 // legal type. 316 if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() || 317 shouldChangeType(CI.getSrcTy(), CI.getType())) 318 if (Instruction *NV = foldOpIntoPhi(CI, PN)) 319 return NV; 320 } 321 322 return nullptr; 323 } 324 325 /// Constants and extensions/truncates from the destination type are always 326 /// free to be evaluated in that type. This is a helper for canEvaluate*. 327 static bool canAlwaysEvaluateInType(Value *V, Type *Ty) { 328 if (isa<Constant>(V)) 329 return true; 330 Value *X; 331 if ((match(V, m_ZExtOrSExt(m_Value(X))) || match(V, m_Trunc(m_Value(X)))) && 332 X->getType() == Ty) 333 return true; 334 335 return false; 336 } 337 338 /// Filter out values that we can not evaluate in the destination type for free. 339 /// This is a helper for canEvaluate*. 340 static bool canNotEvaluateInType(Value *V, Type *Ty) { 341 assert(!isa<Constant>(V) && "Constant should already be handled."); 342 if (!isa<Instruction>(V)) 343 return true; 344 // We don't extend or shrink something that has multiple uses -- doing so 345 // would require duplicating the instruction which isn't profitable. 346 if (!V->hasOneUse()) 347 return true; 348 349 return false; 350 } 351 352 /// Return true if we can evaluate the specified expression tree as type Ty 353 /// instead of its larger type, and arrive with the same value. 354 /// This is used by code that tries to eliminate truncates. 355 /// 356 /// Ty will always be a type smaller than V. We should return true if trunc(V) 357 /// can be computed by computing V in the smaller type. If V is an instruction, 358 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only 359 /// makes sense if x and y can be efficiently truncated. 360 /// 361 /// This function works on both vectors and scalars. 362 /// 363 static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombinerImpl &IC, 364 Instruction *CxtI) { 365 if (canAlwaysEvaluateInType(V, Ty)) 366 return true; 367 if (canNotEvaluateInType(V, Ty)) 368 return false; 369 370 auto *I = cast<Instruction>(V); 371 Type *OrigTy = V->getType(); 372 switch (I->getOpcode()) { 373 case Instruction::Add: 374 case Instruction::Sub: 375 case Instruction::Mul: 376 case Instruction::And: 377 case Instruction::Or: 378 case Instruction::Xor: 379 // These operators can all arbitrarily be extended or truncated. 380 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 381 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 382 383 case Instruction::UDiv: 384 case Instruction::URem: { 385 // UDiv and URem can be truncated if all the truncated bits are zero. 386 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 387 uint32_t BitWidth = Ty->getScalarSizeInBits(); 388 assert(BitWidth < OrigBitWidth && "Unexpected bitwidths!"); 389 APInt Mask = APInt::getBitsSetFrom(OrigBitWidth, BitWidth); 390 if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) && 391 IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) { 392 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 393 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 394 } 395 break; 396 } 397 case Instruction::Shl: { 398 // If we are truncating the result of this SHL, and if it's a shift of an 399 // inrange amount, we can always perform a SHL in a smaller type. 400 uint32_t BitWidth = Ty->getScalarSizeInBits(); 401 KnownBits AmtKnownBits = 402 llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout()); 403 if (AmtKnownBits.getMaxValue().ult(BitWidth)) 404 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 405 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 406 break; 407 } 408 case Instruction::LShr: { 409 // If this is a truncate of a logical shr, we can truncate it to a smaller 410 // lshr iff we know that the bits we would otherwise be shifting in are 411 // already zeros. 412 // TODO: It is enough to check that the bits we would be shifting in are 413 // zero - use AmtKnownBits.getMaxValue(). 414 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 415 uint32_t BitWidth = Ty->getScalarSizeInBits(); 416 KnownBits AmtKnownBits = 417 llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout()); 418 APInt ShiftedBits = APInt::getBitsSetFrom(OrigBitWidth, BitWidth); 419 if (AmtKnownBits.getMaxValue().ult(BitWidth) && 420 IC.MaskedValueIsZero(I->getOperand(0), ShiftedBits, 0, CxtI)) { 421 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 422 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 423 } 424 break; 425 } 426 case Instruction::AShr: { 427 // If this is a truncate of an arithmetic shr, we can truncate it to a 428 // smaller ashr iff we know that all the bits from the sign bit of the 429 // original type and the sign bit of the truncate type are similar. 430 // TODO: It is enough to check that the bits we would be shifting in are 431 // similar to sign bit of the truncate type. 432 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 433 uint32_t BitWidth = Ty->getScalarSizeInBits(); 434 KnownBits AmtKnownBits = 435 llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout()); 436 unsigned ShiftedBits = OrigBitWidth - BitWidth; 437 if (AmtKnownBits.getMaxValue().ult(BitWidth) && 438 ShiftedBits < IC.ComputeNumSignBits(I->getOperand(0), 0, CxtI)) 439 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 440 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 441 break; 442 } 443 case Instruction::Trunc: 444 // trunc(trunc(x)) -> trunc(x) 445 return true; 446 case Instruction::ZExt: 447 case Instruction::SExt: 448 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest 449 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest 450 return true; 451 case Instruction::Select: { 452 SelectInst *SI = cast<SelectInst>(I); 453 return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) && 454 canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI); 455 } 456 case Instruction::PHI: { 457 // We can change a phi if we can change all operands. Note that we never 458 // get into trouble with cyclic PHIs here because we only consider 459 // instructions with a single use. 460 PHINode *PN = cast<PHINode>(I); 461 for (Value *IncValue : PN->incoming_values()) 462 if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI)) 463 return false; 464 return true; 465 } 466 default: 467 // TODO: Can handle more cases here. 468 break; 469 } 470 471 return false; 472 } 473 474 /// Given a vector that is bitcast to an integer, optionally logically 475 /// right-shifted, and truncated, convert it to an extractelement. 476 /// Example (big endian): 477 /// trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32 478 /// ---> 479 /// extractelement <4 x i32> %X, 1 480 static Instruction *foldVecTruncToExtElt(TruncInst &Trunc, 481 InstCombinerImpl &IC) { 482 Value *TruncOp = Trunc.getOperand(0); 483 Type *DestType = Trunc.getType(); 484 if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType)) 485 return nullptr; 486 487 Value *VecInput = nullptr; 488 ConstantInt *ShiftVal = nullptr; 489 if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)), 490 m_LShr(m_BitCast(m_Value(VecInput)), 491 m_ConstantInt(ShiftVal)))) || 492 !isa<VectorType>(VecInput->getType())) 493 return nullptr; 494 495 VectorType *VecType = cast<VectorType>(VecInput->getType()); 496 unsigned VecWidth = VecType->getPrimitiveSizeInBits(); 497 unsigned DestWidth = DestType->getPrimitiveSizeInBits(); 498 unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0; 499 500 if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0)) 501 return nullptr; 502 503 // If the element type of the vector doesn't match the result type, 504 // bitcast it to a vector type that we can extract from. 505 unsigned NumVecElts = VecWidth / DestWidth; 506 if (VecType->getElementType() != DestType) { 507 VecType = FixedVectorType::get(DestType, NumVecElts); 508 VecInput = IC.Builder.CreateBitCast(VecInput, VecType, "bc"); 509 } 510 511 unsigned Elt = ShiftAmount / DestWidth; 512 if (IC.getDataLayout().isBigEndian()) 513 Elt = NumVecElts - 1 - Elt; 514 515 return ExtractElementInst::Create(VecInput, IC.Builder.getInt32(Elt)); 516 } 517 518 /// Funnel/Rotate left/right may occur in a wider type than necessary because of 519 /// type promotion rules. Try to narrow the inputs and convert to funnel shift. 520 Instruction *InstCombinerImpl::narrowFunnelShift(TruncInst &Trunc) { 521 assert((isa<VectorType>(Trunc.getSrcTy()) || 522 shouldChangeType(Trunc.getSrcTy(), Trunc.getType())) && 523 "Don't narrow to an illegal scalar type"); 524 525 // Bail out on strange types. It is possible to handle some of these patterns 526 // even with non-power-of-2 sizes, but it is not a likely scenario. 527 Type *DestTy = Trunc.getType(); 528 unsigned NarrowWidth = DestTy->getScalarSizeInBits(); 529 unsigned WideWidth = Trunc.getSrcTy()->getScalarSizeInBits(); 530 if (!isPowerOf2_32(NarrowWidth)) 531 return nullptr; 532 533 // First, find an or'd pair of opposite shifts: 534 // trunc (or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)) 535 BinaryOperator *Or0, *Or1; 536 if (!match(Trunc.getOperand(0), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1))))) 537 return nullptr; 538 539 Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1; 540 if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) || 541 !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) || 542 Or0->getOpcode() == Or1->getOpcode()) 543 return nullptr; 544 545 // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)). 546 if (Or0->getOpcode() == BinaryOperator::LShr) { 547 std::swap(Or0, Or1); 548 std::swap(ShVal0, ShVal1); 549 std::swap(ShAmt0, ShAmt1); 550 } 551 assert(Or0->getOpcode() == BinaryOperator::Shl && 552 Or1->getOpcode() == BinaryOperator::LShr && 553 "Illegal or(shift,shift) pair"); 554 555 // Match the shift amount operands for a funnel/rotate pattern. This always 556 // matches a subtraction on the R operand. 557 auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * { 558 // The shift amounts may add up to the narrow bit width: 559 // (shl ShVal0, L) | (lshr ShVal1, Width - L) 560 // If this is a funnel shift (different operands are shifted), then the 561 // shift amount can not over-shift (create poison) in the narrow type. 562 unsigned MaxShiftAmountWidth = Log2_32(NarrowWidth); 563 APInt HiBitMask = ~APInt::getLowBitsSet(WideWidth, MaxShiftAmountWidth); 564 if (ShVal0 == ShVal1 || MaskedValueIsZero(L, HiBitMask)) 565 if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) 566 return L; 567 568 // The following patterns currently only work for rotation patterns. 569 // TODO: Add more general funnel-shift compatible patterns. 570 if (ShVal0 != ShVal1) 571 return nullptr; 572 573 // The shift amount may be masked with negation: 574 // (shl ShVal0, (X & (Width - 1))) | (lshr ShVal1, ((-X) & (Width - 1))) 575 Value *X; 576 unsigned Mask = Width - 1; 577 if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) && 578 match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))) 579 return X; 580 581 // Same as above, but the shift amount may be extended after masking: 582 if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) && 583 match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))) 584 return X; 585 586 return nullptr; 587 }; 588 589 Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, NarrowWidth); 590 bool IsFshl = true; // Sub on LSHR. 591 if (!ShAmt) { 592 ShAmt = matchShiftAmount(ShAmt1, ShAmt0, NarrowWidth); 593 IsFshl = false; // Sub on SHL. 594 } 595 if (!ShAmt) 596 return nullptr; 597 598 // The right-shifted value must have high zeros in the wide type (for example 599 // from 'zext', 'and' or 'shift'). High bits of the left-shifted value are 600 // truncated, so those do not matter. 601 APInt HiBitMask = APInt::getHighBitsSet(WideWidth, WideWidth - NarrowWidth); 602 if (!MaskedValueIsZero(ShVal1, HiBitMask, 0, &Trunc)) 603 return nullptr; 604 605 // We have an unnecessarily wide rotate! 606 // trunc (or (shl ShVal0, ShAmt), (lshr ShVal1, BitWidth - ShAmt)) 607 // Narrow the inputs and convert to funnel shift intrinsic: 608 // llvm.fshl.i8(trunc(ShVal), trunc(ShVal), trunc(ShAmt)) 609 Value *NarrowShAmt = Builder.CreateTrunc(ShAmt, DestTy); 610 Value *X, *Y; 611 X = Y = Builder.CreateTrunc(ShVal0, DestTy); 612 if (ShVal0 != ShVal1) 613 Y = Builder.CreateTrunc(ShVal1, DestTy); 614 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr; 615 Function *F = Intrinsic::getDeclaration(Trunc.getModule(), IID, DestTy); 616 return CallInst::Create(F, {X, Y, NarrowShAmt}); 617 } 618 619 /// Try to narrow the width of math or bitwise logic instructions by pulling a 620 /// truncate ahead of binary operators. 621 /// TODO: Transforms for truncated shifts should be moved into here. 622 Instruction *InstCombinerImpl::narrowBinOp(TruncInst &Trunc) { 623 Type *SrcTy = Trunc.getSrcTy(); 624 Type *DestTy = Trunc.getType(); 625 if (!isa<VectorType>(SrcTy) && !shouldChangeType(SrcTy, DestTy)) 626 return nullptr; 627 628 BinaryOperator *BinOp; 629 if (!match(Trunc.getOperand(0), m_OneUse(m_BinOp(BinOp)))) 630 return nullptr; 631 632 Value *BinOp0 = BinOp->getOperand(0); 633 Value *BinOp1 = BinOp->getOperand(1); 634 switch (BinOp->getOpcode()) { 635 case Instruction::And: 636 case Instruction::Or: 637 case Instruction::Xor: 638 case Instruction::Add: 639 case Instruction::Sub: 640 case Instruction::Mul: { 641 Constant *C; 642 if (match(BinOp0, m_Constant(C))) { 643 // trunc (binop C, X) --> binop (trunc C', X) 644 Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy); 645 Value *TruncX = Builder.CreateTrunc(BinOp1, DestTy); 646 return BinaryOperator::Create(BinOp->getOpcode(), NarrowC, TruncX); 647 } 648 if (match(BinOp1, m_Constant(C))) { 649 // trunc (binop X, C) --> binop (trunc X, C') 650 Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy); 651 Value *TruncX = Builder.CreateTrunc(BinOp0, DestTy); 652 return BinaryOperator::Create(BinOp->getOpcode(), TruncX, NarrowC); 653 } 654 Value *X; 655 if (match(BinOp0, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) { 656 // trunc (binop (ext X), Y) --> binop X, (trunc Y) 657 Value *NarrowOp1 = Builder.CreateTrunc(BinOp1, DestTy); 658 return BinaryOperator::Create(BinOp->getOpcode(), X, NarrowOp1); 659 } 660 if (match(BinOp1, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) { 661 // trunc (binop Y, (ext X)) --> binop (trunc Y), X 662 Value *NarrowOp0 = Builder.CreateTrunc(BinOp0, DestTy); 663 return BinaryOperator::Create(BinOp->getOpcode(), NarrowOp0, X); 664 } 665 break; 666 } 667 668 default: break; 669 } 670 671 if (Instruction *NarrowOr = narrowFunnelShift(Trunc)) 672 return NarrowOr; 673 674 return nullptr; 675 } 676 677 /// Try to narrow the width of a splat shuffle. This could be generalized to any 678 /// shuffle with a constant operand, but we limit the transform to avoid 679 /// creating a shuffle type that targets may not be able to lower effectively. 680 static Instruction *shrinkSplatShuffle(TruncInst &Trunc, 681 InstCombiner::BuilderTy &Builder) { 682 auto *Shuf = dyn_cast<ShuffleVectorInst>(Trunc.getOperand(0)); 683 if (Shuf && Shuf->hasOneUse() && match(Shuf->getOperand(1), m_Undef()) && 684 is_splat(Shuf->getShuffleMask()) && 685 Shuf->getType() == Shuf->getOperand(0)->getType()) { 686 // trunc (shuf X, Undef, SplatMask) --> shuf (trunc X), Undef, SplatMask 687 Constant *NarrowUndef = UndefValue::get(Trunc.getType()); 688 Value *NarrowOp = Builder.CreateTrunc(Shuf->getOperand(0), Trunc.getType()); 689 return new ShuffleVectorInst(NarrowOp, NarrowUndef, Shuf->getShuffleMask()); 690 } 691 692 return nullptr; 693 } 694 695 /// Try to narrow the width of an insert element. This could be generalized for 696 /// any vector constant, but we limit the transform to insertion into undef to 697 /// avoid potential backend problems from unsupported insertion widths. This 698 /// could also be extended to handle the case of inserting a scalar constant 699 /// into a vector variable. 700 static Instruction *shrinkInsertElt(CastInst &Trunc, 701 InstCombiner::BuilderTy &Builder) { 702 Instruction::CastOps Opcode = Trunc.getOpcode(); 703 assert((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) && 704 "Unexpected instruction for shrinking"); 705 706 auto *InsElt = dyn_cast<InsertElementInst>(Trunc.getOperand(0)); 707 if (!InsElt || !InsElt->hasOneUse()) 708 return nullptr; 709 710 Type *DestTy = Trunc.getType(); 711 Type *DestScalarTy = DestTy->getScalarType(); 712 Value *VecOp = InsElt->getOperand(0); 713 Value *ScalarOp = InsElt->getOperand(1); 714 Value *Index = InsElt->getOperand(2); 715 716 if (match(VecOp, m_Undef())) { 717 // trunc (inselt undef, X, Index) --> inselt undef, (trunc X), Index 718 // fptrunc (inselt undef, X, Index) --> inselt undef, (fptrunc X), Index 719 UndefValue *NarrowUndef = UndefValue::get(DestTy); 720 Value *NarrowOp = Builder.CreateCast(Opcode, ScalarOp, DestScalarTy); 721 return InsertElementInst::Create(NarrowUndef, NarrowOp, Index); 722 } 723 724 return nullptr; 725 } 726 727 Instruction *InstCombinerImpl::visitTrunc(TruncInst &Trunc) { 728 if (Instruction *Result = commonCastTransforms(Trunc)) 729 return Result; 730 731 Value *Src = Trunc.getOperand(0); 732 Type *DestTy = Trunc.getType(), *SrcTy = Src->getType(); 733 unsigned DestWidth = DestTy->getScalarSizeInBits(); 734 unsigned SrcWidth = SrcTy->getScalarSizeInBits(); 735 736 // Attempt to truncate the entire input expression tree to the destination 737 // type. Only do this if the dest type is a simple type, don't convert the 738 // expression tree to something weird like i93 unless the source is also 739 // strange. 740 if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) && 741 canEvaluateTruncated(Src, DestTy, *this, &Trunc)) { 742 743 // If this cast is a truncate, evaluting in a different type always 744 // eliminates the cast, so it is always a win. 745 LLVM_DEBUG( 746 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 747 " to avoid cast: " 748 << Trunc << '\n'); 749 Value *Res = EvaluateInDifferentType(Src, DestTy, false); 750 assert(Res->getType() == DestTy); 751 return replaceInstUsesWith(Trunc, Res); 752 } 753 754 // For integer types, check if we can shorten the entire input expression to 755 // DestWidth * 2, which won't allow removing the truncate, but reducing the 756 // width may enable further optimizations, e.g. allowing for larger 757 // vectorization factors. 758 if (auto *DestITy = dyn_cast<IntegerType>(DestTy)) { 759 if (DestWidth * 2 < SrcWidth) { 760 auto *NewDestTy = DestITy->getExtendedType(); 761 if (shouldChangeType(SrcTy, NewDestTy) && 762 canEvaluateTruncated(Src, NewDestTy, *this, &Trunc)) { 763 LLVM_DEBUG( 764 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 765 " to reduce the width of operand of" 766 << Trunc << '\n'); 767 Value *Res = EvaluateInDifferentType(Src, NewDestTy, false); 768 return new TruncInst(Res, DestTy); 769 } 770 } 771 } 772 773 // Test if the trunc is the user of a select which is part of a 774 // minimum or maximum operation. If so, don't do any more simplification. 775 // Even simplifying demanded bits can break the canonical form of a 776 // min/max. 777 Value *LHS, *RHS; 778 if (SelectInst *Sel = dyn_cast<SelectInst>(Src)) 779 if (matchSelectPattern(Sel, LHS, RHS).Flavor != SPF_UNKNOWN) 780 return nullptr; 781 782 // See if we can simplify any instructions used by the input whose sole 783 // purpose is to compute bits we don't care about. 784 if (SimplifyDemandedInstructionBits(Trunc)) 785 return &Trunc; 786 787 if (DestWidth == 1) { 788 Value *Zero = Constant::getNullValue(SrcTy); 789 if (DestTy->isIntegerTy()) { 790 // Canonicalize trunc x to i1 -> icmp ne (and x, 1), 0 (scalar only). 791 // TODO: We canonicalize to more instructions here because we are probably 792 // lacking equivalent analysis for trunc relative to icmp. There may also 793 // be codegen concerns. If those trunc limitations were removed, we could 794 // remove this transform. 795 Value *And = Builder.CreateAnd(Src, ConstantInt::get(SrcTy, 1)); 796 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero); 797 } 798 799 // For vectors, we do not canonicalize all truncs to icmp, so optimize 800 // patterns that would be covered within visitICmpInst. 801 Value *X; 802 Constant *C; 803 if (match(Src, m_OneUse(m_LShr(m_Value(X), m_Constant(C))))) { 804 // trunc (lshr X, C) to i1 --> icmp ne (and X, C'), 0 805 Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1)); 806 Constant *MaskC = ConstantExpr::getShl(One, C); 807 Value *And = Builder.CreateAnd(X, MaskC); 808 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero); 809 } 810 if (match(Src, m_OneUse(m_c_Or(m_LShr(m_Value(X), m_Constant(C)), 811 m_Deferred(X))))) { 812 // trunc (or (lshr X, C), X) to i1 --> icmp ne (and X, C'), 0 813 Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1)); 814 Constant *MaskC = ConstantExpr::getShl(One, C); 815 MaskC = ConstantExpr::getOr(MaskC, One); 816 Value *And = Builder.CreateAnd(X, MaskC); 817 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero); 818 } 819 } 820 821 Value *A; 822 Constant *C; 823 if (match(Src, m_LShr(m_SExt(m_Value(A)), m_Constant(C)))) { 824 unsigned AWidth = A->getType()->getScalarSizeInBits(); 825 unsigned MaxShiftAmt = SrcWidth - std::max(DestWidth, AWidth); 826 auto *OldSh = cast<Instruction>(Src); 827 bool IsExact = OldSh->isExact(); 828 829 // If the shift is small enough, all zero bits created by the shift are 830 // removed by the trunc. 831 if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULE, 832 APInt(SrcWidth, MaxShiftAmt)))) { 833 // trunc (lshr (sext A), C) --> ashr A, C 834 if (A->getType() == DestTy) { 835 Constant *MaxAmt = ConstantInt::get(SrcTy, DestWidth - 1, false); 836 Constant *ShAmt = ConstantExpr::getUMin(C, MaxAmt); 837 ShAmt = ConstantExpr::getTrunc(ShAmt, A->getType()); 838 ShAmt = Constant::mergeUndefsWith(ShAmt, C); 839 return IsExact ? BinaryOperator::CreateExactAShr(A, ShAmt) 840 : BinaryOperator::CreateAShr(A, ShAmt); 841 } 842 // The types are mismatched, so create a cast after shifting: 843 // trunc (lshr (sext A), C) --> sext/trunc (ashr A, C) 844 if (Src->hasOneUse()) { 845 Constant *MaxAmt = ConstantInt::get(SrcTy, AWidth - 1, false); 846 Constant *ShAmt = ConstantExpr::getUMin(C, MaxAmt); 847 ShAmt = ConstantExpr::getTrunc(ShAmt, A->getType()); 848 Value *Shift = Builder.CreateAShr(A, ShAmt, "", IsExact); 849 return CastInst::CreateIntegerCast(Shift, DestTy, true); 850 } 851 } 852 // TODO: Mask high bits with 'and'. 853 } 854 855 // trunc (*shr (trunc A), C) --> trunc(*shr A, C) 856 if (match(Src, m_OneUse(m_Shr(m_Trunc(m_Value(A)), m_Constant(C))))) { 857 unsigned MaxShiftAmt = SrcWidth - DestWidth; 858 859 // If the shift is small enough, all zero/sign bits created by the shift are 860 // removed by the trunc. 861 if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULE, 862 APInt(SrcWidth, MaxShiftAmt)))) { 863 auto *OldShift = cast<Instruction>(Src); 864 bool IsExact = OldShift->isExact(); 865 auto *ShAmt = ConstantExpr::getIntegerCast(C, A->getType(), true); 866 ShAmt = Constant::mergeUndefsWith(ShAmt, C); 867 Value *Shift = 868 OldShift->getOpcode() == Instruction::AShr 869 ? Builder.CreateAShr(A, ShAmt, OldShift->getName(), IsExact) 870 : Builder.CreateLShr(A, ShAmt, OldShift->getName(), IsExact); 871 return CastInst::CreateTruncOrBitCast(Shift, DestTy); 872 } 873 } 874 875 if (Instruction *I = narrowBinOp(Trunc)) 876 return I; 877 878 if (Instruction *I = shrinkSplatShuffle(Trunc, Builder)) 879 return I; 880 881 if (Instruction *I = shrinkInsertElt(Trunc, Builder)) 882 return I; 883 884 if (Src->hasOneUse() && 885 (isa<VectorType>(SrcTy) || shouldChangeType(SrcTy, DestTy))) { 886 // Transform "trunc (shl X, cst)" -> "shl (trunc X), cst" so long as the 887 // dest type is native and cst < dest size. 888 if (match(Src, m_Shl(m_Value(A), m_Constant(C))) && 889 !match(A, m_Shr(m_Value(), m_Constant()))) { 890 // Skip shifts of shift by constants. It undoes a combine in 891 // FoldShiftByConstant and is the extend in reg pattern. 892 APInt Threshold = APInt(C->getType()->getScalarSizeInBits(), DestWidth); 893 if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold))) { 894 Value *NewTrunc = Builder.CreateTrunc(A, DestTy, A->getName() + ".tr"); 895 return BinaryOperator::Create(Instruction::Shl, NewTrunc, 896 ConstantExpr::getTrunc(C, DestTy)); 897 } 898 } 899 } 900 901 if (Instruction *I = foldVecTruncToExtElt(Trunc, *this)) 902 return I; 903 904 // Whenever an element is extracted from a vector, and then truncated, 905 // canonicalize by converting it to a bitcast followed by an 906 // extractelement. 907 // 908 // Example (little endian): 909 // trunc (extractelement <4 x i64> %X, 0) to i32 910 // ---> 911 // extractelement <8 x i32> (bitcast <4 x i64> %X to <8 x i32>), i32 0 912 Value *VecOp; 913 ConstantInt *Cst; 914 if (match(Src, m_OneUse(m_ExtractElt(m_Value(VecOp), m_ConstantInt(Cst))))) { 915 auto *VecOpTy = cast<VectorType>(VecOp->getType()); 916 auto VecElts = VecOpTy->getElementCount(); 917 918 // A badly fit destination size would result in an invalid cast. 919 if (SrcWidth % DestWidth == 0) { 920 uint64_t TruncRatio = SrcWidth / DestWidth; 921 uint64_t BitCastNumElts = VecElts.getKnownMinValue() * TruncRatio; 922 uint64_t VecOpIdx = Cst->getZExtValue(); 923 uint64_t NewIdx = DL.isBigEndian() ? (VecOpIdx + 1) * TruncRatio - 1 924 : VecOpIdx * TruncRatio; 925 assert(BitCastNumElts <= std::numeric_limits<uint32_t>::max() && 926 "overflow 32-bits"); 927 928 auto *BitCastTo = 929 VectorType::get(DestTy, BitCastNumElts, VecElts.isScalable()); 930 Value *BitCast = Builder.CreateBitCast(VecOp, BitCastTo); 931 return ExtractElementInst::Create(BitCast, Builder.getInt32(NewIdx)); 932 } 933 } 934 935 return nullptr; 936 } 937 938 Instruction *InstCombinerImpl::transformZExtICmp(ICmpInst *Cmp, ZExtInst &Zext, 939 bool DoTransform) { 940 // If we are just checking for a icmp eq of a single bit and zext'ing it 941 // to an integer, then shift the bit to the appropriate place and then 942 // cast to integer to avoid the comparison. 943 const APInt *Op1CV; 944 if (match(Cmp->getOperand(1), m_APInt(Op1CV))) { 945 946 // zext (x <s 0) to i32 --> x>>u31 true if signbit set. 947 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear. 948 if ((Cmp->getPredicate() == ICmpInst::ICMP_SLT && Op1CV->isNullValue()) || 949 (Cmp->getPredicate() == ICmpInst::ICMP_SGT && Op1CV->isAllOnesValue())) { 950 if (!DoTransform) return Cmp; 951 952 Value *In = Cmp->getOperand(0); 953 Value *Sh = ConstantInt::get(In->getType(), 954 In->getType()->getScalarSizeInBits() - 1); 955 In = Builder.CreateLShr(In, Sh, In->getName() + ".lobit"); 956 if (In->getType() != Zext.getType()) 957 In = Builder.CreateIntCast(In, Zext.getType(), false /*ZExt*/); 958 959 if (Cmp->getPredicate() == ICmpInst::ICMP_SGT) { 960 Constant *One = ConstantInt::get(In->getType(), 1); 961 In = Builder.CreateXor(In, One, In->getName() + ".not"); 962 } 963 964 return replaceInstUsesWith(Zext, In); 965 } 966 967 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set. 968 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. 969 // zext (X == 1) to i32 --> X iff X has only the low bit set. 970 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set. 971 // zext (X != 0) to i32 --> X iff X has only the low bit set. 972 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set. 973 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set. 974 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. 975 if ((Op1CV->isNullValue() || Op1CV->isPowerOf2()) && 976 // This only works for EQ and NE 977 Cmp->isEquality()) { 978 // If Op1C some other power of two, convert: 979 KnownBits Known = computeKnownBits(Cmp->getOperand(0), 0, &Zext); 980 981 APInt KnownZeroMask(~Known.Zero); 982 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1? 983 if (!DoTransform) return Cmp; 984 985 bool isNE = Cmp->getPredicate() == ICmpInst::ICMP_NE; 986 if (!Op1CV->isNullValue() && (*Op1CV != KnownZeroMask)) { 987 // (X&4) == 2 --> false 988 // (X&4) != 2 --> true 989 Constant *Res = ConstantInt::get(Zext.getType(), isNE); 990 return replaceInstUsesWith(Zext, Res); 991 } 992 993 uint32_t ShAmt = KnownZeroMask.logBase2(); 994 Value *In = Cmp->getOperand(0); 995 if (ShAmt) { 996 // Perform a logical shr by shiftamt. 997 // Insert the shift to put the result in the low bit. 998 In = Builder.CreateLShr(In, ConstantInt::get(In->getType(), ShAmt), 999 In->getName() + ".lobit"); 1000 } 1001 1002 if (!Op1CV->isNullValue() == isNE) { // Toggle the low bit. 1003 Constant *One = ConstantInt::get(In->getType(), 1); 1004 In = Builder.CreateXor(In, One); 1005 } 1006 1007 if (Zext.getType() == In->getType()) 1008 return replaceInstUsesWith(Zext, In); 1009 1010 Value *IntCast = Builder.CreateIntCast(In, Zext.getType(), false); 1011 return replaceInstUsesWith(Zext, IntCast); 1012 } 1013 } 1014 } 1015 1016 // icmp ne A, B is equal to xor A, B when A and B only really have one bit. 1017 // It is also profitable to transform icmp eq into not(xor(A, B)) because that 1018 // may lead to additional simplifications. 1019 if (Cmp->isEquality() && Zext.getType() == Cmp->getOperand(0)->getType()) { 1020 if (IntegerType *ITy = dyn_cast<IntegerType>(Zext.getType())) { 1021 Value *LHS = Cmp->getOperand(0); 1022 Value *RHS = Cmp->getOperand(1); 1023 1024 KnownBits KnownLHS = computeKnownBits(LHS, 0, &Zext); 1025 KnownBits KnownRHS = computeKnownBits(RHS, 0, &Zext); 1026 1027 if (KnownLHS.Zero == KnownRHS.Zero && KnownLHS.One == KnownRHS.One) { 1028 APInt KnownBits = KnownLHS.Zero | KnownLHS.One; 1029 APInt UnknownBit = ~KnownBits; 1030 if (UnknownBit.countPopulation() == 1) { 1031 if (!DoTransform) return Cmp; 1032 1033 Value *Result = Builder.CreateXor(LHS, RHS); 1034 1035 // Mask off any bits that are set and won't be shifted away. 1036 if (KnownLHS.One.uge(UnknownBit)) 1037 Result = Builder.CreateAnd(Result, 1038 ConstantInt::get(ITy, UnknownBit)); 1039 1040 // Shift the bit we're testing down to the lsb. 1041 Result = Builder.CreateLShr( 1042 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros())); 1043 1044 if (Cmp->getPredicate() == ICmpInst::ICMP_EQ) 1045 Result = Builder.CreateXor(Result, ConstantInt::get(ITy, 1)); 1046 Result->takeName(Cmp); 1047 return replaceInstUsesWith(Zext, Result); 1048 } 1049 } 1050 } 1051 } 1052 1053 return nullptr; 1054 } 1055 1056 /// Determine if the specified value can be computed in the specified wider type 1057 /// and produce the same low bits. If not, return false. 1058 /// 1059 /// If this function returns true, it can also return a non-zero number of bits 1060 /// (in BitsToClear) which indicates that the value it computes is correct for 1061 /// the zero extend, but that the additional BitsToClear bits need to be zero'd 1062 /// out. For example, to promote something like: 1063 /// 1064 /// %B = trunc i64 %A to i32 1065 /// %C = lshr i32 %B, 8 1066 /// %E = zext i32 %C to i64 1067 /// 1068 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be 1069 /// set to 8 to indicate that the promoted value needs to have bits 24-31 1070 /// cleared in addition to bits 32-63. Since an 'and' will be generated to 1071 /// clear the top bits anyway, doing this has no extra cost. 1072 /// 1073 /// This function works on both vectors and scalars. 1074 static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear, 1075 InstCombinerImpl &IC, Instruction *CxtI) { 1076 BitsToClear = 0; 1077 if (canAlwaysEvaluateInType(V, Ty)) 1078 return true; 1079 if (canNotEvaluateInType(V, Ty)) 1080 return false; 1081 1082 auto *I = cast<Instruction>(V); 1083 unsigned Tmp; 1084 switch (I->getOpcode()) { 1085 case Instruction::ZExt: // zext(zext(x)) -> zext(x). 1086 case Instruction::SExt: // zext(sext(x)) -> sext(x). 1087 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x) 1088 return true; 1089 case Instruction::And: 1090 case Instruction::Or: 1091 case Instruction::Xor: 1092 case Instruction::Add: 1093 case Instruction::Sub: 1094 case Instruction::Mul: 1095 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) || 1096 !canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI)) 1097 return false; 1098 // These can all be promoted if neither operand has 'bits to clear'. 1099 if (BitsToClear == 0 && Tmp == 0) 1100 return true; 1101 1102 // If the operation is an AND/OR/XOR and the bits to clear are zero in the 1103 // other side, BitsToClear is ok. 1104 if (Tmp == 0 && I->isBitwiseLogicOp()) { 1105 // We use MaskedValueIsZero here for generality, but the case we care 1106 // about the most is constant RHS. 1107 unsigned VSize = V->getType()->getScalarSizeInBits(); 1108 if (IC.MaskedValueIsZero(I->getOperand(1), 1109 APInt::getHighBitsSet(VSize, BitsToClear), 1110 0, CxtI)) { 1111 // If this is an And instruction and all of the BitsToClear are 1112 // known to be zero we can reset BitsToClear. 1113 if (I->getOpcode() == Instruction::And) 1114 BitsToClear = 0; 1115 return true; 1116 } 1117 } 1118 1119 // Otherwise, we don't know how to analyze this BitsToClear case yet. 1120 return false; 1121 1122 case Instruction::Shl: { 1123 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the 1124 // upper bits we can reduce BitsToClear by the shift amount. 1125 const APInt *Amt; 1126 if (match(I->getOperand(1), m_APInt(Amt))) { 1127 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI)) 1128 return false; 1129 uint64_t ShiftAmt = Amt->getZExtValue(); 1130 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0; 1131 return true; 1132 } 1133 return false; 1134 } 1135 case Instruction::LShr: { 1136 // We can promote lshr(x, cst) if we can promote x. This requires the 1137 // ultimate 'and' to clear out the high zero bits we're clearing out though. 1138 const APInt *Amt; 1139 if (match(I->getOperand(1), m_APInt(Amt))) { 1140 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI)) 1141 return false; 1142 BitsToClear += Amt->getZExtValue(); 1143 if (BitsToClear > V->getType()->getScalarSizeInBits()) 1144 BitsToClear = V->getType()->getScalarSizeInBits(); 1145 return true; 1146 } 1147 // Cannot promote variable LSHR. 1148 return false; 1149 } 1150 case Instruction::Select: 1151 if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) || 1152 !canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) || 1153 // TODO: If important, we could handle the case when the BitsToClear are 1154 // known zero in the disagreeing side. 1155 Tmp != BitsToClear) 1156 return false; 1157 return true; 1158 1159 case Instruction::PHI: { 1160 // We can change a phi if we can change all operands. Note that we never 1161 // get into trouble with cyclic PHIs here because we only consider 1162 // instructions with a single use. 1163 PHINode *PN = cast<PHINode>(I); 1164 if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI)) 1165 return false; 1166 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) 1167 if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) || 1168 // TODO: If important, we could handle the case when the BitsToClear 1169 // are known zero in the disagreeing input. 1170 Tmp != BitsToClear) 1171 return false; 1172 return true; 1173 } 1174 default: 1175 // TODO: Can handle more cases here. 1176 return false; 1177 } 1178 } 1179 1180 Instruction *InstCombinerImpl::visitZExt(ZExtInst &CI) { 1181 // If this zero extend is only used by a truncate, let the truncate be 1182 // eliminated before we try to optimize this zext. 1183 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back())) 1184 return nullptr; 1185 1186 // If one of the common conversion will work, do it. 1187 if (Instruction *Result = commonCastTransforms(CI)) 1188 return Result; 1189 1190 Value *Src = CI.getOperand(0); 1191 Type *SrcTy = Src->getType(), *DestTy = CI.getType(); 1192 1193 // Try to extend the entire expression tree to the wide destination type. 1194 unsigned BitsToClear; 1195 if (shouldChangeType(SrcTy, DestTy) && 1196 canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) { 1197 assert(BitsToClear <= SrcTy->getScalarSizeInBits() && 1198 "Can't clear more bits than in SrcTy"); 1199 1200 // Okay, we can transform this! Insert the new expression now. 1201 LLVM_DEBUG( 1202 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 1203 " to avoid zero extend: " 1204 << CI << '\n'); 1205 Value *Res = EvaluateInDifferentType(Src, DestTy, false); 1206 assert(Res->getType() == DestTy); 1207 1208 // Preserve debug values referring to Src if the zext is its last use. 1209 if (auto *SrcOp = dyn_cast<Instruction>(Src)) 1210 if (SrcOp->hasOneUse()) 1211 replaceAllDbgUsesWith(*SrcOp, *Res, CI, DT); 1212 1213 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear; 1214 uint32_t DestBitSize = DestTy->getScalarSizeInBits(); 1215 1216 // If the high bits are already filled with zeros, just replace this 1217 // cast with the result. 1218 if (MaskedValueIsZero(Res, 1219 APInt::getHighBitsSet(DestBitSize, 1220 DestBitSize-SrcBitsKept), 1221 0, &CI)) 1222 return replaceInstUsesWith(CI, Res); 1223 1224 // We need to emit an AND to clear the high bits. 1225 Constant *C = ConstantInt::get(Res->getType(), 1226 APInt::getLowBitsSet(DestBitSize, SrcBitsKept)); 1227 return BinaryOperator::CreateAnd(Res, C); 1228 } 1229 1230 // If this is a TRUNC followed by a ZEXT then we are dealing with integral 1231 // types and if the sizes are just right we can convert this into a logical 1232 // 'and' which will be much cheaper than the pair of casts. 1233 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast 1234 // TODO: Subsume this into EvaluateInDifferentType. 1235 1236 // Get the sizes of the types involved. We know that the intermediate type 1237 // will be smaller than A or C, but don't know the relation between A and C. 1238 Value *A = CSrc->getOperand(0); 1239 unsigned SrcSize = A->getType()->getScalarSizeInBits(); 1240 unsigned MidSize = CSrc->getType()->getScalarSizeInBits(); 1241 unsigned DstSize = CI.getType()->getScalarSizeInBits(); 1242 // If we're actually extending zero bits, then if 1243 // SrcSize < DstSize: zext(a & mask) 1244 // SrcSize == DstSize: a & mask 1245 // SrcSize > DstSize: trunc(a) & mask 1246 if (SrcSize < DstSize) { 1247 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize)); 1248 Constant *AndConst = ConstantInt::get(A->getType(), AndValue); 1249 Value *And = Builder.CreateAnd(A, AndConst, CSrc->getName() + ".mask"); 1250 return new ZExtInst(And, CI.getType()); 1251 } 1252 1253 if (SrcSize == DstSize) { 1254 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize)); 1255 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(), 1256 AndValue)); 1257 } 1258 if (SrcSize > DstSize) { 1259 Value *Trunc = Builder.CreateTrunc(A, CI.getType()); 1260 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize)); 1261 return BinaryOperator::CreateAnd(Trunc, 1262 ConstantInt::get(Trunc->getType(), 1263 AndValue)); 1264 } 1265 } 1266 1267 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(Src)) 1268 return transformZExtICmp(Cmp, CI); 1269 1270 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src); 1271 if (SrcI && SrcI->getOpcode() == Instruction::Or) { 1272 // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) if at least one 1273 // of the (zext icmp) can be eliminated. If so, immediately perform the 1274 // according elimination. 1275 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0)); 1276 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1)); 1277 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() && 1278 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType() && 1279 (transformZExtICmp(LHS, CI, false) || 1280 transformZExtICmp(RHS, CI, false))) { 1281 // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) 1282 Value *LCast = Builder.CreateZExt(LHS, CI.getType(), LHS->getName()); 1283 Value *RCast = Builder.CreateZExt(RHS, CI.getType(), RHS->getName()); 1284 Value *Or = Builder.CreateOr(LCast, RCast, CI.getName()); 1285 if (auto *OrInst = dyn_cast<Instruction>(Or)) 1286 Builder.SetInsertPoint(OrInst); 1287 1288 // Perform the elimination. 1289 if (auto *LZExt = dyn_cast<ZExtInst>(LCast)) 1290 transformZExtICmp(LHS, *LZExt); 1291 if (auto *RZExt = dyn_cast<ZExtInst>(RCast)) 1292 transformZExtICmp(RHS, *RZExt); 1293 1294 return replaceInstUsesWith(CI, Or); 1295 } 1296 } 1297 1298 // zext(trunc(X) & C) -> (X & zext(C)). 1299 Constant *C; 1300 Value *X; 1301 if (SrcI && 1302 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) && 1303 X->getType() == CI.getType()) 1304 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType())); 1305 1306 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)). 1307 Value *And; 1308 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) && 1309 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) && 1310 X->getType() == CI.getType()) { 1311 Constant *ZC = ConstantExpr::getZExt(C, CI.getType()); 1312 return BinaryOperator::CreateXor(Builder.CreateAnd(X, ZC), ZC); 1313 } 1314 1315 return nullptr; 1316 } 1317 1318 /// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp. 1319 Instruction *InstCombinerImpl::transformSExtICmp(ICmpInst *ICI, 1320 Instruction &CI) { 1321 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1); 1322 ICmpInst::Predicate Pred = ICI->getPredicate(); 1323 1324 // Don't bother if Op1 isn't of vector or integer type. 1325 if (!Op1->getType()->isIntOrIntVectorTy()) 1326 return nullptr; 1327 1328 if ((Pred == ICmpInst::ICMP_SLT && match(Op1, m_ZeroInt())) || 1329 (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))) { 1330 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative 1331 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive 1332 Value *Sh = ConstantInt::get(Op0->getType(), 1333 Op0->getType()->getScalarSizeInBits() - 1); 1334 Value *In = Builder.CreateAShr(Op0, Sh, Op0->getName() + ".lobit"); 1335 if (In->getType() != CI.getType()) 1336 In = Builder.CreateIntCast(In, CI.getType(), true /*SExt*/); 1337 1338 if (Pred == ICmpInst::ICMP_SGT) 1339 In = Builder.CreateNot(In, In->getName() + ".not"); 1340 return replaceInstUsesWith(CI, In); 1341 } 1342 1343 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 1344 // If we know that only one bit of the LHS of the icmp can be set and we 1345 // have an equality comparison with zero or a power of 2, we can transform 1346 // the icmp and sext into bitwise/integer operations. 1347 if (ICI->hasOneUse() && 1348 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){ 1349 KnownBits Known = computeKnownBits(Op0, 0, &CI); 1350 1351 APInt KnownZeroMask(~Known.Zero); 1352 if (KnownZeroMask.isPowerOf2()) { 1353 Value *In = ICI->getOperand(0); 1354 1355 // If the icmp tests for a known zero bit we can constant fold it. 1356 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) { 1357 Value *V = Pred == ICmpInst::ICMP_NE ? 1358 ConstantInt::getAllOnesValue(CI.getType()) : 1359 ConstantInt::getNullValue(CI.getType()); 1360 return replaceInstUsesWith(CI, V); 1361 } 1362 1363 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) { 1364 // sext ((x & 2^n) == 0) -> (x >> n) - 1 1365 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1 1366 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros(); 1367 // Perform a right shift to place the desired bit in the LSB. 1368 if (ShiftAmt) 1369 In = Builder.CreateLShr(In, 1370 ConstantInt::get(In->getType(), ShiftAmt)); 1371 1372 // At this point "In" is either 1 or 0. Subtract 1 to turn 1373 // {1, 0} -> {0, -1}. 1374 In = Builder.CreateAdd(In, 1375 ConstantInt::getAllOnesValue(In->getType()), 1376 "sext"); 1377 } else { 1378 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1 1379 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1 1380 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros(); 1381 // Perform a left shift to place the desired bit in the MSB. 1382 if (ShiftAmt) 1383 In = Builder.CreateShl(In, 1384 ConstantInt::get(In->getType(), ShiftAmt)); 1385 1386 // Distribute the bit over the whole bit width. 1387 In = Builder.CreateAShr(In, ConstantInt::get(In->getType(), 1388 KnownZeroMask.getBitWidth() - 1), "sext"); 1389 } 1390 1391 if (CI.getType() == In->getType()) 1392 return replaceInstUsesWith(CI, In); 1393 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/); 1394 } 1395 } 1396 } 1397 1398 return nullptr; 1399 } 1400 1401 /// Return true if we can take the specified value and return it as type Ty 1402 /// without inserting any new casts and without changing the value of the common 1403 /// low bits. This is used by code that tries to promote integer operations to 1404 /// a wider types will allow us to eliminate the extension. 1405 /// 1406 /// This function works on both vectors and scalars. 1407 /// 1408 static bool canEvaluateSExtd(Value *V, Type *Ty) { 1409 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() && 1410 "Can't sign extend type to a smaller type"); 1411 if (canAlwaysEvaluateInType(V, Ty)) 1412 return true; 1413 if (canNotEvaluateInType(V, Ty)) 1414 return false; 1415 1416 auto *I = cast<Instruction>(V); 1417 switch (I->getOpcode()) { 1418 case Instruction::SExt: // sext(sext(x)) -> sext(x) 1419 case Instruction::ZExt: // sext(zext(x)) -> zext(x) 1420 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x) 1421 return true; 1422 case Instruction::And: 1423 case Instruction::Or: 1424 case Instruction::Xor: 1425 case Instruction::Add: 1426 case Instruction::Sub: 1427 case Instruction::Mul: 1428 // These operators can all arbitrarily be extended if their inputs can. 1429 return canEvaluateSExtd(I->getOperand(0), Ty) && 1430 canEvaluateSExtd(I->getOperand(1), Ty); 1431 1432 //case Instruction::Shl: TODO 1433 //case Instruction::LShr: TODO 1434 1435 case Instruction::Select: 1436 return canEvaluateSExtd(I->getOperand(1), Ty) && 1437 canEvaluateSExtd(I->getOperand(2), Ty); 1438 1439 case Instruction::PHI: { 1440 // We can change a phi if we can change all operands. Note that we never 1441 // get into trouble with cyclic PHIs here because we only consider 1442 // instructions with a single use. 1443 PHINode *PN = cast<PHINode>(I); 1444 for (Value *IncValue : PN->incoming_values()) 1445 if (!canEvaluateSExtd(IncValue, Ty)) return false; 1446 return true; 1447 } 1448 default: 1449 // TODO: Can handle more cases here. 1450 break; 1451 } 1452 1453 return false; 1454 } 1455 1456 Instruction *InstCombinerImpl::visitSExt(SExtInst &CI) { 1457 // If this sign extend is only used by a truncate, let the truncate be 1458 // eliminated before we try to optimize this sext. 1459 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back())) 1460 return nullptr; 1461 1462 if (Instruction *I = commonCastTransforms(CI)) 1463 return I; 1464 1465 Value *Src = CI.getOperand(0); 1466 Type *SrcTy = Src->getType(), *DestTy = CI.getType(); 1467 1468 // If we know that the value being extended is positive, we can use a zext 1469 // instead. 1470 KnownBits Known = computeKnownBits(Src, 0, &CI); 1471 if (Known.isNonNegative()) 1472 return CastInst::Create(Instruction::ZExt, Src, DestTy); 1473 1474 // Try to extend the entire expression tree to the wide destination type. 1475 if (shouldChangeType(SrcTy, DestTy) && canEvaluateSExtd(Src, DestTy)) { 1476 // Okay, we can transform this! Insert the new expression now. 1477 LLVM_DEBUG( 1478 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 1479 " to avoid sign extend: " 1480 << CI << '\n'); 1481 Value *Res = EvaluateInDifferentType(Src, DestTy, true); 1482 assert(Res->getType() == DestTy); 1483 1484 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits(); 1485 uint32_t DestBitSize = DestTy->getScalarSizeInBits(); 1486 1487 // If the high bits are already filled with sign bit, just replace this 1488 // cast with the result. 1489 if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize) 1490 return replaceInstUsesWith(CI, Res); 1491 1492 // We need to emit a shl + ashr to do the sign extend. 1493 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize); 1494 return BinaryOperator::CreateAShr(Builder.CreateShl(Res, ShAmt, "sext"), 1495 ShAmt); 1496 } 1497 1498 // If the input is a trunc from the destination type, then turn sext(trunc(x)) 1499 // into shifts. 1500 Value *X; 1501 if (match(Src, m_OneUse(m_Trunc(m_Value(X)))) && X->getType() == DestTy) { 1502 // sext(trunc(X)) --> ashr(shl(X, C), C) 1503 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 1504 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 1505 Constant *ShAmt = ConstantInt::get(DestTy, DestBitSize - SrcBitSize); 1506 return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShAmt), ShAmt); 1507 } 1508 1509 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) 1510 return transformSExtICmp(ICI, CI); 1511 1512 // If the input is a shl/ashr pair of a same constant, then this is a sign 1513 // extension from a smaller value. If we could trust arbitrary bitwidth 1514 // integers, we could turn this into a truncate to the smaller bit and then 1515 // use a sext for the whole extension. Since we don't, look deeper and check 1516 // for a truncate. If the source and dest are the same type, eliminate the 1517 // trunc and extend and just do shifts. For example, turn: 1518 // %a = trunc i32 %i to i8 1519 // %b = shl i8 %a, C 1520 // %c = ashr i8 %b, C 1521 // %d = sext i8 %c to i32 1522 // into: 1523 // %a = shl i32 %i, 32-(8-C) 1524 // %d = ashr i32 %a, 32-(8-C) 1525 Value *A = nullptr; 1526 // TODO: Eventually this could be subsumed by EvaluateInDifferentType. 1527 Constant *BA = nullptr, *CA = nullptr; 1528 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_Constant(BA)), 1529 m_Constant(CA))) && 1530 BA->isElementWiseEqual(CA) && A->getType() == DestTy) { 1531 Constant *WideCurrShAmt = ConstantExpr::getSExt(CA, DestTy); 1532 Constant *NumLowbitsLeft = ConstantExpr::getSub( 1533 ConstantInt::get(DestTy, SrcTy->getScalarSizeInBits()), WideCurrShAmt); 1534 Constant *NewShAmt = ConstantExpr::getSub( 1535 ConstantInt::get(DestTy, DestTy->getScalarSizeInBits()), 1536 NumLowbitsLeft); 1537 NewShAmt = 1538 Constant::mergeUndefsWith(Constant::mergeUndefsWith(NewShAmt, BA), CA); 1539 A = Builder.CreateShl(A, NewShAmt, CI.getName()); 1540 return BinaryOperator::CreateAShr(A, NewShAmt); 1541 } 1542 1543 return nullptr; 1544 } 1545 1546 /// Return a Constant* for the specified floating-point constant if it fits 1547 /// in the specified FP type without changing its value. 1548 static bool fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) { 1549 bool losesInfo; 1550 APFloat F = CFP->getValueAPF(); 1551 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo); 1552 return !losesInfo; 1553 } 1554 1555 static Type *shrinkFPConstant(ConstantFP *CFP) { 1556 if (CFP->getType() == Type::getPPC_FP128Ty(CFP->getContext())) 1557 return nullptr; // No constant folding of this. 1558 // See if the value can be truncated to half and then reextended. 1559 if (fitsInFPType(CFP, APFloat::IEEEhalf())) 1560 return Type::getHalfTy(CFP->getContext()); 1561 // See if the value can be truncated to float and then reextended. 1562 if (fitsInFPType(CFP, APFloat::IEEEsingle())) 1563 return Type::getFloatTy(CFP->getContext()); 1564 if (CFP->getType()->isDoubleTy()) 1565 return nullptr; // Won't shrink. 1566 if (fitsInFPType(CFP, APFloat::IEEEdouble())) 1567 return Type::getDoubleTy(CFP->getContext()); 1568 // Don't try to shrink to various long double types. 1569 return nullptr; 1570 } 1571 1572 // Determine if this is a vector of ConstantFPs and if so, return the minimal 1573 // type we can safely truncate all elements to. 1574 // TODO: Make these support undef elements. 1575 static Type *shrinkFPConstantVector(Value *V) { 1576 auto *CV = dyn_cast<Constant>(V); 1577 auto *CVVTy = dyn_cast<FixedVectorType>(V->getType()); 1578 if (!CV || !CVVTy) 1579 return nullptr; 1580 1581 Type *MinType = nullptr; 1582 1583 unsigned NumElts = CVVTy->getNumElements(); 1584 1585 // For fixed-width vectors we find the minimal type by looking 1586 // through the constant values of the vector. 1587 for (unsigned i = 0; i != NumElts; ++i) { 1588 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i)); 1589 if (!CFP) 1590 return nullptr; 1591 1592 Type *T = shrinkFPConstant(CFP); 1593 if (!T) 1594 return nullptr; 1595 1596 // If we haven't found a type yet or this type has a larger mantissa than 1597 // our previous type, this is our new minimal type. 1598 if (!MinType || T->getFPMantissaWidth() > MinType->getFPMantissaWidth()) 1599 MinType = T; 1600 } 1601 1602 // Make a vector type from the minimal type. 1603 return FixedVectorType::get(MinType, NumElts); 1604 } 1605 1606 /// Find the minimum FP type we can safely truncate to. 1607 static Type *getMinimumFPType(Value *V) { 1608 if (auto *FPExt = dyn_cast<FPExtInst>(V)) 1609 return FPExt->getOperand(0)->getType(); 1610 1611 // If this value is a constant, return the constant in the smallest FP type 1612 // that can accurately represent it. This allows us to turn 1613 // (float)((double)X+2.0) into x+2.0f. 1614 if (auto *CFP = dyn_cast<ConstantFP>(V)) 1615 if (Type *T = shrinkFPConstant(CFP)) 1616 return T; 1617 1618 // We can only correctly find a minimum type for a scalable vector when it is 1619 // a splat. For splats of constant values the fpext is wrapped up as a 1620 // ConstantExpr. 1621 if (auto *FPCExt = dyn_cast<ConstantExpr>(V)) 1622 if (FPCExt->getOpcode() == Instruction::FPExt) 1623 return FPCExt->getOperand(0)->getType(); 1624 1625 // Try to shrink a vector of FP constants. This returns nullptr on scalable 1626 // vectors 1627 if (Type *T = shrinkFPConstantVector(V)) 1628 return T; 1629 1630 return V->getType(); 1631 } 1632 1633 /// Return true if the cast from integer to FP can be proven to be exact for all 1634 /// possible inputs (the conversion does not lose any precision). 1635 static bool isKnownExactCastIntToFP(CastInst &I) { 1636 CastInst::CastOps Opcode = I.getOpcode(); 1637 assert((Opcode == CastInst::SIToFP || Opcode == CastInst::UIToFP) && 1638 "Unexpected cast"); 1639 Value *Src = I.getOperand(0); 1640 Type *SrcTy = Src->getType(); 1641 Type *FPTy = I.getType(); 1642 bool IsSigned = Opcode == Instruction::SIToFP; 1643 int SrcSize = (int)SrcTy->getScalarSizeInBits() - IsSigned; 1644 1645 // Easy case - if the source integer type has less bits than the FP mantissa, 1646 // then the cast must be exact. 1647 int DestNumSigBits = FPTy->getFPMantissaWidth(); 1648 if (SrcSize <= DestNumSigBits) 1649 return true; 1650 1651 // Cast from FP to integer and back to FP is independent of the intermediate 1652 // integer width because of poison on overflow. 1653 Value *F; 1654 if (match(Src, m_FPToSI(m_Value(F))) || match(Src, m_FPToUI(m_Value(F)))) { 1655 // If this is uitofp (fptosi F), the source needs an extra bit to avoid 1656 // potential rounding of negative FP input values. 1657 int SrcNumSigBits = F->getType()->getFPMantissaWidth(); 1658 if (!IsSigned && match(Src, m_FPToSI(m_Value()))) 1659 SrcNumSigBits++; 1660 1661 // [su]itofp (fpto[su]i F) --> exact if the source type has less or equal 1662 // significant bits than the destination (and make sure neither type is 1663 // weird -- ppc_fp128). 1664 if (SrcNumSigBits > 0 && DestNumSigBits > 0 && 1665 SrcNumSigBits <= DestNumSigBits) 1666 return true; 1667 } 1668 1669 // TODO: 1670 // Try harder to find if the source integer type has less significant bits. 1671 // For example, compute number of sign bits or compute low bit mask. 1672 return false; 1673 } 1674 1675 Instruction *InstCombinerImpl::visitFPTrunc(FPTruncInst &FPT) { 1676 if (Instruction *I = commonCastTransforms(FPT)) 1677 return I; 1678 1679 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to 1680 // simplify this expression to avoid one or more of the trunc/extend 1681 // operations if we can do so without changing the numerical results. 1682 // 1683 // The exact manner in which the widths of the operands interact to limit 1684 // what we can and cannot do safely varies from operation to operation, and 1685 // is explained below in the various case statements. 1686 Type *Ty = FPT.getType(); 1687 auto *BO = dyn_cast<BinaryOperator>(FPT.getOperand(0)); 1688 if (BO && BO->hasOneUse()) { 1689 Type *LHSMinType = getMinimumFPType(BO->getOperand(0)); 1690 Type *RHSMinType = getMinimumFPType(BO->getOperand(1)); 1691 unsigned OpWidth = BO->getType()->getFPMantissaWidth(); 1692 unsigned LHSWidth = LHSMinType->getFPMantissaWidth(); 1693 unsigned RHSWidth = RHSMinType->getFPMantissaWidth(); 1694 unsigned SrcWidth = std::max(LHSWidth, RHSWidth); 1695 unsigned DstWidth = Ty->getFPMantissaWidth(); 1696 switch (BO->getOpcode()) { 1697 default: break; 1698 case Instruction::FAdd: 1699 case Instruction::FSub: 1700 // For addition and subtraction, the infinitely precise result can 1701 // essentially be arbitrarily wide; proving that double rounding 1702 // will not occur because the result of OpI is exact (as we will for 1703 // FMul, for example) is hopeless. However, we *can* nonetheless 1704 // frequently know that double rounding cannot occur (or that it is 1705 // innocuous) by taking advantage of the specific structure of 1706 // infinitely-precise results that admit double rounding. 1707 // 1708 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient 1709 // to represent both sources, we can guarantee that the double 1710 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis, 1711 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..." 1712 // for proof of this fact). 1713 // 1714 // Note: Figueroa does not consider the case where DstFormat != 1715 // SrcFormat. It's possible (likely even!) that this analysis 1716 // could be tightened for those cases, but they are rare (the main 1717 // case of interest here is (float)((double)float + float)). 1718 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) { 1719 Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty); 1720 Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty); 1721 Instruction *RI = BinaryOperator::Create(BO->getOpcode(), LHS, RHS); 1722 RI->copyFastMathFlags(BO); 1723 return RI; 1724 } 1725 break; 1726 case Instruction::FMul: 1727 // For multiplication, the infinitely precise result has at most 1728 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient 1729 // that such a value can be exactly represented, then no double 1730 // rounding can possibly occur; we can safely perform the operation 1731 // in the destination format if it can represent both sources. 1732 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) { 1733 Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty); 1734 Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty); 1735 return BinaryOperator::CreateFMulFMF(LHS, RHS, BO); 1736 } 1737 break; 1738 case Instruction::FDiv: 1739 // For division, we use again use the bound from Figueroa's 1740 // dissertation. I am entirely certain that this bound can be 1741 // tightened in the unbalanced operand case by an analysis based on 1742 // the diophantine rational approximation bound, but the well-known 1743 // condition used here is a good conservative first pass. 1744 // TODO: Tighten bound via rigorous analysis of the unbalanced case. 1745 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) { 1746 Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty); 1747 Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty); 1748 return BinaryOperator::CreateFDivFMF(LHS, RHS, BO); 1749 } 1750 break; 1751 case Instruction::FRem: { 1752 // Remainder is straightforward. Remainder is always exact, so the 1753 // type of OpI doesn't enter into things at all. We simply evaluate 1754 // in whichever source type is larger, then convert to the 1755 // destination type. 1756 if (SrcWidth == OpWidth) 1757 break; 1758 Value *LHS, *RHS; 1759 if (LHSWidth == SrcWidth) { 1760 LHS = Builder.CreateFPTrunc(BO->getOperand(0), LHSMinType); 1761 RHS = Builder.CreateFPTrunc(BO->getOperand(1), LHSMinType); 1762 } else { 1763 LHS = Builder.CreateFPTrunc(BO->getOperand(0), RHSMinType); 1764 RHS = Builder.CreateFPTrunc(BO->getOperand(1), RHSMinType); 1765 } 1766 1767 Value *ExactResult = Builder.CreateFRemFMF(LHS, RHS, BO); 1768 return CastInst::CreateFPCast(ExactResult, Ty); 1769 } 1770 } 1771 } 1772 1773 // (fptrunc (fneg x)) -> (fneg (fptrunc x)) 1774 Value *X; 1775 Instruction *Op = dyn_cast<Instruction>(FPT.getOperand(0)); 1776 if (Op && Op->hasOneUse()) { 1777 // FIXME: The FMF should propagate from the fptrunc, not the source op. 1778 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 1779 if (isa<FPMathOperator>(Op)) 1780 Builder.setFastMathFlags(Op->getFastMathFlags()); 1781 1782 if (match(Op, m_FNeg(m_Value(X)))) { 1783 Value *InnerTrunc = Builder.CreateFPTrunc(X, Ty); 1784 1785 return UnaryOperator::CreateFNegFMF(InnerTrunc, Op); 1786 } 1787 1788 // If we are truncating a select that has an extended operand, we can 1789 // narrow the other operand and do the select as a narrow op. 1790 Value *Cond, *X, *Y; 1791 if (match(Op, m_Select(m_Value(Cond), m_FPExt(m_Value(X)), m_Value(Y))) && 1792 X->getType() == Ty) { 1793 // fptrunc (select Cond, (fpext X), Y --> select Cond, X, (fptrunc Y) 1794 Value *NarrowY = Builder.CreateFPTrunc(Y, Ty); 1795 Value *Sel = Builder.CreateSelect(Cond, X, NarrowY, "narrow.sel", Op); 1796 return replaceInstUsesWith(FPT, Sel); 1797 } 1798 if (match(Op, m_Select(m_Value(Cond), m_Value(Y), m_FPExt(m_Value(X)))) && 1799 X->getType() == Ty) { 1800 // fptrunc (select Cond, Y, (fpext X) --> select Cond, (fptrunc Y), X 1801 Value *NarrowY = Builder.CreateFPTrunc(Y, Ty); 1802 Value *Sel = Builder.CreateSelect(Cond, NarrowY, X, "narrow.sel", Op); 1803 return replaceInstUsesWith(FPT, Sel); 1804 } 1805 } 1806 1807 if (auto *II = dyn_cast<IntrinsicInst>(FPT.getOperand(0))) { 1808 switch (II->getIntrinsicID()) { 1809 default: break; 1810 case Intrinsic::ceil: 1811 case Intrinsic::fabs: 1812 case Intrinsic::floor: 1813 case Intrinsic::nearbyint: 1814 case Intrinsic::rint: 1815 case Intrinsic::round: 1816 case Intrinsic::roundeven: 1817 case Intrinsic::trunc: { 1818 Value *Src = II->getArgOperand(0); 1819 if (!Src->hasOneUse()) 1820 break; 1821 1822 // Except for fabs, this transformation requires the input of the unary FP 1823 // operation to be itself an fpext from the type to which we're 1824 // truncating. 1825 if (II->getIntrinsicID() != Intrinsic::fabs) { 1826 FPExtInst *FPExtSrc = dyn_cast<FPExtInst>(Src); 1827 if (!FPExtSrc || FPExtSrc->getSrcTy() != Ty) 1828 break; 1829 } 1830 1831 // Do unary FP operation on smaller type. 1832 // (fptrunc (fabs x)) -> (fabs (fptrunc x)) 1833 Value *InnerTrunc = Builder.CreateFPTrunc(Src, Ty); 1834 Function *Overload = Intrinsic::getDeclaration(FPT.getModule(), 1835 II->getIntrinsicID(), Ty); 1836 SmallVector<OperandBundleDef, 1> OpBundles; 1837 II->getOperandBundlesAsDefs(OpBundles); 1838 CallInst *NewCI = 1839 CallInst::Create(Overload, {InnerTrunc}, OpBundles, II->getName()); 1840 NewCI->copyFastMathFlags(II); 1841 return NewCI; 1842 } 1843 } 1844 } 1845 1846 if (Instruction *I = shrinkInsertElt(FPT, Builder)) 1847 return I; 1848 1849 Value *Src = FPT.getOperand(0); 1850 if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) { 1851 auto *FPCast = cast<CastInst>(Src); 1852 if (isKnownExactCastIntToFP(*FPCast)) 1853 return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty); 1854 } 1855 1856 return nullptr; 1857 } 1858 1859 Instruction *InstCombinerImpl::visitFPExt(CastInst &FPExt) { 1860 // If the source operand is a cast from integer to FP and known exact, then 1861 // cast the integer operand directly to the destination type. 1862 Type *Ty = FPExt.getType(); 1863 Value *Src = FPExt.getOperand(0); 1864 if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) { 1865 auto *FPCast = cast<CastInst>(Src); 1866 if (isKnownExactCastIntToFP(*FPCast)) 1867 return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty); 1868 } 1869 1870 return commonCastTransforms(FPExt); 1871 } 1872 1873 /// fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X) 1874 /// This is safe if the intermediate type has enough bits in its mantissa to 1875 /// accurately represent all values of X. For example, this won't work with 1876 /// i64 -> float -> i64. 1877 Instruction *InstCombinerImpl::foldItoFPtoI(CastInst &FI) { 1878 if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0))) 1879 return nullptr; 1880 1881 auto *OpI = cast<CastInst>(FI.getOperand(0)); 1882 Value *X = OpI->getOperand(0); 1883 Type *XType = X->getType(); 1884 Type *DestType = FI.getType(); 1885 bool IsOutputSigned = isa<FPToSIInst>(FI); 1886 1887 // Since we can assume the conversion won't overflow, our decision as to 1888 // whether the input will fit in the float should depend on the minimum 1889 // of the input range and output range. 1890 1891 // This means this is also safe for a signed input and unsigned output, since 1892 // a negative input would lead to undefined behavior. 1893 if (!isKnownExactCastIntToFP(*OpI)) { 1894 // The first cast may not round exactly based on the source integer width 1895 // and FP width, but the overflow UB rules can still allow this to fold. 1896 // If the destination type is narrow, that means the intermediate FP value 1897 // must be large enough to hold the source value exactly. 1898 // For example, (uint8_t)((float)(uint32_t 16777217) is undefined behavior. 1899 int OutputSize = (int)DestType->getScalarSizeInBits() - IsOutputSigned; 1900 if (OutputSize > OpI->getType()->getFPMantissaWidth()) 1901 return nullptr; 1902 } 1903 1904 if (DestType->getScalarSizeInBits() > XType->getScalarSizeInBits()) { 1905 bool IsInputSigned = isa<SIToFPInst>(OpI); 1906 if (IsInputSigned && IsOutputSigned) 1907 return new SExtInst(X, DestType); 1908 return new ZExtInst(X, DestType); 1909 } 1910 if (DestType->getScalarSizeInBits() < XType->getScalarSizeInBits()) 1911 return new TruncInst(X, DestType); 1912 1913 assert(XType == DestType && "Unexpected types for int to FP to int casts"); 1914 return replaceInstUsesWith(FI, X); 1915 } 1916 1917 Instruction *InstCombinerImpl::visitFPToUI(FPToUIInst &FI) { 1918 if (Instruction *I = foldItoFPtoI(FI)) 1919 return I; 1920 1921 return commonCastTransforms(FI); 1922 } 1923 1924 Instruction *InstCombinerImpl::visitFPToSI(FPToSIInst &FI) { 1925 if (Instruction *I = foldItoFPtoI(FI)) 1926 return I; 1927 1928 return commonCastTransforms(FI); 1929 } 1930 1931 Instruction *InstCombinerImpl::visitUIToFP(CastInst &CI) { 1932 return commonCastTransforms(CI); 1933 } 1934 1935 Instruction *InstCombinerImpl::visitSIToFP(CastInst &CI) { 1936 return commonCastTransforms(CI); 1937 } 1938 1939 Instruction *InstCombinerImpl::visitIntToPtr(IntToPtrInst &CI) { 1940 // If the source integer type is not the intptr_t type for this target, do a 1941 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the 1942 // cast to be exposed to other transforms. 1943 unsigned AS = CI.getAddressSpace(); 1944 if (CI.getOperand(0)->getType()->getScalarSizeInBits() != 1945 DL.getPointerSizeInBits(AS)) { 1946 Type *Ty = CI.getOperand(0)->getType()->getWithNewType( 1947 DL.getIntPtrType(CI.getContext(), AS)); 1948 Value *P = Builder.CreateZExtOrTrunc(CI.getOperand(0), Ty); 1949 return new IntToPtrInst(P, CI.getType()); 1950 } 1951 1952 if (Instruction *I = commonCastTransforms(CI)) 1953 return I; 1954 1955 return nullptr; 1956 } 1957 1958 /// Implement the transforms for cast of pointer (bitcast/ptrtoint) 1959 Instruction *InstCombinerImpl::commonPointerCastTransforms(CastInst &CI) { 1960 Value *Src = CI.getOperand(0); 1961 1962 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) { 1963 // If casting the result of a getelementptr instruction with no offset, turn 1964 // this into a cast of the original pointer! 1965 if (GEP->hasAllZeroIndices() && 1966 // If CI is an addrspacecast and GEP changes the poiner type, merging 1967 // GEP into CI would undo canonicalizing addrspacecast with different 1968 // pointer types, causing infinite loops. 1969 (!isa<AddrSpaceCastInst>(CI) || 1970 GEP->getType() == GEP->getPointerOperandType())) { 1971 // Changing the cast operand is usually not a good idea but it is safe 1972 // here because the pointer operand is being replaced with another 1973 // pointer operand so the opcode doesn't need to change. 1974 return replaceOperand(CI, 0, GEP->getOperand(0)); 1975 } 1976 } 1977 1978 return commonCastTransforms(CI); 1979 } 1980 1981 Instruction *InstCombinerImpl::visitPtrToInt(PtrToIntInst &CI) { 1982 // If the destination integer type is not the intptr_t type for this target, 1983 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast 1984 // to be exposed to other transforms. 1985 Value *SrcOp = CI.getPointerOperand(); 1986 Type *SrcTy = SrcOp->getType(); 1987 Type *Ty = CI.getType(); 1988 unsigned AS = CI.getPointerAddressSpace(); 1989 unsigned TySize = Ty->getScalarSizeInBits(); 1990 unsigned PtrSize = DL.getPointerSizeInBits(AS); 1991 if (TySize != PtrSize) { 1992 Type *IntPtrTy = 1993 SrcTy->getWithNewType(DL.getIntPtrType(CI.getContext(), AS)); 1994 Value *P = Builder.CreatePtrToInt(SrcOp, IntPtrTy); 1995 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false); 1996 } 1997 1998 Value *Vec, *Scalar, *Index; 1999 if (match(SrcOp, m_OneUse(m_InsertElt(m_IntToPtr(m_Value(Vec)), 2000 m_Value(Scalar), m_Value(Index)))) && 2001 Vec->getType() == Ty) { 2002 assert(Vec->getType()->getScalarSizeInBits() == PtrSize && "Wrong type"); 2003 // Convert the scalar to int followed by insert to eliminate one cast: 2004 // p2i (ins (i2p Vec), Scalar, Index --> ins Vec, (p2i Scalar), Index 2005 Value *NewCast = Builder.CreatePtrToInt(Scalar, Ty->getScalarType()); 2006 return InsertElementInst::Create(Vec, NewCast, Index); 2007 } 2008 2009 return commonPointerCastTransforms(CI); 2010 } 2011 2012 /// This input value (which is known to have vector type) is being zero extended 2013 /// or truncated to the specified vector type. Since the zext/trunc is done 2014 /// using an integer type, we have a (bitcast(cast(bitcast))) pattern, 2015 /// endianness will impact which end of the vector that is extended or 2016 /// truncated. 2017 /// 2018 /// A vector is always stored with index 0 at the lowest address, which 2019 /// corresponds to the most significant bits for a big endian stored integer and 2020 /// the least significant bits for little endian. A trunc/zext of an integer 2021 /// impacts the big end of the integer. Thus, we need to add/remove elements at 2022 /// the front of the vector for big endian targets, and the back of the vector 2023 /// for little endian targets. 2024 /// 2025 /// Try to replace it with a shuffle (and vector/vector bitcast) if possible. 2026 /// 2027 /// The source and destination vector types may have different element types. 2028 static Instruction * 2029 optimizeVectorResizeWithIntegerBitCasts(Value *InVal, VectorType *DestTy, 2030 InstCombinerImpl &IC) { 2031 // We can only do this optimization if the output is a multiple of the input 2032 // element size, or the input is a multiple of the output element size. 2033 // Convert the input type to have the same element type as the output. 2034 VectorType *SrcTy = cast<VectorType>(InVal->getType()); 2035 2036 if (SrcTy->getElementType() != DestTy->getElementType()) { 2037 // The input types don't need to be identical, but for now they must be the 2038 // same size. There is no specific reason we couldn't handle things like 2039 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten 2040 // there yet. 2041 if (SrcTy->getElementType()->getPrimitiveSizeInBits() != 2042 DestTy->getElementType()->getPrimitiveSizeInBits()) 2043 return nullptr; 2044 2045 SrcTy = 2046 FixedVectorType::get(DestTy->getElementType(), 2047 cast<FixedVectorType>(SrcTy)->getNumElements()); 2048 InVal = IC.Builder.CreateBitCast(InVal, SrcTy); 2049 } 2050 2051 bool IsBigEndian = IC.getDataLayout().isBigEndian(); 2052 unsigned SrcElts = cast<FixedVectorType>(SrcTy)->getNumElements(); 2053 unsigned DestElts = cast<FixedVectorType>(DestTy)->getNumElements(); 2054 2055 assert(SrcElts != DestElts && "Element counts should be different."); 2056 2057 // Now that the element types match, get the shuffle mask and RHS of the 2058 // shuffle to use, which depends on whether we're increasing or decreasing the 2059 // size of the input. 2060 SmallVector<int, 16> ShuffleMaskStorage; 2061 ArrayRef<int> ShuffleMask; 2062 Value *V2; 2063 2064 // Produce an identify shuffle mask for the src vector. 2065 ShuffleMaskStorage.resize(SrcElts); 2066 std::iota(ShuffleMaskStorage.begin(), ShuffleMaskStorage.end(), 0); 2067 2068 if (SrcElts > DestElts) { 2069 // If we're shrinking the number of elements (rewriting an integer 2070 // truncate), just shuffle in the elements corresponding to the least 2071 // significant bits from the input and use undef as the second shuffle 2072 // input. 2073 V2 = UndefValue::get(SrcTy); 2074 // Make sure the shuffle mask selects the "least significant bits" by 2075 // keeping elements from back of the src vector for big endian, and from the 2076 // front for little endian. 2077 ShuffleMask = ShuffleMaskStorage; 2078 if (IsBigEndian) 2079 ShuffleMask = ShuffleMask.take_back(DestElts); 2080 else 2081 ShuffleMask = ShuffleMask.take_front(DestElts); 2082 } else { 2083 // If we're increasing the number of elements (rewriting an integer zext), 2084 // shuffle in all of the elements from InVal. Fill the rest of the result 2085 // elements with zeros from a constant zero. 2086 V2 = Constant::getNullValue(SrcTy); 2087 // Use first elt from V2 when indicating zero in the shuffle mask. 2088 uint32_t NullElt = SrcElts; 2089 // Extend with null values in the "most significant bits" by adding elements 2090 // in front of the src vector for big endian, and at the back for little 2091 // endian. 2092 unsigned DeltaElts = DestElts - SrcElts; 2093 if (IsBigEndian) 2094 ShuffleMaskStorage.insert(ShuffleMaskStorage.begin(), DeltaElts, NullElt); 2095 else 2096 ShuffleMaskStorage.append(DeltaElts, NullElt); 2097 ShuffleMask = ShuffleMaskStorage; 2098 } 2099 2100 return new ShuffleVectorInst(InVal, V2, ShuffleMask); 2101 } 2102 2103 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) { 2104 return Value % Ty->getPrimitiveSizeInBits() == 0; 2105 } 2106 2107 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) { 2108 return Value / Ty->getPrimitiveSizeInBits(); 2109 } 2110 2111 /// V is a value which is inserted into a vector of VecEltTy. 2112 /// Look through the value to see if we can decompose it into 2113 /// insertions into the vector. See the example in the comment for 2114 /// OptimizeIntegerToVectorInsertions for the pattern this handles. 2115 /// The type of V is always a non-zero multiple of VecEltTy's size. 2116 /// Shift is the number of bits between the lsb of V and the lsb of 2117 /// the vector. 2118 /// 2119 /// This returns false if the pattern can't be matched or true if it can, 2120 /// filling in Elements with the elements found here. 2121 static bool collectInsertionElements(Value *V, unsigned Shift, 2122 SmallVectorImpl<Value *> &Elements, 2123 Type *VecEltTy, bool isBigEndian) { 2124 assert(isMultipleOfTypeSize(Shift, VecEltTy) && 2125 "Shift should be a multiple of the element type size"); 2126 2127 // Undef values never contribute useful bits to the result. 2128 if (isa<UndefValue>(V)) return true; 2129 2130 // If we got down to a value of the right type, we win, try inserting into the 2131 // right element. 2132 if (V->getType() == VecEltTy) { 2133 // Inserting null doesn't actually insert any elements. 2134 if (Constant *C = dyn_cast<Constant>(V)) 2135 if (C->isNullValue()) 2136 return true; 2137 2138 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy); 2139 if (isBigEndian) 2140 ElementIndex = Elements.size() - ElementIndex - 1; 2141 2142 // Fail if multiple elements are inserted into this slot. 2143 if (Elements[ElementIndex]) 2144 return false; 2145 2146 Elements[ElementIndex] = V; 2147 return true; 2148 } 2149 2150 if (Constant *C = dyn_cast<Constant>(V)) { 2151 // Figure out the # elements this provides, and bitcast it or slice it up 2152 // as required. 2153 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(), 2154 VecEltTy); 2155 // If the constant is the size of a vector element, we just need to bitcast 2156 // it to the right type so it gets properly inserted. 2157 if (NumElts == 1) 2158 return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy), 2159 Shift, Elements, VecEltTy, isBigEndian); 2160 2161 // Okay, this is a constant that covers multiple elements. Slice it up into 2162 // pieces and insert each element-sized piece into the vector. 2163 if (!isa<IntegerType>(C->getType())) 2164 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(), 2165 C->getType()->getPrimitiveSizeInBits())); 2166 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits(); 2167 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize); 2168 2169 for (unsigned i = 0; i != NumElts; ++i) { 2170 unsigned ShiftI = Shift+i*ElementSize; 2171 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(), 2172 ShiftI)); 2173 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy); 2174 if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy, 2175 isBigEndian)) 2176 return false; 2177 } 2178 return true; 2179 } 2180 2181 if (!V->hasOneUse()) return false; 2182 2183 Instruction *I = dyn_cast<Instruction>(V); 2184 if (!I) return false; 2185 switch (I->getOpcode()) { 2186 default: return false; // Unhandled case. 2187 case Instruction::BitCast: 2188 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 2189 isBigEndian); 2190 case Instruction::ZExt: 2191 if (!isMultipleOfTypeSize( 2192 I->getOperand(0)->getType()->getPrimitiveSizeInBits(), 2193 VecEltTy)) 2194 return false; 2195 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 2196 isBigEndian); 2197 case Instruction::Or: 2198 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 2199 isBigEndian) && 2200 collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy, 2201 isBigEndian); 2202 case Instruction::Shl: { 2203 // Must be shifting by a constant that is a multiple of the element size. 2204 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1)); 2205 if (!CI) return false; 2206 Shift += CI->getZExtValue(); 2207 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false; 2208 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 2209 isBigEndian); 2210 } 2211 2212 } 2213 } 2214 2215 2216 /// If the input is an 'or' instruction, we may be doing shifts and ors to 2217 /// assemble the elements of the vector manually. 2218 /// Try to rip the code out and replace it with insertelements. This is to 2219 /// optimize code like this: 2220 /// 2221 /// %tmp37 = bitcast float %inc to i32 2222 /// %tmp38 = zext i32 %tmp37 to i64 2223 /// %tmp31 = bitcast float %inc5 to i32 2224 /// %tmp32 = zext i32 %tmp31 to i64 2225 /// %tmp33 = shl i64 %tmp32, 32 2226 /// %ins35 = or i64 %tmp33, %tmp38 2227 /// %tmp43 = bitcast i64 %ins35 to <2 x float> 2228 /// 2229 /// Into two insertelements that do "buildvector{%inc, %inc5}". 2230 static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI, 2231 InstCombinerImpl &IC) { 2232 auto *DestVecTy = cast<FixedVectorType>(CI.getType()); 2233 Value *IntInput = CI.getOperand(0); 2234 2235 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements()); 2236 if (!collectInsertionElements(IntInput, 0, Elements, 2237 DestVecTy->getElementType(), 2238 IC.getDataLayout().isBigEndian())) 2239 return nullptr; 2240 2241 // If we succeeded, we know that all of the element are specified by Elements 2242 // or are zero if Elements has a null entry. Recast this as a set of 2243 // insertions. 2244 Value *Result = Constant::getNullValue(CI.getType()); 2245 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 2246 if (!Elements[i]) continue; // Unset element. 2247 2248 Result = IC.Builder.CreateInsertElement(Result, Elements[i], 2249 IC.Builder.getInt32(i)); 2250 } 2251 2252 return Result; 2253 } 2254 2255 /// Canonicalize scalar bitcasts of extracted elements into a bitcast of the 2256 /// vector followed by extract element. The backend tends to handle bitcasts of 2257 /// vectors better than bitcasts of scalars because vector registers are 2258 /// usually not type-specific like scalar integer or scalar floating-point. 2259 static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast, 2260 InstCombinerImpl &IC) { 2261 // TODO: Create and use a pattern matcher for ExtractElementInst. 2262 auto *ExtElt = dyn_cast<ExtractElementInst>(BitCast.getOperand(0)); 2263 if (!ExtElt || !ExtElt->hasOneUse()) 2264 return nullptr; 2265 2266 // The bitcast must be to a vectorizable type, otherwise we can't make a new 2267 // type to extract from. 2268 Type *DestType = BitCast.getType(); 2269 if (!VectorType::isValidElementType(DestType)) 2270 return nullptr; 2271 2272 auto *NewVecType = VectorType::get(DestType, ExtElt->getVectorOperandType()); 2273 auto *NewBC = IC.Builder.CreateBitCast(ExtElt->getVectorOperand(), 2274 NewVecType, "bc"); 2275 return ExtractElementInst::Create(NewBC, ExtElt->getIndexOperand()); 2276 } 2277 2278 /// Change the type of a bitwise logic operation if we can eliminate a bitcast. 2279 static Instruction *foldBitCastBitwiseLogic(BitCastInst &BitCast, 2280 InstCombiner::BuilderTy &Builder) { 2281 Type *DestTy = BitCast.getType(); 2282 BinaryOperator *BO; 2283 if (!DestTy->isIntOrIntVectorTy() || 2284 !match(BitCast.getOperand(0), m_OneUse(m_BinOp(BO))) || 2285 !BO->isBitwiseLogicOp()) 2286 return nullptr; 2287 2288 // FIXME: This transform is restricted to vector types to avoid backend 2289 // problems caused by creating potentially illegal operations. If a fix-up is 2290 // added to handle that situation, we can remove this check. 2291 if (!DestTy->isVectorTy() || !BO->getType()->isVectorTy()) 2292 return nullptr; 2293 2294 Value *X; 2295 if (match(BO->getOperand(0), m_OneUse(m_BitCast(m_Value(X)))) && 2296 X->getType() == DestTy && !isa<Constant>(X)) { 2297 // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y)) 2298 Value *CastedOp1 = Builder.CreateBitCast(BO->getOperand(1), DestTy); 2299 return BinaryOperator::Create(BO->getOpcode(), X, CastedOp1); 2300 } 2301 2302 if (match(BO->getOperand(1), m_OneUse(m_BitCast(m_Value(X)))) && 2303 X->getType() == DestTy && !isa<Constant>(X)) { 2304 // bitcast(logic(Y, bitcast(X))) --> logic'(bitcast(Y), X) 2305 Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy); 2306 return BinaryOperator::Create(BO->getOpcode(), CastedOp0, X); 2307 } 2308 2309 // Canonicalize vector bitcasts to come before vector bitwise logic with a 2310 // constant. This eases recognition of special constants for later ops. 2311 // Example: 2312 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b 2313 Constant *C; 2314 if (match(BO->getOperand(1), m_Constant(C))) { 2315 // bitcast (logic X, C) --> logic (bitcast X, C') 2316 Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy); 2317 Value *CastedC = Builder.CreateBitCast(C, DestTy); 2318 return BinaryOperator::Create(BO->getOpcode(), CastedOp0, CastedC); 2319 } 2320 2321 return nullptr; 2322 } 2323 2324 /// Change the type of a select if we can eliminate a bitcast. 2325 static Instruction *foldBitCastSelect(BitCastInst &BitCast, 2326 InstCombiner::BuilderTy &Builder) { 2327 Value *Cond, *TVal, *FVal; 2328 if (!match(BitCast.getOperand(0), 2329 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) 2330 return nullptr; 2331 2332 // A vector select must maintain the same number of elements in its operands. 2333 Type *CondTy = Cond->getType(); 2334 Type *DestTy = BitCast.getType(); 2335 if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) 2336 if (!DestTy->isVectorTy() || 2337 CondVTy->getElementCount() != 2338 cast<VectorType>(DestTy)->getElementCount()) 2339 return nullptr; 2340 2341 // FIXME: This transform is restricted from changing the select between 2342 // scalars and vectors to avoid backend problems caused by creating 2343 // potentially illegal operations. If a fix-up is added to handle that 2344 // situation, we can remove this check. 2345 if (DestTy->isVectorTy() != TVal->getType()->isVectorTy()) 2346 return nullptr; 2347 2348 auto *Sel = cast<Instruction>(BitCast.getOperand(0)); 2349 Value *X; 2350 if (match(TVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy && 2351 !isa<Constant>(X)) { 2352 // bitcast(select(Cond, bitcast(X), Y)) --> select'(Cond, X, bitcast(Y)) 2353 Value *CastedVal = Builder.CreateBitCast(FVal, DestTy); 2354 return SelectInst::Create(Cond, X, CastedVal, "", nullptr, Sel); 2355 } 2356 2357 if (match(FVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy && 2358 !isa<Constant>(X)) { 2359 // bitcast(select(Cond, Y, bitcast(X))) --> select'(Cond, bitcast(Y), X) 2360 Value *CastedVal = Builder.CreateBitCast(TVal, DestTy); 2361 return SelectInst::Create(Cond, CastedVal, X, "", nullptr, Sel); 2362 } 2363 2364 return nullptr; 2365 } 2366 2367 /// Check if all users of CI are StoreInsts. 2368 static bool hasStoreUsersOnly(CastInst &CI) { 2369 for (User *U : CI.users()) { 2370 if (!isa<StoreInst>(U)) 2371 return false; 2372 } 2373 return true; 2374 } 2375 2376 /// This function handles following case 2377 /// 2378 /// A -> B cast 2379 /// PHI 2380 /// B -> A cast 2381 /// 2382 /// All the related PHI nodes can be replaced by new PHI nodes with type A. 2383 /// The uses of \p CI can be changed to the new PHI node corresponding to \p PN. 2384 Instruction *InstCombinerImpl::optimizeBitCastFromPhi(CastInst &CI, 2385 PHINode *PN) { 2386 // BitCast used by Store can be handled in InstCombineLoadStoreAlloca.cpp. 2387 if (hasStoreUsersOnly(CI)) 2388 return nullptr; 2389 2390 Value *Src = CI.getOperand(0); 2391 Type *SrcTy = Src->getType(); // Type B 2392 Type *DestTy = CI.getType(); // Type A 2393 2394 SmallVector<PHINode *, 4> PhiWorklist; 2395 SmallSetVector<PHINode *, 4> OldPhiNodes; 2396 2397 // Find all of the A->B casts and PHI nodes. 2398 // We need to inspect all related PHI nodes, but PHIs can be cyclic, so 2399 // OldPhiNodes is used to track all known PHI nodes, before adding a new 2400 // PHI to PhiWorklist, it is checked against and added to OldPhiNodes first. 2401 PhiWorklist.push_back(PN); 2402 OldPhiNodes.insert(PN); 2403 while (!PhiWorklist.empty()) { 2404 auto *OldPN = PhiWorklist.pop_back_val(); 2405 for (Value *IncValue : OldPN->incoming_values()) { 2406 if (isa<Constant>(IncValue)) 2407 continue; 2408 2409 if (auto *LI = dyn_cast<LoadInst>(IncValue)) { 2410 // If there is a sequence of one or more load instructions, each loaded 2411 // value is used as address of later load instruction, bitcast is 2412 // necessary to change the value type, don't optimize it. For 2413 // simplicity we give up if the load address comes from another load. 2414 Value *Addr = LI->getOperand(0); 2415 if (Addr == &CI || isa<LoadInst>(Addr)) 2416 return nullptr; 2417 // Don't tranform "load <256 x i32>, <256 x i32>*" to 2418 // "load x86_amx, x86_amx*", because x86_amx* is invalid. 2419 // TODO: Remove this check when bitcast between vector and x86_amx 2420 // is replaced with a specific intrinsic. 2421 if (DestTy->isX86_AMXTy()) 2422 return nullptr; 2423 if (LI->hasOneUse() && LI->isSimple()) 2424 continue; 2425 // If a LoadInst has more than one use, changing the type of loaded 2426 // value may create another bitcast. 2427 return nullptr; 2428 } 2429 2430 if (auto *PNode = dyn_cast<PHINode>(IncValue)) { 2431 if (OldPhiNodes.insert(PNode)) 2432 PhiWorklist.push_back(PNode); 2433 continue; 2434 } 2435 2436 auto *BCI = dyn_cast<BitCastInst>(IncValue); 2437 // We can't handle other instructions. 2438 if (!BCI) 2439 return nullptr; 2440 2441 // Verify it's a A->B cast. 2442 Type *TyA = BCI->getOperand(0)->getType(); 2443 Type *TyB = BCI->getType(); 2444 if (TyA != DestTy || TyB != SrcTy) 2445 return nullptr; 2446 } 2447 } 2448 2449 // Check that each user of each old PHI node is something that we can 2450 // rewrite, so that all of the old PHI nodes can be cleaned up afterwards. 2451 for (auto *OldPN : OldPhiNodes) { 2452 for (User *V : OldPN->users()) { 2453 if (auto *SI = dyn_cast<StoreInst>(V)) { 2454 if (!SI->isSimple() || SI->getOperand(0) != OldPN) 2455 return nullptr; 2456 } else if (auto *BCI = dyn_cast<BitCastInst>(V)) { 2457 // Verify it's a B->A cast. 2458 Type *TyB = BCI->getOperand(0)->getType(); 2459 Type *TyA = BCI->getType(); 2460 if (TyA != DestTy || TyB != SrcTy) 2461 return nullptr; 2462 } else if (auto *PHI = dyn_cast<PHINode>(V)) { 2463 // As long as the user is another old PHI node, then even if we don't 2464 // rewrite it, the PHI web we're considering won't have any users 2465 // outside itself, so it'll be dead. 2466 if (OldPhiNodes.count(PHI) == 0) 2467 return nullptr; 2468 } else { 2469 return nullptr; 2470 } 2471 } 2472 } 2473 2474 // For each old PHI node, create a corresponding new PHI node with a type A. 2475 SmallDenseMap<PHINode *, PHINode *> NewPNodes; 2476 for (auto *OldPN : OldPhiNodes) { 2477 Builder.SetInsertPoint(OldPN); 2478 PHINode *NewPN = Builder.CreatePHI(DestTy, OldPN->getNumOperands()); 2479 NewPNodes[OldPN] = NewPN; 2480 } 2481 2482 // Fill in the operands of new PHI nodes. 2483 for (auto *OldPN : OldPhiNodes) { 2484 PHINode *NewPN = NewPNodes[OldPN]; 2485 for (unsigned j = 0, e = OldPN->getNumOperands(); j != e; ++j) { 2486 Value *V = OldPN->getOperand(j); 2487 Value *NewV = nullptr; 2488 if (auto *C = dyn_cast<Constant>(V)) { 2489 NewV = ConstantExpr::getBitCast(C, DestTy); 2490 } else if (auto *LI = dyn_cast<LoadInst>(V)) { 2491 // Explicitly perform load combine to make sure no opposing transform 2492 // can remove the bitcast in the meantime and trigger an infinite loop. 2493 Builder.SetInsertPoint(LI); 2494 NewV = combineLoadToNewType(*LI, DestTy); 2495 // Remove the old load and its use in the old phi, which itself becomes 2496 // dead once the whole transform finishes. 2497 replaceInstUsesWith(*LI, UndefValue::get(LI->getType())); 2498 eraseInstFromFunction(*LI); 2499 } else if (auto *BCI = dyn_cast<BitCastInst>(V)) { 2500 NewV = BCI->getOperand(0); 2501 } else if (auto *PrevPN = dyn_cast<PHINode>(V)) { 2502 NewV = NewPNodes[PrevPN]; 2503 } 2504 assert(NewV); 2505 NewPN->addIncoming(NewV, OldPN->getIncomingBlock(j)); 2506 } 2507 } 2508 2509 // Traverse all accumulated PHI nodes and process its users, 2510 // which are Stores and BitcCasts. Without this processing 2511 // NewPHI nodes could be replicated and could lead to extra 2512 // moves generated after DeSSA. 2513 // If there is a store with type B, change it to type A. 2514 2515 2516 // Replace users of BitCast B->A with NewPHI. These will help 2517 // later to get rid off a closure formed by OldPHI nodes. 2518 Instruction *RetVal = nullptr; 2519 for (auto *OldPN : OldPhiNodes) { 2520 PHINode *NewPN = NewPNodes[OldPN]; 2521 for (User *V : make_early_inc_range(OldPN->users())) { 2522 if (auto *SI = dyn_cast<StoreInst>(V)) { 2523 assert(SI->isSimple() && SI->getOperand(0) == OldPN); 2524 Builder.SetInsertPoint(SI); 2525 auto *NewBC = 2526 cast<BitCastInst>(Builder.CreateBitCast(NewPN, SrcTy)); 2527 SI->setOperand(0, NewBC); 2528 Worklist.push(SI); 2529 assert(hasStoreUsersOnly(*NewBC)); 2530 } 2531 else if (auto *BCI = dyn_cast<BitCastInst>(V)) { 2532 Type *TyB = BCI->getOperand(0)->getType(); 2533 Type *TyA = BCI->getType(); 2534 assert(TyA == DestTy && TyB == SrcTy); 2535 (void) TyA; 2536 (void) TyB; 2537 Instruction *I = replaceInstUsesWith(*BCI, NewPN); 2538 if (BCI == &CI) 2539 RetVal = I; 2540 } else if (auto *PHI = dyn_cast<PHINode>(V)) { 2541 assert(OldPhiNodes.contains(PHI)); 2542 (void) PHI; 2543 } else { 2544 llvm_unreachable("all uses should be handled"); 2545 } 2546 } 2547 } 2548 2549 return RetVal; 2550 } 2551 2552 Instruction *InstCombinerImpl::visitBitCast(BitCastInst &CI) { 2553 // If the operands are integer typed then apply the integer transforms, 2554 // otherwise just apply the common ones. 2555 Value *Src = CI.getOperand(0); 2556 Type *SrcTy = Src->getType(); 2557 Type *DestTy = CI.getType(); 2558 2559 // Get rid of casts from one type to the same type. These are useless and can 2560 // be replaced by the operand. 2561 if (DestTy == Src->getType()) 2562 return replaceInstUsesWith(CI, Src); 2563 2564 if (isa<PointerType>(SrcTy) && isa<PointerType>(DestTy)) { 2565 PointerType *SrcPTy = cast<PointerType>(SrcTy); 2566 PointerType *DstPTy = cast<PointerType>(DestTy); 2567 Type *DstElTy = DstPTy->getElementType(); 2568 Type *SrcElTy = SrcPTy->getElementType(); 2569 2570 // Casting pointers between the same type, but with different address spaces 2571 // is an addrspace cast rather than a bitcast. 2572 if ((DstElTy == SrcElTy) && 2573 (DstPTy->getAddressSpace() != SrcPTy->getAddressSpace())) 2574 return new AddrSpaceCastInst(Src, DestTy); 2575 2576 // If we are casting a alloca to a pointer to a type of the same 2577 // size, rewrite the allocation instruction to allocate the "right" type. 2578 // There is no need to modify malloc calls because it is their bitcast that 2579 // needs to be cleaned up. 2580 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src)) 2581 if (Instruction *V = PromoteCastOfAllocation(CI, *AI)) 2582 return V; 2583 2584 // When the type pointed to is not sized the cast cannot be 2585 // turned into a gep. 2586 Type *PointeeType = 2587 cast<PointerType>(Src->getType()->getScalarType())->getElementType(); 2588 if (!PointeeType->isSized()) 2589 return nullptr; 2590 2591 // If the source and destination are pointers, and this cast is equivalent 2592 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep. 2593 // This can enhance SROA and other transforms that want type-safe pointers. 2594 unsigned NumZeros = 0; 2595 while (SrcElTy && SrcElTy != DstElTy) { 2596 SrcElTy = GetElementPtrInst::getTypeAtIndex(SrcElTy, (uint64_t)0); 2597 ++NumZeros; 2598 } 2599 2600 // If we found a path from the src to dest, create the getelementptr now. 2601 if (SrcElTy == DstElTy) { 2602 SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder.getInt32(0)); 2603 GetElementPtrInst *GEP = 2604 GetElementPtrInst::Create(SrcPTy->getElementType(), Src, Idxs); 2605 2606 // If the source pointer is dereferenceable, then assume it points to an 2607 // allocated object and apply "inbounds" to the GEP. 2608 bool CanBeNull, CanBeFreed; 2609 if (Src->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed)) { 2610 // In a non-default address space (not 0), a null pointer can not be 2611 // assumed inbounds, so ignore that case (dereferenceable_or_null). 2612 // The reason is that 'null' is not treated differently in these address 2613 // spaces, and we consequently ignore the 'gep inbounds' special case 2614 // for 'null' which allows 'inbounds' on 'null' if the indices are 2615 // zeros. 2616 if (SrcPTy->getAddressSpace() == 0 || !CanBeNull) 2617 GEP->setIsInBounds(); 2618 } 2619 return GEP; 2620 } 2621 } 2622 2623 if (FixedVectorType *DestVTy = dyn_cast<FixedVectorType>(DestTy)) { 2624 // Beware: messing with this target-specific oddity may cause trouble. 2625 if (DestVTy->getNumElements() == 1 && SrcTy->isX86_MMXTy()) { 2626 Value *Elem = Builder.CreateBitCast(Src, DestVTy->getElementType()); 2627 return InsertElementInst::Create(UndefValue::get(DestTy), Elem, 2628 Constant::getNullValue(Type::getInt32Ty(CI.getContext()))); 2629 } 2630 2631 if (isa<IntegerType>(SrcTy)) { 2632 // If this is a cast from an integer to vector, check to see if the input 2633 // is a trunc or zext of a bitcast from vector. If so, we can replace all 2634 // the casts with a shuffle and (potentially) a bitcast. 2635 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) { 2636 CastInst *SrcCast = cast<CastInst>(Src); 2637 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0))) 2638 if (isa<VectorType>(BCIn->getOperand(0)->getType())) 2639 if (Instruction *I = optimizeVectorResizeWithIntegerBitCasts( 2640 BCIn->getOperand(0), cast<VectorType>(DestTy), *this)) 2641 return I; 2642 } 2643 2644 // If the input is an 'or' instruction, we may be doing shifts and ors to 2645 // assemble the elements of the vector manually. Try to rip the code out 2646 // and replace it with insertelements. 2647 if (Value *V = optimizeIntegerToVectorInsertions(CI, *this)) 2648 return replaceInstUsesWith(CI, V); 2649 } 2650 } 2651 2652 if (FixedVectorType *SrcVTy = dyn_cast<FixedVectorType>(SrcTy)) { 2653 if (SrcVTy->getNumElements() == 1) { 2654 // If our destination is not a vector, then make this a straight 2655 // scalar-scalar cast. 2656 if (!DestTy->isVectorTy()) { 2657 Value *Elem = 2658 Builder.CreateExtractElement(Src, 2659 Constant::getNullValue(Type::getInt32Ty(CI.getContext()))); 2660 return CastInst::Create(Instruction::BitCast, Elem, DestTy); 2661 } 2662 2663 // Otherwise, see if our source is an insert. If so, then use the scalar 2664 // component directly: 2665 // bitcast (inselt <1 x elt> V, X, 0) to <n x m> --> bitcast X to <n x m> 2666 if (auto *InsElt = dyn_cast<InsertElementInst>(Src)) 2667 return new BitCastInst(InsElt->getOperand(1), DestTy); 2668 } 2669 } 2670 2671 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(Src)) { 2672 // Okay, we have (bitcast (shuffle ..)). Check to see if this is 2673 // a bitcast to a vector with the same # elts. 2674 Value *ShufOp0 = Shuf->getOperand(0); 2675 Value *ShufOp1 = Shuf->getOperand(1); 2676 auto ShufElts = cast<VectorType>(Shuf->getType())->getElementCount(); 2677 auto SrcVecElts = cast<VectorType>(ShufOp0->getType())->getElementCount(); 2678 if (Shuf->hasOneUse() && DestTy->isVectorTy() && 2679 cast<VectorType>(DestTy)->getElementCount() == ShufElts && 2680 ShufElts == SrcVecElts) { 2681 BitCastInst *Tmp; 2682 // If either of the operands is a cast from CI.getType(), then 2683 // evaluating the shuffle in the casted destination's type will allow 2684 // us to eliminate at least one cast. 2685 if (((Tmp = dyn_cast<BitCastInst>(ShufOp0)) && 2686 Tmp->getOperand(0)->getType() == DestTy) || 2687 ((Tmp = dyn_cast<BitCastInst>(ShufOp1)) && 2688 Tmp->getOperand(0)->getType() == DestTy)) { 2689 Value *LHS = Builder.CreateBitCast(ShufOp0, DestTy); 2690 Value *RHS = Builder.CreateBitCast(ShufOp1, DestTy); 2691 // Return a new shuffle vector. Use the same element ID's, as we 2692 // know the vector types match #elts. 2693 return new ShuffleVectorInst(LHS, RHS, Shuf->getShuffleMask()); 2694 } 2695 } 2696 2697 // A bitcasted-to-scalar and byte-reversing shuffle is better recognized as 2698 // a byte-swap: 2699 // bitcast <N x i8> (shuf X, undef, <N, N-1,...0>) --> bswap (bitcast X) 2700 // TODO: We should match the related pattern for bitreverse. 2701 if (DestTy->isIntegerTy() && 2702 DL.isLegalInteger(DestTy->getScalarSizeInBits()) && 2703 SrcTy->getScalarSizeInBits() == 8 && 2704 ShufElts.getKnownMinValue() % 2 == 0 && Shuf->hasOneUse() && 2705 Shuf->isReverse()) { 2706 assert(ShufOp0->getType() == SrcTy && "Unexpected shuffle mask"); 2707 assert(match(ShufOp1, m_Undef()) && "Unexpected shuffle op"); 2708 Function *Bswap = 2709 Intrinsic::getDeclaration(CI.getModule(), Intrinsic::bswap, DestTy); 2710 Value *ScalarX = Builder.CreateBitCast(ShufOp0, DestTy); 2711 return CallInst::Create(Bswap, { ScalarX }); 2712 } 2713 } 2714 2715 // Handle the A->B->A cast, and there is an intervening PHI node. 2716 if (PHINode *PN = dyn_cast<PHINode>(Src)) 2717 if (Instruction *I = optimizeBitCastFromPhi(CI, PN)) 2718 return I; 2719 2720 if (Instruction *I = canonicalizeBitCastExtElt(CI, *this)) 2721 return I; 2722 2723 if (Instruction *I = foldBitCastBitwiseLogic(CI, Builder)) 2724 return I; 2725 2726 if (Instruction *I = foldBitCastSelect(CI, Builder)) 2727 return I; 2728 2729 if (SrcTy->isPointerTy()) 2730 return commonPointerCastTransforms(CI); 2731 return commonCastTransforms(CI); 2732 } 2733 2734 Instruction *InstCombinerImpl::visitAddrSpaceCast(AddrSpaceCastInst &CI) { 2735 // If the destination pointer element type is not the same as the source's 2736 // first do a bitcast to the destination type, and then the addrspacecast. 2737 // This allows the cast to be exposed to other transforms. 2738 Value *Src = CI.getOperand(0); 2739 PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType()); 2740 PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType()); 2741 2742 Type *DestElemTy = DestTy->getElementType(); 2743 if (SrcTy->getElementType() != DestElemTy) { 2744 Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace()); 2745 // Handle vectors of pointers. 2746 if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) 2747 MidTy = VectorType::get(MidTy, VT->getElementCount()); 2748 2749 Value *NewBitCast = Builder.CreateBitCast(Src, MidTy); 2750 return new AddrSpaceCastInst(NewBitCast, CI.getType()); 2751 } 2752 2753 return commonPointerCastTransforms(CI); 2754 } 2755