1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===// 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 // InstructionCombining - Combine instructions to form fewer, simple 10 // instructions. This pass does not modify the CFG. This pass is where 11 // algebraic simplification happens. 12 // 13 // This pass combines things like: 14 // %Y = add i32 %X, 1 15 // %Z = add i32 %Y, 1 16 // into: 17 // %Z = add i32 %X, 2 18 // 19 // This is a simple worklist driven algorithm. 20 // 21 // This pass guarantees that the following canonicalizations are performed on 22 // the program: 23 // 1. If a binary operator has a constant operand, it is moved to the RHS 24 // 2. Bitwise operators with constant operands are always grouped so that 25 // shifts are performed first, then or's, then and's, then xor's. 26 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible 27 // 4. All cmp instructions on boolean values are replaced with logical ops 28 // 5. add X, X is represented as (X*2) => (X << 1) 29 // 6. Multiplies with a power-of-two constant argument are transformed into 30 // shifts. 31 // ... etc. 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "InstCombineInternal.h" 36 #include "llvm/ADT/APInt.h" 37 #include "llvm/ADT/ArrayRef.h" 38 #include "llvm/ADT/DenseMap.h" 39 #include "llvm/ADT/SmallPtrSet.h" 40 #include "llvm/ADT/SmallVector.h" 41 #include "llvm/ADT/Statistic.h" 42 #include "llvm/Analysis/AliasAnalysis.h" 43 #include "llvm/Analysis/AssumptionCache.h" 44 #include "llvm/Analysis/BasicAliasAnalysis.h" 45 #include "llvm/Analysis/BlockFrequencyInfo.h" 46 #include "llvm/Analysis/CFG.h" 47 #include "llvm/Analysis/ConstantFolding.h" 48 #include "llvm/Analysis/GlobalsModRef.h" 49 #include "llvm/Analysis/InstructionSimplify.h" 50 #include "llvm/Analysis/LazyBlockFrequencyInfo.h" 51 #include "llvm/Analysis/LoopInfo.h" 52 #include "llvm/Analysis/MemoryBuiltins.h" 53 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 54 #include "llvm/Analysis/ProfileSummaryInfo.h" 55 #include "llvm/Analysis/TargetFolder.h" 56 #include "llvm/Analysis/TargetLibraryInfo.h" 57 #include "llvm/Analysis/TargetTransformInfo.h" 58 #include "llvm/Analysis/Utils/Local.h" 59 #include "llvm/Analysis/ValueTracking.h" 60 #include "llvm/Analysis/VectorUtils.h" 61 #include "llvm/IR/BasicBlock.h" 62 #include "llvm/IR/CFG.h" 63 #include "llvm/IR/Constant.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DIBuilder.h" 66 #include "llvm/IR/DataLayout.h" 67 #include "llvm/IR/DebugInfo.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/Dominators.h" 70 #include "llvm/IR/EHPersonalities.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/IRBuilder.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instruction.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/Metadata.h" 80 #include "llvm/IR/Operator.h" 81 #include "llvm/IR/PassManager.h" 82 #include "llvm/IR/PatternMatch.h" 83 #include "llvm/IR/Type.h" 84 #include "llvm/IR/Use.h" 85 #include "llvm/IR/User.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/IR/ValueHandle.h" 88 #include "llvm/InitializePasses.h" 89 #include "llvm/Support/Casting.h" 90 #include "llvm/Support/CommandLine.h" 91 #include "llvm/Support/Compiler.h" 92 #include "llvm/Support/Debug.h" 93 #include "llvm/Support/DebugCounter.h" 94 #include "llvm/Support/ErrorHandling.h" 95 #include "llvm/Support/KnownBits.h" 96 #include "llvm/Support/raw_ostream.h" 97 #include "llvm/Transforms/InstCombine/InstCombine.h" 98 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 99 #include "llvm/Transforms/Utils/Local.h" 100 #include <algorithm> 101 #include <cassert> 102 #include <cstdint> 103 #include <memory> 104 #include <optional> 105 #include <string> 106 #include <utility> 107 108 #define DEBUG_TYPE "instcombine" 109 #include "llvm/Transforms/Utils/InstructionWorklist.h" 110 #include <optional> 111 112 using namespace llvm; 113 using namespace llvm::PatternMatch; 114 115 STATISTIC(NumWorklistIterations, 116 "Number of instruction combining iterations performed"); 117 STATISTIC(NumOneIteration, "Number of functions with one iteration"); 118 STATISTIC(NumTwoIterations, "Number of functions with two iterations"); 119 STATISTIC(NumThreeIterations, "Number of functions with three iterations"); 120 STATISTIC(NumFourOrMoreIterations, 121 "Number of functions with four or more iterations"); 122 123 STATISTIC(NumCombined , "Number of insts combined"); 124 STATISTIC(NumConstProp, "Number of constant folds"); 125 STATISTIC(NumDeadInst , "Number of dead inst eliminated"); 126 STATISTIC(NumSunkInst , "Number of instructions sunk"); 127 STATISTIC(NumExpand, "Number of expansions"); 128 STATISTIC(NumFactor , "Number of factorizations"); 129 STATISTIC(NumReassoc , "Number of reassociations"); 130 DEBUG_COUNTER(VisitCounter, "instcombine-visit", 131 "Controls which instructions are visited"); 132 133 static cl::opt<bool> 134 EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"), 135 cl::init(true)); 136 137 static cl::opt<unsigned> MaxSinkNumUsers( 138 "instcombine-max-sink-users", cl::init(32), 139 cl::desc("Maximum number of undroppable users for instruction sinking")); 140 141 static cl::opt<unsigned> 142 MaxArraySize("instcombine-maxarray-size", cl::init(1024), 143 cl::desc("Maximum array size considered when doing a combine")); 144 145 // FIXME: Remove this flag when it is no longer necessary to convert 146 // llvm.dbg.declare to avoid inaccurate debug info. Setting this to false 147 // increases variable availability at the cost of accuracy. Variables that 148 // cannot be promoted by mem2reg or SROA will be described as living in memory 149 // for their entire lifetime. However, passes like DSE and instcombine can 150 // delete stores to the alloca, leading to misleading and inaccurate debug 151 // information. This flag can be removed when those passes are fixed. 152 static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare", 153 cl::Hidden, cl::init(true)); 154 155 std::optional<Instruction *> 156 InstCombiner::targetInstCombineIntrinsic(IntrinsicInst &II) { 157 // Handle target specific intrinsics 158 if (II.getCalledFunction()->isTargetIntrinsic()) { 159 return TTI.instCombineIntrinsic(*this, II); 160 } 161 return std::nullopt; 162 } 163 164 std::optional<Value *> InstCombiner::targetSimplifyDemandedUseBitsIntrinsic( 165 IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, 166 bool &KnownBitsComputed) { 167 // Handle target specific intrinsics 168 if (II.getCalledFunction()->isTargetIntrinsic()) { 169 return TTI.simplifyDemandedUseBitsIntrinsic(*this, II, DemandedMask, Known, 170 KnownBitsComputed); 171 } 172 return std::nullopt; 173 } 174 175 std::optional<Value *> InstCombiner::targetSimplifyDemandedVectorEltsIntrinsic( 176 IntrinsicInst &II, APInt DemandedElts, APInt &PoisonElts, 177 APInt &PoisonElts2, APInt &PoisonElts3, 178 std::function<void(Instruction *, unsigned, APInt, APInt &)> 179 SimplifyAndSetOp) { 180 // Handle target specific intrinsics 181 if (II.getCalledFunction()->isTargetIntrinsic()) { 182 return TTI.simplifyDemandedVectorEltsIntrinsic( 183 *this, II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3, 184 SimplifyAndSetOp); 185 } 186 return std::nullopt; 187 } 188 189 bool InstCombiner::isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const { 190 return TTI.isValidAddrSpaceCast(FromAS, ToAS); 191 } 192 193 Value *InstCombinerImpl::EmitGEPOffset(User *GEP) { 194 return llvm::emitGEPOffset(&Builder, DL, GEP); 195 } 196 197 /// Legal integers and common types are considered desirable. This is used to 198 /// avoid creating instructions with types that may not be supported well by the 199 /// the backend. 200 /// NOTE: This treats i8, i16 and i32 specially because they are common 201 /// types in frontend languages. 202 bool InstCombinerImpl::isDesirableIntType(unsigned BitWidth) const { 203 switch (BitWidth) { 204 case 8: 205 case 16: 206 case 32: 207 return true; 208 default: 209 return DL.isLegalInteger(BitWidth); 210 } 211 } 212 213 /// Return true if it is desirable to convert an integer computation from a 214 /// given bit width to a new bit width. 215 /// We don't want to convert from a legal or desirable type (like i8) to an 216 /// illegal type or from a smaller to a larger illegal type. A width of '1' 217 /// is always treated as a desirable type because i1 is a fundamental type in 218 /// IR, and there are many specialized optimizations for i1 types. 219 /// Common/desirable widths are equally treated as legal to convert to, in 220 /// order to open up more combining opportunities. 221 bool InstCombinerImpl::shouldChangeType(unsigned FromWidth, 222 unsigned ToWidth) const { 223 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth); 224 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth); 225 226 // Convert to desirable widths even if they are not legal types. 227 // Only shrink types, to prevent infinite loops. 228 if (ToWidth < FromWidth && isDesirableIntType(ToWidth)) 229 return true; 230 231 // If this is a legal or desiable integer from type, and the result would be 232 // an illegal type, don't do the transformation. 233 if ((FromLegal || isDesirableIntType(FromWidth)) && !ToLegal) 234 return false; 235 236 // Otherwise, if both are illegal, do not increase the size of the result. We 237 // do allow things like i160 -> i64, but not i64 -> i160. 238 if (!FromLegal && !ToLegal && ToWidth > FromWidth) 239 return false; 240 241 return true; 242 } 243 244 /// Return true if it is desirable to convert a computation from 'From' to 'To'. 245 /// We don't want to convert from a legal to an illegal type or from a smaller 246 /// to a larger illegal type. i1 is always treated as a legal type because it is 247 /// a fundamental type in IR, and there are many specialized optimizations for 248 /// i1 types. 249 bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const { 250 // TODO: This could be extended to allow vectors. Datalayout changes might be 251 // needed to properly support that. 252 if (!From->isIntegerTy() || !To->isIntegerTy()) 253 return false; 254 255 unsigned FromWidth = From->getPrimitiveSizeInBits(); 256 unsigned ToWidth = To->getPrimitiveSizeInBits(); 257 return shouldChangeType(FromWidth, ToWidth); 258 } 259 260 // Return true, if No Signed Wrap should be maintained for I. 261 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C", 262 // where both B and C should be ConstantInts, results in a constant that does 263 // not overflow. This function only handles the Add and Sub opcodes. For 264 // all other opcodes, the function conservatively returns false. 265 static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) { 266 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 267 if (!OBO || !OBO->hasNoSignedWrap()) 268 return false; 269 270 // We reason about Add and Sub Only. 271 Instruction::BinaryOps Opcode = I.getOpcode(); 272 if (Opcode != Instruction::Add && Opcode != Instruction::Sub) 273 return false; 274 275 const APInt *BVal, *CVal; 276 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal))) 277 return false; 278 279 bool Overflow = false; 280 if (Opcode == Instruction::Add) 281 (void)BVal->sadd_ov(*CVal, Overflow); 282 else 283 (void)BVal->ssub_ov(*CVal, Overflow); 284 285 return !Overflow; 286 } 287 288 static bool hasNoUnsignedWrap(BinaryOperator &I) { 289 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 290 return OBO && OBO->hasNoUnsignedWrap(); 291 } 292 293 static bool hasNoSignedWrap(BinaryOperator &I) { 294 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 295 return OBO && OBO->hasNoSignedWrap(); 296 } 297 298 /// Conservatively clears subclassOptionalData after a reassociation or 299 /// commutation. We preserve fast-math flags when applicable as they can be 300 /// preserved. 301 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) { 302 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I); 303 if (!FPMO) { 304 I.clearSubclassOptionalData(); 305 return; 306 } 307 308 FastMathFlags FMF = I.getFastMathFlags(); 309 I.clearSubclassOptionalData(); 310 I.setFastMathFlags(FMF); 311 } 312 313 /// Combine constant operands of associative operations either before or after a 314 /// cast to eliminate one of the associative operations: 315 /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2))) 316 /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2)) 317 static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1, 318 InstCombinerImpl &IC) { 319 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0)); 320 if (!Cast || !Cast->hasOneUse()) 321 return false; 322 323 // TODO: Enhance logic for other casts and remove this check. 324 auto CastOpcode = Cast->getOpcode(); 325 if (CastOpcode != Instruction::ZExt) 326 return false; 327 328 // TODO: Enhance logic for other BinOps and remove this check. 329 if (!BinOp1->isBitwiseLogicOp()) 330 return false; 331 332 auto AssocOpcode = BinOp1->getOpcode(); 333 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0)); 334 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode) 335 return false; 336 337 Constant *C1, *C2; 338 if (!match(BinOp1->getOperand(1), m_Constant(C1)) || 339 !match(BinOp2->getOperand(1), m_Constant(C2))) 340 return false; 341 342 // TODO: This assumes a zext cast. 343 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2 344 // to the destination type might lose bits. 345 346 // Fold the constants together in the destination type: 347 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC) 348 const DataLayout &DL = IC.getDataLayout(); 349 Type *DestTy = C1->getType(); 350 Constant *CastC2 = ConstantFoldCastOperand(CastOpcode, C2, DestTy, DL); 351 if (!CastC2) 352 return false; 353 Constant *FoldedC = ConstantFoldBinaryOpOperands(AssocOpcode, C1, CastC2, DL); 354 if (!FoldedC) 355 return false; 356 357 IC.replaceOperand(*Cast, 0, BinOp2->getOperand(0)); 358 IC.replaceOperand(*BinOp1, 1, FoldedC); 359 BinOp1->dropPoisonGeneratingFlags(); 360 Cast->dropPoisonGeneratingFlags(); 361 return true; 362 } 363 364 // Simplifies IntToPtr/PtrToInt RoundTrip Cast. 365 // inttoptr ( ptrtoint (x) ) --> x 366 Value *InstCombinerImpl::simplifyIntToPtrRoundTripCast(Value *Val) { 367 auto *IntToPtr = dyn_cast<IntToPtrInst>(Val); 368 if (IntToPtr && DL.getTypeSizeInBits(IntToPtr->getDestTy()) == 369 DL.getTypeSizeInBits(IntToPtr->getSrcTy())) { 370 auto *PtrToInt = dyn_cast<PtrToIntInst>(IntToPtr->getOperand(0)); 371 Type *CastTy = IntToPtr->getDestTy(); 372 if (PtrToInt && 373 CastTy->getPointerAddressSpace() == 374 PtrToInt->getSrcTy()->getPointerAddressSpace() && 375 DL.getTypeSizeInBits(PtrToInt->getSrcTy()) == 376 DL.getTypeSizeInBits(PtrToInt->getDestTy())) 377 return PtrToInt->getOperand(0); 378 } 379 return nullptr; 380 } 381 382 /// This performs a few simplifications for operators that are associative or 383 /// commutative: 384 /// 385 /// Commutative operators: 386 /// 387 /// 1. Order operands such that they are listed from right (least complex) to 388 /// left (most complex). This puts constants before unary operators before 389 /// binary operators. 390 /// 391 /// Associative operators: 392 /// 393 /// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 394 /// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 395 /// 396 /// Associative and commutative operators: 397 /// 398 /// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 399 /// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 400 /// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 401 /// if C1 and C2 are constants. 402 bool InstCombinerImpl::SimplifyAssociativeOrCommutative(BinaryOperator &I) { 403 Instruction::BinaryOps Opcode = I.getOpcode(); 404 bool Changed = false; 405 406 do { 407 // Order operands such that they are listed from right (least complex) to 408 // left (most complex). This puts constants before unary operators before 409 // binary operators. 410 if (I.isCommutative() && getComplexity(I.getOperand(0)) < 411 getComplexity(I.getOperand(1))) 412 Changed = !I.swapOperands(); 413 414 if (I.isCommutative()) { 415 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) { 416 replaceOperand(I, 0, Pair->first); 417 replaceOperand(I, 1, Pair->second); 418 Changed = true; 419 } 420 } 421 422 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); 423 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); 424 425 if (I.isAssociative()) { 426 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 427 if (Op0 && Op0->getOpcode() == Opcode) { 428 Value *A = Op0->getOperand(0); 429 Value *B = Op0->getOperand(1); 430 Value *C = I.getOperand(1); 431 432 // Does "B op C" simplify? 433 if (Value *V = simplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) { 434 // It simplifies to V. Form "A op V". 435 replaceOperand(I, 0, A); 436 replaceOperand(I, 1, V); 437 bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0); 438 bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0); 439 440 // Conservatively clear all optional flags since they may not be 441 // preserved by the reassociation. Reset nsw/nuw based on the above 442 // analysis. 443 ClearSubclassDataAfterReassociation(I); 444 445 // Note: this is only valid because SimplifyBinOp doesn't look at 446 // the operands to Op0. 447 if (IsNUW) 448 I.setHasNoUnsignedWrap(true); 449 450 if (IsNSW) 451 I.setHasNoSignedWrap(true); 452 453 Changed = true; 454 ++NumReassoc; 455 continue; 456 } 457 } 458 459 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 460 if (Op1 && Op1->getOpcode() == Opcode) { 461 Value *A = I.getOperand(0); 462 Value *B = Op1->getOperand(0); 463 Value *C = Op1->getOperand(1); 464 465 // Does "A op B" simplify? 466 if (Value *V = simplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) { 467 // It simplifies to V. Form "V op C". 468 replaceOperand(I, 0, V); 469 replaceOperand(I, 1, C); 470 // Conservatively clear the optional flags, since they may not be 471 // preserved by the reassociation. 472 ClearSubclassDataAfterReassociation(I); 473 Changed = true; 474 ++NumReassoc; 475 continue; 476 } 477 } 478 } 479 480 if (I.isAssociative() && I.isCommutative()) { 481 if (simplifyAssocCastAssoc(&I, *this)) { 482 Changed = true; 483 ++NumReassoc; 484 continue; 485 } 486 487 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 488 if (Op0 && Op0->getOpcode() == Opcode) { 489 Value *A = Op0->getOperand(0); 490 Value *B = Op0->getOperand(1); 491 Value *C = I.getOperand(1); 492 493 // Does "C op A" simplify? 494 if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) { 495 // It simplifies to V. Form "V op B". 496 replaceOperand(I, 0, V); 497 replaceOperand(I, 1, B); 498 // Conservatively clear the optional flags, since they may not be 499 // preserved by the reassociation. 500 ClearSubclassDataAfterReassociation(I); 501 Changed = true; 502 ++NumReassoc; 503 continue; 504 } 505 } 506 507 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 508 if (Op1 && Op1->getOpcode() == Opcode) { 509 Value *A = I.getOperand(0); 510 Value *B = Op1->getOperand(0); 511 Value *C = Op1->getOperand(1); 512 513 // Does "C op A" simplify? 514 if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) { 515 // It simplifies to V. Form "B op V". 516 replaceOperand(I, 0, B); 517 replaceOperand(I, 1, V); 518 // Conservatively clear the optional flags, since they may not be 519 // preserved by the reassociation. 520 ClearSubclassDataAfterReassociation(I); 521 Changed = true; 522 ++NumReassoc; 523 continue; 524 } 525 } 526 527 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 528 // if C1 and C2 are constants. 529 Value *A, *B; 530 Constant *C1, *C2, *CRes; 531 if (Op0 && Op1 && 532 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode && 533 match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) && 534 match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2)))) && 535 (CRes = ConstantFoldBinaryOpOperands(Opcode, C1, C2, DL))) { 536 bool IsNUW = hasNoUnsignedWrap(I) && 537 hasNoUnsignedWrap(*Op0) && 538 hasNoUnsignedWrap(*Op1); 539 BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ? 540 BinaryOperator::CreateNUW(Opcode, A, B) : 541 BinaryOperator::Create(Opcode, A, B); 542 543 if (isa<FPMathOperator>(NewBO)) { 544 FastMathFlags Flags = I.getFastMathFlags() & 545 Op0->getFastMathFlags() & 546 Op1->getFastMathFlags(); 547 NewBO->setFastMathFlags(Flags); 548 } 549 InsertNewInstWith(NewBO, I.getIterator()); 550 NewBO->takeName(Op1); 551 replaceOperand(I, 0, NewBO); 552 replaceOperand(I, 1, CRes); 553 // Conservatively clear the optional flags, since they may not be 554 // preserved by the reassociation. 555 ClearSubclassDataAfterReassociation(I); 556 if (IsNUW) 557 I.setHasNoUnsignedWrap(true); 558 559 Changed = true; 560 continue; 561 } 562 } 563 564 // No further simplifications. 565 return Changed; 566 } while (true); 567 } 568 569 /// Return whether "X LOp (Y ROp Z)" is always equal to 570 /// "(X LOp Y) ROp (X LOp Z)". 571 static bool leftDistributesOverRight(Instruction::BinaryOps LOp, 572 Instruction::BinaryOps ROp) { 573 // X & (Y | Z) <--> (X & Y) | (X & Z) 574 // X & (Y ^ Z) <--> (X & Y) ^ (X & Z) 575 if (LOp == Instruction::And) 576 return ROp == Instruction::Or || ROp == Instruction::Xor; 577 578 // X | (Y & Z) <--> (X | Y) & (X | Z) 579 if (LOp == Instruction::Or) 580 return ROp == Instruction::And; 581 582 // X * (Y + Z) <--> (X * Y) + (X * Z) 583 // X * (Y - Z) <--> (X * Y) - (X * Z) 584 if (LOp == Instruction::Mul) 585 return ROp == Instruction::Add || ROp == Instruction::Sub; 586 587 return false; 588 } 589 590 /// Return whether "(X LOp Y) ROp Z" is always equal to 591 /// "(X ROp Z) LOp (Y ROp Z)". 592 static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, 593 Instruction::BinaryOps ROp) { 594 if (Instruction::isCommutative(ROp)) 595 return leftDistributesOverRight(ROp, LOp); 596 597 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts. 598 return Instruction::isBitwiseLogicOp(LOp) && Instruction::isShift(ROp); 599 600 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z", 601 // but this requires knowing that the addition does not overflow and other 602 // such subtleties. 603 } 604 605 /// This function returns identity value for given opcode, which can be used to 606 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1). 607 static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) { 608 if (isa<Constant>(V)) 609 return nullptr; 610 611 return ConstantExpr::getBinOpIdentity(Opcode, V->getType()); 612 } 613 614 /// This function predicates factorization using distributive laws. By default, 615 /// it just returns the 'Op' inputs. But for special-cases like 616 /// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add 617 /// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to 618 /// allow more factorization opportunities. 619 static Instruction::BinaryOps 620 getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op, 621 Value *&LHS, Value *&RHS, BinaryOperator *OtherOp) { 622 assert(Op && "Expected a binary operator"); 623 LHS = Op->getOperand(0); 624 RHS = Op->getOperand(1); 625 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) { 626 Constant *C; 627 if (match(Op, m_Shl(m_Value(), m_Constant(C)))) { 628 // X << C --> X * (1 << C) 629 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), C); 630 return Instruction::Mul; 631 } 632 // TODO: We can add other conversions e.g. shr => div etc. 633 } 634 if (Instruction::isBitwiseLogicOp(TopOpcode)) { 635 if (OtherOp && OtherOp->getOpcode() == Instruction::AShr && 636 match(Op, m_LShr(m_NonNegative(), m_Value()))) { 637 // lshr nneg C, X --> ashr nneg C, X 638 return Instruction::AShr; 639 } 640 } 641 return Op->getOpcode(); 642 } 643 644 /// This tries to simplify binary operations by factorizing out common terms 645 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)"). 646 static Value *tryFactorization(BinaryOperator &I, const SimplifyQuery &SQ, 647 InstCombiner::BuilderTy &Builder, 648 Instruction::BinaryOps InnerOpcode, Value *A, 649 Value *B, Value *C, Value *D) { 650 assert(A && B && C && D && "All values must be provided"); 651 652 Value *V = nullptr; 653 Value *RetVal = nullptr; 654 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 655 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); 656 657 // Does "X op' Y" always equal "Y op' X"? 658 bool InnerCommutative = Instruction::isCommutative(InnerOpcode); 659 660 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"? 661 if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode)) { 662 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the 663 // commutative case, "(A op' B) op (C op' A)"? 664 if (A == C || (InnerCommutative && A == D)) { 665 if (A != C) 666 std::swap(C, D); 667 // Consider forming "A op' (B op D)". 668 // If "B op D" simplifies then it can be formed with no cost. 669 V = simplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I)); 670 671 // If "B op D" doesn't simplify then only go on if one of the existing 672 // operations "A op' B" and "C op' D" will be zapped as no longer used. 673 if (!V && (LHS->hasOneUse() || RHS->hasOneUse())) 674 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName()); 675 if (V) 676 RetVal = Builder.CreateBinOp(InnerOpcode, A, V); 677 } 678 } 679 680 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"? 681 if (!RetVal && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) { 682 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the 683 // commutative case, "(A op' B) op (B op' D)"? 684 if (B == D || (InnerCommutative && B == C)) { 685 if (B != D) 686 std::swap(C, D); 687 // Consider forming "(A op C) op' B". 688 // If "A op C" simplifies then it can be formed with no cost. 689 V = simplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I)); 690 691 // If "A op C" doesn't simplify then only go on if one of the existing 692 // operations "A op' B" and "C op' D" will be zapped as no longer used. 693 if (!V && (LHS->hasOneUse() || RHS->hasOneUse())) 694 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName()); 695 if (V) 696 RetVal = Builder.CreateBinOp(InnerOpcode, V, B); 697 } 698 } 699 700 if (!RetVal) 701 return nullptr; 702 703 ++NumFactor; 704 RetVal->takeName(&I); 705 706 // Try to add no-overflow flags to the final value. 707 if (isa<OverflowingBinaryOperator>(RetVal)) { 708 bool HasNSW = false; 709 bool HasNUW = false; 710 if (isa<OverflowingBinaryOperator>(&I)) { 711 HasNSW = I.hasNoSignedWrap(); 712 HasNUW = I.hasNoUnsignedWrap(); 713 } 714 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) { 715 HasNSW &= LOBO->hasNoSignedWrap(); 716 HasNUW &= LOBO->hasNoUnsignedWrap(); 717 } 718 719 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) { 720 HasNSW &= ROBO->hasNoSignedWrap(); 721 HasNUW &= ROBO->hasNoUnsignedWrap(); 722 } 723 724 if (TopLevelOpcode == Instruction::Add && InnerOpcode == Instruction::Mul) { 725 // We can propagate 'nsw' if we know that 726 // %Y = mul nsw i16 %X, C 727 // %Z = add nsw i16 %Y, %X 728 // => 729 // %Z = mul nsw i16 %X, C+1 730 // 731 // iff C+1 isn't INT_MIN 732 const APInt *CInt; 733 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue()) 734 cast<Instruction>(RetVal)->setHasNoSignedWrap(HasNSW); 735 736 // nuw can be propagated with any constant or nuw value. 737 cast<Instruction>(RetVal)->setHasNoUnsignedWrap(HasNUW); 738 } 739 } 740 return RetVal; 741 } 742 743 // If `I` has one Const operand and the other matches `(ctpop (not x))`, 744 // replace `(ctpop (not x))` with `(sub nuw nsw BitWidth(x), (ctpop x))`. 745 // This is only useful is the new subtract can fold so we only handle the 746 // following cases: 747 // 1) (add/sub/disjoint_or C, (ctpop (not x)) 748 // -> (add/sub/disjoint_or C', (ctpop x)) 749 // 1) (cmp pred C, (ctpop (not x)) 750 // -> (cmp pred C', (ctpop x)) 751 Instruction *InstCombinerImpl::tryFoldInstWithCtpopWithNot(Instruction *I) { 752 unsigned Opc = I->getOpcode(); 753 unsigned ConstIdx = 1; 754 switch (Opc) { 755 default: 756 return nullptr; 757 // (ctpop (not x)) <-> (sub nuw nsw BitWidth(x) - (ctpop x)) 758 // We can fold the BitWidth(x) with add/sub/icmp as long the other operand 759 // is constant. 760 case Instruction::Sub: 761 ConstIdx = 0; 762 break; 763 case Instruction::ICmp: 764 // Signed predicates aren't correct in some edge cases like for i2 types, as 765 // well since (ctpop x) is known [0, log2(BitWidth(x))] almost all signed 766 // comparisons against it are simplfied to unsigned. 767 if (cast<ICmpInst>(I)->isSigned()) 768 return nullptr; 769 break; 770 case Instruction::Or: 771 if (!match(I, m_DisjointOr(m_Value(), m_Value()))) 772 return nullptr; 773 [[fallthrough]]; 774 case Instruction::Add: 775 break; 776 } 777 778 Value *Op; 779 // Find ctpop. 780 if (!match(I->getOperand(1 - ConstIdx), 781 m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(Op))))) 782 return nullptr; 783 784 Constant *C; 785 // Check other operand is ImmConstant. 786 if (!match(I->getOperand(ConstIdx), m_ImmConstant(C))) 787 return nullptr; 788 789 Type *Ty = Op->getType(); 790 Constant *BitWidthC = ConstantInt::get(Ty, Ty->getScalarSizeInBits()); 791 // Need extra check for icmp. Note if this check is true, it generally means 792 // the icmp will simplify to true/false. 793 if (Opc == Instruction::ICmp && !cast<ICmpInst>(I)->isEquality() && 794 !ConstantExpr::getICmp(ICmpInst::ICMP_UGT, C, BitWidthC)->isZeroValue()) 795 return nullptr; 796 797 // Check we can invert `(not x)` for free. 798 bool Consumes = false; 799 if (!isFreeToInvert(Op, Op->hasOneUse(), Consumes) || !Consumes) 800 return nullptr; 801 Value *NotOp = getFreelyInverted(Op, Op->hasOneUse(), &Builder); 802 assert(NotOp != nullptr && 803 "Desync between isFreeToInvert and getFreelyInverted"); 804 805 Value *CtpopOfNotOp = Builder.CreateIntrinsic(Ty, Intrinsic::ctpop, NotOp); 806 807 Value *R = nullptr; 808 809 // Do the transformation here to avoid potentially introducing an infinite 810 // loop. 811 switch (Opc) { 812 case Instruction::Sub: 813 R = Builder.CreateAdd(CtpopOfNotOp, ConstantExpr::getSub(C, BitWidthC)); 814 break; 815 case Instruction::Or: 816 case Instruction::Add: 817 R = Builder.CreateSub(ConstantExpr::getAdd(C, BitWidthC), CtpopOfNotOp); 818 break; 819 case Instruction::ICmp: 820 R = Builder.CreateICmp(cast<ICmpInst>(I)->getSwappedPredicate(), 821 CtpopOfNotOp, ConstantExpr::getSub(BitWidthC, C)); 822 break; 823 default: 824 llvm_unreachable("Unhandled Opcode"); 825 } 826 assert(R != nullptr); 827 return replaceInstUsesWith(*I, R); 828 } 829 830 // (Binop1 (Binop2 (logic_shift X, C), C1), (logic_shift Y, C)) 831 // IFF 832 // 1) the logic_shifts match 833 // 2) either both binops are binops and one is `and` or 834 // BinOp1 is `and` 835 // (logic_shift (inv_logic_shift C1, C), C) == C1 or 836 // 837 // -> (logic_shift (Binop1 (Binop2 X, inv_logic_shift(C1, C)), Y), C) 838 // 839 // (Binop1 (Binop2 (logic_shift X, Amt), Mask), (logic_shift Y, Amt)) 840 // IFF 841 // 1) the logic_shifts match 842 // 2) BinOp1 == BinOp2 (if BinOp == `add`, then also requires `shl`). 843 // 844 // -> (BinOp (logic_shift (BinOp X, Y)), Mask) 845 // 846 // (Binop1 (Binop2 (arithmetic_shift X, Amt), Mask), (arithmetic_shift Y, Amt)) 847 // IFF 848 // 1) Binop1 is bitwise logical operator `and`, `or` or `xor` 849 // 2) Binop2 is `not` 850 // 851 // -> (arithmetic_shift Binop1((not X), Y), Amt) 852 853 Instruction *InstCombinerImpl::foldBinOpShiftWithShift(BinaryOperator &I) { 854 const DataLayout &DL = I.getModule()->getDataLayout(); 855 auto IsValidBinOpc = [](unsigned Opc) { 856 switch (Opc) { 857 default: 858 return false; 859 case Instruction::And: 860 case Instruction::Or: 861 case Instruction::Xor: 862 case Instruction::Add: 863 // Skip Sub as we only match constant masks which will canonicalize to use 864 // add. 865 return true; 866 } 867 }; 868 869 // Check if we can distribute binop arbitrarily. `add` + `lshr` has extra 870 // constraints. 871 auto IsCompletelyDistributable = [](unsigned BinOpc1, unsigned BinOpc2, 872 unsigned ShOpc) { 873 assert(ShOpc != Instruction::AShr); 874 return (BinOpc1 != Instruction::Add && BinOpc2 != Instruction::Add) || 875 ShOpc == Instruction::Shl; 876 }; 877 878 auto GetInvShift = [](unsigned ShOpc) { 879 assert(ShOpc != Instruction::AShr); 880 return ShOpc == Instruction::LShr ? Instruction::Shl : Instruction::LShr; 881 }; 882 883 auto CanDistributeBinops = [&](unsigned BinOpc1, unsigned BinOpc2, 884 unsigned ShOpc, Constant *CMask, 885 Constant *CShift) { 886 // If the BinOp1 is `and` we don't need to check the mask. 887 if (BinOpc1 == Instruction::And) 888 return true; 889 890 // For all other possible transfers we need complete distributable 891 // binop/shift (anything but `add` + `lshr`). 892 if (!IsCompletelyDistributable(BinOpc1, BinOpc2, ShOpc)) 893 return false; 894 895 // If BinOp2 is `and`, any mask works (this only really helps for non-splat 896 // vecs, otherwise the mask will be simplified and the following check will 897 // handle it). 898 if (BinOpc2 == Instruction::And) 899 return true; 900 901 // Otherwise, need mask that meets the below requirement. 902 // (logic_shift (inv_logic_shift Mask, ShAmt), ShAmt) == Mask 903 Constant *MaskInvShift = 904 ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL); 905 return ConstantFoldBinaryOpOperands(ShOpc, MaskInvShift, CShift, DL) == 906 CMask; 907 }; 908 909 auto MatchBinOp = [&](unsigned ShOpnum) -> Instruction * { 910 Constant *CMask, *CShift; 911 Value *X, *Y, *ShiftedX, *Mask, *Shift; 912 if (!match(I.getOperand(ShOpnum), 913 m_OneUse(m_Shift(m_Value(Y), m_Value(Shift))))) 914 return nullptr; 915 if (!match(I.getOperand(1 - ShOpnum), 916 m_BinOp(m_Value(ShiftedX), m_Value(Mask)))) 917 return nullptr; 918 919 if (!match(ShiftedX, m_OneUse(m_Shift(m_Value(X), m_Specific(Shift))))) 920 return nullptr; 921 922 // Make sure we are matching instruction shifts and not ConstantExpr 923 auto *IY = dyn_cast<Instruction>(I.getOperand(ShOpnum)); 924 auto *IX = dyn_cast<Instruction>(ShiftedX); 925 if (!IY || !IX) 926 return nullptr; 927 928 // LHS and RHS need same shift opcode 929 unsigned ShOpc = IY->getOpcode(); 930 if (ShOpc != IX->getOpcode()) 931 return nullptr; 932 933 // Make sure binop is real instruction and not ConstantExpr 934 auto *BO2 = dyn_cast<Instruction>(I.getOperand(1 - ShOpnum)); 935 if (!BO2) 936 return nullptr; 937 938 unsigned BinOpc = BO2->getOpcode(); 939 // Make sure we have valid binops. 940 if (!IsValidBinOpc(I.getOpcode()) || !IsValidBinOpc(BinOpc)) 941 return nullptr; 942 943 if (ShOpc == Instruction::AShr) { 944 if (Instruction::isBitwiseLogicOp(I.getOpcode()) && 945 BinOpc == Instruction::Xor && match(Mask, m_AllOnes())) { 946 Value *NotX = Builder.CreateNot(X); 947 Value *NewBinOp = Builder.CreateBinOp(I.getOpcode(), Y, NotX); 948 return BinaryOperator::Create( 949 static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp, Shift); 950 } 951 952 return nullptr; 953 } 954 955 // If BinOp1 == BinOp2 and it's bitwise or shl with add, then just 956 // distribute to drop the shift irrelevant of constants. 957 if (BinOpc == I.getOpcode() && 958 IsCompletelyDistributable(I.getOpcode(), BinOpc, ShOpc)) { 959 Value *NewBinOp2 = Builder.CreateBinOp(I.getOpcode(), X, Y); 960 Value *NewBinOp1 = Builder.CreateBinOp( 961 static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp2, Shift); 962 return BinaryOperator::Create(I.getOpcode(), NewBinOp1, Mask); 963 } 964 965 // Otherwise we can only distribute by constant shifting the mask, so 966 // ensure we have constants. 967 if (!match(Shift, m_ImmConstant(CShift))) 968 return nullptr; 969 if (!match(Mask, m_ImmConstant(CMask))) 970 return nullptr; 971 972 // Check if we can distribute the binops. 973 if (!CanDistributeBinops(I.getOpcode(), BinOpc, ShOpc, CMask, CShift)) 974 return nullptr; 975 976 Constant *NewCMask = 977 ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL); 978 Value *NewBinOp2 = Builder.CreateBinOp( 979 static_cast<Instruction::BinaryOps>(BinOpc), X, NewCMask); 980 Value *NewBinOp1 = Builder.CreateBinOp(I.getOpcode(), Y, NewBinOp2); 981 return BinaryOperator::Create(static_cast<Instruction::BinaryOps>(ShOpc), 982 NewBinOp1, CShift); 983 }; 984 985 if (Instruction *R = MatchBinOp(0)) 986 return R; 987 return MatchBinOp(1); 988 } 989 990 // (Binop (zext C), (select C, T, F)) 991 // -> (select C, (binop 1, T), (binop 0, F)) 992 // 993 // (Binop (sext C), (select C, T, F)) 994 // -> (select C, (binop -1, T), (binop 0, F)) 995 // 996 // Attempt to simplify binary operations into a select with folded args, when 997 // one operand of the binop is a select instruction and the other operand is a 998 // zext/sext extension, whose value is the select condition. 999 Instruction * 1000 InstCombinerImpl::foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I) { 1001 // TODO: this simplification may be extended to any speculatable instruction, 1002 // not just binops, and would possibly be handled better in FoldOpIntoSelect. 1003 Instruction::BinaryOps Opc = I.getOpcode(); 1004 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 1005 Value *A, *CondVal, *TrueVal, *FalseVal; 1006 Value *CastOp; 1007 1008 auto MatchSelectAndCast = [&](Value *CastOp, Value *SelectOp) { 1009 return match(CastOp, m_ZExtOrSExt(m_Value(A))) && 1010 A->getType()->getScalarSizeInBits() == 1 && 1011 match(SelectOp, m_Select(m_Value(CondVal), m_Value(TrueVal), 1012 m_Value(FalseVal))); 1013 }; 1014 1015 // Make sure one side of the binop is a select instruction, and the other is a 1016 // zero/sign extension operating on a i1. 1017 if (MatchSelectAndCast(LHS, RHS)) 1018 CastOp = LHS; 1019 else if (MatchSelectAndCast(RHS, LHS)) 1020 CastOp = RHS; 1021 else 1022 return nullptr; 1023 1024 auto NewFoldedConst = [&](bool IsTrueArm, Value *V) { 1025 bool IsCastOpRHS = (CastOp == RHS); 1026 bool IsZExt = isa<ZExtInst>(CastOp); 1027 Constant *C; 1028 1029 if (IsTrueArm) { 1030 C = Constant::getNullValue(V->getType()); 1031 } else if (IsZExt) { 1032 unsigned BitWidth = V->getType()->getScalarSizeInBits(); 1033 C = Constant::getIntegerValue(V->getType(), APInt(BitWidth, 1)); 1034 } else { 1035 C = Constant::getAllOnesValue(V->getType()); 1036 } 1037 1038 return IsCastOpRHS ? Builder.CreateBinOp(Opc, V, C) 1039 : Builder.CreateBinOp(Opc, C, V); 1040 }; 1041 1042 // If the value used in the zext/sext is the select condition, or the negated 1043 // of the select condition, the binop can be simplified. 1044 if (CondVal == A) { 1045 Value *NewTrueVal = NewFoldedConst(false, TrueVal); 1046 return SelectInst::Create(CondVal, NewTrueVal, 1047 NewFoldedConst(true, FalseVal)); 1048 } 1049 1050 if (match(A, m_Not(m_Specific(CondVal)))) { 1051 Value *NewTrueVal = NewFoldedConst(true, TrueVal); 1052 return SelectInst::Create(CondVal, NewTrueVal, 1053 NewFoldedConst(false, FalseVal)); 1054 } 1055 1056 return nullptr; 1057 } 1058 1059 Value *InstCombinerImpl::tryFactorizationFolds(BinaryOperator &I) { 1060 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 1061 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 1062 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 1063 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); 1064 Value *A, *B, *C, *D; 1065 Instruction::BinaryOps LHSOpcode, RHSOpcode; 1066 1067 if (Op0) 1068 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B, Op1); 1069 if (Op1) 1070 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D, Op0); 1071 1072 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize 1073 // a common term. 1074 if (Op0 && Op1 && LHSOpcode == RHSOpcode) 1075 if (Value *V = tryFactorization(I, SQ, Builder, LHSOpcode, A, B, C, D)) 1076 return V; 1077 1078 // The instruction has the form "(A op' B) op (C)". Try to factorize common 1079 // term. 1080 if (Op0) 1081 if (Value *Ident = getIdentityValue(LHSOpcode, RHS)) 1082 if (Value *V = 1083 tryFactorization(I, SQ, Builder, LHSOpcode, A, B, RHS, Ident)) 1084 return V; 1085 1086 // The instruction has the form "(B) op (C op' D)". Try to factorize common 1087 // term. 1088 if (Op1) 1089 if (Value *Ident = getIdentityValue(RHSOpcode, LHS)) 1090 if (Value *V = 1091 tryFactorization(I, SQ, Builder, RHSOpcode, LHS, Ident, C, D)) 1092 return V; 1093 1094 return nullptr; 1095 } 1096 1097 /// This tries to simplify binary operations which some other binary operation 1098 /// distributes over either by factorizing out common terms 1099 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in 1100 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win). 1101 /// Returns the simplified value, or null if it didn't simplify. 1102 Value *InstCombinerImpl::foldUsingDistributiveLaws(BinaryOperator &I) { 1103 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 1104 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 1105 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 1106 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); 1107 1108 // Factorization. 1109 if (Value *R = tryFactorizationFolds(I)) 1110 return R; 1111 1112 // Expansion. 1113 if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) { 1114 // The instruction has the form "(A op' B) op C". See if expanding it out 1115 // to "(A op C) op' (B op C)" results in simplifications. 1116 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; 1117 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op' 1118 1119 // Disable the use of undef because it's not safe to distribute undef. 1120 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef(); 1121 Value *L = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive); 1122 Value *R = simplifyBinOp(TopLevelOpcode, B, C, SQDistributive); 1123 1124 // Do "A op C" and "B op C" both simplify? 1125 if (L && R) { 1126 // They do! Return "L op' R". 1127 ++NumExpand; 1128 C = Builder.CreateBinOp(InnerOpcode, L, R); 1129 C->takeName(&I); 1130 return C; 1131 } 1132 1133 // Does "A op C" simplify to the identity value for the inner opcode? 1134 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) { 1135 // They do! Return "B op C". 1136 ++NumExpand; 1137 C = Builder.CreateBinOp(TopLevelOpcode, B, C); 1138 C->takeName(&I); 1139 return C; 1140 } 1141 1142 // Does "B op C" simplify to the identity value for the inner opcode? 1143 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) { 1144 // They do! Return "A op C". 1145 ++NumExpand; 1146 C = Builder.CreateBinOp(TopLevelOpcode, A, C); 1147 C->takeName(&I); 1148 return C; 1149 } 1150 } 1151 1152 if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) { 1153 // The instruction has the form "A op (B op' C)". See if expanding it out 1154 // to "(A op B) op' (A op C)" results in simplifications. 1155 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); 1156 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op' 1157 1158 // Disable the use of undef because it's not safe to distribute undef. 1159 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef(); 1160 Value *L = simplifyBinOp(TopLevelOpcode, A, B, SQDistributive); 1161 Value *R = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive); 1162 1163 // Do "A op B" and "A op C" both simplify? 1164 if (L && R) { 1165 // They do! Return "L op' R". 1166 ++NumExpand; 1167 A = Builder.CreateBinOp(InnerOpcode, L, R); 1168 A->takeName(&I); 1169 return A; 1170 } 1171 1172 // Does "A op B" simplify to the identity value for the inner opcode? 1173 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) { 1174 // They do! Return "A op C". 1175 ++NumExpand; 1176 A = Builder.CreateBinOp(TopLevelOpcode, A, C); 1177 A->takeName(&I); 1178 return A; 1179 } 1180 1181 // Does "A op C" simplify to the identity value for the inner opcode? 1182 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) { 1183 // They do! Return "A op B". 1184 ++NumExpand; 1185 A = Builder.CreateBinOp(TopLevelOpcode, A, B); 1186 A->takeName(&I); 1187 return A; 1188 } 1189 } 1190 1191 return SimplifySelectsFeedingBinaryOp(I, LHS, RHS); 1192 } 1193 1194 static std::optional<std::pair<Value *, Value *>> 1195 matchSymmetricPhiNodesPair(PHINode *LHS, PHINode *RHS) { 1196 if (LHS->getParent() != RHS->getParent()) 1197 return std::nullopt; 1198 1199 if (LHS->getNumIncomingValues() < 2) 1200 return std::nullopt; 1201 1202 if (!equal(LHS->blocks(), RHS->blocks())) 1203 return std::nullopt; 1204 1205 Value *L0 = LHS->getIncomingValue(0); 1206 Value *R0 = RHS->getIncomingValue(0); 1207 1208 for (unsigned I = 1, E = LHS->getNumIncomingValues(); I != E; ++I) { 1209 Value *L1 = LHS->getIncomingValue(I); 1210 Value *R1 = RHS->getIncomingValue(I); 1211 1212 if ((L0 == L1 && R0 == R1) || (L0 == R1 && R0 == L1)) 1213 continue; 1214 1215 return std::nullopt; 1216 } 1217 1218 return std::optional(std::pair(L0, R0)); 1219 } 1220 1221 std::optional<std::pair<Value *, Value *>> 1222 InstCombinerImpl::matchSymmetricPair(Value *LHS, Value *RHS) { 1223 Instruction *LHSInst = dyn_cast<Instruction>(LHS); 1224 Instruction *RHSInst = dyn_cast<Instruction>(RHS); 1225 if (!LHSInst || !RHSInst || LHSInst->getOpcode() != RHSInst->getOpcode()) 1226 return std::nullopt; 1227 switch (LHSInst->getOpcode()) { 1228 case Instruction::PHI: 1229 return matchSymmetricPhiNodesPair(cast<PHINode>(LHS), cast<PHINode>(RHS)); 1230 case Instruction::Select: { 1231 Value *Cond = LHSInst->getOperand(0); 1232 Value *TrueVal = LHSInst->getOperand(1); 1233 Value *FalseVal = LHSInst->getOperand(2); 1234 if (Cond == RHSInst->getOperand(0) && TrueVal == RHSInst->getOperand(2) && 1235 FalseVal == RHSInst->getOperand(1)) 1236 return std::pair(TrueVal, FalseVal); 1237 return std::nullopt; 1238 } 1239 case Instruction::Call: { 1240 // Match min(a, b) and max(a, b) 1241 MinMaxIntrinsic *LHSMinMax = dyn_cast<MinMaxIntrinsic>(LHSInst); 1242 MinMaxIntrinsic *RHSMinMax = dyn_cast<MinMaxIntrinsic>(RHSInst); 1243 if (LHSMinMax && RHSMinMax && 1244 LHSMinMax->getPredicate() == 1245 ICmpInst::getSwappedPredicate(RHSMinMax->getPredicate()) && 1246 ((LHSMinMax->getLHS() == RHSMinMax->getLHS() && 1247 LHSMinMax->getRHS() == RHSMinMax->getRHS()) || 1248 (LHSMinMax->getLHS() == RHSMinMax->getRHS() && 1249 LHSMinMax->getRHS() == RHSMinMax->getLHS()))) 1250 return std::pair(LHSMinMax->getLHS(), LHSMinMax->getRHS()); 1251 return std::nullopt; 1252 } 1253 default: 1254 return std::nullopt; 1255 } 1256 } 1257 1258 Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I, 1259 Value *LHS, 1260 Value *RHS) { 1261 Value *A, *B, *C, *D, *E, *F; 1262 bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C))); 1263 bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F))); 1264 if (!LHSIsSelect && !RHSIsSelect) 1265 return nullptr; 1266 1267 FastMathFlags FMF; 1268 BuilderTy::FastMathFlagGuard Guard(Builder); 1269 if (isa<FPMathOperator>(&I)) { 1270 FMF = I.getFastMathFlags(); 1271 Builder.setFastMathFlags(FMF); 1272 } 1273 1274 Instruction::BinaryOps Opcode = I.getOpcode(); 1275 SimplifyQuery Q = SQ.getWithInstruction(&I); 1276 1277 Value *Cond, *True = nullptr, *False = nullptr; 1278 1279 // Special-case for add/negate combination. Replace the zero in the negation 1280 // with the trailing add operand: 1281 // (Cond ? TVal : -N) + Z --> Cond ? True : (Z - N) 1282 // (Cond ? -N : FVal) + Z --> Cond ? (Z - N) : False 1283 auto foldAddNegate = [&](Value *TVal, Value *FVal, Value *Z) -> Value * { 1284 // We need an 'add' and exactly 1 arm of the select to have been simplified. 1285 if (Opcode != Instruction::Add || (!True && !False) || (True && False)) 1286 return nullptr; 1287 1288 Value *N; 1289 if (True && match(FVal, m_Neg(m_Value(N)))) { 1290 Value *Sub = Builder.CreateSub(Z, N); 1291 return Builder.CreateSelect(Cond, True, Sub, I.getName()); 1292 } 1293 if (False && match(TVal, m_Neg(m_Value(N)))) { 1294 Value *Sub = Builder.CreateSub(Z, N); 1295 return Builder.CreateSelect(Cond, Sub, False, I.getName()); 1296 } 1297 return nullptr; 1298 }; 1299 1300 if (LHSIsSelect && RHSIsSelect && A == D) { 1301 // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F) 1302 Cond = A; 1303 True = simplifyBinOp(Opcode, B, E, FMF, Q); 1304 False = simplifyBinOp(Opcode, C, F, FMF, Q); 1305 1306 if (LHS->hasOneUse() && RHS->hasOneUse()) { 1307 if (False && !True) 1308 True = Builder.CreateBinOp(Opcode, B, E); 1309 else if (True && !False) 1310 False = Builder.CreateBinOp(Opcode, C, F); 1311 } 1312 } else if (LHSIsSelect && LHS->hasOneUse()) { 1313 // (A ? B : C) op Y -> A ? (B op Y) : (C op Y) 1314 Cond = A; 1315 True = simplifyBinOp(Opcode, B, RHS, FMF, Q); 1316 False = simplifyBinOp(Opcode, C, RHS, FMF, Q); 1317 if (Value *NewSel = foldAddNegate(B, C, RHS)) 1318 return NewSel; 1319 } else if (RHSIsSelect && RHS->hasOneUse()) { 1320 // X op (D ? E : F) -> D ? (X op E) : (X op F) 1321 Cond = D; 1322 True = simplifyBinOp(Opcode, LHS, E, FMF, Q); 1323 False = simplifyBinOp(Opcode, LHS, F, FMF, Q); 1324 if (Value *NewSel = foldAddNegate(E, F, LHS)) 1325 return NewSel; 1326 } 1327 1328 if (!True || !False) 1329 return nullptr; 1330 1331 Value *SI = Builder.CreateSelect(Cond, True, False); 1332 SI->takeName(&I); 1333 return SI; 1334 } 1335 1336 /// Freely adapt every user of V as-if V was changed to !V. 1337 /// WARNING: only if canFreelyInvertAllUsersOf() said this can be done. 1338 void InstCombinerImpl::freelyInvertAllUsersOf(Value *I, Value *IgnoredUser) { 1339 assert(!isa<Constant>(I) && "Shouldn't invert users of constant"); 1340 for (User *U : make_early_inc_range(I->users())) { 1341 if (U == IgnoredUser) 1342 continue; // Don't consider this user. 1343 switch (cast<Instruction>(U)->getOpcode()) { 1344 case Instruction::Select: { 1345 auto *SI = cast<SelectInst>(U); 1346 SI->swapValues(); 1347 SI->swapProfMetadata(); 1348 break; 1349 } 1350 case Instruction::Br: 1351 cast<BranchInst>(U)->swapSuccessors(); // swaps prof metadata too 1352 break; 1353 case Instruction::Xor: 1354 replaceInstUsesWith(cast<Instruction>(*U), I); 1355 // Add to worklist for DCE. 1356 addToWorklist(cast<Instruction>(U)); 1357 break; 1358 default: 1359 llvm_unreachable("Got unexpected user - out of sync with " 1360 "canFreelyInvertAllUsersOf() ?"); 1361 } 1362 } 1363 } 1364 1365 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a 1366 /// constant zero (which is the 'negate' form). 1367 Value *InstCombinerImpl::dyn_castNegVal(Value *V) const { 1368 Value *NegV; 1369 if (match(V, m_Neg(m_Value(NegV)))) 1370 return NegV; 1371 1372 // Constants can be considered to be negated values if they can be folded. 1373 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) 1374 return ConstantExpr::getNeg(C); 1375 1376 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V)) 1377 if (C->getType()->getElementType()->isIntegerTy()) 1378 return ConstantExpr::getNeg(C); 1379 1380 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) { 1381 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) { 1382 Constant *Elt = CV->getAggregateElement(i); 1383 if (!Elt) 1384 return nullptr; 1385 1386 if (isa<UndefValue>(Elt)) 1387 continue; 1388 1389 if (!isa<ConstantInt>(Elt)) 1390 return nullptr; 1391 } 1392 return ConstantExpr::getNeg(CV); 1393 } 1394 1395 // Negate integer vector splats. 1396 if (auto *CV = dyn_cast<Constant>(V)) 1397 if (CV->getType()->isVectorTy() && 1398 CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue()) 1399 return ConstantExpr::getNeg(CV); 1400 1401 return nullptr; 1402 } 1403 1404 /// A binop with a constant operand and a sign-extended boolean operand may be 1405 /// converted into a select of constants by applying the binary operation to 1406 /// the constant with the two possible values of the extended boolean (0 or -1). 1407 Instruction *InstCombinerImpl::foldBinopOfSextBoolToSelect(BinaryOperator &BO) { 1408 // TODO: Handle non-commutative binop (constant is operand 0). 1409 // TODO: Handle zext. 1410 // TODO: Peek through 'not' of cast. 1411 Value *BO0 = BO.getOperand(0); 1412 Value *BO1 = BO.getOperand(1); 1413 Value *X; 1414 Constant *C; 1415 if (!match(BO0, m_SExt(m_Value(X))) || !match(BO1, m_ImmConstant(C)) || 1416 !X->getType()->isIntOrIntVectorTy(1)) 1417 return nullptr; 1418 1419 // bo (sext i1 X), C --> select X, (bo -1, C), (bo 0, C) 1420 Constant *Ones = ConstantInt::getAllOnesValue(BO.getType()); 1421 Constant *Zero = ConstantInt::getNullValue(BO.getType()); 1422 Value *TVal = Builder.CreateBinOp(BO.getOpcode(), Ones, C); 1423 Value *FVal = Builder.CreateBinOp(BO.getOpcode(), Zero, C); 1424 return SelectInst::Create(X, TVal, FVal); 1425 } 1426 1427 static Constant *constantFoldOperationIntoSelectOperand(Instruction &I, 1428 SelectInst *SI, 1429 bool IsTrueArm) { 1430 SmallVector<Constant *> ConstOps; 1431 for (Value *Op : I.operands()) { 1432 CmpInst::Predicate Pred; 1433 Constant *C = nullptr; 1434 if (Op == SI) { 1435 C = dyn_cast<Constant>(IsTrueArm ? SI->getTrueValue() 1436 : SI->getFalseValue()); 1437 } else if (match(SI->getCondition(), 1438 m_ICmp(Pred, m_Specific(Op), m_Constant(C))) && 1439 Pred == (IsTrueArm ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) && 1440 isGuaranteedNotToBeUndefOrPoison(C)) { 1441 // Pass 1442 } else { 1443 C = dyn_cast<Constant>(Op); 1444 } 1445 if (C == nullptr) 1446 return nullptr; 1447 1448 ConstOps.push_back(C); 1449 } 1450 1451 return ConstantFoldInstOperands(&I, ConstOps, I.getModule()->getDataLayout()); 1452 } 1453 1454 static Value *foldOperationIntoSelectOperand(Instruction &I, SelectInst *SI, 1455 Value *NewOp, InstCombiner &IC) { 1456 Instruction *Clone = I.clone(); 1457 Clone->replaceUsesOfWith(SI, NewOp); 1458 IC.InsertNewInstBefore(Clone, SI->getIterator()); 1459 return Clone; 1460 } 1461 1462 Instruction *InstCombinerImpl::FoldOpIntoSelect(Instruction &Op, SelectInst *SI, 1463 bool FoldWithMultiUse) { 1464 // Don't modify shared select instructions unless set FoldWithMultiUse 1465 if (!SI->hasOneUse() && !FoldWithMultiUse) 1466 return nullptr; 1467 1468 Value *TV = SI->getTrueValue(); 1469 Value *FV = SI->getFalseValue(); 1470 if (!(isa<Constant>(TV) || isa<Constant>(FV))) 1471 return nullptr; 1472 1473 // Bool selects with constant operands can be folded to logical ops. 1474 if (SI->getType()->isIntOrIntVectorTy(1)) 1475 return nullptr; 1476 1477 // If it's a bitcast involving vectors, make sure it has the same number of 1478 // elements on both sides. 1479 if (auto *BC = dyn_cast<BitCastInst>(&Op)) { 1480 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy()); 1481 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy()); 1482 1483 // Verify that either both or neither are vectors. 1484 if ((SrcTy == nullptr) != (DestTy == nullptr)) 1485 return nullptr; 1486 1487 // If vectors, verify that they have the same number of elements. 1488 if (SrcTy && SrcTy->getElementCount() != DestTy->getElementCount()) 1489 return nullptr; 1490 } 1491 1492 // Test if a FCmpInst instruction is used exclusively by a select as 1493 // part of a minimum or maximum operation. If so, refrain from doing 1494 // any other folding. This helps out other analyses which understand 1495 // non-obfuscated minimum and maximum idioms. And in this case, at 1496 // least one of the comparison operands has at least one user besides 1497 // the compare (the select), which would often largely negate the 1498 // benefit of folding anyway. 1499 if (auto *CI = dyn_cast<FCmpInst>(SI->getCondition())) { 1500 if (CI->hasOneUse()) { 1501 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1); 1502 if ((TV == Op0 && FV == Op1) || (FV == Op0 && TV == Op1)) 1503 return nullptr; 1504 } 1505 } 1506 1507 // Make sure that one of the select arms constant folds successfully. 1508 Value *NewTV = constantFoldOperationIntoSelectOperand(Op, SI, /*IsTrueArm*/ true); 1509 Value *NewFV = constantFoldOperationIntoSelectOperand(Op, SI, /*IsTrueArm*/ false); 1510 if (!NewTV && !NewFV) 1511 return nullptr; 1512 1513 // Create an instruction for the arm that did not fold. 1514 if (!NewTV) 1515 NewTV = foldOperationIntoSelectOperand(Op, SI, TV, *this); 1516 if (!NewFV) 1517 NewFV = foldOperationIntoSelectOperand(Op, SI, FV, *this); 1518 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI); 1519 } 1520 1521 static Value *simplifyInstructionWithPHI(Instruction &I, PHINode *PN, 1522 Value *InValue, BasicBlock *InBB, 1523 const DataLayout &DL, 1524 const SimplifyQuery SQ) { 1525 // NB: It is a precondition of this transform that the operands be 1526 // phi translatable! This is usually trivially satisfied by limiting it 1527 // to constant ops, and for selects we do a more sophisticated check. 1528 SmallVector<Value *> Ops; 1529 for (Value *Op : I.operands()) { 1530 if (Op == PN) 1531 Ops.push_back(InValue); 1532 else 1533 Ops.push_back(Op->DoPHITranslation(PN->getParent(), InBB)); 1534 } 1535 1536 // Don't consider the simplification successful if we get back a constant 1537 // expression. That's just an instruction in hiding. 1538 // Also reject the case where we simplify back to the phi node. We wouldn't 1539 // be able to remove it in that case. 1540 Value *NewVal = simplifyInstructionWithOperands( 1541 &I, Ops, SQ.getWithInstruction(InBB->getTerminator())); 1542 if (NewVal && NewVal != PN && !match(NewVal, m_ConstantExpr())) 1543 return NewVal; 1544 1545 // Check if incoming PHI value can be replaced with constant 1546 // based on implied condition. 1547 BranchInst *TerminatorBI = dyn_cast<BranchInst>(InBB->getTerminator()); 1548 const ICmpInst *ICmp = dyn_cast<ICmpInst>(&I); 1549 if (TerminatorBI && TerminatorBI->isConditional() && 1550 TerminatorBI->getSuccessor(0) != TerminatorBI->getSuccessor(1) && ICmp) { 1551 bool LHSIsTrue = TerminatorBI->getSuccessor(0) == PN->getParent(); 1552 std::optional<bool> ImpliedCond = 1553 isImpliedCondition(TerminatorBI->getCondition(), ICmp->getPredicate(), 1554 Ops[0], Ops[1], DL, LHSIsTrue); 1555 if (ImpliedCond) 1556 return ConstantInt::getBool(I.getType(), ImpliedCond.value()); 1557 } 1558 1559 return nullptr; 1560 } 1561 1562 Instruction *InstCombinerImpl::foldOpIntoPhi(Instruction &I, PHINode *PN) { 1563 unsigned NumPHIValues = PN->getNumIncomingValues(); 1564 if (NumPHIValues == 0) 1565 return nullptr; 1566 1567 // We normally only transform phis with a single use. However, if a PHI has 1568 // multiple uses and they are all the same operation, we can fold *all* of the 1569 // uses into the PHI. 1570 if (!PN->hasOneUse()) { 1571 // Walk the use list for the instruction, comparing them to I. 1572 for (User *U : PN->users()) { 1573 Instruction *UI = cast<Instruction>(U); 1574 if (UI != &I && !I.isIdenticalTo(UI)) 1575 return nullptr; 1576 } 1577 // Otherwise, we can replace *all* users with the new PHI we form. 1578 } 1579 1580 // Check to see whether the instruction can be folded into each phi operand. 1581 // If there is one operand that does not fold, remember the BB it is in. 1582 // If there is more than one or if *it* is a PHI, bail out. 1583 SmallVector<Value *> NewPhiValues; 1584 BasicBlock *NonSimplifiedBB = nullptr; 1585 Value *NonSimplifiedInVal = nullptr; 1586 for (unsigned i = 0; i != NumPHIValues; ++i) { 1587 Value *InVal = PN->getIncomingValue(i); 1588 BasicBlock *InBB = PN->getIncomingBlock(i); 1589 1590 if (auto *NewVal = simplifyInstructionWithPHI(I, PN, InVal, InBB, DL, SQ)) { 1591 NewPhiValues.push_back(NewVal); 1592 continue; 1593 } 1594 1595 if (NonSimplifiedBB) return nullptr; // More than one non-simplified value. 1596 1597 NonSimplifiedBB = InBB; 1598 NonSimplifiedInVal = InVal; 1599 NewPhiValues.push_back(nullptr); 1600 1601 // If the InVal is an invoke at the end of the pred block, then we can't 1602 // insert a computation after it without breaking the edge. 1603 if (isa<InvokeInst>(InVal)) 1604 if (cast<Instruction>(InVal)->getParent() == NonSimplifiedBB) 1605 return nullptr; 1606 1607 // If the incoming non-constant value is reachable from the phis block, 1608 // we'll push the operation across a loop backedge. This could result in 1609 // an infinite combine loop, and is generally non-profitable (especially 1610 // if the operation was originally outside the loop). 1611 if (isPotentiallyReachable(PN->getParent(), NonSimplifiedBB, nullptr, &DT, 1612 LI)) 1613 return nullptr; 1614 } 1615 1616 // If there is exactly one non-simplified value, we can insert a copy of the 1617 // operation in that block. However, if this is a critical edge, we would be 1618 // inserting the computation on some other paths (e.g. inside a loop). Only 1619 // do this if the pred block is unconditionally branching into the phi block. 1620 // Also, make sure that the pred block is not dead code. 1621 if (NonSimplifiedBB != nullptr) { 1622 BranchInst *BI = dyn_cast<BranchInst>(NonSimplifiedBB->getTerminator()); 1623 if (!BI || !BI->isUnconditional() || 1624 !DT.isReachableFromEntry(NonSimplifiedBB)) 1625 return nullptr; 1626 } 1627 1628 // Okay, we can do the transformation: create the new PHI node. 1629 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues()); 1630 InsertNewInstBefore(NewPN, PN->getIterator()); 1631 NewPN->takeName(PN); 1632 NewPN->setDebugLoc(PN->getDebugLoc()); 1633 1634 // If we are going to have to insert a new computation, do so right before the 1635 // predecessor's terminator. 1636 Instruction *Clone = nullptr; 1637 if (NonSimplifiedBB) { 1638 Clone = I.clone(); 1639 for (Use &U : Clone->operands()) { 1640 if (U == PN) 1641 U = NonSimplifiedInVal; 1642 else 1643 U = U->DoPHITranslation(PN->getParent(), NonSimplifiedBB); 1644 } 1645 InsertNewInstBefore(Clone, NonSimplifiedBB->getTerminator()->getIterator()); 1646 } 1647 1648 for (unsigned i = 0; i != NumPHIValues; ++i) { 1649 if (NewPhiValues[i]) 1650 NewPN->addIncoming(NewPhiValues[i], PN->getIncomingBlock(i)); 1651 else 1652 NewPN->addIncoming(Clone, PN->getIncomingBlock(i)); 1653 } 1654 1655 for (User *U : make_early_inc_range(PN->users())) { 1656 Instruction *User = cast<Instruction>(U); 1657 if (User == &I) continue; 1658 replaceInstUsesWith(*User, NewPN); 1659 eraseInstFromFunction(*User); 1660 } 1661 1662 replaceAllDbgUsesWith(const_cast<PHINode &>(*PN), 1663 const_cast<PHINode &>(*NewPN), 1664 const_cast<PHINode &>(*PN), DT); 1665 return replaceInstUsesWith(I, NewPN); 1666 } 1667 1668 Instruction *InstCombinerImpl::foldBinopWithPhiOperands(BinaryOperator &BO) { 1669 // TODO: This should be similar to the incoming values check in foldOpIntoPhi: 1670 // we are guarding against replicating the binop in >1 predecessor. 1671 // This could miss matching a phi with 2 constant incoming values. 1672 auto *Phi0 = dyn_cast<PHINode>(BO.getOperand(0)); 1673 auto *Phi1 = dyn_cast<PHINode>(BO.getOperand(1)); 1674 if (!Phi0 || !Phi1 || !Phi0->hasOneUse() || !Phi1->hasOneUse() || 1675 Phi0->getNumOperands() != Phi1->getNumOperands()) 1676 return nullptr; 1677 1678 // TODO: Remove the restriction for binop being in the same block as the phis. 1679 if (BO.getParent() != Phi0->getParent() || 1680 BO.getParent() != Phi1->getParent()) 1681 return nullptr; 1682 1683 // Fold if there is at least one specific constant value in phi0 or phi1's 1684 // incoming values that comes from the same block and this specific constant 1685 // value can be used to do optimization for specific binary operator. 1686 // For example: 1687 // %phi0 = phi i32 [0, %bb0], [%i, %bb1] 1688 // %phi1 = phi i32 [%j, %bb0], [0, %bb1] 1689 // %add = add i32 %phi0, %phi1 1690 // ==> 1691 // %add = phi i32 [%j, %bb0], [%i, %bb1] 1692 Constant *C = ConstantExpr::getBinOpIdentity(BO.getOpcode(), BO.getType(), 1693 /*AllowRHSConstant*/ false); 1694 if (C) { 1695 SmallVector<Value *, 4> NewIncomingValues; 1696 auto CanFoldIncomingValuePair = [&](std::tuple<Use &, Use &> T) { 1697 auto &Phi0Use = std::get<0>(T); 1698 auto &Phi1Use = std::get<1>(T); 1699 if (Phi0->getIncomingBlock(Phi0Use) != Phi1->getIncomingBlock(Phi1Use)) 1700 return false; 1701 Value *Phi0UseV = Phi0Use.get(); 1702 Value *Phi1UseV = Phi1Use.get(); 1703 if (Phi0UseV == C) 1704 NewIncomingValues.push_back(Phi1UseV); 1705 else if (Phi1UseV == C) 1706 NewIncomingValues.push_back(Phi0UseV); 1707 else 1708 return false; 1709 return true; 1710 }; 1711 1712 if (all_of(zip(Phi0->operands(), Phi1->operands()), 1713 CanFoldIncomingValuePair)) { 1714 PHINode *NewPhi = 1715 PHINode::Create(Phi0->getType(), Phi0->getNumOperands()); 1716 assert(NewIncomingValues.size() == Phi0->getNumOperands() && 1717 "The number of collected incoming values should equal the number " 1718 "of the original PHINode operands!"); 1719 for (unsigned I = 0; I < Phi0->getNumOperands(); I++) 1720 NewPhi->addIncoming(NewIncomingValues[I], Phi0->getIncomingBlock(I)); 1721 return NewPhi; 1722 } 1723 } 1724 1725 if (Phi0->getNumOperands() != 2 || Phi1->getNumOperands() != 2) 1726 return nullptr; 1727 1728 // Match a pair of incoming constants for one of the predecessor blocks. 1729 BasicBlock *ConstBB, *OtherBB; 1730 Constant *C0, *C1; 1731 if (match(Phi0->getIncomingValue(0), m_ImmConstant(C0))) { 1732 ConstBB = Phi0->getIncomingBlock(0); 1733 OtherBB = Phi0->getIncomingBlock(1); 1734 } else if (match(Phi0->getIncomingValue(1), m_ImmConstant(C0))) { 1735 ConstBB = Phi0->getIncomingBlock(1); 1736 OtherBB = Phi0->getIncomingBlock(0); 1737 } else { 1738 return nullptr; 1739 } 1740 if (!match(Phi1->getIncomingValueForBlock(ConstBB), m_ImmConstant(C1))) 1741 return nullptr; 1742 1743 // The block that we are hoisting to must reach here unconditionally. 1744 // Otherwise, we could be speculatively executing an expensive or 1745 // non-speculative op. 1746 auto *PredBlockBranch = dyn_cast<BranchInst>(OtherBB->getTerminator()); 1747 if (!PredBlockBranch || PredBlockBranch->isConditional() || 1748 !DT.isReachableFromEntry(OtherBB)) 1749 return nullptr; 1750 1751 // TODO: This check could be tightened to only apply to binops (div/rem) that 1752 // are not safe to speculatively execute. But that could allow hoisting 1753 // potentially expensive instructions (fdiv for example). 1754 for (auto BBIter = BO.getParent()->begin(); &*BBIter != &BO; ++BBIter) 1755 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBIter)) 1756 return nullptr; 1757 1758 // Fold constants for the predecessor block with constant incoming values. 1759 Constant *NewC = ConstantFoldBinaryOpOperands(BO.getOpcode(), C0, C1, DL); 1760 if (!NewC) 1761 return nullptr; 1762 1763 // Make a new binop in the predecessor block with the non-constant incoming 1764 // values. 1765 Builder.SetInsertPoint(PredBlockBranch); 1766 Value *NewBO = Builder.CreateBinOp(BO.getOpcode(), 1767 Phi0->getIncomingValueForBlock(OtherBB), 1768 Phi1->getIncomingValueForBlock(OtherBB)); 1769 if (auto *NotFoldedNewBO = dyn_cast<BinaryOperator>(NewBO)) 1770 NotFoldedNewBO->copyIRFlags(&BO); 1771 1772 // Replace the binop with a phi of the new values. The old phis are dead. 1773 PHINode *NewPhi = PHINode::Create(BO.getType(), 2); 1774 NewPhi->addIncoming(NewBO, OtherBB); 1775 NewPhi->addIncoming(NewC, ConstBB); 1776 return NewPhi; 1777 } 1778 1779 Instruction *InstCombinerImpl::foldBinOpIntoSelectOrPhi(BinaryOperator &I) { 1780 if (!isa<Constant>(I.getOperand(1))) 1781 return nullptr; 1782 1783 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) { 1784 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel)) 1785 return NewSel; 1786 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) { 1787 if (Instruction *NewPhi = foldOpIntoPhi(I, PN)) 1788 return NewPhi; 1789 } 1790 return nullptr; 1791 } 1792 1793 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) { 1794 // If this GEP has only 0 indices, it is the same pointer as 1795 // Src. If Src is not a trivial GEP too, don't combine 1796 // the indices. 1797 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() && 1798 !Src.hasOneUse()) 1799 return false; 1800 return true; 1801 } 1802 1803 Instruction *InstCombinerImpl::foldVectorBinop(BinaryOperator &Inst) { 1804 if (!isa<VectorType>(Inst.getType())) 1805 return nullptr; 1806 1807 BinaryOperator::BinaryOps Opcode = Inst.getOpcode(); 1808 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1); 1809 assert(cast<VectorType>(LHS->getType())->getElementCount() == 1810 cast<VectorType>(Inst.getType())->getElementCount()); 1811 assert(cast<VectorType>(RHS->getType())->getElementCount() == 1812 cast<VectorType>(Inst.getType())->getElementCount()); 1813 1814 // If both operands of the binop are vector concatenations, then perform the 1815 // narrow binop on each pair of the source operands followed by concatenation 1816 // of the results. 1817 Value *L0, *L1, *R0, *R1; 1818 ArrayRef<int> Mask; 1819 if (match(LHS, m_Shuffle(m_Value(L0), m_Value(L1), m_Mask(Mask))) && 1820 match(RHS, m_Shuffle(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) && 1821 LHS->hasOneUse() && RHS->hasOneUse() && 1822 cast<ShuffleVectorInst>(LHS)->isConcat() && 1823 cast<ShuffleVectorInst>(RHS)->isConcat()) { 1824 // This transform does not have the speculative execution constraint as 1825 // below because the shuffle is a concatenation. The new binops are 1826 // operating on exactly the same elements as the existing binop. 1827 // TODO: We could ease the mask requirement to allow different undef lanes, 1828 // but that requires an analysis of the binop-with-undef output value. 1829 Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0); 1830 if (auto *BO = dyn_cast<BinaryOperator>(NewBO0)) 1831 BO->copyIRFlags(&Inst); 1832 Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1); 1833 if (auto *BO = dyn_cast<BinaryOperator>(NewBO1)) 1834 BO->copyIRFlags(&Inst); 1835 return new ShuffleVectorInst(NewBO0, NewBO1, Mask); 1836 } 1837 1838 auto createBinOpReverse = [&](Value *X, Value *Y) { 1839 Value *V = Builder.CreateBinOp(Opcode, X, Y, Inst.getName()); 1840 if (auto *BO = dyn_cast<BinaryOperator>(V)) 1841 BO->copyIRFlags(&Inst); 1842 Module *M = Inst.getModule(); 1843 Function *F = Intrinsic::getDeclaration( 1844 M, Intrinsic::experimental_vector_reverse, V->getType()); 1845 return CallInst::Create(F, V); 1846 }; 1847 1848 // NOTE: Reverse shuffles don't require the speculative execution protection 1849 // below because they don't affect which lanes take part in the computation. 1850 1851 Value *V1, *V2; 1852 if (match(LHS, m_VecReverse(m_Value(V1)))) { 1853 // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2)) 1854 if (match(RHS, m_VecReverse(m_Value(V2))) && 1855 (LHS->hasOneUse() || RHS->hasOneUse() || 1856 (LHS == RHS && LHS->hasNUses(2)))) 1857 return createBinOpReverse(V1, V2); 1858 1859 // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat)) 1860 if (LHS->hasOneUse() && isSplatValue(RHS)) 1861 return createBinOpReverse(V1, RHS); 1862 } 1863 // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2)) 1864 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2))))) 1865 return createBinOpReverse(LHS, V2); 1866 1867 // It may not be safe to reorder shuffles and things like div, urem, etc. 1868 // because we may trap when executing those ops on unknown vector elements. 1869 // See PR20059. 1870 if (!isSafeToSpeculativelyExecute(&Inst)) 1871 return nullptr; 1872 1873 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) { 1874 Value *XY = Builder.CreateBinOp(Opcode, X, Y); 1875 if (auto *BO = dyn_cast<BinaryOperator>(XY)) 1876 BO->copyIRFlags(&Inst); 1877 return new ShuffleVectorInst(XY, M); 1878 }; 1879 1880 // If both arguments of the binary operation are shuffles that use the same 1881 // mask and shuffle within a single vector, move the shuffle after the binop. 1882 if (match(LHS, m_Shuffle(m_Value(V1), m_Poison(), m_Mask(Mask))) && 1883 match(RHS, m_Shuffle(m_Value(V2), m_Poison(), m_SpecificMask(Mask))) && 1884 V1->getType() == V2->getType() && 1885 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) { 1886 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask) 1887 return createBinOpShuffle(V1, V2, Mask); 1888 } 1889 1890 // If both arguments of a commutative binop are select-shuffles that use the 1891 // same mask with commuted operands, the shuffles are unnecessary. 1892 if (Inst.isCommutative() && 1893 match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) && 1894 match(RHS, 1895 m_Shuffle(m_Specific(V2), m_Specific(V1), m_SpecificMask(Mask)))) { 1896 auto *LShuf = cast<ShuffleVectorInst>(LHS); 1897 auto *RShuf = cast<ShuffleVectorInst>(RHS); 1898 // TODO: Allow shuffles that contain undefs in the mask? 1899 // That is legal, but it reduces undef knowledge. 1900 // TODO: Allow arbitrary shuffles by shuffling after binop? 1901 // That might be legal, but we have to deal with poison. 1902 if (LShuf->isSelect() && 1903 !is_contained(LShuf->getShuffleMask(), PoisonMaskElem) && 1904 RShuf->isSelect() && 1905 !is_contained(RShuf->getShuffleMask(), PoisonMaskElem)) { 1906 // Example: 1907 // LHS = shuffle V1, V2, <0, 5, 6, 3> 1908 // RHS = shuffle V2, V1, <0, 5, 6, 3> 1909 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2 1910 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2); 1911 NewBO->copyIRFlags(&Inst); 1912 return NewBO; 1913 } 1914 } 1915 1916 // If one argument is a shuffle within one vector and the other is a constant, 1917 // try moving the shuffle after the binary operation. This canonicalization 1918 // intends to move shuffles closer to other shuffles and binops closer to 1919 // other binops, so they can be folded. It may also enable demanded elements 1920 // transforms. 1921 Constant *C; 1922 auto *InstVTy = dyn_cast<FixedVectorType>(Inst.getType()); 1923 if (InstVTy && 1924 match(&Inst, m_c_BinOp(m_OneUse(m_Shuffle(m_Value(V1), m_Poison(), 1925 m_Mask(Mask))), 1926 m_ImmConstant(C))) && 1927 cast<FixedVectorType>(V1->getType())->getNumElements() <= 1928 InstVTy->getNumElements()) { 1929 assert(InstVTy->getScalarType() == V1->getType()->getScalarType() && 1930 "Shuffle should not change scalar type"); 1931 1932 // Find constant NewC that has property: 1933 // shuffle(NewC, ShMask) = C 1934 // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>) 1935 // reorder is not possible. A 1-to-1 mapping is not required. Example: 1936 // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef> 1937 bool ConstOp1 = isa<Constant>(RHS); 1938 ArrayRef<int> ShMask = Mask; 1939 unsigned SrcVecNumElts = 1940 cast<FixedVectorType>(V1->getType())->getNumElements(); 1941 PoisonValue *PoisonScalar = PoisonValue::get(C->getType()->getScalarType()); 1942 SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, PoisonScalar); 1943 bool MayChange = true; 1944 unsigned NumElts = InstVTy->getNumElements(); 1945 for (unsigned I = 0; I < NumElts; ++I) { 1946 Constant *CElt = C->getAggregateElement(I); 1947 if (ShMask[I] >= 0) { 1948 assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle"); 1949 Constant *NewCElt = NewVecC[ShMask[I]]; 1950 // Bail out if: 1951 // 1. The constant vector contains a constant expression. 1952 // 2. The shuffle needs an element of the constant vector that can't 1953 // be mapped to a new constant vector. 1954 // 3. This is a widening shuffle that copies elements of V1 into the 1955 // extended elements (extending with poison is allowed). 1956 if (!CElt || (!isa<PoisonValue>(NewCElt) && NewCElt != CElt) || 1957 I >= SrcVecNumElts) { 1958 MayChange = false; 1959 break; 1960 } 1961 NewVecC[ShMask[I]] = CElt; 1962 } 1963 // If this is a widening shuffle, we must be able to extend with poison 1964 // elements. If the original binop does not produce a poison in the high 1965 // lanes, then this transform is not safe. 1966 // Similarly for poison lanes due to the shuffle mask, we can only 1967 // transform binops that preserve poison. 1968 // TODO: We could shuffle those non-poison constant values into the 1969 // result by using a constant vector (rather than an poison vector) 1970 // as operand 1 of the new binop, but that might be too aggressive 1971 // for target-independent shuffle creation. 1972 if (I >= SrcVecNumElts || ShMask[I] < 0) { 1973 Constant *MaybePoison = 1974 ConstOp1 1975 ? ConstantFoldBinaryOpOperands(Opcode, PoisonScalar, CElt, DL) 1976 : ConstantFoldBinaryOpOperands(Opcode, CElt, PoisonScalar, DL); 1977 if (!MaybePoison || !isa<PoisonValue>(MaybePoison)) { 1978 MayChange = false; 1979 break; 1980 } 1981 } 1982 } 1983 if (MayChange) { 1984 Constant *NewC = ConstantVector::get(NewVecC); 1985 // It may not be safe to execute a binop on a vector with poison elements 1986 // because the entire instruction can be folded to undef or create poison 1987 // that did not exist in the original code. 1988 // TODO: The shift case should not be necessary. 1989 if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1)) 1990 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1); 1991 1992 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask) 1993 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask) 1994 Value *NewLHS = ConstOp1 ? V1 : NewC; 1995 Value *NewRHS = ConstOp1 ? NewC : V1; 1996 return createBinOpShuffle(NewLHS, NewRHS, Mask); 1997 } 1998 } 1999 2000 // Try to reassociate to sink a splat shuffle after a binary operation. 2001 if (Inst.isAssociative() && Inst.isCommutative()) { 2002 // Canonicalize shuffle operand as LHS. 2003 if (isa<ShuffleVectorInst>(RHS)) 2004 std::swap(LHS, RHS); 2005 2006 Value *X; 2007 ArrayRef<int> MaskC; 2008 int SplatIndex; 2009 Value *Y, *OtherOp; 2010 if (!match(LHS, 2011 m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) || 2012 !match(MaskC, m_SplatOrUndefMask(SplatIndex)) || 2013 X->getType() != Inst.getType() || 2014 !match(RHS, m_OneUse(m_BinOp(Opcode, m_Value(Y), m_Value(OtherOp))))) 2015 return nullptr; 2016 2017 // FIXME: This may not be safe if the analysis allows undef elements. By 2018 // moving 'Y' before the splat shuffle, we are implicitly assuming 2019 // that it is not undef/poison at the splat index. 2020 if (isSplatValue(OtherOp, SplatIndex)) { 2021 std::swap(Y, OtherOp); 2022 } else if (!isSplatValue(Y, SplatIndex)) { 2023 return nullptr; 2024 } 2025 2026 // X and Y are splatted values, so perform the binary operation on those 2027 // values followed by a splat followed by the 2nd binary operation: 2028 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp 2029 Value *NewBO = Builder.CreateBinOp(Opcode, X, Y); 2030 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex); 2031 Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask); 2032 Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp); 2033 2034 // Intersect FMF on both new binops. Other (poison-generating) flags are 2035 // dropped to be safe. 2036 if (isa<FPMathOperator>(R)) { 2037 R->copyFastMathFlags(&Inst); 2038 R->andIRFlags(RHS); 2039 } 2040 if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO)) 2041 NewInstBO->copyIRFlags(R); 2042 return R; 2043 } 2044 2045 return nullptr; 2046 } 2047 2048 /// Try to narrow the width of a binop if at least 1 operand is an extend of 2049 /// of a value. This requires a potentially expensive known bits check to make 2050 /// sure the narrow op does not overflow. 2051 Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) { 2052 // We need at least one extended operand. 2053 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1); 2054 2055 // If this is a sub, we swap the operands since we always want an extension 2056 // on the RHS. The LHS can be an extension or a constant. 2057 if (BO.getOpcode() == Instruction::Sub) 2058 std::swap(Op0, Op1); 2059 2060 Value *X; 2061 bool IsSext = match(Op0, m_SExt(m_Value(X))); 2062 if (!IsSext && !match(Op0, m_ZExt(m_Value(X)))) 2063 return nullptr; 2064 2065 // If both operands are the same extension from the same source type and we 2066 // can eliminate at least one (hasOneUse), this might work. 2067 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt; 2068 Value *Y; 2069 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() && 2070 cast<Operator>(Op1)->getOpcode() == CastOpc && 2071 (Op0->hasOneUse() || Op1->hasOneUse()))) { 2072 // If that did not match, see if we have a suitable constant operand. 2073 // Truncating and extending must produce the same constant. 2074 Constant *WideC; 2075 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC))) 2076 return nullptr; 2077 Constant *NarrowC = getLosslessTrunc(WideC, X->getType(), CastOpc); 2078 if (!NarrowC) 2079 return nullptr; 2080 Y = NarrowC; 2081 } 2082 2083 // Swap back now that we found our operands. 2084 if (BO.getOpcode() == Instruction::Sub) 2085 std::swap(X, Y); 2086 2087 // Both operands have narrow versions. Last step: the math must not overflow 2088 // in the narrow width. 2089 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext)) 2090 return nullptr; 2091 2092 // bo (ext X), (ext Y) --> ext (bo X, Y) 2093 // bo (ext X), C --> ext (bo X, C') 2094 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow"); 2095 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) { 2096 if (IsSext) 2097 NewBinOp->setHasNoSignedWrap(); 2098 else 2099 NewBinOp->setHasNoUnsignedWrap(); 2100 } 2101 return CastInst::Create(CastOpc, NarrowBO, BO.getType()); 2102 } 2103 2104 static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2) { 2105 // At least one GEP must be inbounds. 2106 if (!GEP1.isInBounds() && !GEP2.isInBounds()) 2107 return false; 2108 2109 return (GEP1.isInBounds() || GEP1.hasAllZeroIndices()) && 2110 (GEP2.isInBounds() || GEP2.hasAllZeroIndices()); 2111 } 2112 2113 /// Thread a GEP operation with constant indices through the constant true/false 2114 /// arms of a select. 2115 static Instruction *foldSelectGEP(GetElementPtrInst &GEP, 2116 InstCombiner::BuilderTy &Builder) { 2117 if (!GEP.hasAllConstantIndices()) 2118 return nullptr; 2119 2120 Instruction *Sel; 2121 Value *Cond; 2122 Constant *TrueC, *FalseC; 2123 if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) || 2124 !match(Sel, 2125 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC)))) 2126 return nullptr; 2127 2128 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC' 2129 // Propagate 'inbounds' and metadata from existing instructions. 2130 // Note: using IRBuilder to create the constants for efficiency. 2131 SmallVector<Value *, 4> IndexC(GEP.indices()); 2132 bool IsInBounds = GEP.isInBounds(); 2133 Type *Ty = GEP.getSourceElementType(); 2134 Value *NewTrueC = Builder.CreateGEP(Ty, TrueC, IndexC, "", IsInBounds); 2135 Value *NewFalseC = Builder.CreateGEP(Ty, FalseC, IndexC, "", IsInBounds); 2136 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel); 2137 } 2138 2139 Instruction *InstCombinerImpl::visitGEPOfGEP(GetElementPtrInst &GEP, 2140 GEPOperator *Src) { 2141 // Combine Indices - If the source pointer to this getelementptr instruction 2142 // is a getelementptr instruction with matching element type, combine the 2143 // indices of the two getelementptr instructions into a single instruction. 2144 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src)) 2145 return nullptr; 2146 2147 // For constant GEPs, use a more general offset-based folding approach. 2148 Type *PtrTy = Src->getType()->getScalarType(); 2149 if (GEP.hasAllConstantIndices() && 2150 (Src->hasOneUse() || Src->hasAllConstantIndices())) { 2151 // Split Src into a variable part and a constant suffix. 2152 gep_type_iterator GTI = gep_type_begin(*Src); 2153 Type *BaseType = GTI.getIndexedType(); 2154 bool IsFirstType = true; 2155 unsigned NumVarIndices = 0; 2156 for (auto Pair : enumerate(Src->indices())) { 2157 if (!isa<ConstantInt>(Pair.value())) { 2158 BaseType = GTI.getIndexedType(); 2159 IsFirstType = false; 2160 NumVarIndices = Pair.index() + 1; 2161 } 2162 ++GTI; 2163 } 2164 2165 // Determine the offset for the constant suffix of Src. 2166 APInt Offset(DL.getIndexTypeSizeInBits(PtrTy), 0); 2167 if (NumVarIndices != Src->getNumIndices()) { 2168 // FIXME: getIndexedOffsetInType() does not handled scalable vectors. 2169 if (BaseType->isScalableTy()) 2170 return nullptr; 2171 2172 SmallVector<Value *> ConstantIndices; 2173 if (!IsFirstType) 2174 ConstantIndices.push_back( 2175 Constant::getNullValue(Type::getInt32Ty(GEP.getContext()))); 2176 append_range(ConstantIndices, drop_begin(Src->indices(), NumVarIndices)); 2177 Offset += DL.getIndexedOffsetInType(BaseType, ConstantIndices); 2178 } 2179 2180 // Add the offset for GEP (which is fully constant). 2181 if (!GEP.accumulateConstantOffset(DL, Offset)) 2182 return nullptr; 2183 2184 APInt OffsetOld = Offset; 2185 // Convert the total offset back into indices. 2186 SmallVector<APInt> ConstIndices = 2187 DL.getGEPIndicesForOffset(BaseType, Offset); 2188 if (!Offset.isZero() || (!IsFirstType && !ConstIndices[0].isZero())) { 2189 // If both GEP are constant-indexed, and cannot be merged in either way, 2190 // convert them to a GEP of i8. 2191 if (Src->hasAllConstantIndices()) 2192 return replaceInstUsesWith( 2193 GEP, Builder.CreateGEP( 2194 Builder.getInt8Ty(), Src->getOperand(0), 2195 Builder.getInt(OffsetOld), "", 2196 isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)))); 2197 return nullptr; 2198 } 2199 2200 bool IsInBounds = isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)); 2201 SmallVector<Value *> Indices; 2202 append_range(Indices, drop_end(Src->indices(), 2203 Src->getNumIndices() - NumVarIndices)); 2204 for (const APInt &Idx : drop_begin(ConstIndices, !IsFirstType)) { 2205 Indices.push_back(ConstantInt::get(GEP.getContext(), Idx)); 2206 // Even if the total offset is inbounds, we may end up representing it 2207 // by first performing a larger negative offset, and then a smaller 2208 // positive one. The large negative offset might go out of bounds. Only 2209 // preserve inbounds if all signs are the same. 2210 IsInBounds &= Idx.isNonNegative() == ConstIndices[0].isNonNegative(); 2211 } 2212 2213 return replaceInstUsesWith( 2214 GEP, Builder.CreateGEP(Src->getSourceElementType(), Src->getOperand(0), 2215 Indices, "", IsInBounds)); 2216 } 2217 2218 if (Src->getResultElementType() != GEP.getSourceElementType()) 2219 return nullptr; 2220 2221 SmallVector<Value*, 8> Indices; 2222 2223 // Find out whether the last index in the source GEP is a sequential idx. 2224 bool EndsWithSequential = false; 2225 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 2226 I != E; ++I) 2227 EndsWithSequential = I.isSequential(); 2228 2229 // Can we combine the two pointer arithmetics offsets? 2230 if (EndsWithSequential) { 2231 // Replace: gep (gep %P, long B), long A, ... 2232 // With: T = long A+B; gep %P, T, ... 2233 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 2234 Value *GO1 = GEP.getOperand(1); 2235 2236 // If they aren't the same type, then the input hasn't been processed 2237 // by the loop above yet (which canonicalizes sequential index types to 2238 // intptr_t). Just avoid transforming this until the input has been 2239 // normalized. 2240 if (SO1->getType() != GO1->getType()) 2241 return nullptr; 2242 2243 Value *Sum = 2244 simplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP)); 2245 // Only do the combine when we are sure the cost after the 2246 // merge is never more than that before the merge. 2247 if (Sum == nullptr) 2248 return nullptr; 2249 2250 // Update the GEP in place if possible. 2251 if (Src->getNumOperands() == 2) { 2252 GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))); 2253 replaceOperand(GEP, 0, Src->getOperand(0)); 2254 replaceOperand(GEP, 1, Sum); 2255 return &GEP; 2256 } 2257 Indices.append(Src->op_begin()+1, Src->op_end()-1); 2258 Indices.push_back(Sum); 2259 Indices.append(GEP.op_begin()+2, GEP.op_end()); 2260 } else if (isa<Constant>(*GEP.idx_begin()) && 2261 cast<Constant>(*GEP.idx_begin())->isNullValue() && 2262 Src->getNumOperands() != 1) { 2263 // Otherwise we can do the fold if the first index of the GEP is a zero 2264 Indices.append(Src->op_begin()+1, Src->op_end()); 2265 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 2266 } 2267 2268 if (!Indices.empty()) 2269 return replaceInstUsesWith( 2270 GEP, Builder.CreateGEP( 2271 Src->getSourceElementType(), Src->getOperand(0), Indices, "", 2272 isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)))); 2273 2274 return nullptr; 2275 } 2276 2277 Value *InstCombiner::getFreelyInvertedImpl(Value *V, bool WillInvertAllUses, 2278 BuilderTy *Builder, 2279 bool &DoesConsume, unsigned Depth) { 2280 static Value *const NonNull = reinterpret_cast<Value *>(uintptr_t(1)); 2281 // ~(~(X)) -> X. 2282 Value *A, *B; 2283 if (match(V, m_Not(m_Value(A)))) { 2284 DoesConsume = true; 2285 return A; 2286 } 2287 2288 Constant *C; 2289 // Constants can be considered to be not'ed values. 2290 if (match(V, m_ImmConstant(C))) 2291 return ConstantExpr::getNot(C); 2292 2293 if (Depth++ >= MaxAnalysisRecursionDepth) 2294 return nullptr; 2295 2296 // The rest of the cases require that we invert all uses so don't bother 2297 // doing the analysis if we know we can't use the result. 2298 if (!WillInvertAllUses) 2299 return nullptr; 2300 2301 // Compares can be inverted if all of their uses are being modified to use 2302 // the ~V. 2303 if (auto *I = dyn_cast<CmpInst>(V)) { 2304 if (Builder != nullptr) 2305 return Builder->CreateCmp(I->getInversePredicate(), I->getOperand(0), 2306 I->getOperand(1)); 2307 return NonNull; 2308 } 2309 2310 // If `V` is of the form `A + B` then `-1 - V` can be folded into 2311 // `(-1 - B) - A` if we are willing to invert all of the uses. 2312 if (match(V, m_Add(m_Value(A), m_Value(B)))) { 2313 if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder, 2314 DoesConsume, Depth)) 2315 return Builder ? Builder->CreateSub(BV, A) : NonNull; 2316 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder, 2317 DoesConsume, Depth)) 2318 return Builder ? Builder->CreateSub(AV, B) : NonNull; 2319 return nullptr; 2320 } 2321 2322 // If `V` is of the form `A ^ ~B` then `~(A ^ ~B)` can be folded 2323 // into `A ^ B` if we are willing to invert all of the uses. 2324 if (match(V, m_Xor(m_Value(A), m_Value(B)))) { 2325 if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder, 2326 DoesConsume, Depth)) 2327 return Builder ? Builder->CreateXor(A, BV) : NonNull; 2328 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder, 2329 DoesConsume, Depth)) 2330 return Builder ? Builder->CreateXor(AV, B) : NonNull; 2331 return nullptr; 2332 } 2333 2334 // If `V` is of the form `B - A` then `-1 - V` can be folded into 2335 // `A + (-1 - B)` if we are willing to invert all of the uses. 2336 if (match(V, m_Sub(m_Value(A), m_Value(B)))) { 2337 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder, 2338 DoesConsume, Depth)) 2339 return Builder ? Builder->CreateAdd(AV, B) : NonNull; 2340 return nullptr; 2341 } 2342 2343 // If `V` is of the form `(~A) s>> B` then `~((~A) s>> B)` can be folded 2344 // into `A s>> B` if we are willing to invert all of the uses. 2345 if (match(V, m_AShr(m_Value(A), m_Value(B)))) { 2346 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder, 2347 DoesConsume, Depth)) 2348 return Builder ? Builder->CreateAShr(AV, B) : NonNull; 2349 return nullptr; 2350 } 2351 2352 Value *Cond; 2353 // LogicOps are special in that we canonicalize them at the cost of an 2354 // instruction. 2355 bool IsSelect = match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) && 2356 !shouldAvoidAbsorbingNotIntoSelect(*cast<SelectInst>(V)); 2357 // Selects/min/max with invertible operands are freely invertible 2358 if (IsSelect || match(V, m_MaxOrMin(m_Value(A), m_Value(B)))) { 2359 if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder*/ nullptr, 2360 DoesConsume, Depth)) 2361 return nullptr; 2362 if (Value *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder, 2363 DoesConsume, Depth)) { 2364 if (Builder != nullptr) { 2365 Value *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder, 2366 DoesConsume, Depth); 2367 assert(NotB != nullptr && 2368 "Unable to build inverted value for known freely invertable op"); 2369 if (auto *II = dyn_cast<IntrinsicInst>(V)) 2370 return Builder->CreateBinaryIntrinsic( 2371 getInverseMinMaxIntrinsic(II->getIntrinsicID()), NotA, NotB); 2372 return Builder->CreateSelect(Cond, NotA, NotB); 2373 } 2374 return NonNull; 2375 } 2376 } 2377 2378 return nullptr; 2379 } 2380 2381 Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) { 2382 Value *PtrOp = GEP.getOperand(0); 2383 SmallVector<Value *, 8> Indices(GEP.indices()); 2384 Type *GEPType = GEP.getType(); 2385 Type *GEPEltType = GEP.getSourceElementType(); 2386 bool IsGEPSrcEleScalable = GEPEltType->isScalableTy(); 2387 if (Value *V = simplifyGEPInst(GEPEltType, PtrOp, Indices, GEP.isInBounds(), 2388 SQ.getWithInstruction(&GEP))) 2389 return replaceInstUsesWith(GEP, V); 2390 2391 // For vector geps, use the generic demanded vector support. 2392 // Skip if GEP return type is scalable. The number of elements is unknown at 2393 // compile-time. 2394 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) { 2395 auto VWidth = GEPFVTy->getNumElements(); 2396 APInt PoisonElts(VWidth, 0); 2397 APInt AllOnesEltMask(APInt::getAllOnes(VWidth)); 2398 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask, 2399 PoisonElts)) { 2400 if (V != &GEP) 2401 return replaceInstUsesWith(GEP, V); 2402 return &GEP; 2403 } 2404 2405 // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if 2406 // possible (decide on canonical form for pointer broadcast), 3) exploit 2407 // undef elements to decrease demanded bits 2408 } 2409 2410 // Eliminate unneeded casts for indices, and replace indices which displace 2411 // by multiples of a zero size type with zero. 2412 bool MadeChange = false; 2413 2414 // Index width may not be the same width as pointer width. 2415 // Data layout chooses the right type based on supported integer types. 2416 Type *NewScalarIndexTy = 2417 DL.getIndexType(GEP.getPointerOperandType()->getScalarType()); 2418 2419 gep_type_iterator GTI = gep_type_begin(GEP); 2420 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E; 2421 ++I, ++GTI) { 2422 // Skip indices into struct types. 2423 if (GTI.isStruct()) 2424 continue; 2425 2426 Type *IndexTy = (*I)->getType(); 2427 Type *NewIndexType = 2428 IndexTy->isVectorTy() 2429 ? VectorType::get(NewScalarIndexTy, 2430 cast<VectorType>(IndexTy)->getElementCount()) 2431 : NewScalarIndexTy; 2432 2433 // If the element type has zero size then any index over it is equivalent 2434 // to an index of zero, so replace it with zero if it is not zero already. 2435 Type *EltTy = GTI.getIndexedType(); 2436 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero()) 2437 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) { 2438 *I = Constant::getNullValue(NewIndexType); 2439 MadeChange = true; 2440 } 2441 2442 if (IndexTy != NewIndexType) { 2443 // If we are using a wider index than needed for this platform, shrink 2444 // it to what we need. If narrower, sign-extend it to what we need. 2445 // This explicit cast can make subsequent optimizations more obvious. 2446 *I = Builder.CreateIntCast(*I, NewIndexType, true); 2447 MadeChange = true; 2448 } 2449 } 2450 if (MadeChange) 2451 return &GEP; 2452 2453 // Check to see if the inputs to the PHI node are getelementptr instructions. 2454 if (auto *PN = dyn_cast<PHINode>(PtrOp)) { 2455 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0)); 2456 if (!Op1) 2457 return nullptr; 2458 2459 // Don't fold a GEP into itself through a PHI node. This can only happen 2460 // through the back-edge of a loop. Folding a GEP into itself means that 2461 // the value of the previous iteration needs to be stored in the meantime, 2462 // thus requiring an additional register variable to be live, but not 2463 // actually achieving anything (the GEP still needs to be executed once per 2464 // loop iteration). 2465 if (Op1 == &GEP) 2466 return nullptr; 2467 2468 int DI = -1; 2469 2470 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) { 2471 auto *Op2 = dyn_cast<GetElementPtrInst>(*I); 2472 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands() || 2473 Op1->getSourceElementType() != Op2->getSourceElementType()) 2474 return nullptr; 2475 2476 // As for Op1 above, don't try to fold a GEP into itself. 2477 if (Op2 == &GEP) 2478 return nullptr; 2479 2480 // Keep track of the type as we walk the GEP. 2481 Type *CurTy = nullptr; 2482 2483 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) { 2484 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType()) 2485 return nullptr; 2486 2487 if (Op1->getOperand(J) != Op2->getOperand(J)) { 2488 if (DI == -1) { 2489 // We have not seen any differences yet in the GEPs feeding the 2490 // PHI yet, so we record this one if it is allowed to be a 2491 // variable. 2492 2493 // The first two arguments can vary for any GEP, the rest have to be 2494 // static for struct slots 2495 if (J > 1) { 2496 assert(CurTy && "No current type?"); 2497 if (CurTy->isStructTy()) 2498 return nullptr; 2499 } 2500 2501 DI = J; 2502 } else { 2503 // The GEP is different by more than one input. While this could be 2504 // extended to support GEPs that vary by more than one variable it 2505 // doesn't make sense since it greatly increases the complexity and 2506 // would result in an R+R+R addressing mode which no backend 2507 // directly supports and would need to be broken into several 2508 // simpler instructions anyway. 2509 return nullptr; 2510 } 2511 } 2512 2513 // Sink down a layer of the type for the next iteration. 2514 if (J > 0) { 2515 if (J == 1) { 2516 CurTy = Op1->getSourceElementType(); 2517 } else { 2518 CurTy = 2519 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J)); 2520 } 2521 } 2522 } 2523 } 2524 2525 // If not all GEPs are identical we'll have to create a new PHI node. 2526 // Check that the old PHI node has only one use so that it will get 2527 // removed. 2528 if (DI != -1 && !PN->hasOneUse()) 2529 return nullptr; 2530 2531 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone()); 2532 if (DI == -1) { 2533 // All the GEPs feeding the PHI are identical. Clone one down into our 2534 // BB so that it can be merged with the current GEP. 2535 } else { 2536 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP 2537 // into the current block so it can be merged, and create a new PHI to 2538 // set that index. 2539 PHINode *NewPN; 2540 { 2541 IRBuilderBase::InsertPointGuard Guard(Builder); 2542 Builder.SetInsertPoint(PN); 2543 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(), 2544 PN->getNumOperands()); 2545 } 2546 2547 for (auto &I : PN->operands()) 2548 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI), 2549 PN->getIncomingBlock(I)); 2550 2551 NewGEP->setOperand(DI, NewPN); 2552 } 2553 2554 NewGEP->insertBefore(*GEP.getParent(), GEP.getParent()->getFirstInsertionPt()); 2555 return replaceOperand(GEP, 0, NewGEP); 2556 } 2557 2558 if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) 2559 if (Instruction *I = visitGEPOfGEP(GEP, Src)) 2560 return I; 2561 2562 // Skip if GEP source element type is scalable. The type alloc size is unknown 2563 // at compile-time. 2564 if (GEP.getNumIndices() == 1 && !IsGEPSrcEleScalable) { 2565 unsigned AS = GEP.getPointerAddressSpace(); 2566 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() == 2567 DL.getIndexSizeInBits(AS)) { 2568 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedValue(); 2569 2570 if (TyAllocSize == 1) { 2571 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y), 2572 // but only if the result pointer is only used as if it were an integer, 2573 // or both point to the same underlying object (otherwise provenance is 2574 // not necessarily retained). 2575 Value *X = GEP.getPointerOperand(); 2576 Value *Y; 2577 if (match(GEP.getOperand(1), 2578 m_Sub(m_PtrToInt(m_Value(Y)), m_PtrToInt(m_Specific(X)))) && 2579 GEPType == Y->getType()) { 2580 bool HasSameUnderlyingObject = 2581 getUnderlyingObject(X) == getUnderlyingObject(Y); 2582 bool Changed = false; 2583 GEP.replaceUsesWithIf(Y, [&](Use &U) { 2584 bool ShouldReplace = HasSameUnderlyingObject || 2585 isa<ICmpInst>(U.getUser()) || 2586 isa<PtrToIntInst>(U.getUser()); 2587 Changed |= ShouldReplace; 2588 return ShouldReplace; 2589 }); 2590 return Changed ? &GEP : nullptr; 2591 } 2592 } else { 2593 // Canonicalize (gep T* X, V / sizeof(T)) to (gep i8* X, V) 2594 Value *V; 2595 if ((has_single_bit(TyAllocSize) && 2596 match(GEP.getOperand(1), 2597 m_Exact(m_Shr(m_Value(V), 2598 m_SpecificInt(countr_zero(TyAllocSize)))))) || 2599 match(GEP.getOperand(1), 2600 m_Exact(m_IDiv(m_Value(V), m_SpecificInt(TyAllocSize))))) { 2601 GetElementPtrInst *NewGEP = GetElementPtrInst::Create( 2602 Builder.getInt8Ty(), GEP.getPointerOperand(), V); 2603 NewGEP->setIsInBounds(GEP.isInBounds()); 2604 return NewGEP; 2605 } 2606 } 2607 } 2608 } 2609 // We do not handle pointer-vector geps here. 2610 if (GEPType->isVectorTy()) 2611 return nullptr; 2612 2613 if (GEP.getNumIndices() == 1) { 2614 // Try to replace ADD + GEP with GEP + GEP. 2615 Value *Idx1, *Idx2; 2616 if (match(GEP.getOperand(1), 2617 m_OneUse(m_Add(m_Value(Idx1), m_Value(Idx2))))) { 2618 // %idx = add i64 %idx1, %idx2 2619 // %gep = getelementptr i32, ptr %ptr, i64 %idx 2620 // as: 2621 // %newptr = getelementptr i32, ptr %ptr, i64 %idx1 2622 // %newgep = getelementptr i32, ptr %newptr, i64 %idx2 2623 auto *NewPtr = Builder.CreateGEP(GEP.getResultElementType(), 2624 GEP.getPointerOperand(), Idx1); 2625 return GetElementPtrInst::Create(GEP.getResultElementType(), NewPtr, 2626 Idx2); 2627 } 2628 ConstantInt *C; 2629 if (match(GEP.getOperand(1), m_OneUse(m_SExtLike(m_OneUse(m_NSWAdd( 2630 m_Value(Idx1), m_ConstantInt(C))))))) { 2631 // %add = add nsw i32 %idx1, idx2 2632 // %sidx = sext i32 %add to i64 2633 // %gep = getelementptr i32, ptr %ptr, i64 %sidx 2634 // as: 2635 // %newptr = getelementptr i32, ptr %ptr, i32 %idx1 2636 // %newgep = getelementptr i32, ptr %newptr, i32 idx2 2637 auto *NewPtr = Builder.CreateGEP( 2638 GEP.getResultElementType(), GEP.getPointerOperand(), 2639 Builder.CreateSExt(Idx1, GEP.getOperand(1)->getType())); 2640 return GetElementPtrInst::Create( 2641 GEP.getResultElementType(), NewPtr, 2642 Builder.CreateSExt(C, GEP.getOperand(1)->getType())); 2643 } 2644 } 2645 2646 if (!GEP.isInBounds()) { 2647 unsigned IdxWidth = 2648 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace()); 2649 APInt BasePtrOffset(IdxWidth, 0); 2650 Value *UnderlyingPtrOp = 2651 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, 2652 BasePtrOffset); 2653 bool CanBeNull, CanBeFreed; 2654 uint64_t DerefBytes = UnderlyingPtrOp->getPointerDereferenceableBytes( 2655 DL, CanBeNull, CanBeFreed); 2656 if (!CanBeNull && !CanBeFreed && DerefBytes != 0) { 2657 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) && 2658 BasePtrOffset.isNonNegative()) { 2659 APInt AllocSize(IdxWidth, DerefBytes); 2660 if (BasePtrOffset.ule(AllocSize)) { 2661 return GetElementPtrInst::CreateInBounds( 2662 GEP.getSourceElementType(), PtrOp, Indices, GEP.getName()); 2663 } 2664 } 2665 } 2666 } 2667 2668 if (Instruction *R = foldSelectGEP(GEP, Builder)) 2669 return R; 2670 2671 return nullptr; 2672 } 2673 2674 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo &TLI, 2675 Instruction *AI) { 2676 if (isa<ConstantPointerNull>(V)) 2677 return true; 2678 if (auto *LI = dyn_cast<LoadInst>(V)) 2679 return isa<GlobalVariable>(LI->getPointerOperand()); 2680 // Two distinct allocations will never be equal. 2681 return isAllocLikeFn(V, &TLI) && V != AI; 2682 } 2683 2684 /// Given a call CB which uses an address UsedV, return true if we can prove the 2685 /// call's only possible effect is storing to V. 2686 static bool isRemovableWrite(CallBase &CB, Value *UsedV, 2687 const TargetLibraryInfo &TLI) { 2688 if (!CB.use_empty()) 2689 // TODO: add recursion if returned attribute is present 2690 return false; 2691 2692 if (CB.isTerminator()) 2693 // TODO: remove implementation restriction 2694 return false; 2695 2696 if (!CB.willReturn() || !CB.doesNotThrow()) 2697 return false; 2698 2699 // If the only possible side effect of the call is writing to the alloca, 2700 // and the result isn't used, we can safely remove any reads implied by the 2701 // call including those which might read the alloca itself. 2702 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(&CB, TLI); 2703 return Dest && Dest->Ptr == UsedV; 2704 } 2705 2706 static bool isAllocSiteRemovable(Instruction *AI, 2707 SmallVectorImpl<WeakTrackingVH> &Users, 2708 const TargetLibraryInfo &TLI) { 2709 SmallVector<Instruction*, 4> Worklist; 2710 const std::optional<StringRef> Family = getAllocationFamily(AI, &TLI); 2711 Worklist.push_back(AI); 2712 2713 do { 2714 Instruction *PI = Worklist.pop_back_val(); 2715 for (User *U : PI->users()) { 2716 Instruction *I = cast<Instruction>(U); 2717 switch (I->getOpcode()) { 2718 default: 2719 // Give up the moment we see something we can't handle. 2720 return false; 2721 2722 case Instruction::AddrSpaceCast: 2723 case Instruction::BitCast: 2724 case Instruction::GetElementPtr: 2725 Users.emplace_back(I); 2726 Worklist.push_back(I); 2727 continue; 2728 2729 case Instruction::ICmp: { 2730 ICmpInst *ICI = cast<ICmpInst>(I); 2731 // We can fold eq/ne comparisons with null to false/true, respectively. 2732 // We also fold comparisons in some conditions provided the alloc has 2733 // not escaped (see isNeverEqualToUnescapedAlloc). 2734 if (!ICI->isEquality()) 2735 return false; 2736 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0; 2737 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI)) 2738 return false; 2739 2740 // Do not fold compares to aligned_alloc calls, as they may have to 2741 // return null in case the required alignment cannot be satisfied, 2742 // unless we can prove that both alignment and size are valid. 2743 auto AlignmentAndSizeKnownValid = [](CallBase *CB) { 2744 // Check if alignment and size of a call to aligned_alloc is valid, 2745 // that is alignment is a power-of-2 and the size is a multiple of the 2746 // alignment. 2747 const APInt *Alignment; 2748 const APInt *Size; 2749 return match(CB->getArgOperand(0), m_APInt(Alignment)) && 2750 match(CB->getArgOperand(1), m_APInt(Size)) && 2751 Alignment->isPowerOf2() && Size->urem(*Alignment).isZero(); 2752 }; 2753 auto *CB = dyn_cast<CallBase>(AI); 2754 LibFunc TheLibFunc; 2755 if (CB && TLI.getLibFunc(*CB->getCalledFunction(), TheLibFunc) && 2756 TLI.has(TheLibFunc) && TheLibFunc == LibFunc_aligned_alloc && 2757 !AlignmentAndSizeKnownValid(CB)) 2758 return false; 2759 Users.emplace_back(I); 2760 continue; 2761 } 2762 2763 case Instruction::Call: 2764 // Ignore no-op and store intrinsics. 2765 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2766 switch (II->getIntrinsicID()) { 2767 default: 2768 return false; 2769 2770 case Intrinsic::memmove: 2771 case Intrinsic::memcpy: 2772 case Intrinsic::memset: { 2773 MemIntrinsic *MI = cast<MemIntrinsic>(II); 2774 if (MI->isVolatile() || MI->getRawDest() != PI) 2775 return false; 2776 [[fallthrough]]; 2777 } 2778 case Intrinsic::assume: 2779 case Intrinsic::invariant_start: 2780 case Intrinsic::invariant_end: 2781 case Intrinsic::lifetime_start: 2782 case Intrinsic::lifetime_end: 2783 case Intrinsic::objectsize: 2784 Users.emplace_back(I); 2785 continue; 2786 case Intrinsic::launder_invariant_group: 2787 case Intrinsic::strip_invariant_group: 2788 Users.emplace_back(I); 2789 Worklist.push_back(I); 2790 continue; 2791 } 2792 } 2793 2794 if (isRemovableWrite(*cast<CallBase>(I), PI, TLI)) { 2795 Users.emplace_back(I); 2796 continue; 2797 } 2798 2799 if (getFreedOperand(cast<CallBase>(I), &TLI) == PI && 2800 getAllocationFamily(I, &TLI) == Family) { 2801 assert(Family); 2802 Users.emplace_back(I); 2803 continue; 2804 } 2805 2806 if (getReallocatedOperand(cast<CallBase>(I)) == PI && 2807 getAllocationFamily(I, &TLI) == Family) { 2808 assert(Family); 2809 Users.emplace_back(I); 2810 Worklist.push_back(I); 2811 continue; 2812 } 2813 2814 return false; 2815 2816 case Instruction::Store: { 2817 StoreInst *SI = cast<StoreInst>(I); 2818 if (SI->isVolatile() || SI->getPointerOperand() != PI) 2819 return false; 2820 Users.emplace_back(I); 2821 continue; 2822 } 2823 } 2824 llvm_unreachable("missing a return?"); 2825 } 2826 } while (!Worklist.empty()); 2827 return true; 2828 } 2829 2830 Instruction *InstCombinerImpl::visitAllocSite(Instruction &MI) { 2831 assert(isa<AllocaInst>(MI) || isRemovableAlloc(&cast<CallBase>(MI), &TLI)); 2832 2833 // If we have a malloc call which is only used in any amount of comparisons to 2834 // null and free calls, delete the calls and replace the comparisons with true 2835 // or false as appropriate. 2836 2837 // This is based on the principle that we can substitute our own allocation 2838 // function (which will never return null) rather than knowledge of the 2839 // specific function being called. In some sense this can change the permitted 2840 // outputs of a program (when we convert a malloc to an alloca, the fact that 2841 // the allocation is now on the stack is potentially visible, for example), 2842 // but we believe in a permissible manner. 2843 SmallVector<WeakTrackingVH, 64> Users; 2844 2845 // If we are removing an alloca with a dbg.declare, insert dbg.value calls 2846 // before each store. 2847 SmallVector<DbgVariableIntrinsic *, 8> DVIs; 2848 SmallVector<DPValue *, 8> DPVs; 2849 std::unique_ptr<DIBuilder> DIB; 2850 if (isa<AllocaInst>(MI)) { 2851 findDbgUsers(DVIs, &MI, &DPVs); 2852 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false)); 2853 } 2854 2855 if (isAllocSiteRemovable(&MI, Users, TLI)) { 2856 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2857 // Lowering all @llvm.objectsize calls first because they may 2858 // use a bitcast/GEP of the alloca we are removing. 2859 if (!Users[i]) 2860 continue; 2861 2862 Instruction *I = cast<Instruction>(&*Users[i]); 2863 2864 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2865 if (II->getIntrinsicID() == Intrinsic::objectsize) { 2866 SmallVector<Instruction *> InsertedInstructions; 2867 Value *Result = lowerObjectSizeCall( 2868 II, DL, &TLI, AA, /*MustSucceed=*/true, &InsertedInstructions); 2869 for (Instruction *Inserted : InsertedInstructions) 2870 Worklist.add(Inserted); 2871 replaceInstUsesWith(*I, Result); 2872 eraseInstFromFunction(*I); 2873 Users[i] = nullptr; // Skip examining in the next loop. 2874 } 2875 } 2876 } 2877 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2878 if (!Users[i]) 2879 continue; 2880 2881 Instruction *I = cast<Instruction>(&*Users[i]); 2882 2883 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) { 2884 replaceInstUsesWith(*C, 2885 ConstantInt::get(Type::getInt1Ty(C->getContext()), 2886 C->isFalseWhenEqual())); 2887 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 2888 for (auto *DVI : DVIs) 2889 if (DVI->isAddressOfVariable()) 2890 ConvertDebugDeclareToDebugValue(DVI, SI, *DIB); 2891 for (auto *DPV : DPVs) 2892 if (DPV->isAddressOfVariable()) 2893 ConvertDebugDeclareToDebugValue(DPV, SI, *DIB); 2894 } else { 2895 // Casts, GEP, or anything else: we're about to delete this instruction, 2896 // so it can not have any valid uses. 2897 replaceInstUsesWith(*I, PoisonValue::get(I->getType())); 2898 } 2899 eraseInstFromFunction(*I); 2900 } 2901 2902 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) { 2903 // Replace invoke with a NOP intrinsic to maintain the original CFG 2904 Module *M = II->getModule(); 2905 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing); 2906 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(), 2907 std::nullopt, "", II->getParent()); 2908 } 2909 2910 // Remove debug intrinsics which describe the value contained within the 2911 // alloca. In addition to removing dbg.{declare,addr} which simply point to 2912 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.: 2913 // 2914 // ``` 2915 // define void @foo(i32 %0) { 2916 // %a = alloca i32 ; Deleted. 2917 // store i32 %0, i32* %a 2918 // dbg.value(i32 %0, "arg0") ; Not deleted. 2919 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted. 2920 // call void @trivially_inlinable_no_op(i32* %a) 2921 // ret void 2922 // } 2923 // ``` 2924 // 2925 // This may not be required if we stop describing the contents of allocas 2926 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in 2927 // the LowerDbgDeclare utility. 2928 // 2929 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the 2930 // "arg0" dbg.value may be stale after the call. However, failing to remove 2931 // the DW_OP_deref dbg.value causes large gaps in location coverage. 2932 // 2933 // FIXME: the Assignment Tracking project has now likely made this 2934 // redundant (and it's sometimes harmful). 2935 for (auto *DVI : DVIs) 2936 if (DVI->isAddressOfVariable() || DVI->getExpression()->startsWithDeref()) 2937 DVI->eraseFromParent(); 2938 for (auto *DPV : DPVs) 2939 if (DPV->isAddressOfVariable() || DPV->getExpression()->startsWithDeref()) 2940 DPV->eraseFromParent(); 2941 2942 return eraseInstFromFunction(MI); 2943 } 2944 return nullptr; 2945 } 2946 2947 /// Move the call to free before a NULL test. 2948 /// 2949 /// Check if this free is accessed after its argument has been test 2950 /// against NULL (property 0). 2951 /// If yes, it is legal to move this call in its predecessor block. 2952 /// 2953 /// The move is performed only if the block containing the call to free 2954 /// will be removed, i.e.: 2955 /// 1. it has only one predecessor P, and P has two successors 2956 /// 2. it contains the call, noops, and an unconditional branch 2957 /// 3. its successor is the same as its predecessor's successor 2958 /// 2959 /// The profitability is out-of concern here and this function should 2960 /// be called only if the caller knows this transformation would be 2961 /// profitable (e.g., for code size). 2962 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI, 2963 const DataLayout &DL) { 2964 Value *Op = FI.getArgOperand(0); 2965 BasicBlock *FreeInstrBB = FI.getParent(); 2966 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor(); 2967 2968 // Validate part of constraint #1: Only one predecessor 2969 // FIXME: We can extend the number of predecessor, but in that case, we 2970 // would duplicate the call to free in each predecessor and it may 2971 // not be profitable even for code size. 2972 if (!PredBB) 2973 return nullptr; 2974 2975 // Validate constraint #2: Does this block contains only the call to 2976 // free, noops, and an unconditional branch? 2977 BasicBlock *SuccBB; 2978 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator(); 2979 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB))) 2980 return nullptr; 2981 2982 // If there are only 2 instructions in the block, at this point, 2983 // this is the call to free and unconditional. 2984 // If there are more than 2 instructions, check that they are noops 2985 // i.e., they won't hurt the performance of the generated code. 2986 if (FreeInstrBB->size() != 2) { 2987 for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) { 2988 if (&Inst == &FI || &Inst == FreeInstrBBTerminator) 2989 continue; 2990 auto *Cast = dyn_cast<CastInst>(&Inst); 2991 if (!Cast || !Cast->isNoopCast(DL)) 2992 return nullptr; 2993 } 2994 } 2995 // Validate the rest of constraint #1 by matching on the pred branch. 2996 Instruction *TI = PredBB->getTerminator(); 2997 BasicBlock *TrueBB, *FalseBB; 2998 ICmpInst::Predicate Pred; 2999 if (!match(TI, m_Br(m_ICmp(Pred, 3000 m_CombineOr(m_Specific(Op), 3001 m_Specific(Op->stripPointerCasts())), 3002 m_Zero()), 3003 TrueBB, FalseBB))) 3004 return nullptr; 3005 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE) 3006 return nullptr; 3007 3008 // Validate constraint #3: Ensure the null case just falls through. 3009 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB)) 3010 return nullptr; 3011 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && 3012 "Broken CFG: missing edge from predecessor to successor"); 3013 3014 // At this point, we know that everything in FreeInstrBB can be moved 3015 // before TI. 3016 for (Instruction &Instr : llvm::make_early_inc_range(*FreeInstrBB)) { 3017 if (&Instr == FreeInstrBBTerminator) 3018 break; 3019 Instr.moveBeforePreserving(TI); 3020 } 3021 assert(FreeInstrBB->size() == 1 && 3022 "Only the branch instruction should remain"); 3023 3024 // Now that we've moved the call to free before the NULL check, we have to 3025 // remove any attributes on its parameter that imply it's non-null, because 3026 // those attributes might have only been valid because of the NULL check, and 3027 // we can get miscompiles if we keep them. This is conservative if non-null is 3028 // also implied by something other than the NULL check, but it's guaranteed to 3029 // be correct, and the conservativeness won't matter in practice, since the 3030 // attributes are irrelevant for the call to free itself and the pointer 3031 // shouldn't be used after the call. 3032 AttributeList Attrs = FI.getAttributes(); 3033 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0, Attribute::NonNull); 3034 Attribute Dereferenceable = Attrs.getParamAttr(0, Attribute::Dereferenceable); 3035 if (Dereferenceable.isValid()) { 3036 uint64_t Bytes = Dereferenceable.getDereferenceableBytes(); 3037 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0, 3038 Attribute::Dereferenceable); 3039 Attrs = Attrs.addDereferenceableOrNullParamAttr(FI.getContext(), 0, Bytes); 3040 } 3041 FI.setAttributes(Attrs); 3042 3043 return &FI; 3044 } 3045 3046 Instruction *InstCombinerImpl::visitFree(CallInst &FI, Value *Op) { 3047 // free undef -> unreachable. 3048 if (isa<UndefValue>(Op)) { 3049 // Leave a marker since we can't modify the CFG here. 3050 CreateNonTerminatorUnreachable(&FI); 3051 return eraseInstFromFunction(FI); 3052 } 3053 3054 // If we have 'free null' delete the instruction. This can happen in stl code 3055 // when lots of inlining happens. 3056 if (isa<ConstantPointerNull>(Op)) 3057 return eraseInstFromFunction(FI); 3058 3059 // If we had free(realloc(...)) with no intervening uses, then eliminate the 3060 // realloc() entirely. 3061 CallInst *CI = dyn_cast<CallInst>(Op); 3062 if (CI && CI->hasOneUse()) 3063 if (Value *ReallocatedOp = getReallocatedOperand(CI)) 3064 return eraseInstFromFunction(*replaceInstUsesWith(*CI, ReallocatedOp)); 3065 3066 // If we optimize for code size, try to move the call to free before the null 3067 // test so that simplify cfg can remove the empty block and dead code 3068 // elimination the branch. I.e., helps to turn something like: 3069 // if (foo) free(foo); 3070 // into 3071 // free(foo); 3072 // 3073 // Note that we can only do this for 'free' and not for any flavor of 3074 // 'operator delete'; there is no 'operator delete' symbol for which we are 3075 // permitted to invent a call, even if we're passing in a null pointer. 3076 if (MinimizeSize) { 3077 LibFunc Func; 3078 if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free) 3079 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL)) 3080 return I; 3081 } 3082 3083 return nullptr; 3084 } 3085 3086 Instruction *InstCombinerImpl::visitReturnInst(ReturnInst &RI) { 3087 // Nothing for now. 3088 return nullptr; 3089 } 3090 3091 // WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()! 3092 bool InstCombinerImpl::removeInstructionsBeforeUnreachable(Instruction &I) { 3093 // Try to remove the previous instruction if it must lead to unreachable. 3094 // This includes instructions like stores and "llvm.assume" that may not get 3095 // removed by simple dead code elimination. 3096 bool Changed = false; 3097 while (Instruction *Prev = I.getPrevNonDebugInstruction()) { 3098 // While we theoretically can erase EH, that would result in a block that 3099 // used to start with an EH no longer starting with EH, which is invalid. 3100 // To make it valid, we'd need to fixup predecessors to no longer refer to 3101 // this block, but that changes CFG, which is not allowed in InstCombine. 3102 if (Prev->isEHPad()) 3103 break; // Can not drop any more instructions. We're done here. 3104 3105 if (!isGuaranteedToTransferExecutionToSuccessor(Prev)) 3106 break; // Can not drop any more instructions. We're done here. 3107 // Otherwise, this instruction can be freely erased, 3108 // even if it is not side-effect free. 3109 3110 // A value may still have uses before we process it here (for example, in 3111 // another unreachable block), so convert those to poison. 3112 replaceInstUsesWith(*Prev, PoisonValue::get(Prev->getType())); 3113 eraseInstFromFunction(*Prev); 3114 Changed = true; 3115 } 3116 return Changed; 3117 } 3118 3119 Instruction *InstCombinerImpl::visitUnreachableInst(UnreachableInst &I) { 3120 removeInstructionsBeforeUnreachable(I); 3121 return nullptr; 3122 } 3123 3124 Instruction *InstCombinerImpl::visitUnconditionalBranchInst(BranchInst &BI) { 3125 assert(BI.isUnconditional() && "Only for unconditional branches."); 3126 3127 // If this store is the second-to-last instruction in the basic block 3128 // (excluding debug info and bitcasts of pointers) and if the block ends with 3129 // an unconditional branch, try to move the store to the successor block. 3130 3131 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) { 3132 auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) { 3133 return BBI->isDebugOrPseudoInst() || 3134 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()); 3135 }; 3136 3137 BasicBlock::iterator FirstInstr = BBI->getParent()->begin(); 3138 do { 3139 if (BBI != FirstInstr) 3140 --BBI; 3141 } while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI)); 3142 3143 return dyn_cast<StoreInst>(BBI); 3144 }; 3145 3146 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI))) 3147 if (mergeStoreIntoSuccessor(*SI)) 3148 return &BI; 3149 3150 return nullptr; 3151 } 3152 3153 void InstCombinerImpl::addDeadEdge(BasicBlock *From, BasicBlock *To, 3154 SmallVectorImpl<BasicBlock *> &Worklist) { 3155 if (!DeadEdges.insert({From, To}).second) 3156 return; 3157 3158 // Replace phi node operands in successor with poison. 3159 for (PHINode &PN : To->phis()) 3160 for (Use &U : PN.incoming_values()) 3161 if (PN.getIncomingBlock(U) == From && !isa<PoisonValue>(U)) { 3162 replaceUse(U, PoisonValue::get(PN.getType())); 3163 addToWorklist(&PN); 3164 MadeIRChange = true; 3165 } 3166 3167 Worklist.push_back(To); 3168 } 3169 3170 // Under the assumption that I is unreachable, remove it and following 3171 // instructions. Changes are reported directly to MadeIRChange. 3172 void InstCombinerImpl::handleUnreachableFrom( 3173 Instruction *I, SmallVectorImpl<BasicBlock *> &Worklist) { 3174 BasicBlock *BB = I->getParent(); 3175 for (Instruction &Inst : make_early_inc_range( 3176 make_range(std::next(BB->getTerminator()->getReverseIterator()), 3177 std::next(I->getReverseIterator())))) { 3178 if (!Inst.use_empty() && !Inst.getType()->isTokenTy()) { 3179 replaceInstUsesWith(Inst, PoisonValue::get(Inst.getType())); 3180 MadeIRChange = true; 3181 } 3182 if (Inst.isEHPad() || Inst.getType()->isTokenTy()) 3183 continue; 3184 // RemoveDIs: erase debug-info on this instruction manually. 3185 Inst.dropDbgValues(); 3186 eraseInstFromFunction(Inst); 3187 MadeIRChange = true; 3188 } 3189 3190 // RemoveDIs: to match behaviour in dbg.value mode, drop debug-info on 3191 // terminator too. 3192 BB->getTerminator()->dropDbgValues(); 3193 3194 // Handle potentially dead successors. 3195 for (BasicBlock *Succ : successors(BB)) 3196 addDeadEdge(BB, Succ, Worklist); 3197 } 3198 3199 void InstCombinerImpl::handlePotentiallyDeadBlocks( 3200 SmallVectorImpl<BasicBlock *> &Worklist) { 3201 while (!Worklist.empty()) { 3202 BasicBlock *BB = Worklist.pop_back_val(); 3203 if (!all_of(predecessors(BB), [&](BasicBlock *Pred) { 3204 return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred); 3205 })) 3206 continue; 3207 3208 handleUnreachableFrom(&BB->front(), Worklist); 3209 } 3210 } 3211 3212 void InstCombinerImpl::handlePotentiallyDeadSuccessors(BasicBlock *BB, 3213 BasicBlock *LiveSucc) { 3214 SmallVector<BasicBlock *> Worklist; 3215 for (BasicBlock *Succ : successors(BB)) { 3216 // The live successor isn't dead. 3217 if (Succ == LiveSucc) 3218 continue; 3219 3220 addDeadEdge(BB, Succ, Worklist); 3221 } 3222 3223 handlePotentiallyDeadBlocks(Worklist); 3224 } 3225 3226 Instruction *InstCombinerImpl::visitBranchInst(BranchInst &BI) { 3227 if (BI.isUnconditional()) 3228 return visitUnconditionalBranchInst(BI); 3229 3230 // Change br (not X), label True, label False to: br X, label False, True 3231 Value *Cond = BI.getCondition(); 3232 Value *X; 3233 if (match(Cond, m_Not(m_Value(X))) && !isa<Constant>(X)) { 3234 // Swap Destinations and condition... 3235 BI.swapSuccessors(); 3236 return replaceOperand(BI, 0, X); 3237 } 3238 3239 // Canonicalize logical-and-with-invert as logical-or-with-invert. 3240 // This is done by inverting the condition and swapping successors: 3241 // br (X && !Y), T, F --> br !(X && !Y), F, T --> br (!X || Y), F, T 3242 Value *Y; 3243 if (isa<SelectInst>(Cond) && 3244 match(Cond, 3245 m_OneUse(m_LogicalAnd(m_Value(X), m_OneUse(m_Not(m_Value(Y))))))) { 3246 Value *NotX = Builder.CreateNot(X, "not." + X->getName()); 3247 Value *Or = Builder.CreateLogicalOr(NotX, Y); 3248 BI.swapSuccessors(); 3249 return replaceOperand(BI, 0, Or); 3250 } 3251 3252 // If the condition is irrelevant, remove the use so that other 3253 // transforms on the condition become more effective. 3254 if (!isa<ConstantInt>(Cond) && BI.getSuccessor(0) == BI.getSuccessor(1)) 3255 return replaceOperand(BI, 0, ConstantInt::getFalse(Cond->getType())); 3256 3257 // Canonicalize, for example, fcmp_one -> fcmp_oeq. 3258 CmpInst::Predicate Pred; 3259 if (match(Cond, m_OneUse(m_FCmp(Pred, m_Value(), m_Value()))) && 3260 !isCanonicalPredicate(Pred)) { 3261 // Swap destinations and condition. 3262 auto *Cmp = cast<CmpInst>(Cond); 3263 Cmp->setPredicate(CmpInst::getInversePredicate(Pred)); 3264 BI.swapSuccessors(); 3265 Worklist.push(Cmp); 3266 return &BI; 3267 } 3268 3269 if (isa<UndefValue>(Cond)) { 3270 handlePotentiallyDeadSuccessors(BI.getParent(), /*LiveSucc*/ nullptr); 3271 return nullptr; 3272 } 3273 if (auto *CI = dyn_cast<ConstantInt>(Cond)) { 3274 handlePotentiallyDeadSuccessors(BI.getParent(), 3275 BI.getSuccessor(!CI->getZExtValue())); 3276 return nullptr; 3277 } 3278 3279 DC.registerBranch(&BI); 3280 return nullptr; 3281 } 3282 3283 Instruction *InstCombinerImpl::visitSwitchInst(SwitchInst &SI) { 3284 Value *Cond = SI.getCondition(); 3285 Value *Op0; 3286 ConstantInt *AddRHS; 3287 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) { 3288 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'. 3289 for (auto Case : SI.cases()) { 3290 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS); 3291 assert(isa<ConstantInt>(NewCase) && 3292 "Result of expression should be constant"); 3293 Case.setValue(cast<ConstantInt>(NewCase)); 3294 } 3295 return replaceOperand(SI, 0, Op0); 3296 } 3297 3298 ConstantInt *SubLHS; 3299 if (match(Cond, m_Sub(m_ConstantInt(SubLHS), m_Value(Op0)))) { 3300 // Change 'switch (1-X) case 1:' into 'switch (X) case 0'. 3301 for (auto Case : SI.cases()) { 3302 Constant *NewCase = ConstantExpr::getSub(SubLHS, Case.getCaseValue()); 3303 assert(isa<ConstantInt>(NewCase) && 3304 "Result of expression should be constant"); 3305 Case.setValue(cast<ConstantInt>(NewCase)); 3306 } 3307 return replaceOperand(SI, 0, Op0); 3308 } 3309 3310 uint64_t ShiftAmt; 3311 if (match(Cond, m_Shl(m_Value(Op0), m_ConstantInt(ShiftAmt))) && 3312 ShiftAmt < Op0->getType()->getScalarSizeInBits() && 3313 all_of(SI.cases(), [&](const auto &Case) { 3314 return Case.getCaseValue()->getValue().countr_zero() >= ShiftAmt; 3315 })) { 3316 // Change 'switch (X << 2) case 4:' into 'switch (X) case 1:'. 3317 OverflowingBinaryOperator *Shl = cast<OverflowingBinaryOperator>(Cond); 3318 if (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap() || 3319 Shl->hasOneUse()) { 3320 Value *NewCond = Op0; 3321 if (!Shl->hasNoUnsignedWrap() && !Shl->hasNoSignedWrap()) { 3322 // If the shift may wrap, we need to mask off the shifted bits. 3323 unsigned BitWidth = Op0->getType()->getScalarSizeInBits(); 3324 NewCond = Builder.CreateAnd( 3325 Op0, APInt::getLowBitsSet(BitWidth, BitWidth - ShiftAmt)); 3326 } 3327 for (auto Case : SI.cases()) { 3328 const APInt &CaseVal = Case.getCaseValue()->getValue(); 3329 APInt ShiftedCase = Shl->hasNoSignedWrap() ? CaseVal.ashr(ShiftAmt) 3330 : CaseVal.lshr(ShiftAmt); 3331 Case.setValue(ConstantInt::get(SI.getContext(), ShiftedCase)); 3332 } 3333 return replaceOperand(SI, 0, NewCond); 3334 } 3335 } 3336 3337 // Fold switch(zext/sext(X)) into switch(X) if possible. 3338 if (match(Cond, m_ZExtOrSExt(m_Value(Op0)))) { 3339 bool IsZExt = isa<ZExtInst>(Cond); 3340 Type *SrcTy = Op0->getType(); 3341 unsigned NewWidth = SrcTy->getScalarSizeInBits(); 3342 3343 if (all_of(SI.cases(), [&](const auto &Case) { 3344 const APInt &CaseVal = Case.getCaseValue()->getValue(); 3345 return IsZExt ? CaseVal.isIntN(NewWidth) 3346 : CaseVal.isSignedIntN(NewWidth); 3347 })) { 3348 for (auto &Case : SI.cases()) { 3349 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth); 3350 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase)); 3351 } 3352 return replaceOperand(SI, 0, Op0); 3353 } 3354 } 3355 3356 KnownBits Known = computeKnownBits(Cond, 0, &SI); 3357 unsigned LeadingKnownZeros = Known.countMinLeadingZeros(); 3358 unsigned LeadingKnownOnes = Known.countMinLeadingOnes(); 3359 3360 // Compute the number of leading bits we can ignore. 3361 // TODO: A better way to determine this would use ComputeNumSignBits(). 3362 for (const auto &C : SI.cases()) { 3363 LeadingKnownZeros = 3364 std::min(LeadingKnownZeros, C.getCaseValue()->getValue().countl_zero()); 3365 LeadingKnownOnes = 3366 std::min(LeadingKnownOnes, C.getCaseValue()->getValue().countl_one()); 3367 } 3368 3369 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes); 3370 3371 // Shrink the condition operand if the new type is smaller than the old type. 3372 // But do not shrink to a non-standard type, because backend can't generate 3373 // good code for that yet. 3374 // TODO: We can make it aggressive again after fixing PR39569. 3375 if (NewWidth > 0 && NewWidth < Known.getBitWidth() && 3376 shouldChangeType(Known.getBitWidth(), NewWidth)) { 3377 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth); 3378 Builder.SetInsertPoint(&SI); 3379 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc"); 3380 3381 for (auto Case : SI.cases()) { 3382 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth); 3383 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase)); 3384 } 3385 return replaceOperand(SI, 0, NewCond); 3386 } 3387 3388 if (isa<UndefValue>(Cond)) { 3389 handlePotentiallyDeadSuccessors(SI.getParent(), /*LiveSucc*/ nullptr); 3390 return nullptr; 3391 } 3392 if (auto *CI = dyn_cast<ConstantInt>(Cond)) { 3393 handlePotentiallyDeadSuccessors(SI.getParent(), 3394 SI.findCaseValue(CI)->getCaseSuccessor()); 3395 return nullptr; 3396 } 3397 3398 return nullptr; 3399 } 3400 3401 Instruction * 3402 InstCombinerImpl::foldExtractOfOverflowIntrinsic(ExtractValueInst &EV) { 3403 auto *WO = dyn_cast<WithOverflowInst>(EV.getAggregateOperand()); 3404 if (!WO) 3405 return nullptr; 3406 3407 Intrinsic::ID OvID = WO->getIntrinsicID(); 3408 const APInt *C = nullptr; 3409 if (match(WO->getRHS(), m_APIntAllowUndef(C))) { 3410 if (*EV.idx_begin() == 0 && (OvID == Intrinsic::smul_with_overflow || 3411 OvID == Intrinsic::umul_with_overflow)) { 3412 // extractvalue (any_mul_with_overflow X, -1), 0 --> -X 3413 if (C->isAllOnes()) 3414 return BinaryOperator::CreateNeg(WO->getLHS()); 3415 // extractvalue (any_mul_with_overflow X, 2^n), 0 --> X << n 3416 if (C->isPowerOf2()) { 3417 return BinaryOperator::CreateShl( 3418 WO->getLHS(), 3419 ConstantInt::get(WO->getLHS()->getType(), C->logBase2())); 3420 } 3421 } 3422 } 3423 3424 // We're extracting from an overflow intrinsic. See if we're the only user. 3425 // That allows us to simplify multiple result intrinsics to simpler things 3426 // that just get one value. 3427 if (!WO->hasOneUse()) 3428 return nullptr; 3429 3430 // Check if we're grabbing only the result of a 'with overflow' intrinsic 3431 // and replace it with a traditional binary instruction. 3432 if (*EV.idx_begin() == 0) { 3433 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 3434 Value *LHS = WO->getLHS(), *RHS = WO->getRHS(); 3435 // Replace the old instruction's uses with poison. 3436 replaceInstUsesWith(*WO, PoisonValue::get(WO->getType())); 3437 eraseInstFromFunction(*WO); 3438 return BinaryOperator::Create(BinOp, LHS, RHS); 3439 } 3440 3441 assert(*EV.idx_begin() == 1 && "Unexpected extract index for overflow inst"); 3442 3443 // (usub LHS, RHS) overflows when LHS is unsigned-less-than RHS. 3444 if (OvID == Intrinsic::usub_with_overflow) 3445 return new ICmpInst(ICmpInst::ICMP_ULT, WO->getLHS(), WO->getRHS()); 3446 3447 // smul with i1 types overflows when both sides are set: -1 * -1 == +1, but 3448 // +1 is not possible because we assume signed values. 3449 if (OvID == Intrinsic::smul_with_overflow && 3450 WO->getLHS()->getType()->isIntOrIntVectorTy(1)) 3451 return BinaryOperator::CreateAnd(WO->getLHS(), WO->getRHS()); 3452 3453 // If only the overflow result is used, and the right hand side is a 3454 // constant (or constant splat), we can remove the intrinsic by directly 3455 // checking for overflow. 3456 if (C) { 3457 // Compute the no-wrap range for LHS given RHS=C, then construct an 3458 // equivalent icmp, potentially using an offset. 3459 ConstantRange NWR = ConstantRange::makeExactNoWrapRegion( 3460 WO->getBinaryOp(), *C, WO->getNoWrapKind()); 3461 3462 CmpInst::Predicate Pred; 3463 APInt NewRHSC, Offset; 3464 NWR.getEquivalentICmp(Pred, NewRHSC, Offset); 3465 auto *OpTy = WO->getRHS()->getType(); 3466 auto *NewLHS = WO->getLHS(); 3467 if (Offset != 0) 3468 NewLHS = Builder.CreateAdd(NewLHS, ConstantInt::get(OpTy, Offset)); 3469 return new ICmpInst(ICmpInst::getInversePredicate(Pred), NewLHS, 3470 ConstantInt::get(OpTy, NewRHSC)); 3471 } 3472 3473 return nullptr; 3474 } 3475 3476 Instruction *InstCombinerImpl::visitExtractValueInst(ExtractValueInst &EV) { 3477 Value *Agg = EV.getAggregateOperand(); 3478 3479 if (!EV.hasIndices()) 3480 return replaceInstUsesWith(EV, Agg); 3481 3482 if (Value *V = simplifyExtractValueInst(Agg, EV.getIndices(), 3483 SQ.getWithInstruction(&EV))) 3484 return replaceInstUsesWith(EV, V); 3485 3486 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 3487 // We're extracting from an insertvalue instruction, compare the indices 3488 const unsigned *exti, *exte, *insi, *inse; 3489 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 3490 exte = EV.idx_end(), inse = IV->idx_end(); 3491 exti != exte && insi != inse; 3492 ++exti, ++insi) { 3493 if (*insi != *exti) 3494 // The insert and extract both reference distinctly different elements. 3495 // This means the extract is not influenced by the insert, and we can 3496 // replace the aggregate operand of the extract with the aggregate 3497 // operand of the insert. i.e., replace 3498 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 3499 // %E = extractvalue { i32, { i32 } } %I, 0 3500 // with 3501 // %E = extractvalue { i32, { i32 } } %A, 0 3502 return ExtractValueInst::Create(IV->getAggregateOperand(), 3503 EV.getIndices()); 3504 } 3505 if (exti == exte && insi == inse) 3506 // Both iterators are at the end: Index lists are identical. Replace 3507 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 3508 // %C = extractvalue { i32, { i32 } } %B, 1, 0 3509 // with "i32 42" 3510 return replaceInstUsesWith(EV, IV->getInsertedValueOperand()); 3511 if (exti == exte) { 3512 // The extract list is a prefix of the insert list. i.e. replace 3513 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 3514 // %E = extractvalue { i32, { i32 } } %I, 1 3515 // with 3516 // %X = extractvalue { i32, { i32 } } %A, 1 3517 // %E = insertvalue { i32 } %X, i32 42, 0 3518 // by switching the order of the insert and extract (though the 3519 // insertvalue should be left in, since it may have other uses). 3520 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(), 3521 EV.getIndices()); 3522 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 3523 ArrayRef(insi, inse)); 3524 } 3525 if (insi == inse) 3526 // The insert list is a prefix of the extract list 3527 // We can simply remove the common indices from the extract and make it 3528 // operate on the inserted value instead of the insertvalue result. 3529 // i.e., replace 3530 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 3531 // %E = extractvalue { i32, { i32 } } %I, 1, 0 3532 // with 3533 // %E extractvalue { i32 } { i32 42 }, 0 3534 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 3535 ArrayRef(exti, exte)); 3536 } 3537 3538 if (Instruction *R = foldExtractOfOverflowIntrinsic(EV)) 3539 return R; 3540 3541 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) { 3542 // Bail out if the aggregate contains scalable vector type 3543 if (auto *STy = dyn_cast<StructType>(Agg->getType()); 3544 STy && STy->containsScalableVectorType()) 3545 return nullptr; 3546 3547 // If the (non-volatile) load only has one use, we can rewrite this to a 3548 // load from a GEP. This reduces the size of the load. If a load is used 3549 // only by extractvalue instructions then this either must have been 3550 // optimized before, or it is a struct with padding, in which case we 3551 // don't want to do the transformation as it loses padding knowledge. 3552 if (L->isSimple() && L->hasOneUse()) { 3553 // extractvalue has integer indices, getelementptr has Value*s. Convert. 3554 SmallVector<Value*, 4> Indices; 3555 // Prefix an i32 0 since we need the first element. 3556 Indices.push_back(Builder.getInt32(0)); 3557 for (unsigned Idx : EV.indices()) 3558 Indices.push_back(Builder.getInt32(Idx)); 3559 3560 // We need to insert these at the location of the old load, not at that of 3561 // the extractvalue. 3562 Builder.SetInsertPoint(L); 3563 Value *GEP = Builder.CreateInBoundsGEP(L->getType(), 3564 L->getPointerOperand(), Indices); 3565 Instruction *NL = Builder.CreateLoad(EV.getType(), GEP); 3566 // Whatever aliasing information we had for the orignal load must also 3567 // hold for the smaller load, so propagate the annotations. 3568 NL->setAAMetadata(L->getAAMetadata()); 3569 // Returning the load directly will cause the main loop to insert it in 3570 // the wrong spot, so use replaceInstUsesWith(). 3571 return replaceInstUsesWith(EV, NL); 3572 } 3573 } 3574 3575 if (auto *PN = dyn_cast<PHINode>(Agg)) 3576 if (Instruction *Res = foldOpIntoPhi(EV, PN)) 3577 return Res; 3578 3579 // We could simplify extracts from other values. Note that nested extracts may 3580 // already be simplified implicitly by the above: extract (extract (insert) ) 3581 // will be translated into extract ( insert ( extract ) ) first and then just 3582 // the value inserted, if appropriate. Similarly for extracts from single-use 3583 // loads: extract (extract (load)) will be translated to extract (load (gep)) 3584 // and if again single-use then via load (gep (gep)) to load (gep). 3585 // However, double extracts from e.g. function arguments or return values 3586 // aren't handled yet. 3587 return nullptr; 3588 } 3589 3590 /// Return 'true' if the given typeinfo will match anything. 3591 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) { 3592 switch (Personality) { 3593 case EHPersonality::GNU_C: 3594 case EHPersonality::GNU_C_SjLj: 3595 case EHPersonality::Rust: 3596 // The GCC C EH and Rust personality only exists to support cleanups, so 3597 // it's not clear what the semantics of catch clauses are. 3598 return false; 3599 case EHPersonality::Unknown: 3600 return false; 3601 case EHPersonality::GNU_Ada: 3602 // While __gnat_all_others_value will match any Ada exception, it doesn't 3603 // match foreign exceptions (or didn't, before gcc-4.7). 3604 return false; 3605 case EHPersonality::GNU_CXX: 3606 case EHPersonality::GNU_CXX_SjLj: 3607 case EHPersonality::GNU_ObjC: 3608 case EHPersonality::MSVC_X86SEH: 3609 case EHPersonality::MSVC_TableSEH: 3610 case EHPersonality::MSVC_CXX: 3611 case EHPersonality::CoreCLR: 3612 case EHPersonality::Wasm_CXX: 3613 case EHPersonality::XL_CXX: 3614 return TypeInfo->isNullValue(); 3615 } 3616 llvm_unreachable("invalid enum"); 3617 } 3618 3619 static bool shorter_filter(const Value *LHS, const Value *RHS) { 3620 return 3621 cast<ArrayType>(LHS->getType())->getNumElements() 3622 < 3623 cast<ArrayType>(RHS->getType())->getNumElements(); 3624 } 3625 3626 Instruction *InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) { 3627 // The logic here should be correct for any real-world personality function. 3628 // However if that turns out not to be true, the offending logic can always 3629 // be conditioned on the personality function, like the catch-all logic is. 3630 EHPersonality Personality = 3631 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn()); 3632 3633 // Simplify the list of clauses, eg by removing repeated catch clauses 3634 // (these are often created by inlining). 3635 bool MakeNewInstruction = false; // If true, recreate using the following: 3636 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction; 3637 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup. 3638 3639 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already. 3640 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) { 3641 bool isLastClause = i + 1 == e; 3642 if (LI.isCatch(i)) { 3643 // A catch clause. 3644 Constant *CatchClause = LI.getClause(i); 3645 Constant *TypeInfo = CatchClause->stripPointerCasts(); 3646 3647 // If we already saw this clause, there is no point in having a second 3648 // copy of it. 3649 if (AlreadyCaught.insert(TypeInfo).second) { 3650 // This catch clause was not already seen. 3651 NewClauses.push_back(CatchClause); 3652 } else { 3653 // Repeated catch clause - drop the redundant copy. 3654 MakeNewInstruction = true; 3655 } 3656 3657 // If this is a catch-all then there is no point in keeping any following 3658 // clauses or marking the landingpad as having a cleanup. 3659 if (isCatchAll(Personality, TypeInfo)) { 3660 if (!isLastClause) 3661 MakeNewInstruction = true; 3662 CleanupFlag = false; 3663 break; 3664 } 3665 } else { 3666 // A filter clause. If any of the filter elements were already caught 3667 // then they can be dropped from the filter. It is tempting to try to 3668 // exploit the filter further by saying that any typeinfo that does not 3669 // occur in the filter can't be caught later (and thus can be dropped). 3670 // However this would be wrong, since typeinfos can match without being 3671 // equal (for example if one represents a C++ class, and the other some 3672 // class derived from it). 3673 assert(LI.isFilter(i) && "Unsupported landingpad clause!"); 3674 Constant *FilterClause = LI.getClause(i); 3675 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType()); 3676 unsigned NumTypeInfos = FilterType->getNumElements(); 3677 3678 // An empty filter catches everything, so there is no point in keeping any 3679 // following clauses or marking the landingpad as having a cleanup. By 3680 // dealing with this case here the following code is made a bit simpler. 3681 if (!NumTypeInfos) { 3682 NewClauses.push_back(FilterClause); 3683 if (!isLastClause) 3684 MakeNewInstruction = true; 3685 CleanupFlag = false; 3686 break; 3687 } 3688 3689 bool MakeNewFilter = false; // If true, make a new filter. 3690 SmallVector<Constant *, 16> NewFilterElts; // New elements. 3691 if (isa<ConstantAggregateZero>(FilterClause)) { 3692 // Not an empty filter - it contains at least one null typeinfo. 3693 assert(NumTypeInfos > 0 && "Should have handled empty filter already!"); 3694 Constant *TypeInfo = 3695 Constant::getNullValue(FilterType->getElementType()); 3696 // If this typeinfo is a catch-all then the filter can never match. 3697 if (isCatchAll(Personality, TypeInfo)) { 3698 // Throw the filter away. 3699 MakeNewInstruction = true; 3700 continue; 3701 } 3702 3703 // There is no point in having multiple copies of this typeinfo, so 3704 // discard all but the first copy if there is more than one. 3705 NewFilterElts.push_back(TypeInfo); 3706 if (NumTypeInfos > 1) 3707 MakeNewFilter = true; 3708 } else { 3709 ConstantArray *Filter = cast<ConstantArray>(FilterClause); 3710 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements. 3711 NewFilterElts.reserve(NumTypeInfos); 3712 3713 // Remove any filter elements that were already caught or that already 3714 // occurred in the filter. While there, see if any of the elements are 3715 // catch-alls. If so, the filter can be discarded. 3716 bool SawCatchAll = false; 3717 for (unsigned j = 0; j != NumTypeInfos; ++j) { 3718 Constant *Elt = Filter->getOperand(j); 3719 Constant *TypeInfo = Elt->stripPointerCasts(); 3720 if (isCatchAll(Personality, TypeInfo)) { 3721 // This element is a catch-all. Bail out, noting this fact. 3722 SawCatchAll = true; 3723 break; 3724 } 3725 3726 // Even if we've seen a type in a catch clause, we don't want to 3727 // remove it from the filter. An unexpected type handler may be 3728 // set up for a call site which throws an exception of the same 3729 // type caught. In order for the exception thrown by the unexpected 3730 // handler to propagate correctly, the filter must be correctly 3731 // described for the call site. 3732 // 3733 // Example: 3734 // 3735 // void unexpected() { throw 1;} 3736 // void foo() throw (int) { 3737 // std::set_unexpected(unexpected); 3738 // try { 3739 // throw 2.0; 3740 // } catch (int i) {} 3741 // } 3742 3743 // There is no point in having multiple copies of the same typeinfo in 3744 // a filter, so only add it if we didn't already. 3745 if (SeenInFilter.insert(TypeInfo).second) 3746 NewFilterElts.push_back(cast<Constant>(Elt)); 3747 } 3748 // A filter containing a catch-all cannot match anything by definition. 3749 if (SawCatchAll) { 3750 // Throw the filter away. 3751 MakeNewInstruction = true; 3752 continue; 3753 } 3754 3755 // If we dropped something from the filter, make a new one. 3756 if (NewFilterElts.size() < NumTypeInfos) 3757 MakeNewFilter = true; 3758 } 3759 if (MakeNewFilter) { 3760 FilterType = ArrayType::get(FilterType->getElementType(), 3761 NewFilterElts.size()); 3762 FilterClause = ConstantArray::get(FilterType, NewFilterElts); 3763 MakeNewInstruction = true; 3764 } 3765 3766 NewClauses.push_back(FilterClause); 3767 3768 // If the new filter is empty then it will catch everything so there is 3769 // no point in keeping any following clauses or marking the landingpad 3770 // as having a cleanup. The case of the original filter being empty was 3771 // already handled above. 3772 if (MakeNewFilter && !NewFilterElts.size()) { 3773 assert(MakeNewInstruction && "New filter but not a new instruction!"); 3774 CleanupFlag = false; 3775 break; 3776 } 3777 } 3778 } 3779 3780 // If several filters occur in a row then reorder them so that the shortest 3781 // filters come first (those with the smallest number of elements). This is 3782 // advantageous because shorter filters are more likely to match, speeding up 3783 // unwinding, but mostly because it increases the effectiveness of the other 3784 // filter optimizations below. 3785 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) { 3786 unsigned j; 3787 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters. 3788 for (j = i; j != e; ++j) 3789 if (!isa<ArrayType>(NewClauses[j]->getType())) 3790 break; 3791 3792 // Check whether the filters are already sorted by length. We need to know 3793 // if sorting them is actually going to do anything so that we only make a 3794 // new landingpad instruction if it does. 3795 for (unsigned k = i; k + 1 < j; ++k) 3796 if (shorter_filter(NewClauses[k+1], NewClauses[k])) { 3797 // Not sorted, so sort the filters now. Doing an unstable sort would be 3798 // correct too but reordering filters pointlessly might confuse users. 3799 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j, 3800 shorter_filter); 3801 MakeNewInstruction = true; 3802 break; 3803 } 3804 3805 // Look for the next batch of filters. 3806 i = j + 1; 3807 } 3808 3809 // If typeinfos matched if and only if equal, then the elements of a filter L 3810 // that occurs later than a filter F could be replaced by the intersection of 3811 // the elements of F and L. In reality two typeinfos can match without being 3812 // equal (for example if one represents a C++ class, and the other some class 3813 // derived from it) so it would be wrong to perform this transform in general. 3814 // However the transform is correct and useful if F is a subset of L. In that 3815 // case L can be replaced by F, and thus removed altogether since repeating a 3816 // filter is pointless. So here we look at all pairs of filters F and L where 3817 // L follows F in the list of clauses, and remove L if every element of F is 3818 // an element of L. This can occur when inlining C++ functions with exception 3819 // specifications. 3820 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) { 3821 // Examine each filter in turn. 3822 Value *Filter = NewClauses[i]; 3823 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType()); 3824 if (!FTy) 3825 // Not a filter - skip it. 3826 continue; 3827 unsigned FElts = FTy->getNumElements(); 3828 // Examine each filter following this one. Doing this backwards means that 3829 // we don't have to worry about filters disappearing under us when removed. 3830 for (unsigned j = NewClauses.size() - 1; j != i; --j) { 3831 Value *LFilter = NewClauses[j]; 3832 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType()); 3833 if (!LTy) 3834 // Not a filter - skip it. 3835 continue; 3836 // If Filter is a subset of LFilter, i.e. every element of Filter is also 3837 // an element of LFilter, then discard LFilter. 3838 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j; 3839 // If Filter is empty then it is a subset of LFilter. 3840 if (!FElts) { 3841 // Discard LFilter. 3842 NewClauses.erase(J); 3843 MakeNewInstruction = true; 3844 // Move on to the next filter. 3845 continue; 3846 } 3847 unsigned LElts = LTy->getNumElements(); 3848 // If Filter is longer than LFilter then it cannot be a subset of it. 3849 if (FElts > LElts) 3850 // Move on to the next filter. 3851 continue; 3852 // At this point we know that LFilter has at least one element. 3853 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros. 3854 // Filter is a subset of LFilter iff Filter contains only zeros (as we 3855 // already know that Filter is not longer than LFilter). 3856 if (isa<ConstantAggregateZero>(Filter)) { 3857 assert(FElts <= LElts && "Should have handled this case earlier!"); 3858 // Discard LFilter. 3859 NewClauses.erase(J); 3860 MakeNewInstruction = true; 3861 } 3862 // Move on to the next filter. 3863 continue; 3864 } 3865 ConstantArray *LArray = cast<ConstantArray>(LFilter); 3866 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros. 3867 // Since Filter is non-empty and contains only zeros, it is a subset of 3868 // LFilter iff LFilter contains a zero. 3869 assert(FElts > 0 && "Should have eliminated the empty filter earlier!"); 3870 for (unsigned l = 0; l != LElts; ++l) 3871 if (LArray->getOperand(l)->isNullValue()) { 3872 // LFilter contains a zero - discard it. 3873 NewClauses.erase(J); 3874 MakeNewInstruction = true; 3875 break; 3876 } 3877 // Move on to the next filter. 3878 continue; 3879 } 3880 // At this point we know that both filters are ConstantArrays. Loop over 3881 // operands to see whether every element of Filter is also an element of 3882 // LFilter. Since filters tend to be short this is probably faster than 3883 // using a method that scales nicely. 3884 ConstantArray *FArray = cast<ConstantArray>(Filter); 3885 bool AllFound = true; 3886 for (unsigned f = 0; f != FElts; ++f) { 3887 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts(); 3888 AllFound = false; 3889 for (unsigned l = 0; l != LElts; ++l) { 3890 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts(); 3891 if (LTypeInfo == FTypeInfo) { 3892 AllFound = true; 3893 break; 3894 } 3895 } 3896 if (!AllFound) 3897 break; 3898 } 3899 if (AllFound) { 3900 // Discard LFilter. 3901 NewClauses.erase(J); 3902 MakeNewInstruction = true; 3903 } 3904 // Move on to the next filter. 3905 } 3906 } 3907 3908 // If we changed any of the clauses, replace the old landingpad instruction 3909 // with a new one. 3910 if (MakeNewInstruction) { 3911 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(), 3912 NewClauses.size()); 3913 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i) 3914 NLI->addClause(NewClauses[i]); 3915 // A landing pad with no clauses must have the cleanup flag set. It is 3916 // theoretically possible, though highly unlikely, that we eliminated all 3917 // clauses. If so, force the cleanup flag to true. 3918 if (NewClauses.empty()) 3919 CleanupFlag = true; 3920 NLI->setCleanup(CleanupFlag); 3921 return NLI; 3922 } 3923 3924 // Even if none of the clauses changed, we may nonetheless have understood 3925 // that the cleanup flag is pointless. Clear it if so. 3926 if (LI.isCleanup() != CleanupFlag) { 3927 assert(!CleanupFlag && "Adding a cleanup, not removing one?!"); 3928 LI.setCleanup(CleanupFlag); 3929 return &LI; 3930 } 3931 3932 return nullptr; 3933 } 3934 3935 Value * 3936 InstCombinerImpl::pushFreezeToPreventPoisonFromPropagating(FreezeInst &OrigFI) { 3937 // Try to push freeze through instructions that propagate but don't produce 3938 // poison as far as possible. If an operand of freeze follows three 3939 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one 3940 // guaranteed-non-poison operands then push the freeze through to the one 3941 // operand that is not guaranteed non-poison. The actual transform is as 3942 // follows. 3943 // Op1 = ... ; Op1 can be posion 3944 // Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have 3945 // ; single guaranteed-non-poison operands 3946 // ... = Freeze(Op0) 3947 // => 3948 // Op1 = ... 3949 // Op1.fr = Freeze(Op1) 3950 // ... = Inst(Op1.fr, NonPoisonOps...) 3951 auto *OrigOp = OrigFI.getOperand(0); 3952 auto *OrigOpInst = dyn_cast<Instruction>(OrigOp); 3953 3954 // While we could change the other users of OrigOp to use freeze(OrigOp), that 3955 // potentially reduces their optimization potential, so let's only do this iff 3956 // the OrigOp is only used by the freeze. 3957 if (!OrigOpInst || !OrigOpInst->hasOneUse() || isa<PHINode>(OrigOp)) 3958 return nullptr; 3959 3960 // We can't push the freeze through an instruction which can itself create 3961 // poison. If the only source of new poison is flags, we can simply 3962 // strip them (since we know the only use is the freeze and nothing can 3963 // benefit from them.) 3964 if (canCreateUndefOrPoison(cast<Operator>(OrigOp), 3965 /*ConsiderFlagsAndMetadata*/ false)) 3966 return nullptr; 3967 3968 // If operand is guaranteed not to be poison, there is no need to add freeze 3969 // to the operand. So we first find the operand that is not guaranteed to be 3970 // poison. 3971 Use *MaybePoisonOperand = nullptr; 3972 for (Use &U : OrigOpInst->operands()) { 3973 if (isa<MetadataAsValue>(U.get()) || 3974 isGuaranteedNotToBeUndefOrPoison(U.get())) 3975 continue; 3976 if (!MaybePoisonOperand) 3977 MaybePoisonOperand = &U; 3978 else 3979 return nullptr; 3980 } 3981 3982 OrigOpInst->dropPoisonGeneratingFlagsAndMetadata(); 3983 3984 // If all operands are guaranteed to be non-poison, we can drop freeze. 3985 if (!MaybePoisonOperand) 3986 return OrigOp; 3987 3988 Builder.SetInsertPoint(OrigOpInst); 3989 auto *FrozenMaybePoisonOperand = Builder.CreateFreeze( 3990 MaybePoisonOperand->get(), MaybePoisonOperand->get()->getName() + ".fr"); 3991 3992 replaceUse(*MaybePoisonOperand, FrozenMaybePoisonOperand); 3993 return OrigOp; 3994 } 3995 3996 Instruction *InstCombinerImpl::foldFreezeIntoRecurrence(FreezeInst &FI, 3997 PHINode *PN) { 3998 // Detect whether this is a recurrence with a start value and some number of 3999 // backedge values. We'll check whether we can push the freeze through the 4000 // backedge values (possibly dropping poison flags along the way) until we 4001 // reach the phi again. In that case, we can move the freeze to the start 4002 // value. 4003 Use *StartU = nullptr; 4004 SmallVector<Value *> Worklist; 4005 for (Use &U : PN->incoming_values()) { 4006 if (DT.dominates(PN->getParent(), PN->getIncomingBlock(U))) { 4007 // Add backedge value to worklist. 4008 Worklist.push_back(U.get()); 4009 continue; 4010 } 4011 4012 // Don't bother handling multiple start values. 4013 if (StartU) 4014 return nullptr; 4015 StartU = &U; 4016 } 4017 4018 if (!StartU || Worklist.empty()) 4019 return nullptr; // Not a recurrence. 4020 4021 Value *StartV = StartU->get(); 4022 BasicBlock *StartBB = PN->getIncomingBlock(*StartU); 4023 bool StartNeedsFreeze = !isGuaranteedNotToBeUndefOrPoison(StartV); 4024 // We can't insert freeze if the start value is the result of the 4025 // terminator (e.g. an invoke). 4026 if (StartNeedsFreeze && StartBB->getTerminator() == StartV) 4027 return nullptr; 4028 4029 SmallPtrSet<Value *, 32> Visited; 4030 SmallVector<Instruction *> DropFlags; 4031 while (!Worklist.empty()) { 4032 Value *V = Worklist.pop_back_val(); 4033 if (!Visited.insert(V).second) 4034 continue; 4035 4036 if (Visited.size() > 32) 4037 return nullptr; // Limit the total number of values we inspect. 4038 4039 // Assume that PN is non-poison, because it will be after the transform. 4040 if (V == PN || isGuaranteedNotToBeUndefOrPoison(V)) 4041 continue; 4042 4043 Instruction *I = dyn_cast<Instruction>(V); 4044 if (!I || canCreateUndefOrPoison(cast<Operator>(I), 4045 /*ConsiderFlagsAndMetadata*/ false)) 4046 return nullptr; 4047 4048 DropFlags.push_back(I); 4049 append_range(Worklist, I->operands()); 4050 } 4051 4052 for (Instruction *I : DropFlags) 4053 I->dropPoisonGeneratingFlagsAndMetadata(); 4054 4055 if (StartNeedsFreeze) { 4056 Builder.SetInsertPoint(StartBB->getTerminator()); 4057 Value *FrozenStartV = Builder.CreateFreeze(StartV, 4058 StartV->getName() + ".fr"); 4059 replaceUse(*StartU, FrozenStartV); 4060 } 4061 return replaceInstUsesWith(FI, PN); 4062 } 4063 4064 bool InstCombinerImpl::freezeOtherUses(FreezeInst &FI) { 4065 Value *Op = FI.getOperand(0); 4066 4067 if (isa<Constant>(Op) || Op->hasOneUse()) 4068 return false; 4069 4070 // Move the freeze directly after the definition of its operand, so that 4071 // it dominates the maximum number of uses. Note that it may not dominate 4072 // *all* uses if the operand is an invoke/callbr and the use is in a phi on 4073 // the normal/default destination. This is why the domination check in the 4074 // replacement below is still necessary. 4075 BasicBlock::iterator MoveBefore; 4076 if (isa<Argument>(Op)) { 4077 MoveBefore = 4078 FI.getFunction()->getEntryBlock().getFirstNonPHIOrDbgOrAlloca(); 4079 } else { 4080 auto MoveBeforeOpt = cast<Instruction>(Op)->getInsertionPointAfterDef(); 4081 if (!MoveBeforeOpt) 4082 return false; 4083 MoveBefore = *MoveBeforeOpt; 4084 } 4085 4086 // Don't move to the position of a debug intrinsic. 4087 if (isa<DbgInfoIntrinsic>(MoveBefore)) 4088 MoveBefore = MoveBefore->getNextNonDebugInstruction()->getIterator(); 4089 // Re-point iterator to come after any debug-info records, if we're 4090 // running in "RemoveDIs" mode 4091 MoveBefore.setHeadBit(false); 4092 4093 bool Changed = false; 4094 if (&FI != &*MoveBefore) { 4095 FI.moveBefore(*MoveBefore->getParent(), MoveBefore); 4096 Changed = true; 4097 } 4098 4099 Op->replaceUsesWithIf(&FI, [&](Use &U) -> bool { 4100 bool Dominates = DT.dominates(&FI, U); 4101 Changed |= Dominates; 4102 return Dominates; 4103 }); 4104 4105 return Changed; 4106 } 4107 4108 // Check if any direct or bitcast user of this value is a shuffle instruction. 4109 static bool isUsedWithinShuffleVector(Value *V) { 4110 for (auto *U : V->users()) { 4111 if (isa<ShuffleVectorInst>(U)) 4112 return true; 4113 else if (match(U, m_BitCast(m_Specific(V))) && isUsedWithinShuffleVector(U)) 4114 return true; 4115 } 4116 return false; 4117 } 4118 4119 Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) { 4120 Value *Op0 = I.getOperand(0); 4121 4122 if (Value *V = simplifyFreezeInst(Op0, SQ.getWithInstruction(&I))) 4123 return replaceInstUsesWith(I, V); 4124 4125 // freeze (phi const, x) --> phi const, (freeze x) 4126 if (auto *PN = dyn_cast<PHINode>(Op0)) { 4127 if (Instruction *NV = foldOpIntoPhi(I, PN)) 4128 return NV; 4129 if (Instruction *NV = foldFreezeIntoRecurrence(I, PN)) 4130 return NV; 4131 } 4132 4133 if (Value *NI = pushFreezeToPreventPoisonFromPropagating(I)) 4134 return replaceInstUsesWith(I, NI); 4135 4136 // If I is freeze(undef), check its uses and fold it to a fixed constant. 4137 // - or: pick -1 4138 // - select's condition: if the true value is constant, choose it by making 4139 // the condition true. 4140 // - default: pick 0 4141 // 4142 // Note that this transform is intentionally done here rather than 4143 // via an analysis in InstSimplify or at individual user sites. That is 4144 // because we must produce the same value for all uses of the freeze - 4145 // it's the reason "freeze" exists! 4146 // 4147 // TODO: This could use getBinopAbsorber() / getBinopIdentity() to avoid 4148 // duplicating logic for binops at least. 4149 auto getUndefReplacement = [&I](Type *Ty) { 4150 Constant *BestValue = nullptr; 4151 Constant *NullValue = Constant::getNullValue(Ty); 4152 for (const auto *U : I.users()) { 4153 Constant *C = NullValue; 4154 if (match(U, m_Or(m_Value(), m_Value()))) 4155 C = ConstantInt::getAllOnesValue(Ty); 4156 else if (match(U, m_Select(m_Specific(&I), m_Constant(), m_Value()))) 4157 C = ConstantInt::getTrue(Ty); 4158 4159 if (!BestValue) 4160 BestValue = C; 4161 else if (BestValue != C) 4162 BestValue = NullValue; 4163 } 4164 assert(BestValue && "Must have at least one use"); 4165 return BestValue; 4166 }; 4167 4168 if (match(Op0, m_Undef())) { 4169 // Don't fold freeze(undef/poison) if it's used as a vector operand in 4170 // a shuffle. This may improve codegen for shuffles that allow 4171 // unspecified inputs. 4172 if (isUsedWithinShuffleVector(&I)) 4173 return nullptr; 4174 return replaceInstUsesWith(I, getUndefReplacement(I.getType())); 4175 } 4176 4177 Constant *C; 4178 if (match(Op0, m_Constant(C)) && C->containsUndefOrPoisonElement()) { 4179 Constant *ReplaceC = getUndefReplacement(I.getType()->getScalarType()); 4180 return replaceInstUsesWith(I, Constant::replaceUndefsWith(C, ReplaceC)); 4181 } 4182 4183 // Replace uses of Op with freeze(Op). 4184 if (freezeOtherUses(I)) 4185 return &I; 4186 4187 return nullptr; 4188 } 4189 4190 /// Check for case where the call writes to an otherwise dead alloca. This 4191 /// shows up for unused out-params in idiomatic C/C++ code. Note that this 4192 /// helper *only* analyzes the write; doesn't check any other legality aspect. 4193 static bool SoleWriteToDeadLocal(Instruction *I, TargetLibraryInfo &TLI) { 4194 auto *CB = dyn_cast<CallBase>(I); 4195 if (!CB) 4196 // TODO: handle e.g. store to alloca here - only worth doing if we extend 4197 // to allow reload along used path as described below. Otherwise, this 4198 // is simply a store to a dead allocation which will be removed. 4199 return false; 4200 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(CB, TLI); 4201 if (!Dest) 4202 return false; 4203 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(Dest->Ptr)); 4204 if (!AI) 4205 // TODO: allow malloc? 4206 return false; 4207 // TODO: allow memory access dominated by move point? Note that since AI 4208 // could have a reference to itself captured by the call, we would need to 4209 // account for cycles in doing so. 4210 SmallVector<const User *> AllocaUsers; 4211 SmallPtrSet<const User *, 4> Visited; 4212 auto pushUsers = [&](const Instruction &I) { 4213 for (const User *U : I.users()) { 4214 if (Visited.insert(U).second) 4215 AllocaUsers.push_back(U); 4216 } 4217 }; 4218 pushUsers(*AI); 4219 while (!AllocaUsers.empty()) { 4220 auto *UserI = cast<Instruction>(AllocaUsers.pop_back_val()); 4221 if (isa<BitCastInst>(UserI) || isa<GetElementPtrInst>(UserI) || 4222 isa<AddrSpaceCastInst>(UserI)) { 4223 pushUsers(*UserI); 4224 continue; 4225 } 4226 if (UserI == CB) 4227 continue; 4228 // TODO: support lifetime.start/end here 4229 return false; 4230 } 4231 return true; 4232 } 4233 4234 /// Try to move the specified instruction from its current block into the 4235 /// beginning of DestBlock, which can only happen if it's safe to move the 4236 /// instruction past all of the instructions between it and the end of its 4237 /// block. 4238 bool InstCombinerImpl::tryToSinkInstruction(Instruction *I, 4239 BasicBlock *DestBlock) { 4240 BasicBlock *SrcBlock = I->getParent(); 4241 4242 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 4243 if (isa<PHINode>(I) || I->isEHPad() || I->mayThrow() || !I->willReturn() || 4244 I->isTerminator()) 4245 return false; 4246 4247 // Do not sink static or dynamic alloca instructions. Static allocas must 4248 // remain in the entry block, and dynamic allocas must not be sunk in between 4249 // a stacksave / stackrestore pair, which would incorrectly shorten its 4250 // lifetime. 4251 if (isa<AllocaInst>(I)) 4252 return false; 4253 4254 // Do not sink into catchswitch blocks. 4255 if (isa<CatchSwitchInst>(DestBlock->getTerminator())) 4256 return false; 4257 4258 // Do not sink convergent call instructions. 4259 if (auto *CI = dyn_cast<CallInst>(I)) { 4260 if (CI->isConvergent()) 4261 return false; 4262 } 4263 4264 // Unless we can prove that the memory write isn't visibile except on the 4265 // path we're sinking to, we must bail. 4266 if (I->mayWriteToMemory()) { 4267 if (!SoleWriteToDeadLocal(I, TLI)) 4268 return false; 4269 } 4270 4271 // We can only sink load instructions if there is nothing between the load and 4272 // the end of block that could change the value. 4273 if (I->mayReadFromMemory()) { 4274 // We don't want to do any sophisticated alias analysis, so we only check 4275 // the instructions after I in I's parent block if we try to sink to its 4276 // successor block. 4277 if (DestBlock->getUniquePredecessor() != I->getParent()) 4278 return false; 4279 for (BasicBlock::iterator Scan = std::next(I->getIterator()), 4280 E = I->getParent()->end(); 4281 Scan != E; ++Scan) 4282 if (Scan->mayWriteToMemory()) 4283 return false; 4284 } 4285 4286 I->dropDroppableUses([&](const Use *U) { 4287 auto *I = dyn_cast<Instruction>(U->getUser()); 4288 if (I && I->getParent() != DestBlock) { 4289 Worklist.add(I); 4290 return true; 4291 } 4292 return false; 4293 }); 4294 /// FIXME: We could remove droppable uses that are not dominated by 4295 /// the new position. 4296 4297 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); 4298 I->moveBefore(*DestBlock, InsertPos); 4299 ++NumSunkInst; 4300 4301 // Also sink all related debug uses from the source basic block. Otherwise we 4302 // get debug use before the def. Attempt to salvage debug uses first, to 4303 // maximise the range variables have location for. If we cannot salvage, then 4304 // mark the location undef: we know it was supposed to receive a new location 4305 // here, but that computation has been sunk. 4306 SmallVector<DbgVariableIntrinsic *, 2> DbgUsers; 4307 findDbgUsers(DbgUsers, I); 4308 4309 // For all debug values in the destination block, the sunk instruction 4310 // will still be available, so they do not need to be dropped. 4311 SmallVector<DbgVariableIntrinsic *, 2> DbgUsersToSalvage; 4312 SmallVector<DPValue *, 2> DPValuesToSalvage; 4313 for (auto &DbgUser : DbgUsers) 4314 if (DbgUser->getParent() != DestBlock) 4315 DbgUsersToSalvage.push_back(DbgUser); 4316 4317 // Process the sinking DbgUsersToSalvage in reverse order, as we only want 4318 // to clone the last appearing debug intrinsic for each given variable. 4319 SmallVector<DbgVariableIntrinsic *, 2> DbgUsersToSink; 4320 for (DbgVariableIntrinsic *DVI : DbgUsersToSalvage) 4321 if (DVI->getParent() == SrcBlock) 4322 DbgUsersToSink.push_back(DVI); 4323 llvm::sort(DbgUsersToSink, 4324 [](auto *A, auto *B) { return B->comesBefore(A); }); 4325 4326 SmallVector<DbgVariableIntrinsic *, 2> DIIClones; 4327 SmallSet<DebugVariable, 4> SunkVariables; 4328 for (auto *User : DbgUsersToSink) { 4329 // A dbg.declare instruction should not be cloned, since there can only be 4330 // one per variable fragment. It should be left in the original place 4331 // because the sunk instruction is not an alloca (otherwise we could not be 4332 // here). 4333 if (isa<DbgDeclareInst>(User)) 4334 continue; 4335 4336 DebugVariable DbgUserVariable = 4337 DebugVariable(User->getVariable(), User->getExpression(), 4338 User->getDebugLoc()->getInlinedAt()); 4339 4340 if (!SunkVariables.insert(DbgUserVariable).second) 4341 continue; 4342 4343 // Leave dbg.assign intrinsics in their original positions and there should 4344 // be no need to insert a clone. 4345 if (isa<DbgAssignIntrinsic>(User)) 4346 continue; 4347 4348 DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone())); 4349 if (isa<DbgDeclareInst>(User) && isa<CastInst>(I)) 4350 DIIClones.back()->replaceVariableLocationOp(I, I->getOperand(0)); 4351 LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n'); 4352 } 4353 4354 // Perform salvaging without the clones, then sink the clones. 4355 if (!DIIClones.empty()) { 4356 // RemoveDIs: pass in empty vector of DPValues until we get to instrumenting 4357 // this pass. 4358 SmallVector<DPValue *, 1> DummyDPValues; 4359 salvageDebugInfoForDbgValues(*I, DbgUsersToSalvage, DummyDPValues); 4360 // The clones are in reverse order of original appearance, reverse again to 4361 // maintain the original order. 4362 for (auto &DIIClone : llvm::reverse(DIIClones)) { 4363 DIIClone->insertBefore(&*InsertPos); 4364 LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n'); 4365 } 4366 } 4367 4368 return true; 4369 } 4370 4371 bool InstCombinerImpl::run() { 4372 while (!Worklist.isEmpty()) { 4373 // Walk deferred instructions in reverse order, and push them to the 4374 // worklist, which means they'll end up popped from the worklist in-order. 4375 while (Instruction *I = Worklist.popDeferred()) { 4376 // Check to see if we can DCE the instruction. We do this already here to 4377 // reduce the number of uses and thus allow other folds to trigger. 4378 // Note that eraseInstFromFunction() may push additional instructions on 4379 // the deferred worklist, so this will DCE whole instruction chains. 4380 if (isInstructionTriviallyDead(I, &TLI)) { 4381 eraseInstFromFunction(*I); 4382 ++NumDeadInst; 4383 continue; 4384 } 4385 4386 Worklist.push(I); 4387 } 4388 4389 Instruction *I = Worklist.removeOne(); 4390 if (I == nullptr) continue; // skip null values. 4391 4392 // Check to see if we can DCE the instruction. 4393 if (isInstructionTriviallyDead(I, &TLI)) { 4394 eraseInstFromFunction(*I); 4395 ++NumDeadInst; 4396 continue; 4397 } 4398 4399 if (!DebugCounter::shouldExecute(VisitCounter)) 4400 continue; 4401 4402 // See if we can trivially sink this instruction to its user if we can 4403 // prove that the successor is not executed more frequently than our block. 4404 // Return the UserBlock if successful. 4405 auto getOptionalSinkBlockForInst = 4406 [this](Instruction *I) -> std::optional<BasicBlock *> { 4407 if (!EnableCodeSinking) 4408 return std::nullopt; 4409 4410 BasicBlock *BB = I->getParent(); 4411 BasicBlock *UserParent = nullptr; 4412 unsigned NumUsers = 0; 4413 4414 for (auto *U : I->users()) { 4415 if (U->isDroppable()) 4416 continue; 4417 if (NumUsers > MaxSinkNumUsers) 4418 return std::nullopt; 4419 4420 Instruction *UserInst = cast<Instruction>(U); 4421 // Special handling for Phi nodes - get the block the use occurs in. 4422 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) { 4423 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 4424 if (PN->getIncomingValue(i) == I) { 4425 // Bail out if we have uses in different blocks. We don't do any 4426 // sophisticated analysis (i.e finding NearestCommonDominator of 4427 // these use blocks). 4428 if (UserParent && UserParent != PN->getIncomingBlock(i)) 4429 return std::nullopt; 4430 UserParent = PN->getIncomingBlock(i); 4431 } 4432 } 4433 assert(UserParent && "expected to find user block!"); 4434 } else { 4435 if (UserParent && UserParent != UserInst->getParent()) 4436 return std::nullopt; 4437 UserParent = UserInst->getParent(); 4438 } 4439 4440 // Make sure these checks are done only once, naturally we do the checks 4441 // the first time we get the userparent, this will save compile time. 4442 if (NumUsers == 0) { 4443 // Try sinking to another block. If that block is unreachable, then do 4444 // not bother. SimplifyCFG should handle it. 4445 if (UserParent == BB || !DT.isReachableFromEntry(UserParent)) 4446 return std::nullopt; 4447 4448 auto *Term = UserParent->getTerminator(); 4449 // See if the user is one of our successors that has only one 4450 // predecessor, so that we don't have to split the critical edge. 4451 // Another option where we can sink is a block that ends with a 4452 // terminator that does not pass control to other block (such as 4453 // return or unreachable or resume). In this case: 4454 // - I dominates the User (by SSA form); 4455 // - the User will be executed at most once. 4456 // So sinking I down to User is always profitable or neutral. 4457 if (UserParent->getUniquePredecessor() != BB && !succ_empty(Term)) 4458 return std::nullopt; 4459 4460 assert(DT.dominates(BB, UserParent) && "Dominance relation broken?"); 4461 } 4462 4463 NumUsers++; 4464 } 4465 4466 // No user or only has droppable users. 4467 if (!UserParent) 4468 return std::nullopt; 4469 4470 return UserParent; 4471 }; 4472 4473 auto OptBB = getOptionalSinkBlockForInst(I); 4474 if (OptBB) { 4475 auto *UserParent = *OptBB; 4476 // Okay, the CFG is simple enough, try to sink this instruction. 4477 if (tryToSinkInstruction(I, UserParent)) { 4478 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n'); 4479 MadeIRChange = true; 4480 // We'll add uses of the sunk instruction below, but since 4481 // sinking can expose opportunities for it's *operands* add 4482 // them to the worklist 4483 for (Use &U : I->operands()) 4484 if (Instruction *OpI = dyn_cast<Instruction>(U.get())) 4485 Worklist.push(OpI); 4486 } 4487 } 4488 4489 // Now that we have an instruction, try combining it to simplify it. 4490 Builder.SetInsertPoint(I); 4491 Builder.CollectMetadataToCopy( 4492 I, {LLVMContext::MD_dbg, LLVMContext::MD_annotation}); 4493 4494 #ifndef NDEBUG 4495 std::string OrigI; 4496 #endif 4497 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 4498 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n'); 4499 4500 if (Instruction *Result = visit(*I)) { 4501 ++NumCombined; 4502 // Should we replace the old instruction with a new one? 4503 if (Result != I) { 4504 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n' 4505 << " New = " << *Result << '\n'); 4506 4507 Result->copyMetadata(*I, 4508 {LLVMContext::MD_dbg, LLVMContext::MD_annotation}); 4509 // Everything uses the new instruction now. 4510 I->replaceAllUsesWith(Result); 4511 4512 // Move the name to the new instruction first. 4513 Result->takeName(I); 4514 4515 // Insert the new instruction into the basic block... 4516 BasicBlock *InstParent = I->getParent(); 4517 BasicBlock::iterator InsertPos = I->getIterator(); 4518 4519 // Are we replace a PHI with something that isn't a PHI, or vice versa? 4520 if (isa<PHINode>(Result) != isa<PHINode>(I)) { 4521 // We need to fix up the insertion point. 4522 if (isa<PHINode>(I)) // PHI -> Non-PHI 4523 InsertPos = InstParent->getFirstInsertionPt(); 4524 else // Non-PHI -> PHI 4525 InsertPos = InstParent->getFirstNonPHIIt(); 4526 } 4527 4528 Result->insertInto(InstParent, InsertPos); 4529 4530 // Push the new instruction and any users onto the worklist. 4531 Worklist.pushUsersToWorkList(*Result); 4532 Worklist.push(Result); 4533 4534 eraseInstFromFunction(*I); 4535 } else { 4536 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n' 4537 << " New = " << *I << '\n'); 4538 4539 // If the instruction was modified, it's possible that it is now dead. 4540 // if so, remove it. 4541 if (isInstructionTriviallyDead(I, &TLI)) { 4542 eraseInstFromFunction(*I); 4543 } else { 4544 Worklist.pushUsersToWorkList(*I); 4545 Worklist.push(I); 4546 } 4547 } 4548 MadeIRChange = true; 4549 } 4550 } 4551 4552 Worklist.zap(); 4553 return MadeIRChange; 4554 } 4555 4556 // Track the scopes used by !alias.scope and !noalias. In a function, a 4557 // @llvm.experimental.noalias.scope.decl is only useful if that scope is used 4558 // by both sets. If not, the declaration of the scope can be safely omitted. 4559 // The MDNode of the scope can be omitted as well for the instructions that are 4560 // part of this function. We do not do that at this point, as this might become 4561 // too time consuming to do. 4562 class AliasScopeTracker { 4563 SmallPtrSet<const MDNode *, 8> UsedAliasScopesAndLists; 4564 SmallPtrSet<const MDNode *, 8> UsedNoAliasScopesAndLists; 4565 4566 public: 4567 void analyse(Instruction *I) { 4568 // This seems to be faster than checking 'mayReadOrWriteMemory()'. 4569 if (!I->hasMetadataOtherThanDebugLoc()) 4570 return; 4571 4572 auto Track = [](Metadata *ScopeList, auto &Container) { 4573 const auto *MDScopeList = dyn_cast_or_null<MDNode>(ScopeList); 4574 if (!MDScopeList || !Container.insert(MDScopeList).second) 4575 return; 4576 for (const auto &MDOperand : MDScopeList->operands()) 4577 if (auto *MDScope = dyn_cast<MDNode>(MDOperand)) 4578 Container.insert(MDScope); 4579 }; 4580 4581 Track(I->getMetadata(LLVMContext::MD_alias_scope), UsedAliasScopesAndLists); 4582 Track(I->getMetadata(LLVMContext::MD_noalias), UsedNoAliasScopesAndLists); 4583 } 4584 4585 bool isNoAliasScopeDeclDead(Instruction *Inst) { 4586 NoAliasScopeDeclInst *Decl = dyn_cast<NoAliasScopeDeclInst>(Inst); 4587 if (!Decl) 4588 return false; 4589 4590 assert(Decl->use_empty() && 4591 "llvm.experimental.noalias.scope.decl in use ?"); 4592 const MDNode *MDSL = Decl->getScopeList(); 4593 assert(MDSL->getNumOperands() == 1 && 4594 "llvm.experimental.noalias.scope should refer to a single scope"); 4595 auto &MDOperand = MDSL->getOperand(0); 4596 if (auto *MD = dyn_cast<MDNode>(MDOperand)) 4597 return !UsedAliasScopesAndLists.contains(MD) || 4598 !UsedNoAliasScopesAndLists.contains(MD); 4599 4600 // Not an MDNode ? throw away. 4601 return true; 4602 } 4603 }; 4604 4605 /// Populate the IC worklist from a function, by walking it in reverse 4606 /// post-order and adding all reachable code to the worklist. 4607 /// 4608 /// This has a couple of tricks to make the code faster and more powerful. In 4609 /// particular, we constant fold and DCE instructions as we go, to avoid adding 4610 /// them to the worklist (this significantly speeds up instcombine on code where 4611 /// many instructions are dead or constant). Additionally, if we find a branch 4612 /// whose condition is a known constant, we only visit the reachable successors. 4613 bool InstCombinerImpl::prepareWorklist( 4614 Function &F, ReversePostOrderTraversal<BasicBlock *> &RPOT) { 4615 bool MadeIRChange = false; 4616 SmallPtrSet<BasicBlock *, 32> LiveBlocks; 4617 SmallVector<Instruction *, 128> InstrsForInstructionWorklist; 4618 DenseMap<Constant *, Constant *> FoldedConstants; 4619 AliasScopeTracker SeenAliasScopes; 4620 4621 auto HandleOnlyLiveSuccessor = [&](BasicBlock *BB, BasicBlock *LiveSucc) { 4622 for (BasicBlock *Succ : successors(BB)) 4623 if (Succ != LiveSucc && DeadEdges.insert({BB, Succ}).second) 4624 for (PHINode &PN : Succ->phis()) 4625 for (Use &U : PN.incoming_values()) 4626 if (PN.getIncomingBlock(U) == BB && !isa<PoisonValue>(U)) { 4627 U.set(PoisonValue::get(PN.getType())); 4628 MadeIRChange = true; 4629 } 4630 }; 4631 4632 for (BasicBlock *BB : RPOT) { 4633 if (!BB->isEntryBlock() && all_of(predecessors(BB), [&](BasicBlock *Pred) { 4634 return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred); 4635 })) { 4636 HandleOnlyLiveSuccessor(BB, nullptr); 4637 continue; 4638 } 4639 LiveBlocks.insert(BB); 4640 4641 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) { 4642 // ConstantProp instruction if trivially constant. 4643 if (!Inst.use_empty() && 4644 (Inst.getNumOperands() == 0 || isa<Constant>(Inst.getOperand(0)))) 4645 if (Constant *C = ConstantFoldInstruction(&Inst, DL, &TLI)) { 4646 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << Inst 4647 << '\n'); 4648 Inst.replaceAllUsesWith(C); 4649 ++NumConstProp; 4650 if (isInstructionTriviallyDead(&Inst, &TLI)) 4651 Inst.eraseFromParent(); 4652 MadeIRChange = true; 4653 continue; 4654 } 4655 4656 // See if we can constant fold its operands. 4657 for (Use &U : Inst.operands()) { 4658 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U)) 4659 continue; 4660 4661 auto *C = cast<Constant>(U); 4662 Constant *&FoldRes = FoldedConstants[C]; 4663 if (!FoldRes) 4664 FoldRes = ConstantFoldConstant(C, DL, &TLI); 4665 4666 if (FoldRes != C) { 4667 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << Inst 4668 << "\n Old = " << *C 4669 << "\n New = " << *FoldRes << '\n'); 4670 U = FoldRes; 4671 MadeIRChange = true; 4672 } 4673 } 4674 4675 // Skip processing debug and pseudo intrinsics in InstCombine. Processing 4676 // these call instructions consumes non-trivial amount of time and 4677 // provides no value for the optimization. 4678 if (!Inst.isDebugOrPseudoInst()) { 4679 InstrsForInstructionWorklist.push_back(&Inst); 4680 SeenAliasScopes.analyse(&Inst); 4681 } 4682 } 4683 4684 // If this is a branch or switch on a constant, mark only the single 4685 // live successor. Otherwise assume all successors are live. 4686 Instruction *TI = BB->getTerminator(); 4687 if (BranchInst *BI = dyn_cast<BranchInst>(TI); BI && BI->isConditional()) { 4688 if (isa<UndefValue>(BI->getCondition())) { 4689 // Branch on undef is UB. 4690 HandleOnlyLiveSuccessor(BB, nullptr); 4691 continue; 4692 } 4693 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) { 4694 bool CondVal = Cond->getZExtValue(); 4695 HandleOnlyLiveSuccessor(BB, BI->getSuccessor(!CondVal)); 4696 continue; 4697 } 4698 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 4699 if (isa<UndefValue>(SI->getCondition())) { 4700 // Switch on undef is UB. 4701 HandleOnlyLiveSuccessor(BB, nullptr); 4702 continue; 4703 } 4704 if (auto *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 4705 HandleOnlyLiveSuccessor(BB, 4706 SI->findCaseValue(Cond)->getCaseSuccessor()); 4707 continue; 4708 } 4709 } 4710 } 4711 4712 // Remove instructions inside unreachable blocks. This prevents the 4713 // instcombine code from having to deal with some bad special cases, and 4714 // reduces use counts of instructions. 4715 for (BasicBlock &BB : F) { 4716 if (LiveBlocks.count(&BB)) 4717 continue; 4718 4719 unsigned NumDeadInstInBB; 4720 unsigned NumDeadDbgInstInBB; 4721 std::tie(NumDeadInstInBB, NumDeadDbgInstInBB) = 4722 removeAllNonTerminatorAndEHPadInstructions(&BB); 4723 4724 MadeIRChange |= NumDeadInstInBB + NumDeadDbgInstInBB > 0; 4725 NumDeadInst += NumDeadInstInBB; 4726 } 4727 4728 // Once we've found all of the instructions to add to instcombine's worklist, 4729 // add them in reverse order. This way instcombine will visit from the top 4730 // of the function down. This jives well with the way that it adds all uses 4731 // of instructions to the worklist after doing a transformation, thus avoiding 4732 // some N^2 behavior in pathological cases. 4733 Worklist.reserve(InstrsForInstructionWorklist.size()); 4734 for (Instruction *Inst : reverse(InstrsForInstructionWorklist)) { 4735 // DCE instruction if trivially dead. As we iterate in reverse program 4736 // order here, we will clean up whole chains of dead instructions. 4737 if (isInstructionTriviallyDead(Inst, &TLI) || 4738 SeenAliasScopes.isNoAliasScopeDeclDead(Inst)) { 4739 ++NumDeadInst; 4740 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n'); 4741 salvageDebugInfo(*Inst); 4742 Inst->eraseFromParent(); 4743 MadeIRChange = true; 4744 continue; 4745 } 4746 4747 Worklist.push(Inst); 4748 } 4749 4750 return MadeIRChange; 4751 } 4752 4753 static bool combineInstructionsOverFunction( 4754 Function &F, InstructionWorklist &Worklist, AliasAnalysis *AA, 4755 AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, 4756 DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, 4757 ProfileSummaryInfo *PSI, LoopInfo *LI, const InstCombineOptions &Opts) { 4758 auto &DL = F.getParent()->getDataLayout(); 4759 4760 /// Builder - This is an IRBuilder that automatically inserts new 4761 /// instructions into the worklist when they are created. 4762 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder( 4763 F.getContext(), TargetFolder(DL), 4764 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) { 4765 Worklist.add(I); 4766 if (auto *Assume = dyn_cast<AssumeInst>(I)) 4767 AC.registerAssumption(Assume); 4768 })); 4769 4770 ReversePostOrderTraversal<BasicBlock *> RPOT(&F.front()); 4771 4772 // Lower dbg.declare intrinsics otherwise their value may be clobbered 4773 // by instcombiner. 4774 bool MadeIRChange = false; 4775 if (ShouldLowerDbgDeclare) 4776 MadeIRChange = LowerDbgDeclare(F); 4777 4778 // Iterate while there is work to do. 4779 unsigned Iteration = 0; 4780 while (true) { 4781 ++Iteration; 4782 4783 if (Iteration > Opts.MaxIterations && !Opts.VerifyFixpoint) { 4784 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << Opts.MaxIterations 4785 << " on " << F.getName() 4786 << " reached; stopping without verifying fixpoint\n"); 4787 break; 4788 } 4789 4790 ++NumWorklistIterations; 4791 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 4792 << F.getName() << "\n"); 4793 4794 InstCombinerImpl IC(Worklist, Builder, F.hasMinSize(), AA, AC, TLI, TTI, DT, 4795 ORE, BFI, PSI, DL, LI); 4796 IC.MaxArraySizeForCombine = MaxArraySize; 4797 bool MadeChangeInThisIteration = IC.prepareWorklist(F, RPOT); 4798 MadeChangeInThisIteration |= IC.run(); 4799 if (!MadeChangeInThisIteration) 4800 break; 4801 4802 MadeIRChange = true; 4803 if (Iteration > Opts.MaxIterations) { 4804 report_fatal_error( 4805 "Instruction Combining did not reach a fixpoint after " + 4806 Twine(Opts.MaxIterations) + " iterations"); 4807 } 4808 } 4809 4810 if (Iteration == 1) 4811 ++NumOneIteration; 4812 else if (Iteration == 2) 4813 ++NumTwoIterations; 4814 else if (Iteration == 3) 4815 ++NumThreeIterations; 4816 else 4817 ++NumFourOrMoreIterations; 4818 4819 return MadeIRChange; 4820 } 4821 4822 InstCombinePass::InstCombinePass(InstCombineOptions Opts) : Options(Opts) {} 4823 4824 void InstCombinePass::printPipeline( 4825 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) { 4826 static_cast<PassInfoMixin<InstCombinePass> *>(this)->printPipeline( 4827 OS, MapClassName2PassName); 4828 OS << '<'; 4829 OS << "max-iterations=" << Options.MaxIterations << ";"; 4830 OS << (Options.UseLoopInfo ? "" : "no-") << "use-loop-info;"; 4831 OS << (Options.VerifyFixpoint ? "" : "no-") << "verify-fixpoint"; 4832 OS << '>'; 4833 } 4834 4835 PreservedAnalyses InstCombinePass::run(Function &F, 4836 FunctionAnalysisManager &AM) { 4837 auto &AC = AM.getResult<AssumptionAnalysis>(F); 4838 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 4839 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 4840 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 4841 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 4842 4843 // TODO: Only use LoopInfo when the option is set. This requires that the 4844 // callers in the pass pipeline explicitly set the option. 4845 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 4846 if (!LI && Options.UseLoopInfo) 4847 LI = &AM.getResult<LoopAnalysis>(F); 4848 4849 auto *AA = &AM.getResult<AAManager>(F); 4850 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 4851 ProfileSummaryInfo *PSI = 4852 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 4853 auto *BFI = (PSI && PSI->hasProfileSummary()) ? 4854 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr; 4855 4856 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE, 4857 BFI, PSI, LI, Options)) 4858 // No changes, all analyses are preserved. 4859 return PreservedAnalyses::all(); 4860 4861 // Mark all the analyses that instcombine updates as preserved. 4862 PreservedAnalyses PA; 4863 PA.preserveSet<CFGAnalyses>(); 4864 return PA; 4865 } 4866 4867 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const { 4868 AU.setPreservesCFG(); 4869 AU.addRequired<AAResultsWrapperPass>(); 4870 AU.addRequired<AssumptionCacheTracker>(); 4871 AU.addRequired<TargetLibraryInfoWrapperPass>(); 4872 AU.addRequired<TargetTransformInfoWrapperPass>(); 4873 AU.addRequired<DominatorTreeWrapperPass>(); 4874 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 4875 AU.addPreserved<DominatorTreeWrapperPass>(); 4876 AU.addPreserved<AAResultsWrapperPass>(); 4877 AU.addPreserved<BasicAAWrapperPass>(); 4878 AU.addPreserved<GlobalsAAWrapperPass>(); 4879 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 4880 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU); 4881 } 4882 4883 bool InstructionCombiningPass::runOnFunction(Function &F) { 4884 if (skipFunction(F)) 4885 return false; 4886 4887 // Required analyses. 4888 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 4889 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 4890 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 4891 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 4892 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 4893 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 4894 4895 // Optional analyses. 4896 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 4897 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; 4898 ProfileSummaryInfo *PSI = 4899 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 4900 BlockFrequencyInfo *BFI = 4901 (PSI && PSI->hasProfileSummary()) ? 4902 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() : 4903 nullptr; 4904 4905 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE, 4906 BFI, PSI, LI, InstCombineOptions()); 4907 } 4908 4909 char InstructionCombiningPass::ID = 0; 4910 4911 InstructionCombiningPass::InstructionCombiningPass() : FunctionPass(ID) { 4912 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); 4913 } 4914 4915 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", 4916 "Combine redundant instructions", false, false) 4917 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 4918 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 4919 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 4920 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 4921 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 4922 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 4923 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 4924 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass) 4925 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 4926 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine", 4927 "Combine redundant instructions", false, false) 4928 4929 // Initialization Routines 4930 void llvm::initializeInstCombine(PassRegistry &Registry) { 4931 initializeInstructionCombiningPassPass(Registry); 4932 } 4933 4934 FunctionPass *llvm::createInstructionCombiningPass() { 4935 return new InstructionCombiningPass(); 4936 } 4937