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-c/Initialization.h" 37 #include "llvm-c/Transforms/InstCombine.h" 38 #include "llvm/ADT/APInt.h" 39 #include "llvm/ADT/ArrayRef.h" 40 #include "llvm/ADT/DenseMap.h" 41 #include "llvm/ADT/None.h" 42 #include "llvm/ADT/SmallPtrSet.h" 43 #include "llvm/ADT/SmallVector.h" 44 #include "llvm/ADT/Statistic.h" 45 #include "llvm/ADT/TinyPtrVector.h" 46 #include "llvm/Analysis/AliasAnalysis.h" 47 #include "llvm/Analysis/AssumptionCache.h" 48 #include "llvm/Analysis/BasicAliasAnalysis.h" 49 #include "llvm/Analysis/BlockFrequencyInfo.h" 50 #include "llvm/Analysis/CFG.h" 51 #include "llvm/Analysis/ConstantFolding.h" 52 #include "llvm/Analysis/EHPersonalities.h" 53 #include "llvm/Analysis/GlobalsModRef.h" 54 #include "llvm/Analysis/InstructionSimplify.h" 55 #include "llvm/Analysis/LazyBlockFrequencyInfo.h" 56 #include "llvm/Analysis/LoopInfo.h" 57 #include "llvm/Analysis/MemoryBuiltins.h" 58 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 59 #include "llvm/Analysis/ProfileSummaryInfo.h" 60 #include "llvm/Analysis/TargetFolder.h" 61 #include "llvm/Analysis/TargetLibraryInfo.h" 62 #include "llvm/Analysis/TargetTransformInfo.h" 63 #include "llvm/Analysis/ValueTracking.h" 64 #include "llvm/Analysis/VectorUtils.h" 65 #include "llvm/IR/BasicBlock.h" 66 #include "llvm/IR/CFG.h" 67 #include "llvm/IR/Constant.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DIBuilder.h" 70 #include "llvm/IR/DataLayout.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Dominators.h" 73 #include "llvm/IR/Function.h" 74 #include "llvm/IR/GetElementPtrTypeIterator.h" 75 #include "llvm/IR/IRBuilder.h" 76 #include "llvm/IR/InstrTypes.h" 77 #include "llvm/IR/Instruction.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/IntrinsicInst.h" 80 #include "llvm/IR/Intrinsics.h" 81 #include "llvm/IR/LegacyPassManager.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Operator.h" 84 #include "llvm/IR/PassManager.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Type.h" 87 #include "llvm/IR/Use.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/IR/ValueHandle.h" 91 #include "llvm/InitializePasses.h" 92 #include "llvm/Pass.h" 93 #include "llvm/Support/CBindingWrapping.h" 94 #include "llvm/Support/Casting.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/DebugCounter.h" 99 #include "llvm/Support/ErrorHandling.h" 100 #include "llvm/Support/KnownBits.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Transforms/InstCombine/InstCombine.h" 103 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 104 #include "llvm/Transforms/Utils/Local.h" 105 #include <algorithm> 106 #include <cassert> 107 #include <cstdint> 108 #include <memory> 109 #include <string> 110 #include <utility> 111 112 using namespace llvm; 113 using namespace llvm::PatternMatch; 114 115 #define DEBUG_TYPE "instcombine" 116 117 STATISTIC(NumWorklistIterations, 118 "Number of instruction combining iterations performed"); 119 120 STATISTIC(NumCombined , "Number of insts combined"); 121 STATISTIC(NumConstProp, "Number of constant folds"); 122 STATISTIC(NumDeadInst , "Number of dead inst eliminated"); 123 STATISTIC(NumSunkInst , "Number of instructions sunk"); 124 STATISTIC(NumExpand, "Number of expansions"); 125 STATISTIC(NumFactor , "Number of factorizations"); 126 STATISTIC(NumReassoc , "Number of reassociations"); 127 DEBUG_COUNTER(VisitCounter, "instcombine-visit", 128 "Controls which instructions are visited"); 129 130 // FIXME: these limits eventually should be as low as 2. 131 static constexpr unsigned InstCombineDefaultMaxIterations = 1000; 132 #ifndef NDEBUG 133 static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold = 100; 134 #else 135 static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold = 1000; 136 #endif 137 138 static cl::opt<bool> 139 EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"), 140 cl::init(true)); 141 142 static cl::opt<unsigned> LimitMaxIterations( 143 "instcombine-max-iterations", 144 cl::desc("Limit the maximum number of instruction combining iterations"), 145 cl::init(InstCombineDefaultMaxIterations)); 146 147 static cl::opt<unsigned> InfiniteLoopDetectionThreshold( 148 "instcombine-infinite-loop-threshold", 149 cl::desc("Number of instruction combining iterations considered an " 150 "infinite loop"), 151 cl::init(InstCombineDefaultInfiniteLoopThreshold), cl::Hidden); 152 153 static cl::opt<unsigned> 154 MaxArraySize("instcombine-maxarray-size", cl::init(1024), 155 cl::desc("Maximum array size considered when doing a combine")); 156 157 // FIXME: Remove this flag when it is no longer necessary to convert 158 // llvm.dbg.declare to avoid inaccurate debug info. Setting this to false 159 // increases variable availability at the cost of accuracy. Variables that 160 // cannot be promoted by mem2reg or SROA will be described as living in memory 161 // for their entire lifetime. However, passes like DSE and instcombine can 162 // delete stores to the alloca, leading to misleading and inaccurate debug 163 // information. This flag can be removed when those passes are fixed. 164 static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare", 165 cl::Hidden, cl::init(true)); 166 167 Optional<Instruction *> 168 InstCombiner::targetInstCombineIntrinsic(IntrinsicInst &II) { 169 // Handle target specific intrinsics 170 if (II.getCalledFunction()->isTargetIntrinsic()) { 171 return TTI.instCombineIntrinsic(*this, II); 172 } 173 return None; 174 } 175 176 Optional<Value *> InstCombiner::targetSimplifyDemandedUseBitsIntrinsic( 177 IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, 178 bool &KnownBitsComputed) { 179 // Handle target specific intrinsics 180 if (II.getCalledFunction()->isTargetIntrinsic()) { 181 return TTI.simplifyDemandedUseBitsIntrinsic(*this, II, DemandedMask, Known, 182 KnownBitsComputed); 183 } 184 return None; 185 } 186 187 Optional<Value *> InstCombiner::targetSimplifyDemandedVectorEltsIntrinsic( 188 IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, 189 APInt &UndefElts3, 190 std::function<void(Instruction *, unsigned, APInt, APInt &)> 191 SimplifyAndSetOp) { 192 // Handle target specific intrinsics 193 if (II.getCalledFunction()->isTargetIntrinsic()) { 194 return TTI.simplifyDemandedVectorEltsIntrinsic( 195 *this, II, DemandedElts, UndefElts, UndefElts2, UndefElts3, 196 SimplifyAndSetOp); 197 } 198 return None; 199 } 200 201 Value *InstCombinerImpl::EmitGEPOffset(User *GEP) { 202 return llvm::EmitGEPOffset(&Builder, DL, GEP); 203 } 204 205 /// Return true if it is desirable to convert an integer computation from a 206 /// given bit width to a new bit width. 207 /// We don't want to convert from a legal to an illegal type or from a smaller 208 /// to a larger illegal type. A width of '1' is always treated as a legal type 209 /// because i1 is a fundamental type in IR, and there are many specialized 210 /// optimizations for i1 types. Widths of 8, 16 or 32 are equally treated as 211 /// legal to convert to, in order to open up more combining opportunities. 212 /// NOTE: this treats i8, i16 and i32 specially, due to them being so common 213 /// from frontend languages. 214 bool InstCombinerImpl::shouldChangeType(unsigned FromWidth, 215 unsigned ToWidth) const { 216 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth); 217 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth); 218 219 // Convert to widths of 8, 16 or 32 even if they are not legal types. Only 220 // shrink types, to prevent infinite loops. 221 if (ToWidth < FromWidth && (ToWidth == 8 || ToWidth == 16 || ToWidth == 32)) 222 return true; 223 224 // If this is a legal integer from type, and the result would be an illegal 225 // type, don't do the transformation. 226 if (FromLegal && !ToLegal) 227 return false; 228 229 // Otherwise, if both are illegal, do not increase the size of the result. We 230 // do allow things like i160 -> i64, but not i64 -> i160. 231 if (!FromLegal && !ToLegal && ToWidth > FromWidth) 232 return false; 233 234 return true; 235 } 236 237 /// Return true if it is desirable to convert a computation from 'From' to 'To'. 238 /// We don't want to convert from a legal to an illegal type or from a smaller 239 /// to a larger illegal type. i1 is always treated as a legal type because it is 240 /// a fundamental type in IR, and there are many specialized optimizations for 241 /// i1 types. 242 bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const { 243 // TODO: This could be extended to allow vectors. Datalayout changes might be 244 // needed to properly support that. 245 if (!From->isIntegerTy() || !To->isIntegerTy()) 246 return false; 247 248 unsigned FromWidth = From->getPrimitiveSizeInBits(); 249 unsigned ToWidth = To->getPrimitiveSizeInBits(); 250 return shouldChangeType(FromWidth, ToWidth); 251 } 252 253 // Return true, if No Signed Wrap should be maintained for I. 254 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C", 255 // where both B and C should be ConstantInts, results in a constant that does 256 // not overflow. This function only handles the Add and Sub opcodes. For 257 // all other opcodes, the function conservatively returns false. 258 static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) { 259 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 260 if (!OBO || !OBO->hasNoSignedWrap()) 261 return false; 262 263 // We reason about Add and Sub Only. 264 Instruction::BinaryOps Opcode = I.getOpcode(); 265 if (Opcode != Instruction::Add && Opcode != Instruction::Sub) 266 return false; 267 268 const APInt *BVal, *CVal; 269 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal))) 270 return false; 271 272 bool Overflow = false; 273 if (Opcode == Instruction::Add) 274 (void)BVal->sadd_ov(*CVal, Overflow); 275 else 276 (void)BVal->ssub_ov(*CVal, Overflow); 277 278 return !Overflow; 279 } 280 281 static bool hasNoUnsignedWrap(BinaryOperator &I) { 282 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 283 return OBO && OBO->hasNoUnsignedWrap(); 284 } 285 286 static bool hasNoSignedWrap(BinaryOperator &I) { 287 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 288 return OBO && OBO->hasNoSignedWrap(); 289 } 290 291 /// Conservatively clears subclassOptionalData after a reassociation or 292 /// commutation. We preserve fast-math flags when applicable as they can be 293 /// preserved. 294 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) { 295 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I); 296 if (!FPMO) { 297 I.clearSubclassOptionalData(); 298 return; 299 } 300 301 FastMathFlags FMF = I.getFastMathFlags(); 302 I.clearSubclassOptionalData(); 303 I.setFastMathFlags(FMF); 304 } 305 306 /// Combine constant operands of associative operations either before or after a 307 /// cast to eliminate one of the associative operations: 308 /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2))) 309 /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2)) 310 static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1, 311 InstCombinerImpl &IC) { 312 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0)); 313 if (!Cast || !Cast->hasOneUse()) 314 return false; 315 316 // TODO: Enhance logic for other casts and remove this check. 317 auto CastOpcode = Cast->getOpcode(); 318 if (CastOpcode != Instruction::ZExt) 319 return false; 320 321 // TODO: Enhance logic for other BinOps and remove this check. 322 if (!BinOp1->isBitwiseLogicOp()) 323 return false; 324 325 auto AssocOpcode = BinOp1->getOpcode(); 326 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0)); 327 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode) 328 return false; 329 330 Constant *C1, *C2; 331 if (!match(BinOp1->getOperand(1), m_Constant(C1)) || 332 !match(BinOp2->getOperand(1), m_Constant(C2))) 333 return false; 334 335 // TODO: This assumes a zext cast. 336 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2 337 // to the destination type might lose bits. 338 339 // Fold the constants together in the destination type: 340 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC) 341 Type *DestTy = C1->getType(); 342 Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy); 343 Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2); 344 IC.replaceOperand(*Cast, 0, BinOp2->getOperand(0)); 345 IC.replaceOperand(*BinOp1, 1, FoldedC); 346 return true; 347 } 348 349 /// This performs a few simplifications for operators that are associative or 350 /// commutative: 351 /// 352 /// Commutative operators: 353 /// 354 /// 1. Order operands such that they are listed from right (least complex) to 355 /// left (most complex). This puts constants before unary operators before 356 /// binary operators. 357 /// 358 /// Associative operators: 359 /// 360 /// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 361 /// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 362 /// 363 /// Associative and commutative operators: 364 /// 365 /// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 366 /// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 367 /// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 368 /// if C1 and C2 are constants. 369 bool InstCombinerImpl::SimplifyAssociativeOrCommutative(BinaryOperator &I) { 370 Instruction::BinaryOps Opcode = I.getOpcode(); 371 bool Changed = false; 372 373 do { 374 // Order operands such that they are listed from right (least complex) to 375 // left (most complex). This puts constants before unary operators before 376 // binary operators. 377 if (I.isCommutative() && getComplexity(I.getOperand(0)) < 378 getComplexity(I.getOperand(1))) 379 Changed = !I.swapOperands(); 380 381 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); 382 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); 383 384 if (I.isAssociative()) { 385 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 386 if (Op0 && Op0->getOpcode() == Opcode) { 387 Value *A = Op0->getOperand(0); 388 Value *B = Op0->getOperand(1); 389 Value *C = I.getOperand(1); 390 391 // Does "B op C" simplify? 392 if (Value *V = SimplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) { 393 // It simplifies to V. Form "A op V". 394 replaceOperand(I, 0, A); 395 replaceOperand(I, 1, V); 396 bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0); 397 bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0); 398 399 // Conservatively clear all optional flags since they may not be 400 // preserved by the reassociation. Reset nsw/nuw based on the above 401 // analysis. 402 ClearSubclassDataAfterReassociation(I); 403 404 // Note: this is only valid because SimplifyBinOp doesn't look at 405 // the operands to Op0. 406 if (IsNUW) 407 I.setHasNoUnsignedWrap(true); 408 409 if (IsNSW) 410 I.setHasNoSignedWrap(true); 411 412 Changed = true; 413 ++NumReassoc; 414 continue; 415 } 416 } 417 418 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 419 if (Op1 && Op1->getOpcode() == Opcode) { 420 Value *A = I.getOperand(0); 421 Value *B = Op1->getOperand(0); 422 Value *C = Op1->getOperand(1); 423 424 // Does "A op B" simplify? 425 if (Value *V = SimplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) { 426 // It simplifies to V. Form "V op C". 427 replaceOperand(I, 0, V); 428 replaceOperand(I, 1, C); 429 // Conservatively clear the optional flags, since they may not be 430 // preserved by the reassociation. 431 ClearSubclassDataAfterReassociation(I); 432 Changed = true; 433 ++NumReassoc; 434 continue; 435 } 436 } 437 } 438 439 if (I.isAssociative() && I.isCommutative()) { 440 if (simplifyAssocCastAssoc(&I, *this)) { 441 Changed = true; 442 ++NumReassoc; 443 continue; 444 } 445 446 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 447 if (Op0 && Op0->getOpcode() == Opcode) { 448 Value *A = Op0->getOperand(0); 449 Value *B = Op0->getOperand(1); 450 Value *C = I.getOperand(1); 451 452 // Does "C op A" simplify? 453 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) { 454 // It simplifies to V. Form "V op B". 455 replaceOperand(I, 0, V); 456 replaceOperand(I, 1, B); 457 // Conservatively clear the optional flags, since they may not be 458 // preserved by the reassociation. 459 ClearSubclassDataAfterReassociation(I); 460 Changed = true; 461 ++NumReassoc; 462 continue; 463 } 464 } 465 466 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 467 if (Op1 && Op1->getOpcode() == Opcode) { 468 Value *A = I.getOperand(0); 469 Value *B = Op1->getOperand(0); 470 Value *C = Op1->getOperand(1); 471 472 // Does "C op A" simplify? 473 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) { 474 // It simplifies to V. Form "B op V". 475 replaceOperand(I, 0, B); 476 replaceOperand(I, 1, V); 477 // Conservatively clear the optional flags, since they may not be 478 // preserved by the reassociation. 479 ClearSubclassDataAfterReassociation(I); 480 Changed = true; 481 ++NumReassoc; 482 continue; 483 } 484 } 485 486 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 487 // if C1 and C2 are constants. 488 Value *A, *B; 489 Constant *C1, *C2; 490 if (Op0 && Op1 && 491 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode && 492 match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) && 493 match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2))))) { 494 bool IsNUW = hasNoUnsignedWrap(I) && 495 hasNoUnsignedWrap(*Op0) && 496 hasNoUnsignedWrap(*Op1); 497 BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ? 498 BinaryOperator::CreateNUW(Opcode, A, B) : 499 BinaryOperator::Create(Opcode, A, B); 500 501 if (isa<FPMathOperator>(NewBO)) { 502 FastMathFlags Flags = I.getFastMathFlags(); 503 Flags &= Op0->getFastMathFlags(); 504 Flags &= Op1->getFastMathFlags(); 505 NewBO->setFastMathFlags(Flags); 506 } 507 InsertNewInstWith(NewBO, I); 508 NewBO->takeName(Op1); 509 replaceOperand(I, 0, NewBO); 510 replaceOperand(I, 1, ConstantExpr::get(Opcode, C1, C2)); 511 // Conservatively clear the optional flags, since they may not be 512 // preserved by the reassociation. 513 ClearSubclassDataAfterReassociation(I); 514 if (IsNUW) 515 I.setHasNoUnsignedWrap(true); 516 517 Changed = true; 518 continue; 519 } 520 } 521 522 // No further simplifications. 523 return Changed; 524 } while (true); 525 } 526 527 /// Return whether "X LOp (Y ROp Z)" is always equal to 528 /// "(X LOp Y) ROp (X LOp Z)". 529 static bool leftDistributesOverRight(Instruction::BinaryOps LOp, 530 Instruction::BinaryOps ROp) { 531 // X & (Y | Z) <--> (X & Y) | (X & Z) 532 // X & (Y ^ Z) <--> (X & Y) ^ (X & Z) 533 if (LOp == Instruction::And) 534 return ROp == Instruction::Or || ROp == Instruction::Xor; 535 536 // X | (Y & Z) <--> (X | Y) & (X | Z) 537 if (LOp == Instruction::Or) 538 return ROp == Instruction::And; 539 540 // X * (Y + Z) <--> (X * Y) + (X * Z) 541 // X * (Y - Z) <--> (X * Y) - (X * Z) 542 if (LOp == Instruction::Mul) 543 return ROp == Instruction::Add || ROp == Instruction::Sub; 544 545 return false; 546 } 547 548 /// Return whether "(X LOp Y) ROp Z" is always equal to 549 /// "(X ROp Z) LOp (Y ROp Z)". 550 static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, 551 Instruction::BinaryOps ROp) { 552 if (Instruction::isCommutative(ROp)) 553 return leftDistributesOverRight(ROp, LOp); 554 555 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts. 556 return Instruction::isBitwiseLogicOp(LOp) && Instruction::isShift(ROp); 557 558 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z", 559 // but this requires knowing that the addition does not overflow and other 560 // such subtleties. 561 } 562 563 /// This function returns identity value for given opcode, which can be used to 564 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1). 565 static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) { 566 if (isa<Constant>(V)) 567 return nullptr; 568 569 return ConstantExpr::getBinOpIdentity(Opcode, V->getType()); 570 } 571 572 /// This function predicates factorization using distributive laws. By default, 573 /// it just returns the 'Op' inputs. But for special-cases like 574 /// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add 575 /// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to 576 /// allow more factorization opportunities. 577 static Instruction::BinaryOps 578 getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op, 579 Value *&LHS, Value *&RHS) { 580 assert(Op && "Expected a binary operator"); 581 LHS = Op->getOperand(0); 582 RHS = Op->getOperand(1); 583 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) { 584 Constant *C; 585 if (match(Op, m_Shl(m_Value(), m_Constant(C)))) { 586 // X << C --> X * (1 << C) 587 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), C); 588 return Instruction::Mul; 589 } 590 // TODO: We can add other conversions e.g. shr => div etc. 591 } 592 return Op->getOpcode(); 593 } 594 595 /// This tries to simplify binary operations by factorizing out common terms 596 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)"). 597 Value *InstCombinerImpl::tryFactorization(BinaryOperator &I, 598 Instruction::BinaryOps InnerOpcode, 599 Value *A, Value *B, Value *C, 600 Value *D) { 601 assert(A && B && C && D && "All values must be provided"); 602 603 Value *V = nullptr; 604 Value *SimplifiedInst = nullptr; 605 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 606 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); 607 608 // Does "X op' Y" always equal "Y op' X"? 609 bool InnerCommutative = Instruction::isCommutative(InnerOpcode); 610 611 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"? 612 if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode)) 613 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the 614 // commutative case, "(A op' B) op (C op' A)"? 615 if (A == C || (InnerCommutative && A == D)) { 616 if (A != C) 617 std::swap(C, D); 618 // Consider forming "A op' (B op D)". 619 // If "B op D" simplifies then it can be formed with no cost. 620 V = SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I)); 621 // If "B op D" doesn't simplify then only go on if both of the existing 622 // operations "A op' B" and "C op' D" will be zapped as no longer used. 623 if (!V && LHS->hasOneUse() && RHS->hasOneUse()) 624 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName()); 625 if (V) { 626 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V); 627 } 628 } 629 630 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"? 631 if (!SimplifiedInst && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) 632 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the 633 // commutative case, "(A op' B) op (B op' D)"? 634 if (B == D || (InnerCommutative && B == C)) { 635 if (B != D) 636 std::swap(C, D); 637 // Consider forming "(A op C) op' B". 638 // If "A op C" simplifies then it can be formed with no cost. 639 V = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I)); 640 641 // If "A op C" doesn't simplify then only go on if both of the existing 642 // operations "A op' B" and "C op' D" will be zapped as no longer used. 643 if (!V && LHS->hasOneUse() && RHS->hasOneUse()) 644 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName()); 645 if (V) { 646 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B); 647 } 648 } 649 650 if (SimplifiedInst) { 651 ++NumFactor; 652 SimplifiedInst->takeName(&I); 653 654 // Check if we can add NSW/NUW flags to SimplifiedInst. If so, set them. 655 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) { 656 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) { 657 bool HasNSW = false; 658 bool HasNUW = false; 659 if (isa<OverflowingBinaryOperator>(&I)) { 660 HasNSW = I.hasNoSignedWrap(); 661 HasNUW = I.hasNoUnsignedWrap(); 662 } 663 664 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) { 665 HasNSW &= LOBO->hasNoSignedWrap(); 666 HasNUW &= LOBO->hasNoUnsignedWrap(); 667 } 668 669 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) { 670 HasNSW &= ROBO->hasNoSignedWrap(); 671 HasNUW &= ROBO->hasNoUnsignedWrap(); 672 } 673 674 if (TopLevelOpcode == Instruction::Add && 675 InnerOpcode == Instruction::Mul) { 676 // We can propagate 'nsw' if we know that 677 // %Y = mul nsw i16 %X, C 678 // %Z = add nsw i16 %Y, %X 679 // => 680 // %Z = mul nsw i16 %X, C+1 681 // 682 // iff C+1 isn't INT_MIN 683 const APInt *CInt; 684 if (match(V, m_APInt(CInt))) { 685 if (!CInt->isMinSignedValue()) 686 BO->setHasNoSignedWrap(HasNSW); 687 } 688 689 // nuw can be propagated with any constant or nuw value. 690 BO->setHasNoUnsignedWrap(HasNUW); 691 } 692 } 693 } 694 } 695 return SimplifiedInst; 696 } 697 698 /// This tries to simplify binary operations which some other binary operation 699 /// distributes over either by factorizing out common terms 700 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in 701 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win). 702 /// Returns the simplified value, or null if it didn't simplify. 703 Value *InstCombinerImpl::SimplifyUsingDistributiveLaws(BinaryOperator &I) { 704 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 705 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 706 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 707 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); 708 709 { 710 // Factorization. 711 Value *A, *B, *C, *D; 712 Instruction::BinaryOps LHSOpcode, RHSOpcode; 713 if (Op0) 714 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B); 715 if (Op1) 716 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D); 717 718 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize 719 // a common term. 720 if (Op0 && Op1 && LHSOpcode == RHSOpcode) 721 if (Value *V = tryFactorization(I, LHSOpcode, A, B, C, D)) 722 return V; 723 724 // The instruction has the form "(A op' B) op (C)". Try to factorize common 725 // term. 726 if (Op0) 727 if (Value *Ident = getIdentityValue(LHSOpcode, RHS)) 728 if (Value *V = tryFactorization(I, LHSOpcode, A, B, RHS, Ident)) 729 return V; 730 731 // The instruction has the form "(B) op (C op' D)". Try to factorize common 732 // term. 733 if (Op1) 734 if (Value *Ident = getIdentityValue(RHSOpcode, LHS)) 735 if (Value *V = tryFactorization(I, RHSOpcode, LHS, Ident, C, D)) 736 return V; 737 } 738 739 // Expansion. 740 if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) { 741 // The instruction has the form "(A op' B) op C". See if expanding it out 742 // to "(A op C) op' (B op C)" results in simplifications. 743 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; 744 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op' 745 746 // Disable the use of undef because it's not safe to distribute undef. 747 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef(); 748 Value *L = SimplifyBinOp(TopLevelOpcode, A, C, SQDistributive); 749 Value *R = SimplifyBinOp(TopLevelOpcode, B, C, SQDistributive); 750 751 // Do "A op C" and "B op C" both simplify? 752 if (L && R) { 753 // They do! Return "L op' R". 754 ++NumExpand; 755 C = Builder.CreateBinOp(InnerOpcode, L, R); 756 C->takeName(&I); 757 return C; 758 } 759 760 // Does "A op C" simplify to the identity value for the inner opcode? 761 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) { 762 // They do! Return "B op C". 763 ++NumExpand; 764 C = Builder.CreateBinOp(TopLevelOpcode, B, C); 765 C->takeName(&I); 766 return C; 767 } 768 769 // Does "B op C" simplify to the identity value for the inner opcode? 770 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) { 771 // They do! Return "A op C". 772 ++NumExpand; 773 C = Builder.CreateBinOp(TopLevelOpcode, A, C); 774 C->takeName(&I); 775 return C; 776 } 777 } 778 779 if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) { 780 // The instruction has the form "A op (B op' C)". See if expanding it out 781 // to "(A op B) op' (A op C)" results in simplifications. 782 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); 783 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op' 784 785 // Disable the use of undef because it's not safe to distribute undef. 786 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef(); 787 Value *L = SimplifyBinOp(TopLevelOpcode, A, B, SQDistributive); 788 Value *R = SimplifyBinOp(TopLevelOpcode, A, C, SQDistributive); 789 790 // Do "A op B" and "A op C" both simplify? 791 if (L && R) { 792 // They do! Return "L op' R". 793 ++NumExpand; 794 A = Builder.CreateBinOp(InnerOpcode, L, R); 795 A->takeName(&I); 796 return A; 797 } 798 799 // Does "A op B" simplify to the identity value for the inner opcode? 800 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) { 801 // They do! Return "A op C". 802 ++NumExpand; 803 A = Builder.CreateBinOp(TopLevelOpcode, A, C); 804 A->takeName(&I); 805 return A; 806 } 807 808 // Does "A op C" simplify to the identity value for the inner opcode? 809 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) { 810 // They do! Return "A op B". 811 ++NumExpand; 812 A = Builder.CreateBinOp(TopLevelOpcode, A, B); 813 A->takeName(&I); 814 return A; 815 } 816 } 817 818 return SimplifySelectsFeedingBinaryOp(I, LHS, RHS); 819 } 820 821 Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I, 822 Value *LHS, 823 Value *RHS) { 824 Value *A, *B, *C, *D, *E, *F; 825 bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C))); 826 bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F))); 827 if (!LHSIsSelect && !RHSIsSelect) 828 return nullptr; 829 830 FastMathFlags FMF; 831 BuilderTy::FastMathFlagGuard Guard(Builder); 832 if (isa<FPMathOperator>(&I)) { 833 FMF = I.getFastMathFlags(); 834 Builder.setFastMathFlags(FMF); 835 } 836 837 Instruction::BinaryOps Opcode = I.getOpcode(); 838 SimplifyQuery Q = SQ.getWithInstruction(&I); 839 840 Value *Cond, *True = nullptr, *False = nullptr; 841 if (LHSIsSelect && RHSIsSelect && A == D) { 842 // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F) 843 Cond = A; 844 True = SimplifyBinOp(Opcode, B, E, FMF, Q); 845 False = SimplifyBinOp(Opcode, C, F, FMF, Q); 846 847 if (LHS->hasOneUse() && RHS->hasOneUse()) { 848 if (False && !True) 849 True = Builder.CreateBinOp(Opcode, B, E); 850 else if (True && !False) 851 False = Builder.CreateBinOp(Opcode, C, F); 852 } 853 } else if (LHSIsSelect && LHS->hasOneUse()) { 854 // (A ? B : C) op Y -> A ? (B op Y) : (C op Y) 855 Cond = A; 856 True = SimplifyBinOp(Opcode, B, RHS, FMF, Q); 857 False = SimplifyBinOp(Opcode, C, RHS, FMF, Q); 858 } else if (RHSIsSelect && RHS->hasOneUse()) { 859 // X op (D ? E : F) -> D ? (X op E) : (X op F) 860 Cond = D; 861 True = SimplifyBinOp(Opcode, LHS, E, FMF, Q); 862 False = SimplifyBinOp(Opcode, LHS, F, FMF, Q); 863 } 864 865 if (!True || !False) 866 return nullptr; 867 868 Value *SI = Builder.CreateSelect(Cond, True, False); 869 SI->takeName(&I); 870 return SI; 871 } 872 873 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a 874 /// constant zero (which is the 'negate' form). 875 Value *InstCombinerImpl::dyn_castNegVal(Value *V) const { 876 Value *NegV; 877 if (match(V, m_Neg(m_Value(NegV)))) 878 return NegV; 879 880 // Constants can be considered to be negated values if they can be folded. 881 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) 882 return ConstantExpr::getNeg(C); 883 884 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V)) 885 if (C->getType()->getElementType()->isIntegerTy()) 886 return ConstantExpr::getNeg(C); 887 888 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) { 889 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) { 890 Constant *Elt = CV->getAggregateElement(i); 891 if (!Elt) 892 return nullptr; 893 894 if (isa<UndefValue>(Elt)) 895 continue; 896 897 if (!isa<ConstantInt>(Elt)) 898 return nullptr; 899 } 900 return ConstantExpr::getNeg(CV); 901 } 902 903 return nullptr; 904 } 905 906 static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO, 907 InstCombiner::BuilderTy &Builder) { 908 if (auto *Cast = dyn_cast<CastInst>(&I)) 909 return Builder.CreateCast(Cast->getOpcode(), SO, I.getType()); 910 911 assert(I.isBinaryOp() && "Unexpected opcode for select folding"); 912 913 // Figure out if the constant is the left or the right argument. 914 bool ConstIsRHS = isa<Constant>(I.getOperand(1)); 915 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS)); 916 917 if (auto *SOC = dyn_cast<Constant>(SO)) { 918 if (ConstIsRHS) 919 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand); 920 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC); 921 } 922 923 Value *Op0 = SO, *Op1 = ConstOperand; 924 if (!ConstIsRHS) 925 std::swap(Op0, Op1); 926 927 auto *BO = cast<BinaryOperator>(&I); 928 Value *RI = Builder.CreateBinOp(BO->getOpcode(), Op0, Op1, 929 SO->getName() + ".op"); 930 auto *FPInst = dyn_cast<Instruction>(RI); 931 if (FPInst && isa<FPMathOperator>(FPInst)) 932 FPInst->copyFastMathFlags(BO); 933 return RI; 934 } 935 936 Instruction *InstCombinerImpl::FoldOpIntoSelect(Instruction &Op, 937 SelectInst *SI) { 938 // Don't modify shared select instructions. 939 if (!SI->hasOneUse()) 940 return nullptr; 941 942 Value *TV = SI->getTrueValue(); 943 Value *FV = SI->getFalseValue(); 944 if (!(isa<Constant>(TV) || isa<Constant>(FV))) 945 return nullptr; 946 947 // Bool selects with constant operands can be folded to logical ops. 948 if (SI->getType()->isIntOrIntVectorTy(1)) 949 return nullptr; 950 951 // If it's a bitcast involving vectors, make sure it has the same number of 952 // elements on both sides. 953 if (auto *BC = dyn_cast<BitCastInst>(&Op)) { 954 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy()); 955 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy()); 956 957 // Verify that either both or neither are vectors. 958 if ((SrcTy == nullptr) != (DestTy == nullptr)) 959 return nullptr; 960 961 // If vectors, verify that they have the same number of elements. 962 if (SrcTy && cast<FixedVectorType>(SrcTy)->getNumElements() != 963 cast<FixedVectorType>(DestTy)->getNumElements()) 964 return nullptr; 965 } 966 967 // Test if a CmpInst instruction is used exclusively by a select as 968 // part of a minimum or maximum operation. If so, refrain from doing 969 // any other folding. This helps out other analyses which understand 970 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 971 // and CodeGen. And in this case, at least one of the comparison 972 // operands has at least one user besides the compare (the select), 973 // which would often largely negate the benefit of folding anyway. 974 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) { 975 if (CI->hasOneUse()) { 976 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1); 977 978 // FIXME: This is a hack to avoid infinite looping with min/max patterns. 979 // We have to ensure that vector constants that only differ with 980 // undef elements are treated as equivalent. 981 auto areLooselyEqual = [](Value *A, Value *B) { 982 if (A == B) 983 return true; 984 985 // Test for vector constants. 986 Constant *ConstA, *ConstB; 987 if (!match(A, m_Constant(ConstA)) || !match(B, m_Constant(ConstB))) 988 return false; 989 990 // TODO: Deal with FP constants? 991 if (!A->getType()->isIntOrIntVectorTy() || A->getType() != B->getType()) 992 return false; 993 994 // Compare for equality including undefs as equal. 995 auto *Cmp = ConstantExpr::getCompare(ICmpInst::ICMP_EQ, ConstA, ConstB); 996 const APInt *C; 997 return match(Cmp, m_APIntAllowUndef(C)) && C->isOneValue(); 998 }; 999 1000 if ((areLooselyEqual(TV, Op0) && areLooselyEqual(FV, Op1)) || 1001 (areLooselyEqual(FV, Op0) && areLooselyEqual(TV, Op1))) 1002 return nullptr; 1003 } 1004 } 1005 1006 Value *NewTV = foldOperationIntoSelectOperand(Op, TV, Builder); 1007 Value *NewFV = foldOperationIntoSelectOperand(Op, FV, Builder); 1008 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI); 1009 } 1010 1011 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV, 1012 InstCombiner::BuilderTy &Builder) { 1013 bool ConstIsRHS = isa<Constant>(I->getOperand(1)); 1014 Constant *C = cast<Constant>(I->getOperand(ConstIsRHS)); 1015 1016 if (auto *InC = dyn_cast<Constant>(InV)) { 1017 if (ConstIsRHS) 1018 return ConstantExpr::get(I->getOpcode(), InC, C); 1019 return ConstantExpr::get(I->getOpcode(), C, InC); 1020 } 1021 1022 Value *Op0 = InV, *Op1 = C; 1023 if (!ConstIsRHS) 1024 std::swap(Op0, Op1); 1025 1026 Value *RI = Builder.CreateBinOp(I->getOpcode(), Op0, Op1, "phi.bo"); 1027 auto *FPInst = dyn_cast<Instruction>(RI); 1028 if (FPInst && isa<FPMathOperator>(FPInst)) 1029 FPInst->copyFastMathFlags(I); 1030 return RI; 1031 } 1032 1033 Instruction *InstCombinerImpl::foldOpIntoPhi(Instruction &I, PHINode *PN) { 1034 unsigned NumPHIValues = PN->getNumIncomingValues(); 1035 if (NumPHIValues == 0) 1036 return nullptr; 1037 1038 // We normally only transform phis with a single use. However, if a PHI has 1039 // multiple uses and they are all the same operation, we can fold *all* of the 1040 // uses into the PHI. 1041 if (!PN->hasOneUse()) { 1042 // Walk the use list for the instruction, comparing them to I. 1043 for (User *U : PN->users()) { 1044 Instruction *UI = cast<Instruction>(U); 1045 if (UI != &I && !I.isIdenticalTo(UI)) 1046 return nullptr; 1047 } 1048 // Otherwise, we can replace *all* users with the new PHI we form. 1049 } 1050 1051 // Check to see if all of the operands of the PHI are simple constants 1052 // (constantint/constantfp/undef). If there is one non-constant value, 1053 // remember the BB it is in. If there is more than one or if *it* is a PHI, 1054 // bail out. We don't do arbitrary constant expressions here because moving 1055 // their computation can be expensive without a cost model. 1056 BasicBlock *NonConstBB = nullptr; 1057 for (unsigned i = 0; i != NumPHIValues; ++i) { 1058 Value *InVal = PN->getIncomingValue(i); 1059 // If I is a freeze instruction, count undef as a non-constant. 1060 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal) && 1061 (!isa<FreezeInst>(I) || isGuaranteedNotToBeUndefOrPoison(InVal))) 1062 continue; 1063 1064 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi. 1065 if (NonConstBB) return nullptr; // More than one non-const value. 1066 1067 NonConstBB = PN->getIncomingBlock(i); 1068 1069 // If the InVal is an invoke at the end of the pred block, then we can't 1070 // insert a computation after it without breaking the edge. 1071 if (isa<InvokeInst>(InVal)) 1072 if (cast<Instruction>(InVal)->getParent() == NonConstBB) 1073 return nullptr; 1074 1075 // If the incoming non-constant value is in I's block, we will remove one 1076 // instruction, but insert another equivalent one, leading to infinite 1077 // instcombine. 1078 if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI)) 1079 return nullptr; 1080 } 1081 1082 // If there is exactly one non-constant value, we can insert a copy of the 1083 // operation in that block. However, if this is a critical edge, we would be 1084 // inserting the computation on some other paths (e.g. inside a loop). Only 1085 // do this if the pred block is unconditionally branching into the phi block. 1086 // Also, make sure that the pred block is not dead code. 1087 if (NonConstBB != nullptr) { 1088 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator()); 1089 if (!BI || !BI->isUnconditional() || !DT.isReachableFromEntry(NonConstBB)) 1090 return nullptr; 1091 } 1092 1093 // Okay, we can do the transformation: create the new PHI node. 1094 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues()); 1095 InsertNewInstBefore(NewPN, *PN); 1096 NewPN->takeName(PN); 1097 1098 // If we are going to have to insert a new computation, do so right before the 1099 // predecessor's terminator. 1100 if (NonConstBB) 1101 Builder.SetInsertPoint(NonConstBB->getTerminator()); 1102 1103 // Next, add all of the operands to the PHI. 1104 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) { 1105 // We only currently try to fold the condition of a select when it is a phi, 1106 // not the true/false values. 1107 Value *TrueV = SI->getTrueValue(); 1108 Value *FalseV = SI->getFalseValue(); 1109 BasicBlock *PhiTransBB = PN->getParent(); 1110 for (unsigned i = 0; i != NumPHIValues; ++i) { 1111 BasicBlock *ThisBB = PN->getIncomingBlock(i); 1112 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB); 1113 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB); 1114 Value *InV = nullptr; 1115 // Beware of ConstantExpr: it may eventually evaluate to getNullValue, 1116 // even if currently isNullValue gives false. 1117 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)); 1118 // For vector constants, we cannot use isNullValue to fold into 1119 // FalseVInPred versus TrueVInPred. When we have individual nonzero 1120 // elements in the vector, we will incorrectly fold InC to 1121 // `TrueVInPred`. 1122 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC)) 1123 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred; 1124 else { 1125 // Generate the select in the same block as PN's current incoming block. 1126 // Note: ThisBB need not be the NonConstBB because vector constants 1127 // which are constants by definition are handled here. 1128 // FIXME: This can lead to an increase in IR generation because we might 1129 // generate selects for vector constant phi operand, that could not be 1130 // folded to TrueVInPred or FalseVInPred as done for ConstantInt. For 1131 // non-vector phis, this transformation was always profitable because 1132 // the select would be generated exactly once in the NonConstBB. 1133 Builder.SetInsertPoint(ThisBB->getTerminator()); 1134 InV = Builder.CreateSelect(PN->getIncomingValue(i), TrueVInPred, 1135 FalseVInPred, "phi.sel"); 1136 } 1137 NewPN->addIncoming(InV, ThisBB); 1138 } 1139 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) { 1140 Constant *C = cast<Constant>(I.getOperand(1)); 1141 for (unsigned i = 0; i != NumPHIValues; ++i) { 1142 Value *InV = nullptr; 1143 if (auto *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 1144 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C); 1145 else 1146 InV = Builder.CreateCmp(CI->getPredicate(), PN->getIncomingValue(i), 1147 C, "phi.cmp"); 1148 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1149 } 1150 } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) { 1151 for (unsigned i = 0; i != NumPHIValues; ++i) { 1152 Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i), 1153 Builder); 1154 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1155 } 1156 } else if (isa<FreezeInst>(&I)) { 1157 for (unsigned i = 0; i != NumPHIValues; ++i) { 1158 Value *InV; 1159 if (NonConstBB == PN->getIncomingBlock(i)) 1160 InV = Builder.CreateFreeze(PN->getIncomingValue(i), "phi.fr"); 1161 else 1162 InV = PN->getIncomingValue(i); 1163 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1164 } 1165 } else { 1166 CastInst *CI = cast<CastInst>(&I); 1167 Type *RetTy = CI->getType(); 1168 for (unsigned i = 0; i != NumPHIValues; ++i) { 1169 Value *InV; 1170 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 1171 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy); 1172 else 1173 InV = Builder.CreateCast(CI->getOpcode(), PN->getIncomingValue(i), 1174 I.getType(), "phi.cast"); 1175 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1176 } 1177 } 1178 1179 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) { 1180 Instruction *User = cast<Instruction>(*UI++); 1181 if (User == &I) continue; 1182 replaceInstUsesWith(*User, NewPN); 1183 eraseInstFromFunction(*User); 1184 } 1185 return replaceInstUsesWith(I, NewPN); 1186 } 1187 1188 Instruction *InstCombinerImpl::foldBinOpIntoSelectOrPhi(BinaryOperator &I) { 1189 if (!isa<Constant>(I.getOperand(1))) 1190 return nullptr; 1191 1192 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) { 1193 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel)) 1194 return NewSel; 1195 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) { 1196 if (Instruction *NewPhi = foldOpIntoPhi(I, PN)) 1197 return NewPhi; 1198 } 1199 return nullptr; 1200 } 1201 1202 /// Given a pointer type and a constant offset, determine whether or not there 1203 /// is a sequence of GEP indices into the pointed type that will land us at the 1204 /// specified offset. If so, fill them into NewIndices and return the resultant 1205 /// element type, otherwise return null. 1206 Type * 1207 InstCombinerImpl::FindElementAtOffset(PointerType *PtrTy, int64_t Offset, 1208 SmallVectorImpl<Value *> &NewIndices) { 1209 Type *Ty = PtrTy->getElementType(); 1210 if (!Ty->isSized()) 1211 return nullptr; 1212 1213 // Start with the index over the outer type. Note that the type size 1214 // might be zero (even if the offset isn't zero) if the indexed type 1215 // is something like [0 x {int, int}] 1216 Type *IndexTy = DL.getIndexType(PtrTy); 1217 int64_t FirstIdx = 0; 1218 if (int64_t TySize = DL.getTypeAllocSize(Ty)) { 1219 FirstIdx = Offset/TySize; 1220 Offset -= FirstIdx*TySize; 1221 1222 // Handle hosts where % returns negative instead of values [0..TySize). 1223 if (Offset < 0) { 1224 --FirstIdx; 1225 Offset += TySize; 1226 assert(Offset >= 0); 1227 } 1228 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset"); 1229 } 1230 1231 NewIndices.push_back(ConstantInt::get(IndexTy, FirstIdx)); 1232 1233 // Index into the types. If we fail, set OrigBase to null. 1234 while (Offset) { 1235 // Indexing into tail padding between struct/array elements. 1236 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty)) 1237 return nullptr; 1238 1239 if (StructType *STy = dyn_cast<StructType>(Ty)) { 1240 const StructLayout *SL = DL.getStructLayout(STy); 1241 assert(Offset < (int64_t)SL->getSizeInBytes() && 1242 "Offset must stay within the indexed type"); 1243 1244 unsigned Elt = SL->getElementContainingOffset(Offset); 1245 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1246 Elt)); 1247 1248 Offset -= SL->getElementOffset(Elt); 1249 Ty = STy->getElementType(Elt); 1250 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 1251 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType()); 1252 assert(EltSize && "Cannot index into a zero-sized array"); 1253 NewIndices.push_back(ConstantInt::get(IndexTy,Offset/EltSize)); 1254 Offset %= EltSize; 1255 Ty = AT->getElementType(); 1256 } else { 1257 // Otherwise, we can't index into the middle of this atomic type, bail. 1258 return nullptr; 1259 } 1260 } 1261 1262 return Ty; 1263 } 1264 1265 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) { 1266 // If this GEP has only 0 indices, it is the same pointer as 1267 // Src. If Src is not a trivial GEP too, don't combine 1268 // the indices. 1269 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() && 1270 !Src.hasOneUse()) 1271 return false; 1272 return true; 1273 } 1274 1275 /// Return a value X such that Val = X * Scale, or null if none. 1276 /// If the multiplication is known not to overflow, then NoSignedWrap is set. 1277 Value *InstCombinerImpl::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) { 1278 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!"); 1279 assert(cast<IntegerType>(Val->getType())->getBitWidth() == 1280 Scale.getBitWidth() && "Scale not compatible with value!"); 1281 1282 // If Val is zero or Scale is one then Val = Val * Scale. 1283 if (match(Val, m_Zero()) || Scale == 1) { 1284 NoSignedWrap = true; 1285 return Val; 1286 } 1287 1288 // If Scale is zero then it does not divide Val. 1289 if (Scale.isMinValue()) 1290 return nullptr; 1291 1292 // Look through chains of multiplications, searching for a constant that is 1293 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4 1294 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by 1295 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore 1296 // down from Val: 1297 // 1298 // Val = M1 * X || Analysis starts here and works down 1299 // M1 = M2 * Y || Doesn't descend into terms with more 1300 // M2 = Z * 4 \/ than one use 1301 // 1302 // Then to modify a term at the bottom: 1303 // 1304 // Val = M1 * X 1305 // M1 = Z * Y || Replaced M2 with Z 1306 // 1307 // Then to work back up correcting nsw flags. 1308 1309 // Op - the term we are currently analyzing. Starts at Val then drills down. 1310 // Replaced with its descaled value before exiting from the drill down loop. 1311 Value *Op = Val; 1312 1313 // Parent - initially null, but after drilling down notes where Op came from. 1314 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the 1315 // 0'th operand of Val. 1316 std::pair<Instruction *, unsigned> Parent; 1317 1318 // Set if the transform requires a descaling at deeper levels that doesn't 1319 // overflow. 1320 bool RequireNoSignedWrap = false; 1321 1322 // Log base 2 of the scale. Negative if not a power of 2. 1323 int32_t logScale = Scale.exactLogBase2(); 1324 1325 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down 1326 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 1327 // If Op is a constant divisible by Scale then descale to the quotient. 1328 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth. 1329 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder); 1330 if (!Remainder.isMinValue()) 1331 // Not divisible by Scale. 1332 return nullptr; 1333 // Replace with the quotient in the parent. 1334 Op = ConstantInt::get(CI->getType(), Quotient); 1335 NoSignedWrap = true; 1336 break; 1337 } 1338 1339 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) { 1340 if (BO->getOpcode() == Instruction::Mul) { 1341 // Multiplication. 1342 NoSignedWrap = BO->hasNoSignedWrap(); 1343 if (RequireNoSignedWrap && !NoSignedWrap) 1344 return nullptr; 1345 1346 // There are three cases for multiplication: multiplication by exactly 1347 // the scale, multiplication by a constant different to the scale, and 1348 // multiplication by something else. 1349 Value *LHS = BO->getOperand(0); 1350 Value *RHS = BO->getOperand(1); 1351 1352 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 1353 // Multiplication by a constant. 1354 if (CI->getValue() == Scale) { 1355 // Multiplication by exactly the scale, replace the multiplication 1356 // by its left-hand side in the parent. 1357 Op = LHS; 1358 break; 1359 } 1360 1361 // Otherwise drill down into the constant. 1362 if (!Op->hasOneUse()) 1363 return nullptr; 1364 1365 Parent = std::make_pair(BO, 1); 1366 continue; 1367 } 1368 1369 // Multiplication by something else. Drill down into the left-hand side 1370 // since that's where the reassociate pass puts the good stuff. 1371 if (!Op->hasOneUse()) 1372 return nullptr; 1373 1374 Parent = std::make_pair(BO, 0); 1375 continue; 1376 } 1377 1378 if (logScale > 0 && BO->getOpcode() == Instruction::Shl && 1379 isa<ConstantInt>(BO->getOperand(1))) { 1380 // Multiplication by a power of 2. 1381 NoSignedWrap = BO->hasNoSignedWrap(); 1382 if (RequireNoSignedWrap && !NoSignedWrap) 1383 return nullptr; 1384 1385 Value *LHS = BO->getOperand(0); 1386 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))-> 1387 getLimitedValue(Scale.getBitWidth()); 1388 // Op = LHS << Amt. 1389 1390 if (Amt == logScale) { 1391 // Multiplication by exactly the scale, replace the multiplication 1392 // by its left-hand side in the parent. 1393 Op = LHS; 1394 break; 1395 } 1396 if (Amt < logScale || !Op->hasOneUse()) 1397 return nullptr; 1398 1399 // Multiplication by more than the scale. Reduce the multiplying amount 1400 // by the scale in the parent. 1401 Parent = std::make_pair(BO, 1); 1402 Op = ConstantInt::get(BO->getType(), Amt - logScale); 1403 break; 1404 } 1405 } 1406 1407 if (!Op->hasOneUse()) 1408 return nullptr; 1409 1410 if (CastInst *Cast = dyn_cast<CastInst>(Op)) { 1411 if (Cast->getOpcode() == Instruction::SExt) { 1412 // Op is sign-extended from a smaller type, descale in the smaller type. 1413 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 1414 APInt SmallScale = Scale.trunc(SmallSize); 1415 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to 1416 // descale Op as (sext Y) * Scale. In order to have 1417 // sext (Y * SmallScale) = (sext Y) * Scale 1418 // some conditions need to hold however: SmallScale must sign-extend to 1419 // Scale and the multiplication Y * SmallScale should not overflow. 1420 if (SmallScale.sext(Scale.getBitWidth()) != Scale) 1421 // SmallScale does not sign-extend to Scale. 1422 return nullptr; 1423 assert(SmallScale.exactLogBase2() == logScale); 1424 // Require that Y * SmallScale must not overflow. 1425 RequireNoSignedWrap = true; 1426 1427 // Drill down through the cast. 1428 Parent = std::make_pair(Cast, 0); 1429 Scale = SmallScale; 1430 continue; 1431 } 1432 1433 if (Cast->getOpcode() == Instruction::Trunc) { 1434 // Op is truncated from a larger type, descale in the larger type. 1435 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then 1436 // trunc (Y * sext Scale) = (trunc Y) * Scale 1437 // always holds. However (trunc Y) * Scale may overflow even if 1438 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared 1439 // from this point up in the expression (see later). 1440 if (RequireNoSignedWrap) 1441 return nullptr; 1442 1443 // Drill down through the cast. 1444 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 1445 Parent = std::make_pair(Cast, 0); 1446 Scale = Scale.sext(LargeSize); 1447 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits()) 1448 logScale = -1; 1449 assert(Scale.exactLogBase2() == logScale); 1450 continue; 1451 } 1452 } 1453 1454 // Unsupported expression, bail out. 1455 return nullptr; 1456 } 1457 1458 // If Op is zero then Val = Op * Scale. 1459 if (match(Op, m_Zero())) { 1460 NoSignedWrap = true; 1461 return Op; 1462 } 1463 1464 // We know that we can successfully descale, so from here on we can safely 1465 // modify the IR. Op holds the descaled version of the deepest term in the 1466 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known 1467 // not to overflow. 1468 1469 if (!Parent.first) 1470 // The expression only had one term. 1471 return Op; 1472 1473 // Rewrite the parent using the descaled version of its operand. 1474 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!"); 1475 assert(Op != Parent.first->getOperand(Parent.second) && 1476 "Descaling was a no-op?"); 1477 replaceOperand(*Parent.first, Parent.second, Op); 1478 Worklist.push(Parent.first); 1479 1480 // Now work back up the expression correcting nsw flags. The logic is based 1481 // on the following observation: if X * Y is known not to overflow as a signed 1482 // multiplication, and Y is replaced by a value Z with smaller absolute value, 1483 // then X * Z will not overflow as a signed multiplication either. As we work 1484 // our way up, having NoSignedWrap 'true' means that the descaled value at the 1485 // current level has strictly smaller absolute value than the original. 1486 Instruction *Ancestor = Parent.first; 1487 do { 1488 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) { 1489 // If the multiplication wasn't nsw then we can't say anything about the 1490 // value of the descaled multiplication, and we have to clear nsw flags 1491 // from this point on up. 1492 bool OpNoSignedWrap = BO->hasNoSignedWrap(); 1493 NoSignedWrap &= OpNoSignedWrap; 1494 if (NoSignedWrap != OpNoSignedWrap) { 1495 BO->setHasNoSignedWrap(NoSignedWrap); 1496 Worklist.push(Ancestor); 1497 } 1498 } else if (Ancestor->getOpcode() == Instruction::Trunc) { 1499 // The fact that the descaled input to the trunc has smaller absolute 1500 // value than the original input doesn't tell us anything useful about 1501 // the absolute values of the truncations. 1502 NoSignedWrap = false; 1503 } 1504 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) && 1505 "Failed to keep proper track of nsw flags while drilling down?"); 1506 1507 if (Ancestor == Val) 1508 // Got to the top, all done! 1509 return Val; 1510 1511 // Move up one level in the expression. 1512 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!"); 1513 Ancestor = Ancestor->user_back(); 1514 } while (true); 1515 } 1516 1517 Instruction *InstCombinerImpl::foldVectorBinop(BinaryOperator &Inst) { 1518 // FIXME: some of this is likely fine for scalable vectors 1519 if (!isa<FixedVectorType>(Inst.getType())) 1520 return nullptr; 1521 1522 BinaryOperator::BinaryOps Opcode = Inst.getOpcode(); 1523 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1); 1524 assert(cast<VectorType>(LHS->getType())->getElementCount() == 1525 cast<VectorType>(Inst.getType())->getElementCount()); 1526 assert(cast<VectorType>(RHS->getType())->getElementCount() == 1527 cast<VectorType>(Inst.getType())->getElementCount()); 1528 1529 // If both operands of the binop are vector concatenations, then perform the 1530 // narrow binop on each pair of the source operands followed by concatenation 1531 // of the results. 1532 Value *L0, *L1, *R0, *R1; 1533 ArrayRef<int> Mask; 1534 if (match(LHS, m_Shuffle(m_Value(L0), m_Value(L1), m_Mask(Mask))) && 1535 match(RHS, m_Shuffle(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) && 1536 LHS->hasOneUse() && RHS->hasOneUse() && 1537 cast<ShuffleVectorInst>(LHS)->isConcat() && 1538 cast<ShuffleVectorInst>(RHS)->isConcat()) { 1539 // This transform does not have the speculative execution constraint as 1540 // below because the shuffle is a concatenation. The new binops are 1541 // operating on exactly the same elements as the existing binop. 1542 // TODO: We could ease the mask requirement to allow different undef lanes, 1543 // but that requires an analysis of the binop-with-undef output value. 1544 Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0); 1545 if (auto *BO = dyn_cast<BinaryOperator>(NewBO0)) 1546 BO->copyIRFlags(&Inst); 1547 Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1); 1548 if (auto *BO = dyn_cast<BinaryOperator>(NewBO1)) 1549 BO->copyIRFlags(&Inst); 1550 return new ShuffleVectorInst(NewBO0, NewBO1, Mask); 1551 } 1552 1553 // It may not be safe to reorder shuffles and things like div, urem, etc. 1554 // because we may trap when executing those ops on unknown vector elements. 1555 // See PR20059. 1556 if (!isSafeToSpeculativelyExecute(&Inst)) 1557 return nullptr; 1558 1559 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) { 1560 Value *XY = Builder.CreateBinOp(Opcode, X, Y); 1561 if (auto *BO = dyn_cast<BinaryOperator>(XY)) 1562 BO->copyIRFlags(&Inst); 1563 return new ShuffleVectorInst(XY, UndefValue::get(XY->getType()), M); 1564 }; 1565 1566 // If both arguments of the binary operation are shuffles that use the same 1567 // mask and shuffle within a single vector, move the shuffle after the binop. 1568 Value *V1, *V2; 1569 if (match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(Mask))) && 1570 match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(Mask))) && 1571 V1->getType() == V2->getType() && 1572 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) { 1573 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask) 1574 return createBinOpShuffle(V1, V2, Mask); 1575 } 1576 1577 // If both arguments of a commutative binop are select-shuffles that use the 1578 // same mask with commuted operands, the shuffles are unnecessary. 1579 if (Inst.isCommutative() && 1580 match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) && 1581 match(RHS, 1582 m_Shuffle(m_Specific(V2), m_Specific(V1), m_SpecificMask(Mask)))) { 1583 auto *LShuf = cast<ShuffleVectorInst>(LHS); 1584 auto *RShuf = cast<ShuffleVectorInst>(RHS); 1585 // TODO: Allow shuffles that contain undefs in the mask? 1586 // That is legal, but it reduces undef knowledge. 1587 // TODO: Allow arbitrary shuffles by shuffling after binop? 1588 // That might be legal, but we have to deal with poison. 1589 if (LShuf->isSelect() && 1590 !is_contained(LShuf->getShuffleMask(), UndefMaskElem) && 1591 RShuf->isSelect() && 1592 !is_contained(RShuf->getShuffleMask(), UndefMaskElem)) { 1593 // Example: 1594 // LHS = shuffle V1, V2, <0, 5, 6, 3> 1595 // RHS = shuffle V2, V1, <0, 5, 6, 3> 1596 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2 1597 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2); 1598 NewBO->copyIRFlags(&Inst); 1599 return NewBO; 1600 } 1601 } 1602 1603 // If one argument is a shuffle within one vector and the other is a constant, 1604 // try moving the shuffle after the binary operation. This canonicalization 1605 // intends to move shuffles closer to other shuffles and binops closer to 1606 // other binops, so they can be folded. It may also enable demanded elements 1607 // transforms. 1608 unsigned NumElts = cast<FixedVectorType>(Inst.getType())->getNumElements(); 1609 Constant *C; 1610 if (match(&Inst, 1611 m_c_BinOp(m_OneUse(m_Shuffle(m_Value(V1), m_Undef(), m_Mask(Mask))), 1612 m_Constant(C))) && !isa<ConstantExpr>(C) && 1613 cast<FixedVectorType>(V1->getType())->getNumElements() <= NumElts) { 1614 assert(Inst.getType()->getScalarType() == V1->getType()->getScalarType() && 1615 "Shuffle should not change scalar type"); 1616 1617 // Find constant NewC that has property: 1618 // shuffle(NewC, ShMask) = C 1619 // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>) 1620 // reorder is not possible. A 1-to-1 mapping is not required. Example: 1621 // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef> 1622 bool ConstOp1 = isa<Constant>(RHS); 1623 ArrayRef<int> ShMask = Mask; 1624 unsigned SrcVecNumElts = 1625 cast<FixedVectorType>(V1->getType())->getNumElements(); 1626 UndefValue *UndefScalar = UndefValue::get(C->getType()->getScalarType()); 1627 SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, UndefScalar); 1628 bool MayChange = true; 1629 for (unsigned I = 0; I < NumElts; ++I) { 1630 Constant *CElt = C->getAggregateElement(I); 1631 if (ShMask[I] >= 0) { 1632 assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle"); 1633 Constant *NewCElt = NewVecC[ShMask[I]]; 1634 // Bail out if: 1635 // 1. The constant vector contains a constant expression. 1636 // 2. The shuffle needs an element of the constant vector that can't 1637 // be mapped to a new constant vector. 1638 // 3. This is a widening shuffle that copies elements of V1 into the 1639 // extended elements (extending with undef is allowed). 1640 if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) || 1641 I >= SrcVecNumElts) { 1642 MayChange = false; 1643 break; 1644 } 1645 NewVecC[ShMask[I]] = CElt; 1646 } 1647 // If this is a widening shuffle, we must be able to extend with undef 1648 // elements. If the original binop does not produce an undef in the high 1649 // lanes, then this transform is not safe. 1650 // Similarly for undef lanes due to the shuffle mask, we can only 1651 // transform binops that preserve undef. 1652 // TODO: We could shuffle those non-undef constant values into the 1653 // result by using a constant vector (rather than an undef vector) 1654 // as operand 1 of the new binop, but that might be too aggressive 1655 // for target-independent shuffle creation. 1656 if (I >= SrcVecNumElts || ShMask[I] < 0) { 1657 Constant *MaybeUndef = 1658 ConstOp1 ? ConstantExpr::get(Opcode, UndefScalar, CElt) 1659 : ConstantExpr::get(Opcode, CElt, UndefScalar); 1660 if (!isa<UndefValue>(MaybeUndef)) { 1661 MayChange = false; 1662 break; 1663 } 1664 } 1665 } 1666 if (MayChange) { 1667 Constant *NewC = ConstantVector::get(NewVecC); 1668 // It may not be safe to execute a binop on a vector with undef elements 1669 // because the entire instruction can be folded to undef or create poison 1670 // that did not exist in the original code. 1671 if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1)) 1672 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1); 1673 1674 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask) 1675 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask) 1676 Value *NewLHS = ConstOp1 ? V1 : NewC; 1677 Value *NewRHS = ConstOp1 ? NewC : V1; 1678 return createBinOpShuffle(NewLHS, NewRHS, Mask); 1679 } 1680 } 1681 1682 // Try to reassociate to sink a splat shuffle after a binary operation. 1683 if (Inst.isAssociative() && Inst.isCommutative()) { 1684 // Canonicalize shuffle operand as LHS. 1685 if (isa<ShuffleVectorInst>(RHS)) 1686 std::swap(LHS, RHS); 1687 1688 Value *X; 1689 ArrayRef<int> MaskC; 1690 int SplatIndex; 1691 BinaryOperator *BO; 1692 if (!match(LHS, 1693 m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) || 1694 !match(MaskC, m_SplatOrUndefMask(SplatIndex)) || 1695 X->getType() != Inst.getType() || !match(RHS, m_OneUse(m_BinOp(BO))) || 1696 BO->getOpcode() != Opcode) 1697 return nullptr; 1698 1699 // FIXME: This may not be safe if the analysis allows undef elements. By 1700 // moving 'Y' before the splat shuffle, we are implicitly assuming 1701 // that it is not undef/poison at the splat index. 1702 Value *Y, *OtherOp; 1703 if (isSplatValue(BO->getOperand(0), SplatIndex)) { 1704 Y = BO->getOperand(0); 1705 OtherOp = BO->getOperand(1); 1706 } else if (isSplatValue(BO->getOperand(1), SplatIndex)) { 1707 Y = BO->getOperand(1); 1708 OtherOp = BO->getOperand(0); 1709 } else { 1710 return nullptr; 1711 } 1712 1713 // X and Y are splatted values, so perform the binary operation on those 1714 // values followed by a splat followed by the 2nd binary operation: 1715 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp 1716 Value *NewBO = Builder.CreateBinOp(Opcode, X, Y); 1717 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex); 1718 Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask); 1719 Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp); 1720 1721 // Intersect FMF on both new binops. Other (poison-generating) flags are 1722 // dropped to be safe. 1723 if (isa<FPMathOperator>(R)) { 1724 R->copyFastMathFlags(&Inst); 1725 R->andIRFlags(BO); 1726 } 1727 if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO)) 1728 NewInstBO->copyIRFlags(R); 1729 return R; 1730 } 1731 1732 return nullptr; 1733 } 1734 1735 /// Try to narrow the width of a binop if at least 1 operand is an extend of 1736 /// of a value. This requires a potentially expensive known bits check to make 1737 /// sure the narrow op does not overflow. 1738 Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) { 1739 // We need at least one extended operand. 1740 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1); 1741 1742 // If this is a sub, we swap the operands since we always want an extension 1743 // on the RHS. The LHS can be an extension or a constant. 1744 if (BO.getOpcode() == Instruction::Sub) 1745 std::swap(Op0, Op1); 1746 1747 Value *X; 1748 bool IsSext = match(Op0, m_SExt(m_Value(X))); 1749 if (!IsSext && !match(Op0, m_ZExt(m_Value(X)))) 1750 return nullptr; 1751 1752 // If both operands are the same extension from the same source type and we 1753 // can eliminate at least one (hasOneUse), this might work. 1754 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt; 1755 Value *Y; 1756 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() && 1757 cast<Operator>(Op1)->getOpcode() == CastOpc && 1758 (Op0->hasOneUse() || Op1->hasOneUse()))) { 1759 // If that did not match, see if we have a suitable constant operand. 1760 // Truncating and extending must produce the same constant. 1761 Constant *WideC; 1762 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC))) 1763 return nullptr; 1764 Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType()); 1765 if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC) 1766 return nullptr; 1767 Y = NarrowC; 1768 } 1769 1770 // Swap back now that we found our operands. 1771 if (BO.getOpcode() == Instruction::Sub) 1772 std::swap(X, Y); 1773 1774 // Both operands have narrow versions. Last step: the math must not overflow 1775 // in the narrow width. 1776 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext)) 1777 return nullptr; 1778 1779 // bo (ext X), (ext Y) --> ext (bo X, Y) 1780 // bo (ext X), C --> ext (bo X, C') 1781 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow"); 1782 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) { 1783 if (IsSext) 1784 NewBinOp->setHasNoSignedWrap(); 1785 else 1786 NewBinOp->setHasNoUnsignedWrap(); 1787 } 1788 return CastInst::Create(CastOpc, NarrowBO, BO.getType()); 1789 } 1790 1791 static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2) { 1792 // At least one GEP must be inbounds. 1793 if (!GEP1.isInBounds() && !GEP2.isInBounds()) 1794 return false; 1795 1796 return (GEP1.isInBounds() || GEP1.hasAllZeroIndices()) && 1797 (GEP2.isInBounds() || GEP2.hasAllZeroIndices()); 1798 } 1799 1800 /// Thread a GEP operation with constant indices through the constant true/false 1801 /// arms of a select. 1802 static Instruction *foldSelectGEP(GetElementPtrInst &GEP, 1803 InstCombiner::BuilderTy &Builder) { 1804 if (!GEP.hasAllConstantIndices()) 1805 return nullptr; 1806 1807 Instruction *Sel; 1808 Value *Cond; 1809 Constant *TrueC, *FalseC; 1810 if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) || 1811 !match(Sel, 1812 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC)))) 1813 return nullptr; 1814 1815 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC' 1816 // Propagate 'inbounds' and metadata from existing instructions. 1817 // Note: using IRBuilder to create the constants for efficiency. 1818 SmallVector<Value *, 4> IndexC(GEP.idx_begin(), GEP.idx_end()); 1819 bool IsInBounds = GEP.isInBounds(); 1820 Value *NewTrueC = IsInBounds ? Builder.CreateInBoundsGEP(TrueC, IndexC) 1821 : Builder.CreateGEP(TrueC, IndexC); 1822 Value *NewFalseC = IsInBounds ? Builder.CreateInBoundsGEP(FalseC, IndexC) 1823 : Builder.CreateGEP(FalseC, IndexC); 1824 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel); 1825 } 1826 1827 Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) { 1828 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end()); 1829 Type *GEPType = GEP.getType(); 1830 Type *GEPEltType = GEP.getSourceElementType(); 1831 bool IsGEPSrcEleScalable = isa<ScalableVectorType>(GEPEltType); 1832 if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP))) 1833 return replaceInstUsesWith(GEP, V); 1834 1835 // For vector geps, use the generic demanded vector support. 1836 // Skip if GEP return type is scalable. The number of elements is unknown at 1837 // compile-time. 1838 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) { 1839 auto VWidth = GEPFVTy->getNumElements(); 1840 APInt UndefElts(VWidth, 0); 1841 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1842 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask, 1843 UndefElts)) { 1844 if (V != &GEP) 1845 return replaceInstUsesWith(GEP, V); 1846 return &GEP; 1847 } 1848 1849 // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if 1850 // possible (decide on canonical form for pointer broadcast), 3) exploit 1851 // undef elements to decrease demanded bits 1852 } 1853 1854 Value *PtrOp = GEP.getOperand(0); 1855 1856 // Eliminate unneeded casts for indices, and replace indices which displace 1857 // by multiples of a zero size type with zero. 1858 bool MadeChange = false; 1859 1860 // Index width may not be the same width as pointer width. 1861 // Data layout chooses the right type based on supported integer types. 1862 Type *NewScalarIndexTy = 1863 DL.getIndexType(GEP.getPointerOperandType()->getScalarType()); 1864 1865 gep_type_iterator GTI = gep_type_begin(GEP); 1866 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E; 1867 ++I, ++GTI) { 1868 // Skip indices into struct types. 1869 if (GTI.isStruct()) 1870 continue; 1871 1872 Type *IndexTy = (*I)->getType(); 1873 Type *NewIndexType = 1874 IndexTy->isVectorTy() 1875 ? VectorType::get(NewScalarIndexTy, 1876 cast<VectorType>(IndexTy)->getElementCount()) 1877 : NewScalarIndexTy; 1878 1879 // If the element type has zero size then any index over it is equivalent 1880 // to an index of zero, so replace it with zero if it is not zero already. 1881 Type *EltTy = GTI.getIndexedType(); 1882 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero()) 1883 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) { 1884 *I = Constant::getNullValue(NewIndexType); 1885 MadeChange = true; 1886 } 1887 1888 if (IndexTy != NewIndexType) { 1889 // If we are using a wider index than needed for this platform, shrink 1890 // it to what we need. If narrower, sign-extend it to what we need. 1891 // This explicit cast can make subsequent optimizations more obvious. 1892 *I = Builder.CreateIntCast(*I, NewIndexType, true); 1893 MadeChange = true; 1894 } 1895 } 1896 if (MadeChange) 1897 return &GEP; 1898 1899 // Check to see if the inputs to the PHI node are getelementptr instructions. 1900 if (auto *PN = dyn_cast<PHINode>(PtrOp)) { 1901 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0)); 1902 if (!Op1) 1903 return nullptr; 1904 1905 // Don't fold a GEP into itself through a PHI node. This can only happen 1906 // through the back-edge of a loop. Folding a GEP into itself means that 1907 // the value of the previous iteration needs to be stored in the meantime, 1908 // thus requiring an additional register variable to be live, but not 1909 // actually achieving anything (the GEP still needs to be executed once per 1910 // loop iteration). 1911 if (Op1 == &GEP) 1912 return nullptr; 1913 1914 int DI = -1; 1915 1916 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) { 1917 auto *Op2 = dyn_cast<GetElementPtrInst>(*I); 1918 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands()) 1919 return nullptr; 1920 1921 // As for Op1 above, don't try to fold a GEP into itself. 1922 if (Op2 == &GEP) 1923 return nullptr; 1924 1925 // Keep track of the type as we walk the GEP. 1926 Type *CurTy = nullptr; 1927 1928 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) { 1929 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType()) 1930 return nullptr; 1931 1932 if (Op1->getOperand(J) != Op2->getOperand(J)) { 1933 if (DI == -1) { 1934 // We have not seen any differences yet in the GEPs feeding the 1935 // PHI yet, so we record this one if it is allowed to be a 1936 // variable. 1937 1938 // The first two arguments can vary for any GEP, the rest have to be 1939 // static for struct slots 1940 if (J > 1) { 1941 assert(CurTy && "No current type?"); 1942 if (CurTy->isStructTy()) 1943 return nullptr; 1944 } 1945 1946 DI = J; 1947 } else { 1948 // The GEP is different by more than one input. While this could be 1949 // extended to support GEPs that vary by more than one variable it 1950 // doesn't make sense since it greatly increases the complexity and 1951 // would result in an R+R+R addressing mode which no backend 1952 // directly supports and would need to be broken into several 1953 // simpler instructions anyway. 1954 return nullptr; 1955 } 1956 } 1957 1958 // Sink down a layer of the type for the next iteration. 1959 if (J > 0) { 1960 if (J == 1) { 1961 CurTy = Op1->getSourceElementType(); 1962 } else { 1963 CurTy = 1964 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J)); 1965 } 1966 } 1967 } 1968 } 1969 1970 // If not all GEPs are identical we'll have to create a new PHI node. 1971 // Check that the old PHI node has only one use so that it will get 1972 // removed. 1973 if (DI != -1 && !PN->hasOneUse()) 1974 return nullptr; 1975 1976 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone()); 1977 if (DI == -1) { 1978 // All the GEPs feeding the PHI are identical. Clone one down into our 1979 // BB so that it can be merged with the current GEP. 1980 } else { 1981 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP 1982 // into the current block so it can be merged, and create a new PHI to 1983 // set that index. 1984 PHINode *NewPN; 1985 { 1986 IRBuilderBase::InsertPointGuard Guard(Builder); 1987 Builder.SetInsertPoint(PN); 1988 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(), 1989 PN->getNumOperands()); 1990 } 1991 1992 for (auto &I : PN->operands()) 1993 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI), 1994 PN->getIncomingBlock(I)); 1995 1996 NewGEP->setOperand(DI, NewPN); 1997 } 1998 1999 GEP.getParent()->getInstList().insert( 2000 GEP.getParent()->getFirstInsertionPt(), NewGEP); 2001 replaceOperand(GEP, 0, NewGEP); 2002 PtrOp = NewGEP; 2003 } 2004 2005 // Combine Indices - If the source pointer to this getelementptr instruction 2006 // is a getelementptr instruction, combine the indices of the two 2007 // getelementptr instructions into a single instruction. 2008 if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) { 2009 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src)) 2010 return nullptr; 2011 2012 // Try to reassociate loop invariant GEP chains to enable LICM. 2013 if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 && 2014 Src->hasOneUse()) { 2015 if (Loop *L = LI->getLoopFor(GEP.getParent())) { 2016 Value *GO1 = GEP.getOperand(1); 2017 Value *SO1 = Src->getOperand(1); 2018 // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is 2019 // invariant: this breaks the dependence between GEPs and allows LICM 2020 // to hoist the invariant part out of the loop. 2021 if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) { 2022 // We have to be careful here. 2023 // We have something like: 2024 // %src = getelementptr <ty>, <ty>* %base, <ty> %idx 2025 // %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2 2026 // If we just swap idx & idx2 then we could inadvertantly 2027 // change %src from a vector to a scalar, or vice versa. 2028 // Cases: 2029 // 1) %base a scalar & idx a scalar & idx2 a vector 2030 // => Swapping idx & idx2 turns %src into a vector type. 2031 // 2) %base a scalar & idx a vector & idx2 a scalar 2032 // => Swapping idx & idx2 turns %src in a scalar type 2033 // 3) %base, %idx, and %idx2 are scalars 2034 // => %src & %gep are scalars 2035 // => swapping idx & idx2 is safe 2036 // 4) %base a vector 2037 // => %src is a vector 2038 // => swapping idx & idx2 is safe. 2039 auto *SO0 = Src->getOperand(0); 2040 auto *SO0Ty = SO0->getType(); 2041 if (!isa<VectorType>(GEPType) || // case 3 2042 isa<VectorType>(SO0Ty)) { // case 4 2043 Src->setOperand(1, GO1); 2044 GEP.setOperand(1, SO1); 2045 return &GEP; 2046 } else { 2047 // Case 1 or 2 2048 // -- have to recreate %src & %gep 2049 // put NewSrc at same location as %src 2050 Builder.SetInsertPoint(cast<Instruction>(PtrOp)); 2051 auto *NewSrc = cast<GetElementPtrInst>( 2052 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName())); 2053 NewSrc->setIsInBounds(Src->isInBounds()); 2054 auto *NewGEP = GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1}); 2055 NewGEP->setIsInBounds(GEP.isInBounds()); 2056 return NewGEP; 2057 } 2058 } 2059 } 2060 } 2061 2062 // Note that if our source is a gep chain itself then we wait for that 2063 // chain to be resolved before we perform this transformation. This 2064 // avoids us creating a TON of code in some cases. 2065 if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0))) 2066 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) 2067 return nullptr; // Wait until our source is folded to completion. 2068 2069 SmallVector<Value*, 8> Indices; 2070 2071 // Find out whether the last index in the source GEP is a sequential idx. 2072 bool EndsWithSequential = false; 2073 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 2074 I != E; ++I) 2075 EndsWithSequential = I.isSequential(); 2076 2077 // Can we combine the two pointer arithmetics offsets? 2078 if (EndsWithSequential) { 2079 // Replace: gep (gep %P, long B), long A, ... 2080 // With: T = long A+B; gep %P, T, ... 2081 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 2082 Value *GO1 = GEP.getOperand(1); 2083 2084 // If they aren't the same type, then the input hasn't been processed 2085 // by the loop above yet (which canonicalizes sequential index types to 2086 // intptr_t). Just avoid transforming this until the input has been 2087 // normalized. 2088 if (SO1->getType() != GO1->getType()) 2089 return nullptr; 2090 2091 Value *Sum = 2092 SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP)); 2093 // Only do the combine when we are sure the cost after the 2094 // merge is never more than that before the merge. 2095 if (Sum == nullptr) 2096 return nullptr; 2097 2098 // Update the GEP in place if possible. 2099 if (Src->getNumOperands() == 2) { 2100 GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))); 2101 replaceOperand(GEP, 0, Src->getOperand(0)); 2102 replaceOperand(GEP, 1, Sum); 2103 return &GEP; 2104 } 2105 Indices.append(Src->op_begin()+1, Src->op_end()-1); 2106 Indices.push_back(Sum); 2107 Indices.append(GEP.op_begin()+2, GEP.op_end()); 2108 } else if (isa<Constant>(*GEP.idx_begin()) && 2109 cast<Constant>(*GEP.idx_begin())->isNullValue() && 2110 Src->getNumOperands() != 1) { 2111 // Otherwise we can do the fold if the first index of the GEP is a zero 2112 Indices.append(Src->op_begin()+1, Src->op_end()); 2113 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 2114 } 2115 2116 if (!Indices.empty()) 2117 return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)) 2118 ? GetElementPtrInst::CreateInBounds( 2119 Src->getSourceElementType(), Src->getOperand(0), Indices, 2120 GEP.getName()) 2121 : GetElementPtrInst::Create(Src->getSourceElementType(), 2122 Src->getOperand(0), Indices, 2123 GEP.getName()); 2124 } 2125 2126 // Skip if GEP source element type is scalable. The type alloc size is unknown 2127 // at compile-time. 2128 if (GEP.getNumIndices() == 1 && !IsGEPSrcEleScalable) { 2129 unsigned AS = GEP.getPointerAddressSpace(); 2130 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() == 2131 DL.getIndexSizeInBits(AS)) { 2132 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedSize(); 2133 2134 bool Matched = false; 2135 uint64_t C; 2136 Value *V = nullptr; 2137 if (TyAllocSize == 1) { 2138 V = GEP.getOperand(1); 2139 Matched = true; 2140 } else if (match(GEP.getOperand(1), 2141 m_AShr(m_Value(V), m_ConstantInt(C)))) { 2142 if (TyAllocSize == 1ULL << C) 2143 Matched = true; 2144 } else if (match(GEP.getOperand(1), 2145 m_SDiv(m_Value(V), m_ConstantInt(C)))) { 2146 if (TyAllocSize == C) 2147 Matched = true; 2148 } 2149 2150 if (Matched) { 2151 // Canonicalize (gep i8* X, -(ptrtoint Y)) 2152 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y))) 2153 // The GEP pattern is emitted by the SCEV expander for certain kinds of 2154 // pointer arithmetic. 2155 if (match(V, m_Neg(m_PtrToInt(m_Value())))) { 2156 Operator *Index = cast<Operator>(V); 2157 Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType()); 2158 Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1)); 2159 return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType); 2160 } 2161 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) 2162 // to (bitcast Y) 2163 Value *Y; 2164 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)), 2165 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) 2166 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType); 2167 } 2168 } 2169 } 2170 2171 // We do not handle pointer-vector geps here. 2172 if (GEPType->isVectorTy()) 2173 return nullptr; 2174 2175 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). 2176 Value *StrippedPtr = PtrOp->stripPointerCasts(); 2177 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType()); 2178 2179 if (StrippedPtr != PtrOp) { 2180 bool HasZeroPointerIndex = false; 2181 Type *StrippedPtrEltTy = StrippedPtrTy->getElementType(); 2182 2183 if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) 2184 HasZeroPointerIndex = C->isZero(); 2185 2186 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... 2187 // into : GEP [10 x i8]* X, i32 0, ... 2188 // 2189 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... 2190 // into : GEP i8* X, ... 2191 // 2192 // This occurs when the program declares an array extern like "int X[];" 2193 if (HasZeroPointerIndex) { 2194 if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) { 2195 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? 2196 if (CATy->getElementType() == StrippedPtrEltTy) { 2197 // -> GEP i8* X, ... 2198 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); 2199 GetElementPtrInst *Res = GetElementPtrInst::Create( 2200 StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName()); 2201 Res->setIsInBounds(GEP.isInBounds()); 2202 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) 2203 return Res; 2204 // Insert Res, and create an addrspacecast. 2205 // e.g., 2206 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ... 2207 // -> 2208 // %0 = GEP i8 addrspace(1)* X, ... 2209 // addrspacecast i8 addrspace(1)* %0 to i8* 2210 return new AddrSpaceCastInst(Builder.Insert(Res), GEPType); 2211 } 2212 2213 if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) { 2214 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? 2215 if (CATy->getElementType() == XATy->getElementType()) { 2216 // -> GEP [10 x i8]* X, i32 0, ... 2217 // At this point, we know that the cast source type is a pointer 2218 // to an array of the same type as the destination pointer 2219 // array. Because the array type is never stepped over (there 2220 // is a leading zero) we can fold the cast into this GEP. 2221 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) { 2222 GEP.setSourceElementType(XATy); 2223 return replaceOperand(GEP, 0, StrippedPtr); 2224 } 2225 // Cannot replace the base pointer directly because StrippedPtr's 2226 // address space is different. Instead, create a new GEP followed by 2227 // an addrspacecast. 2228 // e.g., 2229 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*), 2230 // i32 0, ... 2231 // -> 2232 // %0 = GEP [10 x i8] addrspace(1)* X, ... 2233 // addrspacecast i8 addrspace(1)* %0 to i8* 2234 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end()); 2235 Value *NewGEP = 2236 GEP.isInBounds() 2237 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2238 Idx, GEP.getName()) 2239 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2240 GEP.getName()); 2241 return new AddrSpaceCastInst(NewGEP, GEPType); 2242 } 2243 } 2244 } 2245 } else if (GEP.getNumOperands() == 2 && !IsGEPSrcEleScalable) { 2246 // Skip if GEP source element type is scalable. The type alloc size is 2247 // unknown at compile-time. 2248 // Transform things like: %t = getelementptr i32* 2249 // bitcast ([2 x i32]* %str to i32*), i32 %V into: %t1 = getelementptr [2 2250 // x i32]* %str, i32 0, i32 %V; bitcast 2251 if (StrippedPtrEltTy->isArrayTy() && 2252 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) == 2253 DL.getTypeAllocSize(GEPEltType)) { 2254 Type *IdxType = DL.getIndexType(GEPType); 2255 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) }; 2256 Value *NewGEP = 2257 GEP.isInBounds() 2258 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2259 GEP.getName()) 2260 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2261 GEP.getName()); 2262 2263 // V and GEP are both pointer types --> BitCast 2264 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType); 2265 } 2266 2267 // Transform things like: 2268 // %V = mul i64 %N, 4 2269 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V 2270 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast 2271 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) { 2272 // Check that changing the type amounts to dividing the index by a scale 2273 // factor. 2274 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize(); 2275 uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy).getFixedSize(); 2276 if (ResSize && SrcSize % ResSize == 0) { 2277 Value *Idx = GEP.getOperand(1); 2278 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2279 uint64_t Scale = SrcSize / ResSize; 2280 2281 // Earlier transforms ensure that the index has the right type 2282 // according to Data Layout, which considerably simplifies the 2283 // logic by eliminating implicit casts. 2284 assert(Idx->getType() == DL.getIndexType(GEPType) && 2285 "Index type does not match the Data Layout preferences"); 2286 2287 bool NSW; 2288 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2289 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2290 // If the multiplication NewIdx * Scale may overflow then the new 2291 // GEP may not be "inbounds". 2292 Value *NewGEP = 2293 GEP.isInBounds() && NSW 2294 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2295 NewIdx, GEP.getName()) 2296 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx, 2297 GEP.getName()); 2298 2299 // The NewGEP must be pointer typed, so must the old one -> BitCast 2300 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2301 GEPType); 2302 } 2303 } 2304 } 2305 2306 // Similarly, transform things like: 2307 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp 2308 // (where tmp = 8*tmp2) into: 2309 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast 2310 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() && 2311 StrippedPtrEltTy->isArrayTy()) { 2312 // Check that changing to the array element type amounts to dividing the 2313 // index by a scale factor. 2314 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize(); 2315 uint64_t ArrayEltSize = 2316 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) 2317 .getFixedSize(); 2318 if (ResSize && ArrayEltSize % ResSize == 0) { 2319 Value *Idx = GEP.getOperand(1); 2320 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2321 uint64_t Scale = ArrayEltSize / ResSize; 2322 2323 // Earlier transforms ensure that the index has the right type 2324 // according to the Data Layout, which considerably simplifies 2325 // the logic by eliminating implicit casts. 2326 assert(Idx->getType() == DL.getIndexType(GEPType) && 2327 "Index type does not match the Data Layout preferences"); 2328 2329 bool NSW; 2330 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2331 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2332 // If the multiplication NewIdx * Scale may overflow then the new 2333 // GEP may not be "inbounds". 2334 Type *IndTy = DL.getIndexType(GEPType); 2335 Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx}; 2336 2337 Value *NewGEP = 2338 GEP.isInBounds() && NSW 2339 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2340 Off, GEP.getName()) 2341 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off, 2342 GEP.getName()); 2343 // The NewGEP must be pointer typed, so must the old one -> BitCast 2344 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2345 GEPType); 2346 } 2347 } 2348 } 2349 } 2350 } 2351 2352 // addrspacecast between types is canonicalized as a bitcast, then an 2353 // addrspacecast. To take advantage of the below bitcast + struct GEP, look 2354 // through the addrspacecast. 2355 Value *ASCStrippedPtrOp = PtrOp; 2356 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) { 2357 // X = bitcast A addrspace(1)* to B addrspace(1)* 2358 // Y = addrspacecast A addrspace(1)* to B addrspace(2)* 2359 // Z = gep Y, <...constant indices...> 2360 // Into an addrspacecasted GEP of the struct. 2361 if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0))) 2362 ASCStrippedPtrOp = BC; 2363 } 2364 2365 if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) { 2366 Value *SrcOp = BCI->getOperand(0); 2367 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy()); 2368 Type *SrcEltType = SrcType->getElementType(); 2369 2370 // GEP directly using the source operand if this GEP is accessing an element 2371 // of a bitcasted pointer to vector or array of the same dimensions: 2372 // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z 2373 // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z 2374 auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy, 2375 const DataLayout &DL) { 2376 auto *VecVTy = cast<FixedVectorType>(VecTy); 2377 return ArrTy->getArrayElementType() == VecVTy->getElementType() && 2378 ArrTy->getArrayNumElements() == VecVTy->getNumElements() && 2379 DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy); 2380 }; 2381 if (GEP.getNumOperands() == 3 && 2382 ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() && 2383 areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) || 2384 (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() && 2385 areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) { 2386 2387 // Create a new GEP here, as using `setOperand()` followed by 2388 // `setSourceElementType()` won't actually update the type of the 2389 // existing GEP Value. Causing issues if this Value is accessed when 2390 // constructing an AddrSpaceCastInst 2391 Value *NGEP = 2392 GEP.isInBounds() 2393 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}) 2394 : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}); 2395 NGEP->takeName(&GEP); 2396 2397 // Preserve GEP address space to satisfy users 2398 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2399 return new AddrSpaceCastInst(NGEP, GEPType); 2400 2401 return replaceInstUsesWith(GEP, NGEP); 2402 } 2403 2404 // See if we can simplify: 2405 // X = bitcast A* to B* 2406 // Y = gep X, <...constant indices...> 2407 // into a gep of the original struct. This is important for SROA and alias 2408 // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. 2409 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType); 2410 APInt Offset(OffsetBits, 0); 2411 if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) { 2412 // If this GEP instruction doesn't move the pointer, just replace the GEP 2413 // with a bitcast of the real input to the dest type. 2414 if (!Offset) { 2415 // If the bitcast is of an allocation, and the allocation will be 2416 // converted to match the type of the cast, don't touch this. 2417 if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) { 2418 // See if the bitcast simplifies, if so, don't nuke this GEP yet. 2419 if (Instruction *I = visitBitCast(*BCI)) { 2420 if (I != BCI) { 2421 I->takeName(BCI); 2422 BCI->getParent()->getInstList().insert(BCI->getIterator(), I); 2423 replaceInstUsesWith(*BCI, I); 2424 } 2425 return &GEP; 2426 } 2427 } 2428 2429 if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace()) 2430 return new AddrSpaceCastInst(SrcOp, GEPType); 2431 return new BitCastInst(SrcOp, GEPType); 2432 } 2433 2434 // Otherwise, if the offset is non-zero, we need to find out if there is a 2435 // field at Offset in 'A's type. If so, we can pull the cast through the 2436 // GEP. 2437 SmallVector<Value*, 8> NewIndices; 2438 if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) { 2439 Value *NGEP = 2440 GEP.isInBounds() 2441 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices) 2442 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices); 2443 2444 if (NGEP->getType() == GEPType) 2445 return replaceInstUsesWith(GEP, NGEP); 2446 NGEP->takeName(&GEP); 2447 2448 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2449 return new AddrSpaceCastInst(NGEP, GEPType); 2450 return new BitCastInst(NGEP, GEPType); 2451 } 2452 } 2453 } 2454 2455 if (!GEP.isInBounds()) { 2456 unsigned IdxWidth = 2457 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace()); 2458 APInt BasePtrOffset(IdxWidth, 0); 2459 Value *UnderlyingPtrOp = 2460 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, 2461 BasePtrOffset); 2462 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) { 2463 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) && 2464 BasePtrOffset.isNonNegative()) { 2465 APInt AllocSize( 2466 IdxWidth, 2467 DL.getTypeAllocSize(AI->getAllocatedType()).getKnownMinSize()); 2468 if (BasePtrOffset.ule(AllocSize)) { 2469 return GetElementPtrInst::CreateInBounds( 2470 GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1), 2471 GEP.getName()); 2472 } 2473 } 2474 } 2475 } 2476 2477 if (Instruction *R = foldSelectGEP(GEP, Builder)) 2478 return R; 2479 2480 return nullptr; 2481 } 2482 2483 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI, 2484 Instruction *AI) { 2485 if (isa<ConstantPointerNull>(V)) 2486 return true; 2487 if (auto *LI = dyn_cast<LoadInst>(V)) 2488 return isa<GlobalVariable>(LI->getPointerOperand()); 2489 // Two distinct allocations will never be equal. 2490 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking 2491 // through bitcasts of V can cause 2492 // the result statement below to be true, even when AI and V (ex: 2493 // i8* ->i32* ->i8* of AI) are the same allocations. 2494 return isAllocLikeFn(V, TLI) && V != AI; 2495 } 2496 2497 static bool isAllocSiteRemovable(Instruction *AI, 2498 SmallVectorImpl<WeakTrackingVH> &Users, 2499 const TargetLibraryInfo *TLI) { 2500 SmallVector<Instruction*, 4> Worklist; 2501 Worklist.push_back(AI); 2502 2503 do { 2504 Instruction *PI = Worklist.pop_back_val(); 2505 for (User *U : PI->users()) { 2506 Instruction *I = cast<Instruction>(U); 2507 switch (I->getOpcode()) { 2508 default: 2509 // Give up the moment we see something we can't handle. 2510 return false; 2511 2512 case Instruction::AddrSpaceCast: 2513 case Instruction::BitCast: 2514 case Instruction::GetElementPtr: 2515 Users.emplace_back(I); 2516 Worklist.push_back(I); 2517 continue; 2518 2519 case Instruction::ICmp: { 2520 ICmpInst *ICI = cast<ICmpInst>(I); 2521 // We can fold eq/ne comparisons with null to false/true, respectively. 2522 // We also fold comparisons in some conditions provided the alloc has 2523 // not escaped (see isNeverEqualToUnescapedAlloc). 2524 if (!ICI->isEquality()) 2525 return false; 2526 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0; 2527 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI)) 2528 return false; 2529 Users.emplace_back(I); 2530 continue; 2531 } 2532 2533 case Instruction::Call: 2534 // Ignore no-op and store intrinsics. 2535 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2536 switch (II->getIntrinsicID()) { 2537 default: 2538 return false; 2539 2540 case Intrinsic::memmove: 2541 case Intrinsic::memcpy: 2542 case Intrinsic::memset: { 2543 MemIntrinsic *MI = cast<MemIntrinsic>(II); 2544 if (MI->isVolatile() || MI->getRawDest() != PI) 2545 return false; 2546 LLVM_FALLTHROUGH; 2547 } 2548 case Intrinsic::assume: 2549 case Intrinsic::invariant_start: 2550 case Intrinsic::invariant_end: 2551 case Intrinsic::lifetime_start: 2552 case Intrinsic::lifetime_end: 2553 case Intrinsic::objectsize: 2554 Users.emplace_back(I); 2555 continue; 2556 } 2557 } 2558 2559 if (isFreeCall(I, TLI)) { 2560 Users.emplace_back(I); 2561 continue; 2562 } 2563 return false; 2564 2565 case Instruction::Store: { 2566 StoreInst *SI = cast<StoreInst>(I); 2567 if (SI->isVolatile() || SI->getPointerOperand() != PI) 2568 return false; 2569 Users.emplace_back(I); 2570 continue; 2571 } 2572 } 2573 llvm_unreachable("missing a return?"); 2574 } 2575 } while (!Worklist.empty()); 2576 return true; 2577 } 2578 2579 Instruction *InstCombinerImpl::visitAllocSite(Instruction &MI) { 2580 // If we have a malloc call which is only used in any amount of comparisons to 2581 // null and free calls, delete the calls and replace the comparisons with true 2582 // or false as appropriate. 2583 2584 // This is based on the principle that we can substitute our own allocation 2585 // function (which will never return null) rather than knowledge of the 2586 // specific function being called. In some sense this can change the permitted 2587 // outputs of a program (when we convert a malloc to an alloca, the fact that 2588 // the allocation is now on the stack is potentially visible, for example), 2589 // but we believe in a permissible manner. 2590 SmallVector<WeakTrackingVH, 64> Users; 2591 2592 // If we are removing an alloca with a dbg.declare, insert dbg.value calls 2593 // before each store. 2594 SmallVector<DbgVariableIntrinsic *, 8> DVIs; 2595 std::unique_ptr<DIBuilder> DIB; 2596 if (isa<AllocaInst>(MI)) { 2597 findDbgUsers(DVIs, &MI); 2598 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false)); 2599 } 2600 2601 if (isAllocSiteRemovable(&MI, Users, &TLI)) { 2602 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2603 // Lowering all @llvm.objectsize calls first because they may 2604 // use a bitcast/GEP of the alloca we are removing. 2605 if (!Users[i]) 2606 continue; 2607 2608 Instruction *I = cast<Instruction>(&*Users[i]); 2609 2610 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2611 if (II->getIntrinsicID() == Intrinsic::objectsize) { 2612 Value *Result = 2613 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true); 2614 replaceInstUsesWith(*I, Result); 2615 eraseInstFromFunction(*I); 2616 Users[i] = nullptr; // Skip examining in the next loop. 2617 } 2618 } 2619 } 2620 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2621 if (!Users[i]) 2622 continue; 2623 2624 Instruction *I = cast<Instruction>(&*Users[i]); 2625 2626 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) { 2627 replaceInstUsesWith(*C, 2628 ConstantInt::get(Type::getInt1Ty(C->getContext()), 2629 C->isFalseWhenEqual())); 2630 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 2631 for (auto *DVI : DVIs) 2632 if (DVI->isAddressOfVariable()) 2633 ConvertDebugDeclareToDebugValue(DVI, SI, *DIB); 2634 } else { 2635 // Casts, GEP, or anything else: we're about to delete this instruction, 2636 // so it can not have any valid uses. 2637 replaceInstUsesWith(*I, UndefValue::get(I->getType())); 2638 } 2639 eraseInstFromFunction(*I); 2640 } 2641 2642 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) { 2643 // Replace invoke with a NOP intrinsic to maintain the original CFG 2644 Module *M = II->getModule(); 2645 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing); 2646 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(), 2647 None, "", II->getParent()); 2648 } 2649 2650 // Remove debug intrinsics which describe the value contained within the 2651 // alloca. In addition to removing dbg.{declare,addr} which simply point to 2652 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.: 2653 // 2654 // ``` 2655 // define void @foo(i32 %0) { 2656 // %a = alloca i32 ; Deleted. 2657 // store i32 %0, i32* %a 2658 // dbg.value(i32 %0, "arg0") ; Not deleted. 2659 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted. 2660 // call void @trivially_inlinable_no_op(i32* %a) 2661 // ret void 2662 // } 2663 // ``` 2664 // 2665 // This may not be required if we stop describing the contents of allocas 2666 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in 2667 // the LowerDbgDeclare utility. 2668 // 2669 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the 2670 // "arg0" dbg.value may be stale after the call. However, failing to remove 2671 // the DW_OP_deref dbg.value causes large gaps in location coverage. 2672 for (auto *DVI : DVIs) 2673 if (DVI->isAddressOfVariable() || DVI->getExpression()->startsWithDeref()) 2674 DVI->eraseFromParent(); 2675 2676 return eraseInstFromFunction(MI); 2677 } 2678 return nullptr; 2679 } 2680 2681 /// Move the call to free before a NULL test. 2682 /// 2683 /// Check if this free is accessed after its argument has been test 2684 /// against NULL (property 0). 2685 /// If yes, it is legal to move this call in its predecessor block. 2686 /// 2687 /// The move is performed only if the block containing the call to free 2688 /// will be removed, i.e.: 2689 /// 1. it has only one predecessor P, and P has two successors 2690 /// 2. it contains the call, noops, and an unconditional branch 2691 /// 3. its successor is the same as its predecessor's successor 2692 /// 2693 /// The profitability is out-of concern here and this function should 2694 /// be called only if the caller knows this transformation would be 2695 /// profitable (e.g., for code size). 2696 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI, 2697 const DataLayout &DL) { 2698 Value *Op = FI.getArgOperand(0); 2699 BasicBlock *FreeInstrBB = FI.getParent(); 2700 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor(); 2701 2702 // Validate part of constraint #1: Only one predecessor 2703 // FIXME: We can extend the number of predecessor, but in that case, we 2704 // would duplicate the call to free in each predecessor and it may 2705 // not be profitable even for code size. 2706 if (!PredBB) 2707 return nullptr; 2708 2709 // Validate constraint #2: Does this block contains only the call to 2710 // free, noops, and an unconditional branch? 2711 BasicBlock *SuccBB; 2712 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator(); 2713 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB))) 2714 return nullptr; 2715 2716 // If there are only 2 instructions in the block, at this point, 2717 // this is the call to free and unconditional. 2718 // If there are more than 2 instructions, check that they are noops 2719 // i.e., they won't hurt the performance of the generated code. 2720 if (FreeInstrBB->size() != 2) { 2721 for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) { 2722 if (&Inst == &FI || &Inst == FreeInstrBBTerminator) 2723 continue; 2724 auto *Cast = dyn_cast<CastInst>(&Inst); 2725 if (!Cast || !Cast->isNoopCast(DL)) 2726 return nullptr; 2727 } 2728 } 2729 // Validate the rest of constraint #1 by matching on the pred branch. 2730 Instruction *TI = PredBB->getTerminator(); 2731 BasicBlock *TrueBB, *FalseBB; 2732 ICmpInst::Predicate Pred; 2733 if (!match(TI, m_Br(m_ICmp(Pred, 2734 m_CombineOr(m_Specific(Op), 2735 m_Specific(Op->stripPointerCasts())), 2736 m_Zero()), 2737 TrueBB, FalseBB))) 2738 return nullptr; 2739 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE) 2740 return nullptr; 2741 2742 // Validate constraint #3: Ensure the null case just falls through. 2743 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB)) 2744 return nullptr; 2745 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && 2746 "Broken CFG: missing edge from predecessor to successor"); 2747 2748 // At this point, we know that everything in FreeInstrBB can be moved 2749 // before TI. 2750 for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end(); 2751 It != End;) { 2752 Instruction &Instr = *It++; 2753 if (&Instr == FreeInstrBBTerminator) 2754 break; 2755 Instr.moveBefore(TI); 2756 } 2757 assert(FreeInstrBB->size() == 1 && 2758 "Only the branch instruction should remain"); 2759 return &FI; 2760 } 2761 2762 Instruction *InstCombinerImpl::visitFree(CallInst &FI) { 2763 Value *Op = FI.getArgOperand(0); 2764 2765 // free undef -> unreachable. 2766 if (isa<UndefValue>(Op)) { 2767 // Leave a marker since we can't modify the CFG here. 2768 CreateNonTerminatorUnreachable(&FI); 2769 return eraseInstFromFunction(FI); 2770 } 2771 2772 // If we have 'free null' delete the instruction. This can happen in stl code 2773 // when lots of inlining happens. 2774 if (isa<ConstantPointerNull>(Op)) 2775 return eraseInstFromFunction(FI); 2776 2777 // If we optimize for code size, try to move the call to free before the null 2778 // test so that simplify cfg can remove the empty block and dead code 2779 // elimination the branch. I.e., helps to turn something like: 2780 // if (foo) free(foo); 2781 // into 2782 // free(foo); 2783 // 2784 // Note that we can only do this for 'free' and not for any flavor of 2785 // 'operator delete'; there is no 'operator delete' symbol for which we are 2786 // permitted to invent a call, even if we're passing in a null pointer. 2787 if (MinimizeSize) { 2788 LibFunc Func; 2789 if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free) 2790 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL)) 2791 return I; 2792 } 2793 2794 return nullptr; 2795 } 2796 2797 static bool isMustTailCall(Value *V) { 2798 if (auto *CI = dyn_cast<CallInst>(V)) 2799 return CI->isMustTailCall(); 2800 return false; 2801 } 2802 2803 Instruction *InstCombinerImpl::visitReturnInst(ReturnInst &RI) { 2804 if (RI.getNumOperands() == 0) // ret void 2805 return nullptr; 2806 2807 Value *ResultOp = RI.getOperand(0); 2808 Type *VTy = ResultOp->getType(); 2809 if (!VTy->isIntegerTy() || isa<Constant>(ResultOp)) 2810 return nullptr; 2811 2812 // Don't replace result of musttail calls. 2813 if (isMustTailCall(ResultOp)) 2814 return nullptr; 2815 2816 // There might be assume intrinsics dominating this return that completely 2817 // determine the value. If so, constant fold it. 2818 KnownBits Known = computeKnownBits(ResultOp, 0, &RI); 2819 if (Known.isConstant()) 2820 return replaceOperand(RI, 0, 2821 Constant::getIntegerValue(VTy, Known.getConstant())); 2822 2823 return nullptr; 2824 } 2825 2826 Instruction *InstCombinerImpl::visitUnreachableInst(UnreachableInst &I) { 2827 // Try to remove the previous instruction if it must lead to unreachable. 2828 // This includes instructions like stores and "llvm.assume" that may not get 2829 // removed by simple dead code elimination. 2830 Instruction *Prev = I.getPrevNonDebugInstruction(); 2831 if (Prev && !Prev->isEHPad() && 2832 isGuaranteedToTransferExecutionToSuccessor(Prev)) { 2833 // Temporarily disable removal of volatile stores preceding unreachable, 2834 // pending a potential LangRef change permitting volatile stores to trap. 2835 // TODO: Either remove this code, or properly integrate the check into 2836 // isGuaranteedToTransferExecutionToSuccessor(). 2837 if (auto *SI = dyn_cast<StoreInst>(Prev)) 2838 if (SI->isVolatile()) 2839 return nullptr; 2840 2841 // A value may still have uses before we process it here (for example, in 2842 // another unreachable block), so convert those to undef. 2843 replaceInstUsesWith(*Prev, UndefValue::get(Prev->getType())); 2844 eraseInstFromFunction(*Prev); 2845 return &I; 2846 } 2847 return nullptr; 2848 } 2849 2850 Instruction *InstCombinerImpl::visitUnconditionalBranchInst(BranchInst &BI) { 2851 assert(BI.isUnconditional() && "Only for unconditional branches."); 2852 2853 // If this store is the second-to-last instruction in the basic block 2854 // (excluding debug info and bitcasts of pointers) and if the block ends with 2855 // an unconditional branch, try to move the store to the successor block. 2856 2857 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) { 2858 auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) { 2859 return isa<DbgInfoIntrinsic>(BBI) || 2860 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()); 2861 }; 2862 2863 BasicBlock::iterator FirstInstr = BBI->getParent()->begin(); 2864 do { 2865 if (BBI != FirstInstr) 2866 --BBI; 2867 } while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI)); 2868 2869 return dyn_cast<StoreInst>(BBI); 2870 }; 2871 2872 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI))) 2873 if (mergeStoreIntoSuccessor(*SI)) 2874 return &BI; 2875 2876 return nullptr; 2877 } 2878 2879 Instruction *InstCombinerImpl::visitBranchInst(BranchInst &BI) { 2880 if (BI.isUnconditional()) 2881 return visitUnconditionalBranchInst(BI); 2882 2883 // Change br (not X), label True, label False to: br X, label False, True 2884 Value *X = nullptr; 2885 if (match(&BI, m_Br(m_Not(m_Value(X)), m_BasicBlock(), m_BasicBlock())) && 2886 !isa<Constant>(X)) { 2887 // Swap Destinations and condition... 2888 BI.swapSuccessors(); 2889 return replaceOperand(BI, 0, X); 2890 } 2891 2892 // If the condition is irrelevant, remove the use so that other 2893 // transforms on the condition become more effective. 2894 if (!isa<ConstantInt>(BI.getCondition()) && 2895 BI.getSuccessor(0) == BI.getSuccessor(1)) 2896 return replaceOperand( 2897 BI, 0, ConstantInt::getFalse(BI.getCondition()->getType())); 2898 2899 // Canonicalize, for example, fcmp_one -> fcmp_oeq. 2900 CmpInst::Predicate Pred; 2901 if (match(&BI, m_Br(m_OneUse(m_FCmp(Pred, m_Value(), m_Value())), 2902 m_BasicBlock(), m_BasicBlock())) && 2903 !isCanonicalPredicate(Pred)) { 2904 // Swap destinations and condition. 2905 CmpInst *Cond = cast<CmpInst>(BI.getCondition()); 2906 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 2907 BI.swapSuccessors(); 2908 Worklist.push(Cond); 2909 return &BI; 2910 } 2911 2912 return nullptr; 2913 } 2914 2915 Instruction *InstCombinerImpl::visitSwitchInst(SwitchInst &SI) { 2916 Value *Cond = SI.getCondition(); 2917 Value *Op0; 2918 ConstantInt *AddRHS; 2919 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) { 2920 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'. 2921 for (auto Case : SI.cases()) { 2922 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS); 2923 assert(isa<ConstantInt>(NewCase) && 2924 "Result of expression should be constant"); 2925 Case.setValue(cast<ConstantInt>(NewCase)); 2926 } 2927 return replaceOperand(SI, 0, Op0); 2928 } 2929 2930 KnownBits Known = computeKnownBits(Cond, 0, &SI); 2931 unsigned LeadingKnownZeros = Known.countMinLeadingZeros(); 2932 unsigned LeadingKnownOnes = Known.countMinLeadingOnes(); 2933 2934 // Compute the number of leading bits we can ignore. 2935 // TODO: A better way to determine this would use ComputeNumSignBits(). 2936 for (auto &C : SI.cases()) { 2937 LeadingKnownZeros = std::min( 2938 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros()); 2939 LeadingKnownOnes = std::min( 2940 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes()); 2941 } 2942 2943 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes); 2944 2945 // Shrink the condition operand if the new type is smaller than the old type. 2946 // But do not shrink to a non-standard type, because backend can't generate 2947 // good code for that yet. 2948 // TODO: We can make it aggressive again after fixing PR39569. 2949 if (NewWidth > 0 && NewWidth < Known.getBitWidth() && 2950 shouldChangeType(Known.getBitWidth(), NewWidth)) { 2951 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth); 2952 Builder.SetInsertPoint(&SI); 2953 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc"); 2954 2955 for (auto Case : SI.cases()) { 2956 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth); 2957 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase)); 2958 } 2959 return replaceOperand(SI, 0, NewCond); 2960 } 2961 2962 return nullptr; 2963 } 2964 2965 Instruction *InstCombinerImpl::visitExtractValueInst(ExtractValueInst &EV) { 2966 Value *Agg = EV.getAggregateOperand(); 2967 2968 if (!EV.hasIndices()) 2969 return replaceInstUsesWith(EV, Agg); 2970 2971 if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(), 2972 SQ.getWithInstruction(&EV))) 2973 return replaceInstUsesWith(EV, V); 2974 2975 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 2976 // We're extracting from an insertvalue instruction, compare the indices 2977 const unsigned *exti, *exte, *insi, *inse; 2978 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 2979 exte = EV.idx_end(), inse = IV->idx_end(); 2980 exti != exte && insi != inse; 2981 ++exti, ++insi) { 2982 if (*insi != *exti) 2983 // The insert and extract both reference distinctly different elements. 2984 // This means the extract is not influenced by the insert, and we can 2985 // replace the aggregate operand of the extract with the aggregate 2986 // operand of the insert. i.e., replace 2987 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 2988 // %E = extractvalue { i32, { i32 } } %I, 0 2989 // with 2990 // %E = extractvalue { i32, { i32 } } %A, 0 2991 return ExtractValueInst::Create(IV->getAggregateOperand(), 2992 EV.getIndices()); 2993 } 2994 if (exti == exte && insi == inse) 2995 // Both iterators are at the end: Index lists are identical. Replace 2996 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 2997 // %C = extractvalue { i32, { i32 } } %B, 1, 0 2998 // with "i32 42" 2999 return replaceInstUsesWith(EV, IV->getInsertedValueOperand()); 3000 if (exti == exte) { 3001 // The extract list is a prefix of the insert list. i.e. replace 3002 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 3003 // %E = extractvalue { i32, { i32 } } %I, 1 3004 // with 3005 // %X = extractvalue { i32, { i32 } } %A, 1 3006 // %E = insertvalue { i32 } %X, i32 42, 0 3007 // by switching the order of the insert and extract (though the 3008 // insertvalue should be left in, since it may have other uses). 3009 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(), 3010 EV.getIndices()); 3011 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 3012 makeArrayRef(insi, inse)); 3013 } 3014 if (insi == inse) 3015 // The insert list is a prefix of the extract list 3016 // We can simply remove the common indices from the extract and make it 3017 // operate on the inserted value instead of the insertvalue result. 3018 // i.e., replace 3019 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 3020 // %E = extractvalue { i32, { i32 } } %I, 1, 0 3021 // with 3022 // %E extractvalue { i32 } { i32 42 }, 0 3023 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 3024 makeArrayRef(exti, exte)); 3025 } 3026 if (WithOverflowInst *WO = dyn_cast<WithOverflowInst>(Agg)) { 3027 // We're extracting from an overflow intrinsic, see if we're the only user, 3028 // which allows us to simplify multiple result intrinsics to simpler 3029 // things that just get one value. 3030 if (WO->hasOneUse()) { 3031 // Check if we're grabbing only the result of a 'with overflow' intrinsic 3032 // and replace it with a traditional binary instruction. 3033 if (*EV.idx_begin() == 0) { 3034 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 3035 Value *LHS = WO->getLHS(), *RHS = WO->getRHS(); 3036 replaceInstUsesWith(*WO, UndefValue::get(WO->getType())); 3037 eraseInstFromFunction(*WO); 3038 return BinaryOperator::Create(BinOp, LHS, RHS); 3039 } 3040 3041 // If the normal result of the add is dead, and the RHS is a constant, 3042 // we can transform this into a range comparison. 3043 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 3044 if (WO->getIntrinsicID() == Intrinsic::uadd_with_overflow) 3045 if (ConstantInt *CI = dyn_cast<ConstantInt>(WO->getRHS())) 3046 return new ICmpInst(ICmpInst::ICMP_UGT, WO->getLHS(), 3047 ConstantExpr::getNot(CI)); 3048 } 3049 } 3050 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) 3051 // If the (non-volatile) load only has one use, we can rewrite this to a 3052 // load from a GEP. This reduces the size of the load. If a load is used 3053 // only by extractvalue instructions then this either must have been 3054 // optimized before, or it is a struct with padding, in which case we 3055 // don't want to do the transformation as it loses padding knowledge. 3056 if (L->isSimple() && L->hasOneUse()) { 3057 // extractvalue has integer indices, getelementptr has Value*s. Convert. 3058 SmallVector<Value*, 4> Indices; 3059 // Prefix an i32 0 since we need the first element. 3060 Indices.push_back(Builder.getInt32(0)); 3061 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); 3062 I != E; ++I) 3063 Indices.push_back(Builder.getInt32(*I)); 3064 3065 // We need to insert these at the location of the old load, not at that of 3066 // the extractvalue. 3067 Builder.SetInsertPoint(L); 3068 Value *GEP = Builder.CreateInBoundsGEP(L->getType(), 3069 L->getPointerOperand(), Indices); 3070 Instruction *NL = Builder.CreateLoad(EV.getType(), GEP); 3071 // Whatever aliasing information we had for the orignal load must also 3072 // hold for the smaller load, so propagate the annotations. 3073 AAMDNodes Nodes; 3074 L->getAAMetadata(Nodes); 3075 NL->setAAMetadata(Nodes); 3076 // Returning the load directly will cause the main loop to insert it in 3077 // the wrong spot, so use replaceInstUsesWith(). 3078 return replaceInstUsesWith(EV, NL); 3079 } 3080 // We could simplify extracts from other values. Note that nested extracts may 3081 // already be simplified implicitly by the above: extract (extract (insert) ) 3082 // will be translated into extract ( insert ( extract ) ) first and then just 3083 // the value inserted, if appropriate. Similarly for extracts from single-use 3084 // loads: extract (extract (load)) will be translated to extract (load (gep)) 3085 // and if again single-use then via load (gep (gep)) to load (gep). 3086 // However, double extracts from e.g. function arguments or return values 3087 // aren't handled yet. 3088 return nullptr; 3089 } 3090 3091 /// Return 'true' if the given typeinfo will match anything. 3092 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) { 3093 switch (Personality) { 3094 case EHPersonality::GNU_C: 3095 case EHPersonality::GNU_C_SjLj: 3096 case EHPersonality::Rust: 3097 // The GCC C EH and Rust personality only exists to support cleanups, so 3098 // it's not clear what the semantics of catch clauses are. 3099 return false; 3100 case EHPersonality::Unknown: 3101 return false; 3102 case EHPersonality::GNU_Ada: 3103 // While __gnat_all_others_value will match any Ada exception, it doesn't 3104 // match foreign exceptions (or didn't, before gcc-4.7). 3105 return false; 3106 case EHPersonality::GNU_CXX: 3107 case EHPersonality::GNU_CXX_SjLj: 3108 case EHPersonality::GNU_ObjC: 3109 case EHPersonality::MSVC_X86SEH: 3110 case EHPersonality::MSVC_TableSEH: 3111 case EHPersonality::MSVC_CXX: 3112 case EHPersonality::CoreCLR: 3113 case EHPersonality::Wasm_CXX: 3114 case EHPersonality::XL_CXX: 3115 return TypeInfo->isNullValue(); 3116 } 3117 llvm_unreachable("invalid enum"); 3118 } 3119 3120 static bool shorter_filter(const Value *LHS, const Value *RHS) { 3121 return 3122 cast<ArrayType>(LHS->getType())->getNumElements() 3123 < 3124 cast<ArrayType>(RHS->getType())->getNumElements(); 3125 } 3126 3127 Instruction *InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) { 3128 // The logic here should be correct for any real-world personality function. 3129 // However if that turns out not to be true, the offending logic can always 3130 // be conditioned on the personality function, like the catch-all logic is. 3131 EHPersonality Personality = 3132 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn()); 3133 3134 // Simplify the list of clauses, eg by removing repeated catch clauses 3135 // (these are often created by inlining). 3136 bool MakeNewInstruction = false; // If true, recreate using the following: 3137 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction; 3138 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup. 3139 3140 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already. 3141 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) { 3142 bool isLastClause = i + 1 == e; 3143 if (LI.isCatch(i)) { 3144 // A catch clause. 3145 Constant *CatchClause = LI.getClause(i); 3146 Constant *TypeInfo = CatchClause->stripPointerCasts(); 3147 3148 // If we already saw this clause, there is no point in having a second 3149 // copy of it. 3150 if (AlreadyCaught.insert(TypeInfo).second) { 3151 // This catch clause was not already seen. 3152 NewClauses.push_back(CatchClause); 3153 } else { 3154 // Repeated catch clause - drop the redundant copy. 3155 MakeNewInstruction = true; 3156 } 3157 3158 // If this is a catch-all then there is no point in keeping any following 3159 // clauses or marking the landingpad as having a cleanup. 3160 if (isCatchAll(Personality, TypeInfo)) { 3161 if (!isLastClause) 3162 MakeNewInstruction = true; 3163 CleanupFlag = false; 3164 break; 3165 } 3166 } else { 3167 // A filter clause. If any of the filter elements were already caught 3168 // then they can be dropped from the filter. It is tempting to try to 3169 // exploit the filter further by saying that any typeinfo that does not 3170 // occur in the filter can't be caught later (and thus can be dropped). 3171 // However this would be wrong, since typeinfos can match without being 3172 // equal (for example if one represents a C++ class, and the other some 3173 // class derived from it). 3174 assert(LI.isFilter(i) && "Unsupported landingpad clause!"); 3175 Constant *FilterClause = LI.getClause(i); 3176 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType()); 3177 unsigned NumTypeInfos = FilterType->getNumElements(); 3178 3179 // An empty filter catches everything, so there is no point in keeping any 3180 // following clauses or marking the landingpad as having a cleanup. By 3181 // dealing with this case here the following code is made a bit simpler. 3182 if (!NumTypeInfos) { 3183 NewClauses.push_back(FilterClause); 3184 if (!isLastClause) 3185 MakeNewInstruction = true; 3186 CleanupFlag = false; 3187 break; 3188 } 3189 3190 bool MakeNewFilter = false; // If true, make a new filter. 3191 SmallVector<Constant *, 16> NewFilterElts; // New elements. 3192 if (isa<ConstantAggregateZero>(FilterClause)) { 3193 // Not an empty filter - it contains at least one null typeinfo. 3194 assert(NumTypeInfos > 0 && "Should have handled empty filter already!"); 3195 Constant *TypeInfo = 3196 Constant::getNullValue(FilterType->getElementType()); 3197 // If this typeinfo is a catch-all then the filter can never match. 3198 if (isCatchAll(Personality, TypeInfo)) { 3199 // Throw the filter away. 3200 MakeNewInstruction = true; 3201 continue; 3202 } 3203 3204 // There is no point in having multiple copies of this typeinfo, so 3205 // discard all but the first copy if there is more than one. 3206 NewFilterElts.push_back(TypeInfo); 3207 if (NumTypeInfos > 1) 3208 MakeNewFilter = true; 3209 } else { 3210 ConstantArray *Filter = cast<ConstantArray>(FilterClause); 3211 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements. 3212 NewFilterElts.reserve(NumTypeInfos); 3213 3214 // Remove any filter elements that were already caught or that already 3215 // occurred in the filter. While there, see if any of the elements are 3216 // catch-alls. If so, the filter can be discarded. 3217 bool SawCatchAll = false; 3218 for (unsigned j = 0; j != NumTypeInfos; ++j) { 3219 Constant *Elt = Filter->getOperand(j); 3220 Constant *TypeInfo = Elt->stripPointerCasts(); 3221 if (isCatchAll(Personality, TypeInfo)) { 3222 // This element is a catch-all. Bail out, noting this fact. 3223 SawCatchAll = true; 3224 break; 3225 } 3226 3227 // Even if we've seen a type in a catch clause, we don't want to 3228 // remove it from the filter. An unexpected type handler may be 3229 // set up for a call site which throws an exception of the same 3230 // type caught. In order for the exception thrown by the unexpected 3231 // handler to propagate correctly, the filter must be correctly 3232 // described for the call site. 3233 // 3234 // Example: 3235 // 3236 // void unexpected() { throw 1;} 3237 // void foo() throw (int) { 3238 // std::set_unexpected(unexpected); 3239 // try { 3240 // throw 2.0; 3241 // } catch (int i) {} 3242 // } 3243 3244 // There is no point in having multiple copies of the same typeinfo in 3245 // a filter, so only add it if we didn't already. 3246 if (SeenInFilter.insert(TypeInfo).second) 3247 NewFilterElts.push_back(cast<Constant>(Elt)); 3248 } 3249 // A filter containing a catch-all cannot match anything by definition. 3250 if (SawCatchAll) { 3251 // Throw the filter away. 3252 MakeNewInstruction = true; 3253 continue; 3254 } 3255 3256 // If we dropped something from the filter, make a new one. 3257 if (NewFilterElts.size() < NumTypeInfos) 3258 MakeNewFilter = true; 3259 } 3260 if (MakeNewFilter) { 3261 FilterType = ArrayType::get(FilterType->getElementType(), 3262 NewFilterElts.size()); 3263 FilterClause = ConstantArray::get(FilterType, NewFilterElts); 3264 MakeNewInstruction = true; 3265 } 3266 3267 NewClauses.push_back(FilterClause); 3268 3269 // If the new filter is empty then it will catch everything so there is 3270 // no point in keeping any following clauses or marking the landingpad 3271 // as having a cleanup. The case of the original filter being empty was 3272 // already handled above. 3273 if (MakeNewFilter && !NewFilterElts.size()) { 3274 assert(MakeNewInstruction && "New filter but not a new instruction!"); 3275 CleanupFlag = false; 3276 break; 3277 } 3278 } 3279 } 3280 3281 // If several filters occur in a row then reorder them so that the shortest 3282 // filters come first (those with the smallest number of elements). This is 3283 // advantageous because shorter filters are more likely to match, speeding up 3284 // unwinding, but mostly because it increases the effectiveness of the other 3285 // filter optimizations below. 3286 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) { 3287 unsigned j; 3288 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters. 3289 for (j = i; j != e; ++j) 3290 if (!isa<ArrayType>(NewClauses[j]->getType())) 3291 break; 3292 3293 // Check whether the filters are already sorted by length. We need to know 3294 // if sorting them is actually going to do anything so that we only make a 3295 // new landingpad instruction if it does. 3296 for (unsigned k = i; k + 1 < j; ++k) 3297 if (shorter_filter(NewClauses[k+1], NewClauses[k])) { 3298 // Not sorted, so sort the filters now. Doing an unstable sort would be 3299 // correct too but reordering filters pointlessly might confuse users. 3300 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j, 3301 shorter_filter); 3302 MakeNewInstruction = true; 3303 break; 3304 } 3305 3306 // Look for the next batch of filters. 3307 i = j + 1; 3308 } 3309 3310 // If typeinfos matched if and only if equal, then the elements of a filter L 3311 // that occurs later than a filter F could be replaced by the intersection of 3312 // the elements of F and L. In reality two typeinfos can match without being 3313 // equal (for example if one represents a C++ class, and the other some class 3314 // derived from it) so it would be wrong to perform this transform in general. 3315 // However the transform is correct and useful if F is a subset of L. In that 3316 // case L can be replaced by F, and thus removed altogether since repeating a 3317 // filter is pointless. So here we look at all pairs of filters F and L where 3318 // L follows F in the list of clauses, and remove L if every element of F is 3319 // an element of L. This can occur when inlining C++ functions with exception 3320 // specifications. 3321 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) { 3322 // Examine each filter in turn. 3323 Value *Filter = NewClauses[i]; 3324 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType()); 3325 if (!FTy) 3326 // Not a filter - skip it. 3327 continue; 3328 unsigned FElts = FTy->getNumElements(); 3329 // Examine each filter following this one. Doing this backwards means that 3330 // we don't have to worry about filters disappearing under us when removed. 3331 for (unsigned j = NewClauses.size() - 1; j != i; --j) { 3332 Value *LFilter = NewClauses[j]; 3333 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType()); 3334 if (!LTy) 3335 // Not a filter - skip it. 3336 continue; 3337 // If Filter is a subset of LFilter, i.e. every element of Filter is also 3338 // an element of LFilter, then discard LFilter. 3339 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j; 3340 // If Filter is empty then it is a subset of LFilter. 3341 if (!FElts) { 3342 // Discard LFilter. 3343 NewClauses.erase(J); 3344 MakeNewInstruction = true; 3345 // Move on to the next filter. 3346 continue; 3347 } 3348 unsigned LElts = LTy->getNumElements(); 3349 // If Filter is longer than LFilter then it cannot be a subset of it. 3350 if (FElts > LElts) 3351 // Move on to the next filter. 3352 continue; 3353 // At this point we know that LFilter has at least one element. 3354 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros. 3355 // Filter is a subset of LFilter iff Filter contains only zeros (as we 3356 // already know that Filter is not longer than LFilter). 3357 if (isa<ConstantAggregateZero>(Filter)) { 3358 assert(FElts <= LElts && "Should have handled this case earlier!"); 3359 // Discard LFilter. 3360 NewClauses.erase(J); 3361 MakeNewInstruction = true; 3362 } 3363 // Move on to the next filter. 3364 continue; 3365 } 3366 ConstantArray *LArray = cast<ConstantArray>(LFilter); 3367 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros. 3368 // Since Filter is non-empty and contains only zeros, it is a subset of 3369 // LFilter iff LFilter contains a zero. 3370 assert(FElts > 0 && "Should have eliminated the empty filter earlier!"); 3371 for (unsigned l = 0; l != LElts; ++l) 3372 if (LArray->getOperand(l)->isNullValue()) { 3373 // LFilter contains a zero - discard it. 3374 NewClauses.erase(J); 3375 MakeNewInstruction = true; 3376 break; 3377 } 3378 // Move on to the next filter. 3379 continue; 3380 } 3381 // At this point we know that both filters are ConstantArrays. Loop over 3382 // operands to see whether every element of Filter is also an element of 3383 // LFilter. Since filters tend to be short this is probably faster than 3384 // using a method that scales nicely. 3385 ConstantArray *FArray = cast<ConstantArray>(Filter); 3386 bool AllFound = true; 3387 for (unsigned f = 0; f != FElts; ++f) { 3388 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts(); 3389 AllFound = false; 3390 for (unsigned l = 0; l != LElts; ++l) { 3391 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts(); 3392 if (LTypeInfo == FTypeInfo) { 3393 AllFound = true; 3394 break; 3395 } 3396 } 3397 if (!AllFound) 3398 break; 3399 } 3400 if (AllFound) { 3401 // Discard LFilter. 3402 NewClauses.erase(J); 3403 MakeNewInstruction = true; 3404 } 3405 // Move on to the next filter. 3406 } 3407 } 3408 3409 // If we changed any of the clauses, replace the old landingpad instruction 3410 // with a new one. 3411 if (MakeNewInstruction) { 3412 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(), 3413 NewClauses.size()); 3414 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i) 3415 NLI->addClause(NewClauses[i]); 3416 // A landing pad with no clauses must have the cleanup flag set. It is 3417 // theoretically possible, though highly unlikely, that we eliminated all 3418 // clauses. If so, force the cleanup flag to true. 3419 if (NewClauses.empty()) 3420 CleanupFlag = true; 3421 NLI->setCleanup(CleanupFlag); 3422 return NLI; 3423 } 3424 3425 // Even if none of the clauses changed, we may nonetheless have understood 3426 // that the cleanup flag is pointless. Clear it if so. 3427 if (LI.isCleanup() != CleanupFlag) { 3428 assert(!CleanupFlag && "Adding a cleanup, not removing one?!"); 3429 LI.setCleanup(CleanupFlag); 3430 return &LI; 3431 } 3432 3433 return nullptr; 3434 } 3435 3436 Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) { 3437 Value *Op0 = I.getOperand(0); 3438 3439 if (Value *V = SimplifyFreezeInst(Op0, SQ.getWithInstruction(&I))) 3440 return replaceInstUsesWith(I, V); 3441 3442 // freeze (phi const, x) --> phi const, (freeze x) 3443 if (auto *PN = dyn_cast<PHINode>(Op0)) { 3444 if (Instruction *NV = foldOpIntoPhi(I, PN)) 3445 return NV; 3446 } 3447 3448 if (match(Op0, m_Undef())) { 3449 // If I is freeze(undef), see its uses and fold it to the best constant. 3450 // - or: pick -1 3451 // - select's condition: pick the value that leads to choosing a constant 3452 // - other ops: pick 0 3453 Constant *BestValue = nullptr; 3454 Constant *NullValue = Constant::getNullValue(I.getType()); 3455 for (const auto *U : I.users()) { 3456 Constant *C = NullValue; 3457 3458 if (match(U, m_Or(m_Value(), m_Value()))) 3459 C = Constant::getAllOnesValue(I.getType()); 3460 else if (const auto *SI = dyn_cast<SelectInst>(U)) { 3461 if (SI->getCondition() == &I) { 3462 APInt CondVal(1, isa<Constant>(SI->getFalseValue()) ? 0 : 1); 3463 C = Constant::getIntegerValue(I.getType(), CondVal); 3464 } 3465 } 3466 3467 if (!BestValue) 3468 BestValue = C; 3469 else if (BestValue != C) 3470 BestValue = NullValue; 3471 } 3472 3473 return replaceInstUsesWith(I, BestValue); 3474 } 3475 3476 return nullptr; 3477 } 3478 3479 /// Try to move the specified instruction from its current block into the 3480 /// beginning of DestBlock, which can only happen if it's safe to move the 3481 /// instruction past all of the instructions between it and the end of its 3482 /// block. 3483 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 3484 assert(I->getSingleUndroppableUse() && "Invariants didn't hold!"); 3485 BasicBlock *SrcBlock = I->getParent(); 3486 3487 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 3488 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() || 3489 I->isTerminator()) 3490 return false; 3491 3492 // Do not sink static or dynamic alloca instructions. Static allocas must 3493 // remain in the entry block, and dynamic allocas must not be sunk in between 3494 // a stacksave / stackrestore pair, which would incorrectly shorten its 3495 // lifetime. 3496 if (isa<AllocaInst>(I)) 3497 return false; 3498 3499 // Do not sink into catchswitch blocks. 3500 if (isa<CatchSwitchInst>(DestBlock->getTerminator())) 3501 return false; 3502 3503 // Do not sink convergent call instructions. 3504 if (auto *CI = dyn_cast<CallInst>(I)) { 3505 if (CI->isConvergent()) 3506 return false; 3507 } 3508 // We can only sink load instructions if there is nothing between the load and 3509 // the end of block that could change the value. 3510 if (I->mayReadFromMemory()) { 3511 // We don't want to do any sophisticated alias analysis, so we only check 3512 // the instructions after I in I's parent block if we try to sink to its 3513 // successor block. 3514 if (DestBlock->getUniquePredecessor() != I->getParent()) 3515 return false; 3516 for (BasicBlock::iterator Scan = I->getIterator(), 3517 E = I->getParent()->end(); 3518 Scan != E; ++Scan) 3519 if (Scan->mayWriteToMemory()) 3520 return false; 3521 } 3522 3523 I->dropDroppableUses([DestBlock](const Use *U) { 3524 if (auto *I = dyn_cast<Instruction>(U->getUser())) 3525 return I->getParent() != DestBlock; 3526 return true; 3527 }); 3528 /// FIXME: We could remove droppable uses that are not dominated by 3529 /// the new position. 3530 3531 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); 3532 I->moveBefore(&*InsertPos); 3533 ++NumSunkInst; 3534 3535 // Also sink all related debug uses from the source basic block. Otherwise we 3536 // get debug use before the def. Attempt to salvage debug uses first, to 3537 // maximise the range variables have location for. If we cannot salvage, then 3538 // mark the location undef: we know it was supposed to receive a new location 3539 // here, but that computation has been sunk. 3540 SmallVector<DbgVariableIntrinsic *, 2> DbgUsers; 3541 findDbgUsers(DbgUsers, I); 3542 3543 // Update the arguments of a dbg.declare instruction, so that it 3544 // does not point into a sunk instruction. 3545 auto updateDbgDeclare = [&I](DbgVariableIntrinsic *DII) { 3546 if (!isa<DbgDeclareInst>(DII)) 3547 return false; 3548 3549 if (isa<CastInst>(I)) 3550 DII->setOperand( 3551 0, MetadataAsValue::get(I->getContext(), 3552 ValueAsMetadata::get(I->getOperand(0)))); 3553 return true; 3554 }; 3555 3556 SmallVector<DbgVariableIntrinsic *, 2> DIIClones; 3557 for (auto User : DbgUsers) { 3558 // A dbg.declare instruction should not be cloned, since there can only be 3559 // one per variable fragment. It should be left in the original place 3560 // because the sunk instruction is not an alloca (otherwise we could not be 3561 // here). 3562 if (User->getParent() != SrcBlock || updateDbgDeclare(User)) 3563 continue; 3564 3565 DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone())); 3566 LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n'); 3567 } 3568 3569 // Perform salvaging without the clones, then sink the clones. 3570 if (!DIIClones.empty()) { 3571 salvageDebugInfoForDbgValues(*I, DbgUsers); 3572 for (auto &DIIClone : DIIClones) { 3573 DIIClone->insertBefore(&*InsertPos); 3574 LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n'); 3575 } 3576 } 3577 3578 return true; 3579 } 3580 3581 bool InstCombinerImpl::run() { 3582 while (!Worklist.isEmpty()) { 3583 // Walk deferred instructions in reverse order, and push them to the 3584 // worklist, which means they'll end up popped from the worklist in-order. 3585 while (Instruction *I = Worklist.popDeferred()) { 3586 // Check to see if we can DCE the instruction. We do this already here to 3587 // reduce the number of uses and thus allow other folds to trigger. 3588 // Note that eraseInstFromFunction() may push additional instructions on 3589 // the deferred worklist, so this will DCE whole instruction chains. 3590 if (isInstructionTriviallyDead(I, &TLI)) { 3591 eraseInstFromFunction(*I); 3592 ++NumDeadInst; 3593 continue; 3594 } 3595 3596 Worklist.push(I); 3597 } 3598 3599 Instruction *I = Worklist.removeOne(); 3600 if (I == nullptr) continue; // skip null values. 3601 3602 // Check to see if we can DCE the instruction. 3603 if (isInstructionTriviallyDead(I, &TLI)) { 3604 eraseInstFromFunction(*I); 3605 ++NumDeadInst; 3606 continue; 3607 } 3608 3609 if (!DebugCounter::shouldExecute(VisitCounter)) 3610 continue; 3611 3612 // Instruction isn't dead, see if we can constant propagate it. 3613 if (!I->use_empty() && 3614 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) { 3615 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) { 3616 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I 3617 << '\n'); 3618 3619 // Add operands to the worklist. 3620 replaceInstUsesWith(*I, C); 3621 ++NumConstProp; 3622 if (isInstructionTriviallyDead(I, &TLI)) 3623 eraseInstFromFunction(*I); 3624 MadeIRChange = true; 3625 continue; 3626 } 3627 } 3628 3629 // See if we can trivially sink this instruction to its user if we can 3630 // prove that the successor is not executed more frequently than our block. 3631 if (EnableCodeSinking) 3632 if (Use *SingleUse = I->getSingleUndroppableUse()) { 3633 BasicBlock *BB = I->getParent(); 3634 Instruction *UserInst = cast<Instruction>(SingleUse->getUser()); 3635 BasicBlock *UserParent; 3636 3637 // Get the block the use occurs in. 3638 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 3639 UserParent = PN->getIncomingBlock(*SingleUse); 3640 else 3641 UserParent = UserInst->getParent(); 3642 3643 // Try sinking to another block. If that block is unreachable, then do 3644 // not bother. SimplifyCFG should handle it. 3645 if (UserParent != BB && DT.isReachableFromEntry(UserParent)) { 3646 // See if the user is one of our successors that has only one 3647 // predecessor, so that we don't have to split the critical edge. 3648 bool ShouldSink = UserParent->getUniquePredecessor() == BB; 3649 // Another option where we can sink is a block that ends with a 3650 // terminator that does not pass control to other block (such as 3651 // return or unreachable). In this case: 3652 // - I dominates the User (by SSA form); 3653 // - the User will be executed at most once. 3654 // So sinking I down to User is always profitable or neutral. 3655 if (!ShouldSink) { 3656 auto *Term = UserParent->getTerminator(); 3657 ShouldSink = isa<ReturnInst>(Term) || isa<UnreachableInst>(Term); 3658 } 3659 if (ShouldSink) { 3660 assert(DT.dominates(BB, UserParent) && 3661 "Dominance relation broken?"); 3662 // Okay, the CFG is simple enough, try to sink this instruction. 3663 if (TryToSinkInstruction(I, UserParent)) { 3664 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n'); 3665 MadeIRChange = true; 3666 // We'll add uses of the sunk instruction below, but since sinking 3667 // can expose opportunities for it's *operands* add them to the 3668 // worklist 3669 for (Use &U : I->operands()) 3670 if (Instruction *OpI = dyn_cast<Instruction>(U.get())) 3671 Worklist.push(OpI); 3672 } 3673 } 3674 } 3675 } 3676 3677 // Now that we have an instruction, try combining it to simplify it. 3678 Builder.SetInsertPoint(I); 3679 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 3680 3681 #ifndef NDEBUG 3682 std::string OrigI; 3683 #endif 3684 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 3685 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n'); 3686 3687 if (Instruction *Result = visit(*I)) { 3688 ++NumCombined; 3689 // Should we replace the old instruction with a new one? 3690 if (Result != I) { 3691 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n' 3692 << " New = " << *Result << '\n'); 3693 3694 if (I->getDebugLoc()) 3695 Result->setDebugLoc(I->getDebugLoc()); 3696 // Everything uses the new instruction now. 3697 I->replaceAllUsesWith(Result); 3698 3699 // Move the name to the new instruction first. 3700 Result->takeName(I); 3701 3702 // Insert the new instruction into the basic block... 3703 BasicBlock *InstParent = I->getParent(); 3704 BasicBlock::iterator InsertPos = I->getIterator(); 3705 3706 // Are we replace a PHI with something that isn't a PHI, or vice versa? 3707 if (isa<PHINode>(Result) != isa<PHINode>(I)) { 3708 // We need to fix up the insertion point. 3709 if (isa<PHINode>(I)) // PHI -> Non-PHI 3710 InsertPos = InstParent->getFirstInsertionPt(); 3711 else // Non-PHI -> PHI 3712 InsertPos = InstParent->getFirstNonPHI()->getIterator(); 3713 } 3714 3715 InstParent->getInstList().insert(InsertPos, Result); 3716 3717 // Push the new instruction and any users onto the worklist. 3718 Worklist.pushUsersToWorkList(*Result); 3719 Worklist.push(Result); 3720 3721 eraseInstFromFunction(*I); 3722 } else { 3723 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n' 3724 << " New = " << *I << '\n'); 3725 3726 // If the instruction was modified, it's possible that it is now dead. 3727 // if so, remove it. 3728 if (isInstructionTriviallyDead(I, &TLI)) { 3729 eraseInstFromFunction(*I); 3730 } else { 3731 Worklist.pushUsersToWorkList(*I); 3732 Worklist.push(I); 3733 } 3734 } 3735 MadeIRChange = true; 3736 } 3737 } 3738 3739 Worklist.zap(); 3740 return MadeIRChange; 3741 } 3742 3743 /// Populate the IC worklist from a function, by walking it in depth-first 3744 /// order and adding all reachable code to the worklist. 3745 /// 3746 /// This has a couple of tricks to make the code faster and more powerful. In 3747 /// particular, we constant fold and DCE instructions as we go, to avoid adding 3748 /// them to the worklist (this significantly speeds up instcombine on code where 3749 /// many instructions are dead or constant). Additionally, if we find a branch 3750 /// whose condition is a known constant, we only visit the reachable successors. 3751 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL, 3752 const TargetLibraryInfo *TLI, 3753 InstCombineWorklist &ICWorklist) { 3754 bool MadeIRChange = false; 3755 SmallPtrSet<BasicBlock *, 32> Visited; 3756 SmallVector<BasicBlock*, 256> Worklist; 3757 Worklist.push_back(&F.front()); 3758 3759 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; 3760 DenseMap<Constant *, Constant *> FoldedConstants; 3761 3762 do { 3763 BasicBlock *BB = Worklist.pop_back_val(); 3764 3765 // We have now visited this block! If we've already been here, ignore it. 3766 if (!Visited.insert(BB).second) 3767 continue; 3768 3769 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 3770 Instruction *Inst = &*BBI++; 3771 3772 // ConstantProp instruction if trivially constant. 3773 if (!Inst->use_empty() && 3774 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0)))) 3775 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) { 3776 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst 3777 << '\n'); 3778 Inst->replaceAllUsesWith(C); 3779 ++NumConstProp; 3780 if (isInstructionTriviallyDead(Inst, TLI)) 3781 Inst->eraseFromParent(); 3782 MadeIRChange = true; 3783 continue; 3784 } 3785 3786 // See if we can constant fold its operands. 3787 for (Use &U : Inst->operands()) { 3788 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U)) 3789 continue; 3790 3791 auto *C = cast<Constant>(U); 3792 Constant *&FoldRes = FoldedConstants[C]; 3793 if (!FoldRes) 3794 FoldRes = ConstantFoldConstant(C, DL, TLI); 3795 3796 if (FoldRes != C) { 3797 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst 3798 << "\n Old = " << *C 3799 << "\n New = " << *FoldRes << '\n'); 3800 U = FoldRes; 3801 MadeIRChange = true; 3802 } 3803 } 3804 3805 // Skip processing debug intrinsics in InstCombine. Processing these call instructions 3806 // consumes non-trivial amount of time and provides no value for the optimization. 3807 if (!isa<DbgInfoIntrinsic>(Inst)) 3808 InstrsForInstCombineWorklist.push_back(Inst); 3809 } 3810 3811 // Recursively visit successors. If this is a branch or switch on a 3812 // constant, only visit the reachable successor. 3813 Instruction *TI = BB->getTerminator(); 3814 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 3815 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { 3816 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); 3817 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); 3818 Worklist.push_back(ReachableBB); 3819 continue; 3820 } 3821 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 3822 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 3823 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor()); 3824 continue; 3825 } 3826 } 3827 3828 for (BasicBlock *SuccBB : successors(TI)) 3829 Worklist.push_back(SuccBB); 3830 } while (!Worklist.empty()); 3831 3832 // Remove instructions inside unreachable blocks. This prevents the 3833 // instcombine code from having to deal with some bad special cases, and 3834 // reduces use counts of instructions. 3835 for (BasicBlock &BB : F) { 3836 if (Visited.count(&BB)) 3837 continue; 3838 3839 unsigned NumDeadInstInBB; 3840 unsigned NumDeadDbgInstInBB; 3841 std::tie(NumDeadInstInBB, NumDeadDbgInstInBB) = 3842 removeAllNonTerminatorAndEHPadInstructions(&BB); 3843 3844 MadeIRChange |= NumDeadInstInBB + NumDeadDbgInstInBB > 0; 3845 NumDeadInst += NumDeadInstInBB; 3846 } 3847 3848 // Once we've found all of the instructions to add to instcombine's worklist, 3849 // add them in reverse order. This way instcombine will visit from the top 3850 // of the function down. This jives well with the way that it adds all uses 3851 // of instructions to the worklist after doing a transformation, thus avoiding 3852 // some N^2 behavior in pathological cases. 3853 ICWorklist.reserve(InstrsForInstCombineWorklist.size()); 3854 for (Instruction *Inst : reverse(InstrsForInstCombineWorklist)) { 3855 // DCE instruction if trivially dead. As we iterate in reverse program 3856 // order here, we will clean up whole chains of dead instructions. 3857 if (isInstructionTriviallyDead(Inst, TLI)) { 3858 ++NumDeadInst; 3859 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n'); 3860 salvageDebugInfo(*Inst); 3861 Inst->eraseFromParent(); 3862 MadeIRChange = true; 3863 continue; 3864 } 3865 3866 ICWorklist.push(Inst); 3867 } 3868 3869 return MadeIRChange; 3870 } 3871 3872 static bool combineInstructionsOverFunction( 3873 Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, 3874 AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, 3875 DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, 3876 ProfileSummaryInfo *PSI, unsigned MaxIterations, LoopInfo *LI) { 3877 auto &DL = F.getParent()->getDataLayout(); 3878 MaxIterations = std::min(MaxIterations, LimitMaxIterations.getValue()); 3879 3880 /// Builder - This is an IRBuilder that automatically inserts new 3881 /// instructions into the worklist when they are created. 3882 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder( 3883 F.getContext(), TargetFolder(DL), 3884 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) { 3885 Worklist.add(I); 3886 if (match(I, m_Intrinsic<Intrinsic::assume>())) 3887 AC.registerAssumption(cast<CallInst>(I)); 3888 })); 3889 3890 // Lower dbg.declare intrinsics otherwise their value may be clobbered 3891 // by instcombiner. 3892 bool MadeIRChange = false; 3893 if (ShouldLowerDbgDeclare) 3894 MadeIRChange = LowerDbgDeclare(F); 3895 3896 // Iterate while there is work to do. 3897 unsigned Iteration = 0; 3898 while (true) { 3899 ++NumWorklistIterations; 3900 ++Iteration; 3901 3902 if (Iteration > InfiniteLoopDetectionThreshold) { 3903 report_fatal_error( 3904 "Instruction Combining seems stuck in an infinite loop after " + 3905 Twine(InfiniteLoopDetectionThreshold) + " iterations."); 3906 } 3907 3908 if (Iteration > MaxIterations) { 3909 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterations 3910 << " on " << F.getName() 3911 << " reached; stopping before reaching a fixpoint\n"); 3912 break; 3913 } 3914 3915 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 3916 << F.getName() << "\n"); 3917 3918 MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist); 3919 3920 InstCombinerImpl IC(Worklist, Builder, F.hasMinSize(), AA, AC, TLI, TTI, DT, 3921 ORE, BFI, PSI, DL, LI); 3922 IC.MaxArraySizeForCombine = MaxArraySize; 3923 3924 if (!IC.run()) 3925 break; 3926 3927 MadeIRChange = true; 3928 } 3929 3930 return MadeIRChange; 3931 } 3932 3933 InstCombinePass::InstCombinePass() : MaxIterations(LimitMaxIterations) {} 3934 3935 InstCombinePass::InstCombinePass(unsigned MaxIterations) 3936 : MaxIterations(MaxIterations) {} 3937 3938 PreservedAnalyses InstCombinePass::run(Function &F, 3939 FunctionAnalysisManager &AM) { 3940 auto &AC = AM.getResult<AssumptionAnalysis>(F); 3941 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 3942 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 3943 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 3944 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 3945 3946 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 3947 3948 auto *AA = &AM.getResult<AAManager>(F); 3949 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 3950 ProfileSummaryInfo *PSI = 3951 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 3952 auto *BFI = (PSI && PSI->hasProfileSummary()) ? 3953 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr; 3954 3955 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE, 3956 BFI, PSI, MaxIterations, LI)) 3957 // No changes, all analyses are preserved. 3958 return PreservedAnalyses::all(); 3959 3960 // Mark all the analyses that instcombine updates as preserved. 3961 PreservedAnalyses PA; 3962 PA.preserveSet<CFGAnalyses>(); 3963 PA.preserve<AAManager>(); 3964 PA.preserve<BasicAA>(); 3965 PA.preserve<GlobalsAA>(); 3966 return PA; 3967 } 3968 3969 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const { 3970 AU.setPreservesCFG(); 3971 AU.addRequired<AAResultsWrapperPass>(); 3972 AU.addRequired<AssumptionCacheTracker>(); 3973 AU.addRequired<TargetLibraryInfoWrapperPass>(); 3974 AU.addRequired<TargetTransformInfoWrapperPass>(); 3975 AU.addRequired<DominatorTreeWrapperPass>(); 3976 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 3977 AU.addPreserved<DominatorTreeWrapperPass>(); 3978 AU.addPreserved<AAResultsWrapperPass>(); 3979 AU.addPreserved<BasicAAWrapperPass>(); 3980 AU.addPreserved<GlobalsAAWrapperPass>(); 3981 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 3982 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU); 3983 } 3984 3985 bool InstructionCombiningPass::runOnFunction(Function &F) { 3986 if (skipFunction(F)) 3987 return false; 3988 3989 // Required analyses. 3990 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 3991 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 3992 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 3993 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 3994 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3995 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 3996 3997 // Optional analyses. 3998 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 3999 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; 4000 ProfileSummaryInfo *PSI = 4001 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 4002 BlockFrequencyInfo *BFI = 4003 (PSI && PSI->hasProfileSummary()) ? 4004 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() : 4005 nullptr; 4006 4007 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE, 4008 BFI, PSI, MaxIterations, LI); 4009 } 4010 4011 char InstructionCombiningPass::ID = 0; 4012 4013 InstructionCombiningPass::InstructionCombiningPass() 4014 : FunctionPass(ID), MaxIterations(InstCombineDefaultMaxIterations) { 4015 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); 4016 } 4017 4018 InstructionCombiningPass::InstructionCombiningPass(unsigned MaxIterations) 4019 : FunctionPass(ID), MaxIterations(MaxIterations) { 4020 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); 4021 } 4022 4023 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", 4024 "Combine redundant instructions", false, false) 4025 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 4026 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 4027 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 4028 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 4029 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 4030 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 4031 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 4032 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass) 4033 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 4034 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine", 4035 "Combine redundant instructions", false, false) 4036 4037 // Initialization Routines 4038 void llvm::initializeInstCombine(PassRegistry &Registry) { 4039 initializeInstructionCombiningPassPass(Registry); 4040 } 4041 4042 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { 4043 initializeInstructionCombiningPassPass(*unwrap(R)); 4044 } 4045 4046 FunctionPass *llvm::createInstructionCombiningPass() { 4047 return new InstructionCombiningPass(); 4048 } 4049 4050 FunctionPass *llvm::createInstructionCombiningPass(unsigned MaxIterations) { 4051 return new InstructionCombiningPass(MaxIterations); 4052 } 4053 4054 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) { 4055 unwrap(PM)->add(createInstructionCombiningPass()); 4056 } 4057