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 if (NonConstBB != nullptr) { 1087 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator()); 1088 if (!BI || !BI->isUnconditional()) return nullptr; 1089 } 1090 1091 // Okay, we can do the transformation: create the new PHI node. 1092 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues()); 1093 InsertNewInstBefore(NewPN, *PN); 1094 NewPN->takeName(PN); 1095 1096 // If we are going to have to insert a new computation, do so right before the 1097 // predecessor's terminator. 1098 if (NonConstBB) 1099 Builder.SetInsertPoint(NonConstBB->getTerminator()); 1100 1101 // Next, add all of the operands to the PHI. 1102 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) { 1103 // We only currently try to fold the condition of a select when it is a phi, 1104 // not the true/false values. 1105 Value *TrueV = SI->getTrueValue(); 1106 Value *FalseV = SI->getFalseValue(); 1107 BasicBlock *PhiTransBB = PN->getParent(); 1108 for (unsigned i = 0; i != NumPHIValues; ++i) { 1109 BasicBlock *ThisBB = PN->getIncomingBlock(i); 1110 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB); 1111 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB); 1112 Value *InV = nullptr; 1113 // Beware of ConstantExpr: it may eventually evaluate to getNullValue, 1114 // even if currently isNullValue gives false. 1115 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)); 1116 // For vector constants, we cannot use isNullValue to fold into 1117 // FalseVInPred versus TrueVInPred. When we have individual nonzero 1118 // elements in the vector, we will incorrectly fold InC to 1119 // `TrueVInPred`. 1120 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC)) 1121 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred; 1122 else { 1123 // Generate the select in the same block as PN's current incoming block. 1124 // Note: ThisBB need not be the NonConstBB because vector constants 1125 // which are constants by definition are handled here. 1126 // FIXME: This can lead to an increase in IR generation because we might 1127 // generate selects for vector constant phi operand, that could not be 1128 // folded to TrueVInPred or FalseVInPred as done for ConstantInt. For 1129 // non-vector phis, this transformation was always profitable because 1130 // the select would be generated exactly once in the NonConstBB. 1131 Builder.SetInsertPoint(ThisBB->getTerminator()); 1132 InV = Builder.CreateSelect(PN->getIncomingValue(i), TrueVInPred, 1133 FalseVInPred, "phi.sel"); 1134 } 1135 NewPN->addIncoming(InV, ThisBB); 1136 } 1137 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) { 1138 Constant *C = cast<Constant>(I.getOperand(1)); 1139 for (unsigned i = 0; i != NumPHIValues; ++i) { 1140 Value *InV = nullptr; 1141 if (auto *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 1142 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C); 1143 else 1144 InV = Builder.CreateCmp(CI->getPredicate(), PN->getIncomingValue(i), 1145 C, "phi.cmp"); 1146 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1147 } 1148 } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) { 1149 for (unsigned i = 0; i != NumPHIValues; ++i) { 1150 Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i), 1151 Builder); 1152 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1153 } 1154 } else if (isa<FreezeInst>(&I)) { 1155 for (unsigned i = 0; i != NumPHIValues; ++i) { 1156 Value *InV; 1157 if (NonConstBB == PN->getIncomingBlock(i)) 1158 InV = Builder.CreateFreeze(PN->getIncomingValue(i), "phi.fr"); 1159 else 1160 InV = PN->getIncomingValue(i); 1161 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1162 } 1163 } else { 1164 CastInst *CI = cast<CastInst>(&I); 1165 Type *RetTy = CI->getType(); 1166 for (unsigned i = 0; i != NumPHIValues; ++i) { 1167 Value *InV; 1168 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 1169 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy); 1170 else 1171 InV = Builder.CreateCast(CI->getOpcode(), PN->getIncomingValue(i), 1172 I.getType(), "phi.cast"); 1173 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1174 } 1175 } 1176 1177 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) { 1178 Instruction *User = cast<Instruction>(*UI++); 1179 if (User == &I) continue; 1180 replaceInstUsesWith(*User, NewPN); 1181 eraseInstFromFunction(*User); 1182 } 1183 return replaceInstUsesWith(I, NewPN); 1184 } 1185 1186 Instruction *InstCombinerImpl::foldBinOpIntoSelectOrPhi(BinaryOperator &I) { 1187 if (!isa<Constant>(I.getOperand(1))) 1188 return nullptr; 1189 1190 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) { 1191 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel)) 1192 return NewSel; 1193 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) { 1194 if (Instruction *NewPhi = foldOpIntoPhi(I, PN)) 1195 return NewPhi; 1196 } 1197 return nullptr; 1198 } 1199 1200 /// Given a pointer type and a constant offset, determine whether or not there 1201 /// is a sequence of GEP indices into the pointed type that will land us at the 1202 /// specified offset. If so, fill them into NewIndices and return the resultant 1203 /// element type, otherwise return null. 1204 Type * 1205 InstCombinerImpl::FindElementAtOffset(PointerType *PtrTy, int64_t Offset, 1206 SmallVectorImpl<Value *> &NewIndices) { 1207 Type *Ty = PtrTy->getElementType(); 1208 if (!Ty->isSized()) 1209 return nullptr; 1210 1211 // Start with the index over the outer type. Note that the type size 1212 // might be zero (even if the offset isn't zero) if the indexed type 1213 // is something like [0 x {int, int}] 1214 Type *IndexTy = DL.getIndexType(PtrTy); 1215 int64_t FirstIdx = 0; 1216 if (int64_t TySize = DL.getTypeAllocSize(Ty)) { 1217 FirstIdx = Offset/TySize; 1218 Offset -= FirstIdx*TySize; 1219 1220 // Handle hosts where % returns negative instead of values [0..TySize). 1221 if (Offset < 0) { 1222 --FirstIdx; 1223 Offset += TySize; 1224 assert(Offset >= 0); 1225 } 1226 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset"); 1227 } 1228 1229 NewIndices.push_back(ConstantInt::get(IndexTy, FirstIdx)); 1230 1231 // Index into the types. If we fail, set OrigBase to null. 1232 while (Offset) { 1233 // Indexing into tail padding between struct/array elements. 1234 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty)) 1235 return nullptr; 1236 1237 if (StructType *STy = dyn_cast<StructType>(Ty)) { 1238 const StructLayout *SL = DL.getStructLayout(STy); 1239 assert(Offset < (int64_t)SL->getSizeInBytes() && 1240 "Offset must stay within the indexed type"); 1241 1242 unsigned Elt = SL->getElementContainingOffset(Offset); 1243 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1244 Elt)); 1245 1246 Offset -= SL->getElementOffset(Elt); 1247 Ty = STy->getElementType(Elt); 1248 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 1249 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType()); 1250 assert(EltSize && "Cannot index into a zero-sized array"); 1251 NewIndices.push_back(ConstantInt::get(IndexTy,Offset/EltSize)); 1252 Offset %= EltSize; 1253 Ty = AT->getElementType(); 1254 } else { 1255 // Otherwise, we can't index into the middle of this atomic type, bail. 1256 return nullptr; 1257 } 1258 } 1259 1260 return Ty; 1261 } 1262 1263 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) { 1264 // If this GEP has only 0 indices, it is the same pointer as 1265 // Src. If Src is not a trivial GEP too, don't combine 1266 // the indices. 1267 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() && 1268 !Src.hasOneUse()) 1269 return false; 1270 return true; 1271 } 1272 1273 /// Return a value X such that Val = X * Scale, or null if none. 1274 /// If the multiplication is known not to overflow, then NoSignedWrap is set. 1275 Value *InstCombinerImpl::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) { 1276 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!"); 1277 assert(cast<IntegerType>(Val->getType())->getBitWidth() == 1278 Scale.getBitWidth() && "Scale not compatible with value!"); 1279 1280 // If Val is zero or Scale is one then Val = Val * Scale. 1281 if (match(Val, m_Zero()) || Scale == 1) { 1282 NoSignedWrap = true; 1283 return Val; 1284 } 1285 1286 // If Scale is zero then it does not divide Val. 1287 if (Scale.isMinValue()) 1288 return nullptr; 1289 1290 // Look through chains of multiplications, searching for a constant that is 1291 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4 1292 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by 1293 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore 1294 // down from Val: 1295 // 1296 // Val = M1 * X || Analysis starts here and works down 1297 // M1 = M2 * Y || Doesn't descend into terms with more 1298 // M2 = Z * 4 \/ than one use 1299 // 1300 // Then to modify a term at the bottom: 1301 // 1302 // Val = M1 * X 1303 // M1 = Z * Y || Replaced M2 with Z 1304 // 1305 // Then to work back up correcting nsw flags. 1306 1307 // Op - the term we are currently analyzing. Starts at Val then drills down. 1308 // Replaced with its descaled value before exiting from the drill down loop. 1309 Value *Op = Val; 1310 1311 // Parent - initially null, but after drilling down notes where Op came from. 1312 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the 1313 // 0'th operand of Val. 1314 std::pair<Instruction *, unsigned> Parent; 1315 1316 // Set if the transform requires a descaling at deeper levels that doesn't 1317 // overflow. 1318 bool RequireNoSignedWrap = false; 1319 1320 // Log base 2 of the scale. Negative if not a power of 2. 1321 int32_t logScale = Scale.exactLogBase2(); 1322 1323 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down 1324 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 1325 // If Op is a constant divisible by Scale then descale to the quotient. 1326 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth. 1327 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder); 1328 if (!Remainder.isMinValue()) 1329 // Not divisible by Scale. 1330 return nullptr; 1331 // Replace with the quotient in the parent. 1332 Op = ConstantInt::get(CI->getType(), Quotient); 1333 NoSignedWrap = true; 1334 break; 1335 } 1336 1337 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) { 1338 if (BO->getOpcode() == Instruction::Mul) { 1339 // Multiplication. 1340 NoSignedWrap = BO->hasNoSignedWrap(); 1341 if (RequireNoSignedWrap && !NoSignedWrap) 1342 return nullptr; 1343 1344 // There are three cases for multiplication: multiplication by exactly 1345 // the scale, multiplication by a constant different to the scale, and 1346 // multiplication by something else. 1347 Value *LHS = BO->getOperand(0); 1348 Value *RHS = BO->getOperand(1); 1349 1350 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 1351 // Multiplication by a constant. 1352 if (CI->getValue() == Scale) { 1353 // Multiplication by exactly the scale, replace the multiplication 1354 // by its left-hand side in the parent. 1355 Op = LHS; 1356 break; 1357 } 1358 1359 // Otherwise drill down into the constant. 1360 if (!Op->hasOneUse()) 1361 return nullptr; 1362 1363 Parent = std::make_pair(BO, 1); 1364 continue; 1365 } 1366 1367 // Multiplication by something else. Drill down into the left-hand side 1368 // since that's where the reassociate pass puts the good stuff. 1369 if (!Op->hasOneUse()) 1370 return nullptr; 1371 1372 Parent = std::make_pair(BO, 0); 1373 continue; 1374 } 1375 1376 if (logScale > 0 && BO->getOpcode() == Instruction::Shl && 1377 isa<ConstantInt>(BO->getOperand(1))) { 1378 // Multiplication by a power of 2. 1379 NoSignedWrap = BO->hasNoSignedWrap(); 1380 if (RequireNoSignedWrap && !NoSignedWrap) 1381 return nullptr; 1382 1383 Value *LHS = BO->getOperand(0); 1384 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))-> 1385 getLimitedValue(Scale.getBitWidth()); 1386 // Op = LHS << Amt. 1387 1388 if (Amt == logScale) { 1389 // Multiplication by exactly the scale, replace the multiplication 1390 // by its left-hand side in the parent. 1391 Op = LHS; 1392 break; 1393 } 1394 if (Amt < logScale || !Op->hasOneUse()) 1395 return nullptr; 1396 1397 // Multiplication by more than the scale. Reduce the multiplying amount 1398 // by the scale in the parent. 1399 Parent = std::make_pair(BO, 1); 1400 Op = ConstantInt::get(BO->getType(), Amt - logScale); 1401 break; 1402 } 1403 } 1404 1405 if (!Op->hasOneUse()) 1406 return nullptr; 1407 1408 if (CastInst *Cast = dyn_cast<CastInst>(Op)) { 1409 if (Cast->getOpcode() == Instruction::SExt) { 1410 // Op is sign-extended from a smaller type, descale in the smaller type. 1411 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 1412 APInt SmallScale = Scale.trunc(SmallSize); 1413 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to 1414 // descale Op as (sext Y) * Scale. In order to have 1415 // sext (Y * SmallScale) = (sext Y) * Scale 1416 // some conditions need to hold however: SmallScale must sign-extend to 1417 // Scale and the multiplication Y * SmallScale should not overflow. 1418 if (SmallScale.sext(Scale.getBitWidth()) != Scale) 1419 // SmallScale does not sign-extend to Scale. 1420 return nullptr; 1421 assert(SmallScale.exactLogBase2() == logScale); 1422 // Require that Y * SmallScale must not overflow. 1423 RequireNoSignedWrap = true; 1424 1425 // Drill down through the cast. 1426 Parent = std::make_pair(Cast, 0); 1427 Scale = SmallScale; 1428 continue; 1429 } 1430 1431 if (Cast->getOpcode() == Instruction::Trunc) { 1432 // Op is truncated from a larger type, descale in the larger type. 1433 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then 1434 // trunc (Y * sext Scale) = (trunc Y) * Scale 1435 // always holds. However (trunc Y) * Scale may overflow even if 1436 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared 1437 // from this point up in the expression (see later). 1438 if (RequireNoSignedWrap) 1439 return nullptr; 1440 1441 // Drill down through the cast. 1442 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 1443 Parent = std::make_pair(Cast, 0); 1444 Scale = Scale.sext(LargeSize); 1445 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits()) 1446 logScale = -1; 1447 assert(Scale.exactLogBase2() == logScale); 1448 continue; 1449 } 1450 } 1451 1452 // Unsupported expression, bail out. 1453 return nullptr; 1454 } 1455 1456 // If Op is zero then Val = Op * Scale. 1457 if (match(Op, m_Zero())) { 1458 NoSignedWrap = true; 1459 return Op; 1460 } 1461 1462 // We know that we can successfully descale, so from here on we can safely 1463 // modify the IR. Op holds the descaled version of the deepest term in the 1464 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known 1465 // not to overflow. 1466 1467 if (!Parent.first) 1468 // The expression only had one term. 1469 return Op; 1470 1471 // Rewrite the parent using the descaled version of its operand. 1472 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!"); 1473 assert(Op != Parent.first->getOperand(Parent.second) && 1474 "Descaling was a no-op?"); 1475 replaceOperand(*Parent.first, Parent.second, Op); 1476 Worklist.push(Parent.first); 1477 1478 // Now work back up the expression correcting nsw flags. The logic is based 1479 // on the following observation: if X * Y is known not to overflow as a signed 1480 // multiplication, and Y is replaced by a value Z with smaller absolute value, 1481 // then X * Z will not overflow as a signed multiplication either. As we work 1482 // our way up, having NoSignedWrap 'true' means that the descaled value at the 1483 // current level has strictly smaller absolute value than the original. 1484 Instruction *Ancestor = Parent.first; 1485 do { 1486 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) { 1487 // If the multiplication wasn't nsw then we can't say anything about the 1488 // value of the descaled multiplication, and we have to clear nsw flags 1489 // from this point on up. 1490 bool OpNoSignedWrap = BO->hasNoSignedWrap(); 1491 NoSignedWrap &= OpNoSignedWrap; 1492 if (NoSignedWrap != OpNoSignedWrap) { 1493 BO->setHasNoSignedWrap(NoSignedWrap); 1494 Worklist.push(Ancestor); 1495 } 1496 } else if (Ancestor->getOpcode() == Instruction::Trunc) { 1497 // The fact that the descaled input to the trunc has smaller absolute 1498 // value than the original input doesn't tell us anything useful about 1499 // the absolute values of the truncations. 1500 NoSignedWrap = false; 1501 } 1502 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) && 1503 "Failed to keep proper track of nsw flags while drilling down?"); 1504 1505 if (Ancestor == Val) 1506 // Got to the top, all done! 1507 return Val; 1508 1509 // Move up one level in the expression. 1510 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!"); 1511 Ancestor = Ancestor->user_back(); 1512 } while (true); 1513 } 1514 1515 Instruction *InstCombinerImpl::foldVectorBinop(BinaryOperator &Inst) { 1516 // FIXME: some of this is likely fine for scalable vectors 1517 if (!isa<FixedVectorType>(Inst.getType())) 1518 return nullptr; 1519 1520 BinaryOperator::BinaryOps Opcode = Inst.getOpcode(); 1521 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1); 1522 assert(cast<VectorType>(LHS->getType())->getElementCount() == 1523 cast<VectorType>(Inst.getType())->getElementCount()); 1524 assert(cast<VectorType>(RHS->getType())->getElementCount() == 1525 cast<VectorType>(Inst.getType())->getElementCount()); 1526 1527 // If both operands of the binop are vector concatenations, then perform the 1528 // narrow binop on each pair of the source operands followed by concatenation 1529 // of the results. 1530 Value *L0, *L1, *R0, *R1; 1531 ArrayRef<int> Mask; 1532 if (match(LHS, m_Shuffle(m_Value(L0), m_Value(L1), m_Mask(Mask))) && 1533 match(RHS, m_Shuffle(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) && 1534 LHS->hasOneUse() && RHS->hasOneUse() && 1535 cast<ShuffleVectorInst>(LHS)->isConcat() && 1536 cast<ShuffleVectorInst>(RHS)->isConcat()) { 1537 // This transform does not have the speculative execution constraint as 1538 // below because the shuffle is a concatenation. The new binops are 1539 // operating on exactly the same elements as the existing binop. 1540 // TODO: We could ease the mask requirement to allow different undef lanes, 1541 // but that requires an analysis of the binop-with-undef output value. 1542 Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0); 1543 if (auto *BO = dyn_cast<BinaryOperator>(NewBO0)) 1544 BO->copyIRFlags(&Inst); 1545 Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1); 1546 if (auto *BO = dyn_cast<BinaryOperator>(NewBO1)) 1547 BO->copyIRFlags(&Inst); 1548 return new ShuffleVectorInst(NewBO0, NewBO1, Mask); 1549 } 1550 1551 // It may not be safe to reorder shuffles and things like div, urem, etc. 1552 // because we may trap when executing those ops on unknown vector elements. 1553 // See PR20059. 1554 if (!isSafeToSpeculativelyExecute(&Inst)) 1555 return nullptr; 1556 1557 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) { 1558 Value *XY = Builder.CreateBinOp(Opcode, X, Y); 1559 if (auto *BO = dyn_cast<BinaryOperator>(XY)) 1560 BO->copyIRFlags(&Inst); 1561 return new ShuffleVectorInst(XY, UndefValue::get(XY->getType()), M); 1562 }; 1563 1564 // If both arguments of the binary operation are shuffles that use the same 1565 // mask and shuffle within a single vector, move the shuffle after the binop. 1566 Value *V1, *V2; 1567 if (match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(Mask))) && 1568 match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(Mask))) && 1569 V1->getType() == V2->getType() && 1570 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) { 1571 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask) 1572 return createBinOpShuffle(V1, V2, Mask); 1573 } 1574 1575 // If both arguments of a commutative binop are select-shuffles that use the 1576 // same mask with commuted operands, the shuffles are unnecessary. 1577 if (Inst.isCommutative() && 1578 match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) && 1579 match(RHS, 1580 m_Shuffle(m_Specific(V2), m_Specific(V1), m_SpecificMask(Mask)))) { 1581 auto *LShuf = cast<ShuffleVectorInst>(LHS); 1582 auto *RShuf = cast<ShuffleVectorInst>(RHS); 1583 // TODO: Allow shuffles that contain undefs in the mask? 1584 // That is legal, but it reduces undef knowledge. 1585 // TODO: Allow arbitrary shuffles by shuffling after binop? 1586 // That might be legal, but we have to deal with poison. 1587 if (LShuf->isSelect() && 1588 !is_contained(LShuf->getShuffleMask(), UndefMaskElem) && 1589 RShuf->isSelect() && 1590 !is_contained(RShuf->getShuffleMask(), UndefMaskElem)) { 1591 // Example: 1592 // LHS = shuffle V1, V2, <0, 5, 6, 3> 1593 // RHS = shuffle V2, V1, <0, 5, 6, 3> 1594 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2 1595 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2); 1596 NewBO->copyIRFlags(&Inst); 1597 return NewBO; 1598 } 1599 } 1600 1601 // If one argument is a shuffle within one vector and the other is a constant, 1602 // try moving the shuffle after the binary operation. This canonicalization 1603 // intends to move shuffles closer to other shuffles and binops closer to 1604 // other binops, so they can be folded. It may also enable demanded elements 1605 // transforms. 1606 unsigned NumElts = cast<FixedVectorType>(Inst.getType())->getNumElements(); 1607 Constant *C; 1608 if (match(&Inst, 1609 m_c_BinOp(m_OneUse(m_Shuffle(m_Value(V1), m_Undef(), m_Mask(Mask))), 1610 m_Constant(C))) && !isa<ConstantExpr>(C) && 1611 cast<FixedVectorType>(V1->getType())->getNumElements() <= NumElts) { 1612 assert(Inst.getType()->getScalarType() == V1->getType()->getScalarType() && 1613 "Shuffle should not change scalar type"); 1614 1615 // Find constant NewC that has property: 1616 // shuffle(NewC, ShMask) = C 1617 // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>) 1618 // reorder is not possible. A 1-to-1 mapping is not required. Example: 1619 // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef> 1620 bool ConstOp1 = isa<Constant>(RHS); 1621 ArrayRef<int> ShMask = Mask; 1622 unsigned SrcVecNumElts = 1623 cast<FixedVectorType>(V1->getType())->getNumElements(); 1624 UndefValue *UndefScalar = UndefValue::get(C->getType()->getScalarType()); 1625 SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, UndefScalar); 1626 bool MayChange = true; 1627 for (unsigned I = 0; I < NumElts; ++I) { 1628 Constant *CElt = C->getAggregateElement(I); 1629 if (ShMask[I] >= 0) { 1630 assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle"); 1631 Constant *NewCElt = NewVecC[ShMask[I]]; 1632 // Bail out if: 1633 // 1. The constant vector contains a constant expression. 1634 // 2. The shuffle needs an element of the constant vector that can't 1635 // be mapped to a new constant vector. 1636 // 3. This is a widening shuffle that copies elements of V1 into the 1637 // extended elements (extending with undef is allowed). 1638 if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) || 1639 I >= SrcVecNumElts) { 1640 MayChange = false; 1641 break; 1642 } 1643 NewVecC[ShMask[I]] = CElt; 1644 } 1645 // If this is a widening shuffle, we must be able to extend with undef 1646 // elements. If the original binop does not produce an undef in the high 1647 // lanes, then this transform is not safe. 1648 // Similarly for undef lanes due to the shuffle mask, we can only 1649 // transform binops that preserve undef. 1650 // TODO: We could shuffle those non-undef constant values into the 1651 // result by using a constant vector (rather than an undef vector) 1652 // as operand 1 of the new binop, but that might be too aggressive 1653 // for target-independent shuffle creation. 1654 if (I >= SrcVecNumElts || ShMask[I] < 0) { 1655 Constant *MaybeUndef = 1656 ConstOp1 ? ConstantExpr::get(Opcode, UndefScalar, CElt) 1657 : ConstantExpr::get(Opcode, CElt, UndefScalar); 1658 if (!isa<UndefValue>(MaybeUndef)) { 1659 MayChange = false; 1660 break; 1661 } 1662 } 1663 } 1664 if (MayChange) { 1665 Constant *NewC = ConstantVector::get(NewVecC); 1666 // It may not be safe to execute a binop on a vector with undef elements 1667 // because the entire instruction can be folded to undef or create poison 1668 // that did not exist in the original code. 1669 if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1)) 1670 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1); 1671 1672 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask) 1673 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask) 1674 Value *NewLHS = ConstOp1 ? V1 : NewC; 1675 Value *NewRHS = ConstOp1 ? NewC : V1; 1676 return createBinOpShuffle(NewLHS, NewRHS, Mask); 1677 } 1678 } 1679 1680 // Try to reassociate to sink a splat shuffle after a binary operation. 1681 if (Inst.isAssociative() && Inst.isCommutative()) { 1682 // Canonicalize shuffle operand as LHS. 1683 if (isa<ShuffleVectorInst>(RHS)) 1684 std::swap(LHS, RHS); 1685 1686 Value *X; 1687 ArrayRef<int> MaskC; 1688 int SplatIndex; 1689 BinaryOperator *BO; 1690 if (!match(LHS, 1691 m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) || 1692 !match(MaskC, m_SplatOrUndefMask(SplatIndex)) || 1693 X->getType() != Inst.getType() || !match(RHS, m_OneUse(m_BinOp(BO))) || 1694 BO->getOpcode() != Opcode) 1695 return nullptr; 1696 1697 // FIXME: This may not be safe if the analysis allows undef elements. By 1698 // moving 'Y' before the splat shuffle, we are implicitly assuming 1699 // that it is not undef/poison at the splat index. 1700 Value *Y, *OtherOp; 1701 if (isSplatValue(BO->getOperand(0), SplatIndex)) { 1702 Y = BO->getOperand(0); 1703 OtherOp = BO->getOperand(1); 1704 } else if (isSplatValue(BO->getOperand(1), SplatIndex)) { 1705 Y = BO->getOperand(1); 1706 OtherOp = BO->getOperand(0); 1707 } else { 1708 return nullptr; 1709 } 1710 1711 // X and Y are splatted values, so perform the binary operation on those 1712 // values followed by a splat followed by the 2nd binary operation: 1713 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp 1714 Value *NewBO = Builder.CreateBinOp(Opcode, X, Y); 1715 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex); 1716 Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask); 1717 Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp); 1718 1719 // Intersect FMF on both new binops. Other (poison-generating) flags are 1720 // dropped to be safe. 1721 if (isa<FPMathOperator>(R)) { 1722 R->copyFastMathFlags(&Inst); 1723 R->andIRFlags(BO); 1724 } 1725 if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO)) 1726 NewInstBO->copyIRFlags(R); 1727 return R; 1728 } 1729 1730 return nullptr; 1731 } 1732 1733 /// Try to narrow the width of a binop if at least 1 operand is an extend of 1734 /// of a value. This requires a potentially expensive known bits check to make 1735 /// sure the narrow op does not overflow. 1736 Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) { 1737 // We need at least one extended operand. 1738 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1); 1739 1740 // If this is a sub, we swap the operands since we always want an extension 1741 // on the RHS. The LHS can be an extension or a constant. 1742 if (BO.getOpcode() == Instruction::Sub) 1743 std::swap(Op0, Op1); 1744 1745 Value *X; 1746 bool IsSext = match(Op0, m_SExt(m_Value(X))); 1747 if (!IsSext && !match(Op0, m_ZExt(m_Value(X)))) 1748 return nullptr; 1749 1750 // If both operands are the same extension from the same source type and we 1751 // can eliminate at least one (hasOneUse), this might work. 1752 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt; 1753 Value *Y; 1754 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() && 1755 cast<Operator>(Op1)->getOpcode() == CastOpc && 1756 (Op0->hasOneUse() || Op1->hasOneUse()))) { 1757 // If that did not match, see if we have a suitable constant operand. 1758 // Truncating and extending must produce the same constant. 1759 Constant *WideC; 1760 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC))) 1761 return nullptr; 1762 Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType()); 1763 if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC) 1764 return nullptr; 1765 Y = NarrowC; 1766 } 1767 1768 // Swap back now that we found our operands. 1769 if (BO.getOpcode() == Instruction::Sub) 1770 std::swap(X, Y); 1771 1772 // Both operands have narrow versions. Last step: the math must not overflow 1773 // in the narrow width. 1774 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext)) 1775 return nullptr; 1776 1777 // bo (ext X), (ext Y) --> ext (bo X, Y) 1778 // bo (ext X), C --> ext (bo X, C') 1779 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow"); 1780 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) { 1781 if (IsSext) 1782 NewBinOp->setHasNoSignedWrap(); 1783 else 1784 NewBinOp->setHasNoUnsignedWrap(); 1785 } 1786 return CastInst::Create(CastOpc, NarrowBO, BO.getType()); 1787 } 1788 1789 static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2) { 1790 // At least one GEP must be inbounds. 1791 if (!GEP1.isInBounds() && !GEP2.isInBounds()) 1792 return false; 1793 1794 return (GEP1.isInBounds() || GEP1.hasAllZeroIndices()) && 1795 (GEP2.isInBounds() || GEP2.hasAllZeroIndices()); 1796 } 1797 1798 /// Thread a GEP operation with constant indices through the constant true/false 1799 /// arms of a select. 1800 static Instruction *foldSelectGEP(GetElementPtrInst &GEP, 1801 InstCombiner::BuilderTy &Builder) { 1802 if (!GEP.hasAllConstantIndices()) 1803 return nullptr; 1804 1805 Instruction *Sel; 1806 Value *Cond; 1807 Constant *TrueC, *FalseC; 1808 if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) || 1809 !match(Sel, 1810 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC)))) 1811 return nullptr; 1812 1813 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC' 1814 // Propagate 'inbounds' and metadata from existing instructions. 1815 // Note: using IRBuilder to create the constants for efficiency. 1816 SmallVector<Value *, 4> IndexC(GEP.idx_begin(), GEP.idx_end()); 1817 bool IsInBounds = GEP.isInBounds(); 1818 Value *NewTrueC = IsInBounds ? Builder.CreateInBoundsGEP(TrueC, IndexC) 1819 : Builder.CreateGEP(TrueC, IndexC); 1820 Value *NewFalseC = IsInBounds ? Builder.CreateInBoundsGEP(FalseC, IndexC) 1821 : Builder.CreateGEP(FalseC, IndexC); 1822 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel); 1823 } 1824 1825 Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) { 1826 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end()); 1827 Type *GEPType = GEP.getType(); 1828 Type *GEPEltType = GEP.getSourceElementType(); 1829 bool IsGEPSrcEleScalable = isa<ScalableVectorType>(GEPEltType); 1830 if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP))) 1831 return replaceInstUsesWith(GEP, V); 1832 1833 // For vector geps, use the generic demanded vector support. 1834 // Skip if GEP return type is scalable. The number of elements is unknown at 1835 // compile-time. 1836 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) { 1837 auto VWidth = GEPFVTy->getNumElements(); 1838 APInt UndefElts(VWidth, 0); 1839 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1840 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask, 1841 UndefElts)) { 1842 if (V != &GEP) 1843 return replaceInstUsesWith(GEP, V); 1844 return &GEP; 1845 } 1846 1847 // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if 1848 // possible (decide on canonical form for pointer broadcast), 3) exploit 1849 // undef elements to decrease demanded bits 1850 } 1851 1852 Value *PtrOp = GEP.getOperand(0); 1853 1854 // Eliminate unneeded casts for indices, and replace indices which displace 1855 // by multiples of a zero size type with zero. 1856 bool MadeChange = false; 1857 1858 // Index width may not be the same width as pointer width. 1859 // Data layout chooses the right type based on supported integer types. 1860 Type *NewScalarIndexTy = 1861 DL.getIndexType(GEP.getPointerOperandType()->getScalarType()); 1862 1863 gep_type_iterator GTI = gep_type_begin(GEP); 1864 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E; 1865 ++I, ++GTI) { 1866 // Skip indices into struct types. 1867 if (GTI.isStruct()) 1868 continue; 1869 1870 Type *IndexTy = (*I)->getType(); 1871 Type *NewIndexType = 1872 IndexTy->isVectorTy() 1873 ? VectorType::get(NewScalarIndexTy, 1874 cast<VectorType>(IndexTy)->getElementCount()) 1875 : NewScalarIndexTy; 1876 1877 // If the element type has zero size then any index over it is equivalent 1878 // to an index of zero, so replace it with zero if it is not zero already. 1879 Type *EltTy = GTI.getIndexedType(); 1880 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero()) 1881 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) { 1882 *I = Constant::getNullValue(NewIndexType); 1883 MadeChange = true; 1884 } 1885 1886 if (IndexTy != NewIndexType) { 1887 // If we are using a wider index than needed for this platform, shrink 1888 // it to what we need. If narrower, sign-extend it to what we need. 1889 // This explicit cast can make subsequent optimizations more obvious. 1890 *I = Builder.CreateIntCast(*I, NewIndexType, true); 1891 MadeChange = true; 1892 } 1893 } 1894 if (MadeChange) 1895 return &GEP; 1896 1897 // Check to see if the inputs to the PHI node are getelementptr instructions. 1898 if (auto *PN = dyn_cast<PHINode>(PtrOp)) { 1899 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0)); 1900 if (!Op1) 1901 return nullptr; 1902 1903 // Don't fold a GEP into itself through a PHI node. This can only happen 1904 // through the back-edge of a loop. Folding a GEP into itself means that 1905 // the value of the previous iteration needs to be stored in the meantime, 1906 // thus requiring an additional register variable to be live, but not 1907 // actually achieving anything (the GEP still needs to be executed once per 1908 // loop iteration). 1909 if (Op1 == &GEP) 1910 return nullptr; 1911 1912 int DI = -1; 1913 1914 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) { 1915 auto *Op2 = dyn_cast<GetElementPtrInst>(*I); 1916 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands()) 1917 return nullptr; 1918 1919 // As for Op1 above, don't try to fold a GEP into itself. 1920 if (Op2 == &GEP) 1921 return nullptr; 1922 1923 // Keep track of the type as we walk the GEP. 1924 Type *CurTy = nullptr; 1925 1926 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) { 1927 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType()) 1928 return nullptr; 1929 1930 if (Op1->getOperand(J) != Op2->getOperand(J)) { 1931 if (DI == -1) { 1932 // We have not seen any differences yet in the GEPs feeding the 1933 // PHI yet, so we record this one if it is allowed to be a 1934 // variable. 1935 1936 // The first two arguments can vary for any GEP, the rest have to be 1937 // static for struct slots 1938 if (J > 1) { 1939 assert(CurTy && "No current type?"); 1940 if (CurTy->isStructTy()) 1941 return nullptr; 1942 } 1943 1944 DI = J; 1945 } else { 1946 // The GEP is different by more than one input. While this could be 1947 // extended to support GEPs that vary by more than one variable it 1948 // doesn't make sense since it greatly increases the complexity and 1949 // would result in an R+R+R addressing mode which no backend 1950 // directly supports and would need to be broken into several 1951 // simpler instructions anyway. 1952 return nullptr; 1953 } 1954 } 1955 1956 // Sink down a layer of the type for the next iteration. 1957 if (J > 0) { 1958 if (J == 1) { 1959 CurTy = Op1->getSourceElementType(); 1960 } else { 1961 CurTy = 1962 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J)); 1963 } 1964 } 1965 } 1966 } 1967 1968 // If not all GEPs are identical we'll have to create a new PHI node. 1969 // Check that the old PHI node has only one use so that it will get 1970 // removed. 1971 if (DI != -1 && !PN->hasOneUse()) 1972 return nullptr; 1973 1974 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone()); 1975 if (DI == -1) { 1976 // All the GEPs feeding the PHI are identical. Clone one down into our 1977 // BB so that it can be merged with the current GEP. 1978 } else { 1979 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP 1980 // into the current block so it can be merged, and create a new PHI to 1981 // set that index. 1982 PHINode *NewPN; 1983 { 1984 IRBuilderBase::InsertPointGuard Guard(Builder); 1985 Builder.SetInsertPoint(PN); 1986 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(), 1987 PN->getNumOperands()); 1988 } 1989 1990 for (auto &I : PN->operands()) 1991 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI), 1992 PN->getIncomingBlock(I)); 1993 1994 NewGEP->setOperand(DI, NewPN); 1995 } 1996 1997 GEP.getParent()->getInstList().insert( 1998 GEP.getParent()->getFirstInsertionPt(), NewGEP); 1999 replaceOperand(GEP, 0, NewGEP); 2000 PtrOp = NewGEP; 2001 } 2002 2003 // Combine Indices - If the source pointer to this getelementptr instruction 2004 // is a getelementptr instruction, combine the indices of the two 2005 // getelementptr instructions into a single instruction. 2006 if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) { 2007 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src)) 2008 return nullptr; 2009 2010 // Try to reassociate loop invariant GEP chains to enable LICM. 2011 if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 && 2012 Src->hasOneUse()) { 2013 if (Loop *L = LI->getLoopFor(GEP.getParent())) { 2014 Value *GO1 = GEP.getOperand(1); 2015 Value *SO1 = Src->getOperand(1); 2016 // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is 2017 // invariant: this breaks the dependence between GEPs and allows LICM 2018 // to hoist the invariant part out of the loop. 2019 if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) { 2020 // We have to be careful here. 2021 // We have something like: 2022 // %src = getelementptr <ty>, <ty>* %base, <ty> %idx 2023 // %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2 2024 // If we just swap idx & idx2 then we could inadvertantly 2025 // change %src from a vector to a scalar, or vice versa. 2026 // Cases: 2027 // 1) %base a scalar & idx a scalar & idx2 a vector 2028 // => Swapping idx & idx2 turns %src into a vector type. 2029 // 2) %base a scalar & idx a vector & idx2 a scalar 2030 // => Swapping idx & idx2 turns %src in a scalar type 2031 // 3) %base, %idx, and %idx2 are scalars 2032 // => %src & %gep are scalars 2033 // => swapping idx & idx2 is safe 2034 // 4) %base a vector 2035 // => %src is a vector 2036 // => swapping idx & idx2 is safe. 2037 auto *SO0 = Src->getOperand(0); 2038 auto *SO0Ty = SO0->getType(); 2039 if (!isa<VectorType>(GEPType) || // case 3 2040 isa<VectorType>(SO0Ty)) { // case 4 2041 Src->setOperand(1, GO1); 2042 GEP.setOperand(1, SO1); 2043 return &GEP; 2044 } else { 2045 // Case 1 or 2 2046 // -- have to recreate %src & %gep 2047 // put NewSrc at same location as %src 2048 Builder.SetInsertPoint(cast<Instruction>(PtrOp)); 2049 auto *NewSrc = cast<GetElementPtrInst>( 2050 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName())); 2051 NewSrc->setIsInBounds(Src->isInBounds()); 2052 auto *NewGEP = GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1}); 2053 NewGEP->setIsInBounds(GEP.isInBounds()); 2054 return NewGEP; 2055 } 2056 } 2057 } 2058 } 2059 2060 // Note that if our source is a gep chain itself then we wait for that 2061 // chain to be resolved before we perform this transformation. This 2062 // avoids us creating a TON of code in some cases. 2063 if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0))) 2064 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) 2065 return nullptr; // Wait until our source is folded to completion. 2066 2067 SmallVector<Value*, 8> Indices; 2068 2069 // Find out whether the last index in the source GEP is a sequential idx. 2070 bool EndsWithSequential = false; 2071 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 2072 I != E; ++I) 2073 EndsWithSequential = I.isSequential(); 2074 2075 // Can we combine the two pointer arithmetics offsets? 2076 if (EndsWithSequential) { 2077 // Replace: gep (gep %P, long B), long A, ... 2078 // With: T = long A+B; gep %P, T, ... 2079 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 2080 Value *GO1 = GEP.getOperand(1); 2081 2082 // If they aren't the same type, then the input hasn't been processed 2083 // by the loop above yet (which canonicalizes sequential index types to 2084 // intptr_t). Just avoid transforming this until the input has been 2085 // normalized. 2086 if (SO1->getType() != GO1->getType()) 2087 return nullptr; 2088 2089 Value *Sum = 2090 SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP)); 2091 // Only do the combine when we are sure the cost after the 2092 // merge is never more than that before the merge. 2093 if (Sum == nullptr) 2094 return nullptr; 2095 2096 // Update the GEP in place if possible. 2097 if (Src->getNumOperands() == 2) { 2098 GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))); 2099 replaceOperand(GEP, 0, Src->getOperand(0)); 2100 replaceOperand(GEP, 1, Sum); 2101 return &GEP; 2102 } 2103 Indices.append(Src->op_begin()+1, Src->op_end()-1); 2104 Indices.push_back(Sum); 2105 Indices.append(GEP.op_begin()+2, GEP.op_end()); 2106 } else if (isa<Constant>(*GEP.idx_begin()) && 2107 cast<Constant>(*GEP.idx_begin())->isNullValue() && 2108 Src->getNumOperands() != 1) { 2109 // Otherwise we can do the fold if the first index of the GEP is a zero 2110 Indices.append(Src->op_begin()+1, Src->op_end()); 2111 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 2112 } 2113 2114 if (!Indices.empty()) 2115 return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)) 2116 ? GetElementPtrInst::CreateInBounds( 2117 Src->getSourceElementType(), Src->getOperand(0), Indices, 2118 GEP.getName()) 2119 : GetElementPtrInst::Create(Src->getSourceElementType(), 2120 Src->getOperand(0), Indices, 2121 GEP.getName()); 2122 } 2123 2124 // Skip if GEP source element type is scalable. The type alloc size is unknown 2125 // at compile-time. 2126 if (GEP.getNumIndices() == 1 && !IsGEPSrcEleScalable) { 2127 unsigned AS = GEP.getPointerAddressSpace(); 2128 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() == 2129 DL.getIndexSizeInBits(AS)) { 2130 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedSize(); 2131 2132 bool Matched = false; 2133 uint64_t C; 2134 Value *V = nullptr; 2135 if (TyAllocSize == 1) { 2136 V = GEP.getOperand(1); 2137 Matched = true; 2138 } else if (match(GEP.getOperand(1), 2139 m_AShr(m_Value(V), m_ConstantInt(C)))) { 2140 if (TyAllocSize == 1ULL << C) 2141 Matched = true; 2142 } else if (match(GEP.getOperand(1), 2143 m_SDiv(m_Value(V), m_ConstantInt(C)))) { 2144 if (TyAllocSize == C) 2145 Matched = true; 2146 } 2147 2148 if (Matched) { 2149 // Canonicalize (gep i8* X, -(ptrtoint Y)) 2150 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y))) 2151 // The GEP pattern is emitted by the SCEV expander for certain kinds of 2152 // pointer arithmetic. 2153 if (match(V, m_Neg(m_PtrToInt(m_Value())))) { 2154 Operator *Index = cast<Operator>(V); 2155 Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType()); 2156 Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1)); 2157 return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType); 2158 } 2159 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) 2160 // to (bitcast Y) 2161 Value *Y; 2162 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)), 2163 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) 2164 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType); 2165 } 2166 } 2167 } 2168 2169 // We do not handle pointer-vector geps here. 2170 if (GEPType->isVectorTy()) 2171 return nullptr; 2172 2173 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). 2174 Value *StrippedPtr = PtrOp->stripPointerCasts(); 2175 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType()); 2176 2177 if (StrippedPtr != PtrOp) { 2178 bool HasZeroPointerIndex = false; 2179 Type *StrippedPtrEltTy = StrippedPtrTy->getElementType(); 2180 2181 if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) 2182 HasZeroPointerIndex = C->isZero(); 2183 2184 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... 2185 // into : GEP [10 x i8]* X, i32 0, ... 2186 // 2187 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... 2188 // into : GEP i8* X, ... 2189 // 2190 // This occurs when the program declares an array extern like "int X[];" 2191 if (HasZeroPointerIndex) { 2192 if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) { 2193 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? 2194 if (CATy->getElementType() == StrippedPtrEltTy) { 2195 // -> GEP i8* X, ... 2196 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); 2197 GetElementPtrInst *Res = GetElementPtrInst::Create( 2198 StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName()); 2199 Res->setIsInBounds(GEP.isInBounds()); 2200 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) 2201 return Res; 2202 // Insert Res, and create an addrspacecast. 2203 // e.g., 2204 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ... 2205 // -> 2206 // %0 = GEP i8 addrspace(1)* X, ... 2207 // addrspacecast i8 addrspace(1)* %0 to i8* 2208 return new AddrSpaceCastInst(Builder.Insert(Res), GEPType); 2209 } 2210 2211 if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) { 2212 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? 2213 if (CATy->getElementType() == XATy->getElementType()) { 2214 // -> GEP [10 x i8]* X, i32 0, ... 2215 // At this point, we know that the cast source type is a pointer 2216 // to an array of the same type as the destination pointer 2217 // array. Because the array type is never stepped over (there 2218 // is a leading zero) we can fold the cast into this GEP. 2219 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) { 2220 GEP.setSourceElementType(XATy); 2221 return replaceOperand(GEP, 0, StrippedPtr); 2222 } 2223 // Cannot replace the base pointer directly because StrippedPtr's 2224 // address space is different. Instead, create a new GEP followed by 2225 // an addrspacecast. 2226 // e.g., 2227 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*), 2228 // i32 0, ... 2229 // -> 2230 // %0 = GEP [10 x i8] addrspace(1)* X, ... 2231 // addrspacecast i8 addrspace(1)* %0 to i8* 2232 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end()); 2233 Value *NewGEP = 2234 GEP.isInBounds() 2235 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2236 Idx, GEP.getName()) 2237 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2238 GEP.getName()); 2239 return new AddrSpaceCastInst(NewGEP, GEPType); 2240 } 2241 } 2242 } 2243 } else if (GEP.getNumOperands() == 2 && !IsGEPSrcEleScalable) { 2244 // Skip if GEP source element type is scalable. The type alloc size is 2245 // unknown at compile-time. 2246 // Transform things like: %t = getelementptr i32* 2247 // bitcast ([2 x i32]* %str to i32*), i32 %V into: %t1 = getelementptr [2 2248 // x i32]* %str, i32 0, i32 %V; bitcast 2249 if (StrippedPtrEltTy->isArrayTy() && 2250 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) == 2251 DL.getTypeAllocSize(GEPEltType)) { 2252 Type *IdxType = DL.getIndexType(GEPType); 2253 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) }; 2254 Value *NewGEP = 2255 GEP.isInBounds() 2256 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2257 GEP.getName()) 2258 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2259 GEP.getName()); 2260 2261 // V and GEP are both pointer types --> BitCast 2262 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType); 2263 } 2264 2265 // Transform things like: 2266 // %V = mul i64 %N, 4 2267 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V 2268 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast 2269 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) { 2270 // Check that changing the type amounts to dividing the index by a scale 2271 // factor. 2272 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize(); 2273 uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy).getFixedSize(); 2274 if (ResSize && SrcSize % ResSize == 0) { 2275 Value *Idx = GEP.getOperand(1); 2276 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2277 uint64_t Scale = SrcSize / ResSize; 2278 2279 // Earlier transforms ensure that the index has the right type 2280 // according to Data Layout, which considerably simplifies the 2281 // logic by eliminating implicit casts. 2282 assert(Idx->getType() == DL.getIndexType(GEPType) && 2283 "Index type does not match the Data Layout preferences"); 2284 2285 bool NSW; 2286 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2287 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2288 // If the multiplication NewIdx * Scale may overflow then the new 2289 // GEP may not be "inbounds". 2290 Value *NewGEP = 2291 GEP.isInBounds() && NSW 2292 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2293 NewIdx, GEP.getName()) 2294 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx, 2295 GEP.getName()); 2296 2297 // The NewGEP must be pointer typed, so must the old one -> BitCast 2298 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2299 GEPType); 2300 } 2301 } 2302 } 2303 2304 // Similarly, transform things like: 2305 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp 2306 // (where tmp = 8*tmp2) into: 2307 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast 2308 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() && 2309 StrippedPtrEltTy->isArrayTy()) { 2310 // Check that changing to the array element type amounts to dividing the 2311 // index by a scale factor. 2312 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize(); 2313 uint64_t ArrayEltSize = 2314 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) 2315 .getFixedSize(); 2316 if (ResSize && ArrayEltSize % ResSize == 0) { 2317 Value *Idx = GEP.getOperand(1); 2318 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2319 uint64_t Scale = ArrayEltSize / ResSize; 2320 2321 // Earlier transforms ensure that the index has the right type 2322 // according to the Data Layout, which considerably simplifies 2323 // the logic by eliminating implicit casts. 2324 assert(Idx->getType() == DL.getIndexType(GEPType) && 2325 "Index type does not match the Data Layout preferences"); 2326 2327 bool NSW; 2328 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2329 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2330 // If the multiplication NewIdx * Scale may overflow then the new 2331 // GEP may not be "inbounds". 2332 Type *IndTy = DL.getIndexType(GEPType); 2333 Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx}; 2334 2335 Value *NewGEP = 2336 GEP.isInBounds() && NSW 2337 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2338 Off, GEP.getName()) 2339 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off, 2340 GEP.getName()); 2341 // The NewGEP must be pointer typed, so must the old one -> BitCast 2342 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2343 GEPType); 2344 } 2345 } 2346 } 2347 } 2348 } 2349 2350 // addrspacecast between types is canonicalized as a bitcast, then an 2351 // addrspacecast. To take advantage of the below bitcast + struct GEP, look 2352 // through the addrspacecast. 2353 Value *ASCStrippedPtrOp = PtrOp; 2354 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) { 2355 // X = bitcast A addrspace(1)* to B addrspace(1)* 2356 // Y = addrspacecast A addrspace(1)* to B addrspace(2)* 2357 // Z = gep Y, <...constant indices...> 2358 // Into an addrspacecasted GEP of the struct. 2359 if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0))) 2360 ASCStrippedPtrOp = BC; 2361 } 2362 2363 if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) { 2364 Value *SrcOp = BCI->getOperand(0); 2365 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy()); 2366 Type *SrcEltType = SrcType->getElementType(); 2367 2368 // GEP directly using the source operand if this GEP is accessing an element 2369 // of a bitcasted pointer to vector or array of the same dimensions: 2370 // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z 2371 // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z 2372 auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy, 2373 const DataLayout &DL) { 2374 auto *VecVTy = cast<FixedVectorType>(VecTy); 2375 return ArrTy->getArrayElementType() == VecVTy->getElementType() && 2376 ArrTy->getArrayNumElements() == VecVTy->getNumElements() && 2377 DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy); 2378 }; 2379 if (GEP.getNumOperands() == 3 && 2380 ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() && 2381 areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) || 2382 (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() && 2383 areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) { 2384 2385 // Create a new GEP here, as using `setOperand()` followed by 2386 // `setSourceElementType()` won't actually update the type of the 2387 // existing GEP Value. Causing issues if this Value is accessed when 2388 // constructing an AddrSpaceCastInst 2389 Value *NGEP = 2390 GEP.isInBounds() 2391 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}) 2392 : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}); 2393 NGEP->takeName(&GEP); 2394 2395 // Preserve GEP address space to satisfy users 2396 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2397 return new AddrSpaceCastInst(NGEP, GEPType); 2398 2399 return replaceInstUsesWith(GEP, NGEP); 2400 } 2401 2402 // See if we can simplify: 2403 // X = bitcast A* to B* 2404 // Y = gep X, <...constant indices...> 2405 // into a gep of the original struct. This is important for SROA and alias 2406 // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. 2407 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType); 2408 APInt Offset(OffsetBits, 0); 2409 if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) { 2410 // If this GEP instruction doesn't move the pointer, just replace the GEP 2411 // with a bitcast of the real input to the dest type. 2412 if (!Offset) { 2413 // If the bitcast is of an allocation, and the allocation will be 2414 // converted to match the type of the cast, don't touch this. 2415 if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) { 2416 // See if the bitcast simplifies, if so, don't nuke this GEP yet. 2417 if (Instruction *I = visitBitCast(*BCI)) { 2418 if (I != BCI) { 2419 I->takeName(BCI); 2420 BCI->getParent()->getInstList().insert(BCI->getIterator(), I); 2421 replaceInstUsesWith(*BCI, I); 2422 } 2423 return &GEP; 2424 } 2425 } 2426 2427 if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace()) 2428 return new AddrSpaceCastInst(SrcOp, GEPType); 2429 return new BitCastInst(SrcOp, GEPType); 2430 } 2431 2432 // Otherwise, if the offset is non-zero, we need to find out if there is a 2433 // field at Offset in 'A's type. If so, we can pull the cast through the 2434 // GEP. 2435 SmallVector<Value*, 8> NewIndices; 2436 if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) { 2437 Value *NGEP = 2438 GEP.isInBounds() 2439 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices) 2440 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices); 2441 2442 if (NGEP->getType() == GEPType) 2443 return replaceInstUsesWith(GEP, NGEP); 2444 NGEP->takeName(&GEP); 2445 2446 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2447 return new AddrSpaceCastInst(NGEP, GEPType); 2448 return new BitCastInst(NGEP, GEPType); 2449 } 2450 } 2451 } 2452 2453 if (!GEP.isInBounds()) { 2454 unsigned IdxWidth = 2455 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace()); 2456 APInt BasePtrOffset(IdxWidth, 0); 2457 Value *UnderlyingPtrOp = 2458 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, 2459 BasePtrOffset); 2460 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) { 2461 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) && 2462 BasePtrOffset.isNonNegative()) { 2463 APInt AllocSize( 2464 IdxWidth, 2465 DL.getTypeAllocSize(AI->getAllocatedType()).getKnownMinSize()); 2466 if (BasePtrOffset.ule(AllocSize)) { 2467 return GetElementPtrInst::CreateInBounds( 2468 GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1), 2469 GEP.getName()); 2470 } 2471 } 2472 } 2473 } 2474 2475 if (Instruction *R = foldSelectGEP(GEP, Builder)) 2476 return R; 2477 2478 return nullptr; 2479 } 2480 2481 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI, 2482 Instruction *AI) { 2483 if (isa<ConstantPointerNull>(V)) 2484 return true; 2485 if (auto *LI = dyn_cast<LoadInst>(V)) 2486 return isa<GlobalVariable>(LI->getPointerOperand()); 2487 // Two distinct allocations will never be equal. 2488 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking 2489 // through bitcasts of V can cause 2490 // the result statement below to be true, even when AI and V (ex: 2491 // i8* ->i32* ->i8* of AI) are the same allocations. 2492 return isAllocLikeFn(V, TLI) && V != AI; 2493 } 2494 2495 static bool isAllocSiteRemovable(Instruction *AI, 2496 SmallVectorImpl<WeakTrackingVH> &Users, 2497 const TargetLibraryInfo *TLI) { 2498 SmallVector<Instruction*, 4> Worklist; 2499 Worklist.push_back(AI); 2500 2501 do { 2502 Instruction *PI = Worklist.pop_back_val(); 2503 for (User *U : PI->users()) { 2504 Instruction *I = cast<Instruction>(U); 2505 switch (I->getOpcode()) { 2506 default: 2507 // Give up the moment we see something we can't handle. 2508 return false; 2509 2510 case Instruction::AddrSpaceCast: 2511 case Instruction::BitCast: 2512 case Instruction::GetElementPtr: 2513 Users.emplace_back(I); 2514 Worklist.push_back(I); 2515 continue; 2516 2517 case Instruction::ICmp: { 2518 ICmpInst *ICI = cast<ICmpInst>(I); 2519 // We can fold eq/ne comparisons with null to false/true, respectively. 2520 // We also fold comparisons in some conditions provided the alloc has 2521 // not escaped (see isNeverEqualToUnescapedAlloc). 2522 if (!ICI->isEquality()) 2523 return false; 2524 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0; 2525 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI)) 2526 return false; 2527 Users.emplace_back(I); 2528 continue; 2529 } 2530 2531 case Instruction::Call: 2532 // Ignore no-op and store intrinsics. 2533 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2534 switch (II->getIntrinsicID()) { 2535 default: 2536 return false; 2537 2538 case Intrinsic::memmove: 2539 case Intrinsic::memcpy: 2540 case Intrinsic::memset: { 2541 MemIntrinsic *MI = cast<MemIntrinsic>(II); 2542 if (MI->isVolatile() || MI->getRawDest() != PI) 2543 return false; 2544 LLVM_FALLTHROUGH; 2545 } 2546 case Intrinsic::assume: 2547 case Intrinsic::invariant_start: 2548 case Intrinsic::invariant_end: 2549 case Intrinsic::lifetime_start: 2550 case Intrinsic::lifetime_end: 2551 case Intrinsic::objectsize: 2552 Users.emplace_back(I); 2553 continue; 2554 } 2555 } 2556 2557 if (isFreeCall(I, TLI)) { 2558 Users.emplace_back(I); 2559 continue; 2560 } 2561 return false; 2562 2563 case Instruction::Store: { 2564 StoreInst *SI = cast<StoreInst>(I); 2565 if (SI->isVolatile() || SI->getPointerOperand() != PI) 2566 return false; 2567 Users.emplace_back(I); 2568 continue; 2569 } 2570 } 2571 llvm_unreachable("missing a return?"); 2572 } 2573 } while (!Worklist.empty()); 2574 return true; 2575 } 2576 2577 Instruction *InstCombinerImpl::visitAllocSite(Instruction &MI) { 2578 // If we have a malloc call which is only used in any amount of comparisons to 2579 // null and free calls, delete the calls and replace the comparisons with true 2580 // or false as appropriate. 2581 2582 // This is based on the principle that we can substitute our own allocation 2583 // function (which will never return null) rather than knowledge of the 2584 // specific function being called. In some sense this can change the permitted 2585 // outputs of a program (when we convert a malloc to an alloca, the fact that 2586 // the allocation is now on the stack is potentially visible, for example), 2587 // but we believe in a permissible manner. 2588 SmallVector<WeakTrackingVH, 64> Users; 2589 2590 // If we are removing an alloca with a dbg.declare, insert dbg.value calls 2591 // before each store. 2592 SmallVector<DbgVariableIntrinsic *, 8> DVIs; 2593 std::unique_ptr<DIBuilder> DIB; 2594 if (isa<AllocaInst>(MI)) { 2595 findDbgUsers(DVIs, &MI); 2596 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false)); 2597 } 2598 2599 if (isAllocSiteRemovable(&MI, Users, &TLI)) { 2600 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2601 // Lowering all @llvm.objectsize calls first because they may 2602 // use a bitcast/GEP of the alloca we are removing. 2603 if (!Users[i]) 2604 continue; 2605 2606 Instruction *I = cast<Instruction>(&*Users[i]); 2607 2608 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2609 if (II->getIntrinsicID() == Intrinsic::objectsize) { 2610 Value *Result = 2611 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true); 2612 replaceInstUsesWith(*I, Result); 2613 eraseInstFromFunction(*I); 2614 Users[i] = nullptr; // Skip examining in the next loop. 2615 } 2616 } 2617 } 2618 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2619 if (!Users[i]) 2620 continue; 2621 2622 Instruction *I = cast<Instruction>(&*Users[i]); 2623 2624 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) { 2625 replaceInstUsesWith(*C, 2626 ConstantInt::get(Type::getInt1Ty(C->getContext()), 2627 C->isFalseWhenEqual())); 2628 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 2629 for (auto *DVI : DVIs) 2630 if (DVI->isAddressOfVariable()) 2631 ConvertDebugDeclareToDebugValue(DVI, SI, *DIB); 2632 } else { 2633 // Casts, GEP, or anything else: we're about to delete this instruction, 2634 // so it can not have any valid uses. 2635 replaceInstUsesWith(*I, UndefValue::get(I->getType())); 2636 } 2637 eraseInstFromFunction(*I); 2638 } 2639 2640 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) { 2641 // Replace invoke with a NOP intrinsic to maintain the original CFG 2642 Module *M = II->getModule(); 2643 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing); 2644 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(), 2645 None, "", II->getParent()); 2646 } 2647 2648 // Remove debug intrinsics which describe the value contained within the 2649 // alloca. In addition to removing dbg.{declare,addr} which simply point to 2650 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.: 2651 // 2652 // ``` 2653 // define void @foo(i32 %0) { 2654 // %a = alloca i32 ; Deleted. 2655 // store i32 %0, i32* %a 2656 // dbg.value(i32 %0, "arg0") ; Not deleted. 2657 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted. 2658 // call void @trivially_inlinable_no_op(i32* %a) 2659 // ret void 2660 // } 2661 // ``` 2662 // 2663 // This may not be required if we stop describing the contents of allocas 2664 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in 2665 // the LowerDbgDeclare utility. 2666 // 2667 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the 2668 // "arg0" dbg.value may be stale after the call. However, failing to remove 2669 // the DW_OP_deref dbg.value causes large gaps in location coverage. 2670 for (auto *DVI : DVIs) 2671 if (DVI->isAddressOfVariable() || DVI->getExpression()->startsWithDeref()) 2672 DVI->eraseFromParent(); 2673 2674 return eraseInstFromFunction(MI); 2675 } 2676 return nullptr; 2677 } 2678 2679 /// Move the call to free before a NULL test. 2680 /// 2681 /// Check if this free is accessed after its argument has been test 2682 /// against NULL (property 0). 2683 /// If yes, it is legal to move this call in its predecessor block. 2684 /// 2685 /// The move is performed only if the block containing the call to free 2686 /// will be removed, i.e.: 2687 /// 1. it has only one predecessor P, and P has two successors 2688 /// 2. it contains the call, noops, and an unconditional branch 2689 /// 3. its successor is the same as its predecessor's successor 2690 /// 2691 /// The profitability is out-of concern here and this function should 2692 /// be called only if the caller knows this transformation would be 2693 /// profitable (e.g., for code size). 2694 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI, 2695 const DataLayout &DL) { 2696 Value *Op = FI.getArgOperand(0); 2697 BasicBlock *FreeInstrBB = FI.getParent(); 2698 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor(); 2699 2700 // Validate part of constraint #1: Only one predecessor 2701 // FIXME: We can extend the number of predecessor, but in that case, we 2702 // would duplicate the call to free in each predecessor and it may 2703 // not be profitable even for code size. 2704 if (!PredBB) 2705 return nullptr; 2706 2707 // Validate constraint #2: Does this block contains only the call to 2708 // free, noops, and an unconditional branch? 2709 BasicBlock *SuccBB; 2710 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator(); 2711 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB))) 2712 return nullptr; 2713 2714 // If there are only 2 instructions in the block, at this point, 2715 // this is the call to free and unconditional. 2716 // If there are more than 2 instructions, check that they are noops 2717 // i.e., they won't hurt the performance of the generated code. 2718 if (FreeInstrBB->size() != 2) { 2719 for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) { 2720 if (&Inst == &FI || &Inst == FreeInstrBBTerminator) 2721 continue; 2722 auto *Cast = dyn_cast<CastInst>(&Inst); 2723 if (!Cast || !Cast->isNoopCast(DL)) 2724 return nullptr; 2725 } 2726 } 2727 // Validate the rest of constraint #1 by matching on the pred branch. 2728 Instruction *TI = PredBB->getTerminator(); 2729 BasicBlock *TrueBB, *FalseBB; 2730 ICmpInst::Predicate Pred; 2731 if (!match(TI, m_Br(m_ICmp(Pred, 2732 m_CombineOr(m_Specific(Op), 2733 m_Specific(Op->stripPointerCasts())), 2734 m_Zero()), 2735 TrueBB, FalseBB))) 2736 return nullptr; 2737 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE) 2738 return nullptr; 2739 2740 // Validate constraint #3: Ensure the null case just falls through. 2741 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB)) 2742 return nullptr; 2743 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && 2744 "Broken CFG: missing edge from predecessor to successor"); 2745 2746 // At this point, we know that everything in FreeInstrBB can be moved 2747 // before TI. 2748 for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end(); 2749 It != End;) { 2750 Instruction &Instr = *It++; 2751 if (&Instr == FreeInstrBBTerminator) 2752 break; 2753 Instr.moveBefore(TI); 2754 } 2755 assert(FreeInstrBB->size() == 1 && 2756 "Only the branch instruction should remain"); 2757 return &FI; 2758 } 2759 2760 Instruction *InstCombinerImpl::visitFree(CallInst &FI) { 2761 Value *Op = FI.getArgOperand(0); 2762 2763 // free undef -> unreachable. 2764 if (isa<UndefValue>(Op)) { 2765 // Leave a marker since we can't modify the CFG here. 2766 CreateNonTerminatorUnreachable(&FI); 2767 return eraseInstFromFunction(FI); 2768 } 2769 2770 // If we have 'free null' delete the instruction. This can happen in stl code 2771 // when lots of inlining happens. 2772 if (isa<ConstantPointerNull>(Op)) 2773 return eraseInstFromFunction(FI); 2774 2775 // If we optimize for code size, try to move the call to free before the null 2776 // test so that simplify cfg can remove the empty block and dead code 2777 // elimination the branch. I.e., helps to turn something like: 2778 // if (foo) free(foo); 2779 // into 2780 // free(foo); 2781 // 2782 // Note that we can only do this for 'free' and not for any flavor of 2783 // 'operator delete'; there is no 'operator delete' symbol for which we are 2784 // permitted to invent a call, even if we're passing in a null pointer. 2785 if (MinimizeSize) { 2786 LibFunc Func; 2787 if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free) 2788 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL)) 2789 return I; 2790 } 2791 2792 return nullptr; 2793 } 2794 2795 static bool isMustTailCall(Value *V) { 2796 if (auto *CI = dyn_cast<CallInst>(V)) 2797 return CI->isMustTailCall(); 2798 return false; 2799 } 2800 2801 Instruction *InstCombinerImpl::visitReturnInst(ReturnInst &RI) { 2802 if (RI.getNumOperands() == 0) // ret void 2803 return nullptr; 2804 2805 Value *ResultOp = RI.getOperand(0); 2806 Type *VTy = ResultOp->getType(); 2807 if (!VTy->isIntegerTy() || isa<Constant>(ResultOp)) 2808 return nullptr; 2809 2810 // Don't replace result of musttail calls. 2811 if (isMustTailCall(ResultOp)) 2812 return nullptr; 2813 2814 // There might be assume intrinsics dominating this return that completely 2815 // determine the value. If so, constant fold it. 2816 KnownBits Known = computeKnownBits(ResultOp, 0, &RI); 2817 if (Known.isConstant()) 2818 return replaceOperand(RI, 0, 2819 Constant::getIntegerValue(VTy, Known.getConstant())); 2820 2821 return nullptr; 2822 } 2823 2824 Instruction *InstCombinerImpl::visitUnreachableInst(UnreachableInst &I) { 2825 // Try to remove the previous instruction if it must lead to unreachable. 2826 // This includes instructions like stores and "llvm.assume" that may not get 2827 // removed by simple dead code elimination. 2828 Instruction *Prev = I.getPrevNonDebugInstruction(); 2829 if (Prev && !Prev->isEHPad() && 2830 isGuaranteedToTransferExecutionToSuccessor(Prev)) { 2831 // Temporarily disable removal of volatile stores preceding unreachable, 2832 // pending a potential LangRef change permitting volatile stores to trap. 2833 // TODO: Either remove this code, or properly integrate the check into 2834 // isGuaranteedToTransferExecutionToSuccessor(). 2835 if (auto *SI = dyn_cast<StoreInst>(Prev)) 2836 if (SI->isVolatile()) 2837 return nullptr; 2838 2839 // A value may still have uses before we process it here (for example, in 2840 // another unreachable block), so convert those to undef. 2841 replaceInstUsesWith(*Prev, UndefValue::get(Prev->getType())); 2842 eraseInstFromFunction(*Prev); 2843 return &I; 2844 } 2845 return nullptr; 2846 } 2847 2848 Instruction *InstCombinerImpl::visitUnconditionalBranchInst(BranchInst &BI) { 2849 assert(BI.isUnconditional() && "Only for unconditional branches."); 2850 2851 // If this store is the second-to-last instruction in the basic block 2852 // (excluding debug info and bitcasts of pointers) and if the block ends with 2853 // an unconditional branch, try to move the store to the successor block. 2854 2855 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) { 2856 auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) { 2857 return isa<DbgInfoIntrinsic>(BBI) || 2858 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()); 2859 }; 2860 2861 BasicBlock::iterator FirstInstr = BBI->getParent()->begin(); 2862 do { 2863 if (BBI != FirstInstr) 2864 --BBI; 2865 } while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI)); 2866 2867 return dyn_cast<StoreInst>(BBI); 2868 }; 2869 2870 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI))) 2871 if (mergeStoreIntoSuccessor(*SI)) 2872 return &BI; 2873 2874 return nullptr; 2875 } 2876 2877 Instruction *InstCombinerImpl::visitBranchInst(BranchInst &BI) { 2878 if (BI.isUnconditional()) 2879 return visitUnconditionalBranchInst(BI); 2880 2881 // Change br (not X), label True, label False to: br X, label False, True 2882 Value *X = nullptr; 2883 if (match(&BI, m_Br(m_Not(m_Value(X)), m_BasicBlock(), m_BasicBlock())) && 2884 !isa<Constant>(X)) { 2885 // Swap Destinations and condition... 2886 BI.swapSuccessors(); 2887 return replaceOperand(BI, 0, X); 2888 } 2889 2890 // If the condition is irrelevant, remove the use so that other 2891 // transforms on the condition become more effective. 2892 if (!isa<ConstantInt>(BI.getCondition()) && 2893 BI.getSuccessor(0) == BI.getSuccessor(1)) 2894 return replaceOperand( 2895 BI, 0, ConstantInt::getFalse(BI.getCondition()->getType())); 2896 2897 // Canonicalize, for example, fcmp_one -> fcmp_oeq. 2898 CmpInst::Predicate Pred; 2899 if (match(&BI, m_Br(m_OneUse(m_FCmp(Pred, m_Value(), m_Value())), 2900 m_BasicBlock(), m_BasicBlock())) && 2901 !isCanonicalPredicate(Pred)) { 2902 // Swap destinations and condition. 2903 CmpInst *Cond = cast<CmpInst>(BI.getCondition()); 2904 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 2905 BI.swapSuccessors(); 2906 Worklist.push(Cond); 2907 return &BI; 2908 } 2909 2910 return nullptr; 2911 } 2912 2913 Instruction *InstCombinerImpl::visitSwitchInst(SwitchInst &SI) { 2914 Value *Cond = SI.getCondition(); 2915 Value *Op0; 2916 ConstantInt *AddRHS; 2917 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) { 2918 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'. 2919 for (auto Case : SI.cases()) { 2920 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS); 2921 assert(isa<ConstantInt>(NewCase) && 2922 "Result of expression should be constant"); 2923 Case.setValue(cast<ConstantInt>(NewCase)); 2924 } 2925 return replaceOperand(SI, 0, Op0); 2926 } 2927 2928 KnownBits Known = computeKnownBits(Cond, 0, &SI); 2929 unsigned LeadingKnownZeros = Known.countMinLeadingZeros(); 2930 unsigned LeadingKnownOnes = Known.countMinLeadingOnes(); 2931 2932 // Compute the number of leading bits we can ignore. 2933 // TODO: A better way to determine this would use ComputeNumSignBits(). 2934 for (auto &C : SI.cases()) { 2935 LeadingKnownZeros = std::min( 2936 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros()); 2937 LeadingKnownOnes = std::min( 2938 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes()); 2939 } 2940 2941 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes); 2942 2943 // Shrink the condition operand if the new type is smaller than the old type. 2944 // But do not shrink to a non-standard type, because backend can't generate 2945 // good code for that yet. 2946 // TODO: We can make it aggressive again after fixing PR39569. 2947 if (NewWidth > 0 && NewWidth < Known.getBitWidth() && 2948 shouldChangeType(Known.getBitWidth(), NewWidth)) { 2949 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth); 2950 Builder.SetInsertPoint(&SI); 2951 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc"); 2952 2953 for (auto Case : SI.cases()) { 2954 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth); 2955 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase)); 2956 } 2957 return replaceOperand(SI, 0, NewCond); 2958 } 2959 2960 return nullptr; 2961 } 2962 2963 Instruction *InstCombinerImpl::visitExtractValueInst(ExtractValueInst &EV) { 2964 Value *Agg = EV.getAggregateOperand(); 2965 2966 if (!EV.hasIndices()) 2967 return replaceInstUsesWith(EV, Agg); 2968 2969 if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(), 2970 SQ.getWithInstruction(&EV))) 2971 return replaceInstUsesWith(EV, V); 2972 2973 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 2974 // We're extracting from an insertvalue instruction, compare the indices 2975 const unsigned *exti, *exte, *insi, *inse; 2976 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 2977 exte = EV.idx_end(), inse = IV->idx_end(); 2978 exti != exte && insi != inse; 2979 ++exti, ++insi) { 2980 if (*insi != *exti) 2981 // The insert and extract both reference distinctly different elements. 2982 // This means the extract is not influenced by the insert, and we can 2983 // replace the aggregate operand of the extract with the aggregate 2984 // operand of the insert. i.e., replace 2985 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 2986 // %E = extractvalue { i32, { i32 } } %I, 0 2987 // with 2988 // %E = extractvalue { i32, { i32 } } %A, 0 2989 return ExtractValueInst::Create(IV->getAggregateOperand(), 2990 EV.getIndices()); 2991 } 2992 if (exti == exte && insi == inse) 2993 // Both iterators are at the end: Index lists are identical. Replace 2994 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 2995 // %C = extractvalue { i32, { i32 } } %B, 1, 0 2996 // with "i32 42" 2997 return replaceInstUsesWith(EV, IV->getInsertedValueOperand()); 2998 if (exti == exte) { 2999 // The extract list is a prefix of the insert list. i.e. replace 3000 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 3001 // %E = extractvalue { i32, { i32 } } %I, 1 3002 // with 3003 // %X = extractvalue { i32, { i32 } } %A, 1 3004 // %E = insertvalue { i32 } %X, i32 42, 0 3005 // by switching the order of the insert and extract (though the 3006 // insertvalue should be left in, since it may have other uses). 3007 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(), 3008 EV.getIndices()); 3009 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 3010 makeArrayRef(insi, inse)); 3011 } 3012 if (insi == inse) 3013 // The insert list is a prefix of the extract list 3014 // We can simply remove the common indices from the extract and make it 3015 // operate on the inserted value instead of the insertvalue result. 3016 // i.e., replace 3017 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 3018 // %E = extractvalue { i32, { i32 } } %I, 1, 0 3019 // with 3020 // %E extractvalue { i32 } { i32 42 }, 0 3021 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 3022 makeArrayRef(exti, exte)); 3023 } 3024 if (WithOverflowInst *WO = dyn_cast<WithOverflowInst>(Agg)) { 3025 // We're extracting from an overflow intrinsic, see if we're the only user, 3026 // which allows us to simplify multiple result intrinsics to simpler 3027 // things that just get one value. 3028 if (WO->hasOneUse()) { 3029 // Check if we're grabbing only the result of a 'with overflow' intrinsic 3030 // and replace it with a traditional binary instruction. 3031 if (*EV.idx_begin() == 0) { 3032 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 3033 Value *LHS = WO->getLHS(), *RHS = WO->getRHS(); 3034 replaceInstUsesWith(*WO, UndefValue::get(WO->getType())); 3035 eraseInstFromFunction(*WO); 3036 return BinaryOperator::Create(BinOp, LHS, RHS); 3037 } 3038 3039 // If the normal result of the add is dead, and the RHS is a constant, 3040 // we can transform this into a range comparison. 3041 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 3042 if (WO->getIntrinsicID() == Intrinsic::uadd_with_overflow) 3043 if (ConstantInt *CI = dyn_cast<ConstantInt>(WO->getRHS())) 3044 return new ICmpInst(ICmpInst::ICMP_UGT, WO->getLHS(), 3045 ConstantExpr::getNot(CI)); 3046 } 3047 } 3048 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) 3049 // If the (non-volatile) load only has one use, we can rewrite this to a 3050 // load from a GEP. This reduces the size of the load. If a load is used 3051 // only by extractvalue instructions then this either must have been 3052 // optimized before, or it is a struct with padding, in which case we 3053 // don't want to do the transformation as it loses padding knowledge. 3054 if (L->isSimple() && L->hasOneUse()) { 3055 // extractvalue has integer indices, getelementptr has Value*s. Convert. 3056 SmallVector<Value*, 4> Indices; 3057 // Prefix an i32 0 since we need the first element. 3058 Indices.push_back(Builder.getInt32(0)); 3059 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); 3060 I != E; ++I) 3061 Indices.push_back(Builder.getInt32(*I)); 3062 3063 // We need to insert these at the location of the old load, not at that of 3064 // the extractvalue. 3065 Builder.SetInsertPoint(L); 3066 Value *GEP = Builder.CreateInBoundsGEP(L->getType(), 3067 L->getPointerOperand(), Indices); 3068 Instruction *NL = Builder.CreateLoad(EV.getType(), GEP); 3069 // Whatever aliasing information we had for the orignal load must also 3070 // hold for the smaller load, so propagate the annotations. 3071 AAMDNodes Nodes; 3072 L->getAAMetadata(Nodes); 3073 NL->setAAMetadata(Nodes); 3074 // Returning the load directly will cause the main loop to insert it in 3075 // the wrong spot, so use replaceInstUsesWith(). 3076 return replaceInstUsesWith(EV, NL); 3077 } 3078 // We could simplify extracts from other values. Note that nested extracts may 3079 // already be simplified implicitly by the above: extract (extract (insert) ) 3080 // will be translated into extract ( insert ( extract ) ) first and then just 3081 // the value inserted, if appropriate. Similarly for extracts from single-use 3082 // loads: extract (extract (load)) will be translated to extract (load (gep)) 3083 // and if again single-use then via load (gep (gep)) to load (gep). 3084 // However, double extracts from e.g. function arguments or return values 3085 // aren't handled yet. 3086 return nullptr; 3087 } 3088 3089 /// Return 'true' if the given typeinfo will match anything. 3090 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) { 3091 switch (Personality) { 3092 case EHPersonality::GNU_C: 3093 case EHPersonality::GNU_C_SjLj: 3094 case EHPersonality::Rust: 3095 // The GCC C EH and Rust personality only exists to support cleanups, so 3096 // it's not clear what the semantics of catch clauses are. 3097 return false; 3098 case EHPersonality::Unknown: 3099 return false; 3100 case EHPersonality::GNU_Ada: 3101 // While __gnat_all_others_value will match any Ada exception, it doesn't 3102 // match foreign exceptions (or didn't, before gcc-4.7). 3103 return false; 3104 case EHPersonality::GNU_CXX: 3105 case EHPersonality::GNU_CXX_SjLj: 3106 case EHPersonality::GNU_ObjC: 3107 case EHPersonality::MSVC_X86SEH: 3108 case EHPersonality::MSVC_TableSEH: 3109 case EHPersonality::MSVC_CXX: 3110 case EHPersonality::CoreCLR: 3111 case EHPersonality::Wasm_CXX: 3112 case EHPersonality::XL_CXX: 3113 return TypeInfo->isNullValue(); 3114 } 3115 llvm_unreachable("invalid enum"); 3116 } 3117 3118 static bool shorter_filter(const Value *LHS, const Value *RHS) { 3119 return 3120 cast<ArrayType>(LHS->getType())->getNumElements() 3121 < 3122 cast<ArrayType>(RHS->getType())->getNumElements(); 3123 } 3124 3125 Instruction *InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) { 3126 // The logic here should be correct for any real-world personality function. 3127 // However if that turns out not to be true, the offending logic can always 3128 // be conditioned on the personality function, like the catch-all logic is. 3129 EHPersonality Personality = 3130 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn()); 3131 3132 // Simplify the list of clauses, eg by removing repeated catch clauses 3133 // (these are often created by inlining). 3134 bool MakeNewInstruction = false; // If true, recreate using the following: 3135 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction; 3136 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup. 3137 3138 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already. 3139 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) { 3140 bool isLastClause = i + 1 == e; 3141 if (LI.isCatch(i)) { 3142 // A catch clause. 3143 Constant *CatchClause = LI.getClause(i); 3144 Constant *TypeInfo = CatchClause->stripPointerCasts(); 3145 3146 // If we already saw this clause, there is no point in having a second 3147 // copy of it. 3148 if (AlreadyCaught.insert(TypeInfo).second) { 3149 // This catch clause was not already seen. 3150 NewClauses.push_back(CatchClause); 3151 } else { 3152 // Repeated catch clause - drop the redundant copy. 3153 MakeNewInstruction = true; 3154 } 3155 3156 // If this is a catch-all then there is no point in keeping any following 3157 // clauses or marking the landingpad as having a cleanup. 3158 if (isCatchAll(Personality, TypeInfo)) { 3159 if (!isLastClause) 3160 MakeNewInstruction = true; 3161 CleanupFlag = false; 3162 break; 3163 } 3164 } else { 3165 // A filter clause. If any of the filter elements were already caught 3166 // then they can be dropped from the filter. It is tempting to try to 3167 // exploit the filter further by saying that any typeinfo that does not 3168 // occur in the filter can't be caught later (and thus can be dropped). 3169 // However this would be wrong, since typeinfos can match without being 3170 // equal (for example if one represents a C++ class, and the other some 3171 // class derived from it). 3172 assert(LI.isFilter(i) && "Unsupported landingpad clause!"); 3173 Constant *FilterClause = LI.getClause(i); 3174 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType()); 3175 unsigned NumTypeInfos = FilterType->getNumElements(); 3176 3177 // An empty filter catches everything, so there is no point in keeping any 3178 // following clauses or marking the landingpad as having a cleanup. By 3179 // dealing with this case here the following code is made a bit simpler. 3180 if (!NumTypeInfos) { 3181 NewClauses.push_back(FilterClause); 3182 if (!isLastClause) 3183 MakeNewInstruction = true; 3184 CleanupFlag = false; 3185 break; 3186 } 3187 3188 bool MakeNewFilter = false; // If true, make a new filter. 3189 SmallVector<Constant *, 16> NewFilterElts; // New elements. 3190 if (isa<ConstantAggregateZero>(FilterClause)) { 3191 // Not an empty filter - it contains at least one null typeinfo. 3192 assert(NumTypeInfos > 0 && "Should have handled empty filter already!"); 3193 Constant *TypeInfo = 3194 Constant::getNullValue(FilterType->getElementType()); 3195 // If this typeinfo is a catch-all then the filter can never match. 3196 if (isCatchAll(Personality, TypeInfo)) { 3197 // Throw the filter away. 3198 MakeNewInstruction = true; 3199 continue; 3200 } 3201 3202 // There is no point in having multiple copies of this typeinfo, so 3203 // discard all but the first copy if there is more than one. 3204 NewFilterElts.push_back(TypeInfo); 3205 if (NumTypeInfos > 1) 3206 MakeNewFilter = true; 3207 } else { 3208 ConstantArray *Filter = cast<ConstantArray>(FilterClause); 3209 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements. 3210 NewFilterElts.reserve(NumTypeInfos); 3211 3212 // Remove any filter elements that were already caught or that already 3213 // occurred in the filter. While there, see if any of the elements are 3214 // catch-alls. If so, the filter can be discarded. 3215 bool SawCatchAll = false; 3216 for (unsigned j = 0; j != NumTypeInfos; ++j) { 3217 Constant *Elt = Filter->getOperand(j); 3218 Constant *TypeInfo = Elt->stripPointerCasts(); 3219 if (isCatchAll(Personality, TypeInfo)) { 3220 // This element is a catch-all. Bail out, noting this fact. 3221 SawCatchAll = true; 3222 break; 3223 } 3224 3225 // Even if we've seen a type in a catch clause, we don't want to 3226 // remove it from the filter. An unexpected type handler may be 3227 // set up for a call site which throws an exception of the same 3228 // type caught. In order for the exception thrown by the unexpected 3229 // handler to propagate correctly, the filter must be correctly 3230 // described for the call site. 3231 // 3232 // Example: 3233 // 3234 // void unexpected() { throw 1;} 3235 // void foo() throw (int) { 3236 // std::set_unexpected(unexpected); 3237 // try { 3238 // throw 2.0; 3239 // } catch (int i) {} 3240 // } 3241 3242 // There is no point in having multiple copies of the same typeinfo in 3243 // a filter, so only add it if we didn't already. 3244 if (SeenInFilter.insert(TypeInfo).second) 3245 NewFilterElts.push_back(cast<Constant>(Elt)); 3246 } 3247 // A filter containing a catch-all cannot match anything by definition. 3248 if (SawCatchAll) { 3249 // Throw the filter away. 3250 MakeNewInstruction = true; 3251 continue; 3252 } 3253 3254 // If we dropped something from the filter, make a new one. 3255 if (NewFilterElts.size() < NumTypeInfos) 3256 MakeNewFilter = true; 3257 } 3258 if (MakeNewFilter) { 3259 FilterType = ArrayType::get(FilterType->getElementType(), 3260 NewFilterElts.size()); 3261 FilterClause = ConstantArray::get(FilterType, NewFilterElts); 3262 MakeNewInstruction = true; 3263 } 3264 3265 NewClauses.push_back(FilterClause); 3266 3267 // If the new filter is empty then it will catch everything so there is 3268 // no point in keeping any following clauses or marking the landingpad 3269 // as having a cleanup. The case of the original filter being empty was 3270 // already handled above. 3271 if (MakeNewFilter && !NewFilterElts.size()) { 3272 assert(MakeNewInstruction && "New filter but not a new instruction!"); 3273 CleanupFlag = false; 3274 break; 3275 } 3276 } 3277 } 3278 3279 // If several filters occur in a row then reorder them so that the shortest 3280 // filters come first (those with the smallest number of elements). This is 3281 // advantageous because shorter filters are more likely to match, speeding up 3282 // unwinding, but mostly because it increases the effectiveness of the other 3283 // filter optimizations below. 3284 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) { 3285 unsigned j; 3286 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters. 3287 for (j = i; j != e; ++j) 3288 if (!isa<ArrayType>(NewClauses[j]->getType())) 3289 break; 3290 3291 // Check whether the filters are already sorted by length. We need to know 3292 // if sorting them is actually going to do anything so that we only make a 3293 // new landingpad instruction if it does. 3294 for (unsigned k = i; k + 1 < j; ++k) 3295 if (shorter_filter(NewClauses[k+1], NewClauses[k])) { 3296 // Not sorted, so sort the filters now. Doing an unstable sort would be 3297 // correct too but reordering filters pointlessly might confuse users. 3298 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j, 3299 shorter_filter); 3300 MakeNewInstruction = true; 3301 break; 3302 } 3303 3304 // Look for the next batch of filters. 3305 i = j + 1; 3306 } 3307 3308 // If typeinfos matched if and only if equal, then the elements of a filter L 3309 // that occurs later than a filter F could be replaced by the intersection of 3310 // the elements of F and L. In reality two typeinfos can match without being 3311 // equal (for example if one represents a C++ class, and the other some class 3312 // derived from it) so it would be wrong to perform this transform in general. 3313 // However the transform is correct and useful if F is a subset of L. In that 3314 // case L can be replaced by F, and thus removed altogether since repeating a 3315 // filter is pointless. So here we look at all pairs of filters F and L where 3316 // L follows F in the list of clauses, and remove L if every element of F is 3317 // an element of L. This can occur when inlining C++ functions with exception 3318 // specifications. 3319 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) { 3320 // Examine each filter in turn. 3321 Value *Filter = NewClauses[i]; 3322 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType()); 3323 if (!FTy) 3324 // Not a filter - skip it. 3325 continue; 3326 unsigned FElts = FTy->getNumElements(); 3327 // Examine each filter following this one. Doing this backwards means that 3328 // we don't have to worry about filters disappearing under us when removed. 3329 for (unsigned j = NewClauses.size() - 1; j != i; --j) { 3330 Value *LFilter = NewClauses[j]; 3331 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType()); 3332 if (!LTy) 3333 // Not a filter - skip it. 3334 continue; 3335 // If Filter is a subset of LFilter, i.e. every element of Filter is also 3336 // an element of LFilter, then discard LFilter. 3337 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j; 3338 // If Filter is empty then it is a subset of LFilter. 3339 if (!FElts) { 3340 // Discard LFilter. 3341 NewClauses.erase(J); 3342 MakeNewInstruction = true; 3343 // Move on to the next filter. 3344 continue; 3345 } 3346 unsigned LElts = LTy->getNumElements(); 3347 // If Filter is longer than LFilter then it cannot be a subset of it. 3348 if (FElts > LElts) 3349 // Move on to the next filter. 3350 continue; 3351 // At this point we know that LFilter has at least one element. 3352 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros. 3353 // Filter is a subset of LFilter iff Filter contains only zeros (as we 3354 // already know that Filter is not longer than LFilter). 3355 if (isa<ConstantAggregateZero>(Filter)) { 3356 assert(FElts <= LElts && "Should have handled this case earlier!"); 3357 // Discard LFilter. 3358 NewClauses.erase(J); 3359 MakeNewInstruction = true; 3360 } 3361 // Move on to the next filter. 3362 continue; 3363 } 3364 ConstantArray *LArray = cast<ConstantArray>(LFilter); 3365 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros. 3366 // Since Filter is non-empty and contains only zeros, it is a subset of 3367 // LFilter iff LFilter contains a zero. 3368 assert(FElts > 0 && "Should have eliminated the empty filter earlier!"); 3369 for (unsigned l = 0; l != LElts; ++l) 3370 if (LArray->getOperand(l)->isNullValue()) { 3371 // LFilter contains a zero - discard it. 3372 NewClauses.erase(J); 3373 MakeNewInstruction = true; 3374 break; 3375 } 3376 // Move on to the next filter. 3377 continue; 3378 } 3379 // At this point we know that both filters are ConstantArrays. Loop over 3380 // operands to see whether every element of Filter is also an element of 3381 // LFilter. Since filters tend to be short this is probably faster than 3382 // using a method that scales nicely. 3383 ConstantArray *FArray = cast<ConstantArray>(Filter); 3384 bool AllFound = true; 3385 for (unsigned f = 0; f != FElts; ++f) { 3386 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts(); 3387 AllFound = false; 3388 for (unsigned l = 0; l != LElts; ++l) { 3389 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts(); 3390 if (LTypeInfo == FTypeInfo) { 3391 AllFound = true; 3392 break; 3393 } 3394 } 3395 if (!AllFound) 3396 break; 3397 } 3398 if (AllFound) { 3399 // Discard LFilter. 3400 NewClauses.erase(J); 3401 MakeNewInstruction = true; 3402 } 3403 // Move on to the next filter. 3404 } 3405 } 3406 3407 // If we changed any of the clauses, replace the old landingpad instruction 3408 // with a new one. 3409 if (MakeNewInstruction) { 3410 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(), 3411 NewClauses.size()); 3412 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i) 3413 NLI->addClause(NewClauses[i]); 3414 // A landing pad with no clauses must have the cleanup flag set. It is 3415 // theoretically possible, though highly unlikely, that we eliminated all 3416 // clauses. If so, force the cleanup flag to true. 3417 if (NewClauses.empty()) 3418 CleanupFlag = true; 3419 NLI->setCleanup(CleanupFlag); 3420 return NLI; 3421 } 3422 3423 // Even if none of the clauses changed, we may nonetheless have understood 3424 // that the cleanup flag is pointless. Clear it if so. 3425 if (LI.isCleanup() != CleanupFlag) { 3426 assert(!CleanupFlag && "Adding a cleanup, not removing one?!"); 3427 LI.setCleanup(CleanupFlag); 3428 return &LI; 3429 } 3430 3431 return nullptr; 3432 } 3433 3434 Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) { 3435 Value *Op0 = I.getOperand(0); 3436 3437 if (Value *V = SimplifyFreezeInst(Op0, SQ.getWithInstruction(&I))) 3438 return replaceInstUsesWith(I, V); 3439 3440 // freeze (phi const, x) --> phi const, (freeze x) 3441 if (auto *PN = dyn_cast<PHINode>(Op0)) { 3442 if (Instruction *NV = foldOpIntoPhi(I, PN)) 3443 return NV; 3444 } 3445 3446 if (match(Op0, m_Undef())) { 3447 // If I is freeze(undef), see its uses and fold it to the best constant. 3448 // - or: pick -1 3449 // - select's condition: pick the value that leads to choosing a constant 3450 // - other ops: pick 0 3451 Constant *BestValue = nullptr; 3452 Constant *NullValue = Constant::getNullValue(I.getType()); 3453 for (const auto *U : I.users()) { 3454 Constant *C = NullValue; 3455 3456 if (match(U, m_Or(m_Value(), m_Value()))) 3457 C = Constant::getAllOnesValue(I.getType()); 3458 else if (const auto *SI = dyn_cast<SelectInst>(U)) { 3459 if (SI->getCondition() == &I) { 3460 APInt CondVal(1, isa<Constant>(SI->getFalseValue()) ? 0 : 1); 3461 C = Constant::getIntegerValue(I.getType(), CondVal); 3462 } 3463 } 3464 3465 if (!BestValue) 3466 BestValue = C; 3467 else if (BestValue != C) 3468 BestValue = NullValue; 3469 } 3470 3471 return replaceInstUsesWith(I, BestValue); 3472 } 3473 3474 return nullptr; 3475 } 3476 3477 /// Try to move the specified instruction from its current block into the 3478 /// beginning of DestBlock, which can only happen if it's safe to move the 3479 /// instruction past all of the instructions between it and the end of its 3480 /// block. 3481 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 3482 assert(I->getSingleUndroppableUse() && "Invariants didn't hold!"); 3483 BasicBlock *SrcBlock = I->getParent(); 3484 3485 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 3486 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() || 3487 I->isTerminator()) 3488 return false; 3489 3490 // Do not sink static or dynamic alloca instructions. Static allocas must 3491 // remain in the entry block, and dynamic allocas must not be sunk in between 3492 // a stacksave / stackrestore pair, which would incorrectly shorten its 3493 // lifetime. 3494 if (isa<AllocaInst>(I)) 3495 return false; 3496 3497 // Do not sink into catchswitch blocks. 3498 if (isa<CatchSwitchInst>(DestBlock->getTerminator())) 3499 return false; 3500 3501 // Do not sink convergent call instructions. 3502 if (auto *CI = dyn_cast<CallInst>(I)) { 3503 if (CI->isConvergent()) 3504 return false; 3505 } 3506 // We can only sink load instructions if there is nothing between the load and 3507 // the end of block that could change the value. 3508 if (I->mayReadFromMemory()) { 3509 // We don't want to do any sophisticated alias analysis, so we only check 3510 // the instructions after I in I's parent block if we try to sink to its 3511 // successor block. 3512 if (DestBlock->getUniquePredecessor() != I->getParent()) 3513 return false; 3514 for (BasicBlock::iterator Scan = I->getIterator(), 3515 E = I->getParent()->end(); 3516 Scan != E; ++Scan) 3517 if (Scan->mayWriteToMemory()) 3518 return false; 3519 } 3520 3521 I->dropDroppableUses([DestBlock](const Use *U) { 3522 if (auto *I = dyn_cast<Instruction>(U->getUser())) 3523 return I->getParent() != DestBlock; 3524 return true; 3525 }); 3526 /// FIXME: We could remove droppable uses that are not dominated by 3527 /// the new position. 3528 3529 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); 3530 I->moveBefore(&*InsertPos); 3531 ++NumSunkInst; 3532 3533 // Also sink all related debug uses from the source basic block. Otherwise we 3534 // get debug use before the def. Attempt to salvage debug uses first, to 3535 // maximise the range variables have location for. If we cannot salvage, then 3536 // mark the location undef: we know it was supposed to receive a new location 3537 // here, but that computation has been sunk. 3538 SmallVector<DbgVariableIntrinsic *, 2> DbgUsers; 3539 findDbgUsers(DbgUsers, I); 3540 3541 // Update the arguments of a dbg.declare instruction, so that it 3542 // does not point into a sunk instruction. 3543 auto updateDbgDeclare = [&I](DbgVariableIntrinsic *DII) { 3544 if (!isa<DbgDeclareInst>(DII)) 3545 return false; 3546 3547 if (isa<CastInst>(I)) 3548 DII->setOperand( 3549 0, MetadataAsValue::get(I->getContext(), 3550 ValueAsMetadata::get(I->getOperand(0)))); 3551 return true; 3552 }; 3553 3554 SmallVector<DbgVariableIntrinsic *, 2> DIIClones; 3555 for (auto User : DbgUsers) { 3556 // A dbg.declare instruction should not be cloned, since there can only be 3557 // one per variable fragment. It should be left in the original place 3558 // because the sunk instruction is not an alloca (otherwise we could not be 3559 // here). 3560 if (User->getParent() != SrcBlock || updateDbgDeclare(User)) 3561 continue; 3562 3563 DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone())); 3564 LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n'); 3565 } 3566 3567 // Perform salvaging without the clones, then sink the clones. 3568 if (!DIIClones.empty()) { 3569 salvageDebugInfoForDbgValues(*I, DbgUsers); 3570 for (auto &DIIClone : DIIClones) { 3571 DIIClone->insertBefore(&*InsertPos); 3572 LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n'); 3573 } 3574 } 3575 3576 return true; 3577 } 3578 3579 bool InstCombinerImpl::run() { 3580 while (!Worklist.isEmpty()) { 3581 // Walk deferred instructions in reverse order, and push them to the 3582 // worklist, which means they'll end up popped from the worklist in-order. 3583 while (Instruction *I = Worklist.popDeferred()) { 3584 // Check to see if we can DCE the instruction. We do this already here to 3585 // reduce the number of uses and thus allow other folds to trigger. 3586 // Note that eraseInstFromFunction() may push additional instructions on 3587 // the deferred worklist, so this will DCE whole instruction chains. 3588 if (isInstructionTriviallyDead(I, &TLI)) { 3589 eraseInstFromFunction(*I); 3590 ++NumDeadInst; 3591 continue; 3592 } 3593 3594 Worklist.push(I); 3595 } 3596 3597 Instruction *I = Worklist.removeOne(); 3598 if (I == nullptr) continue; // skip null values. 3599 3600 // Check to see if we can DCE the instruction. 3601 if (isInstructionTriviallyDead(I, &TLI)) { 3602 eraseInstFromFunction(*I); 3603 ++NumDeadInst; 3604 continue; 3605 } 3606 3607 if (!DebugCounter::shouldExecute(VisitCounter)) 3608 continue; 3609 3610 // Instruction isn't dead, see if we can constant propagate it. 3611 if (!I->use_empty() && 3612 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) { 3613 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) { 3614 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I 3615 << '\n'); 3616 3617 // Add operands to the worklist. 3618 replaceInstUsesWith(*I, C); 3619 ++NumConstProp; 3620 if (isInstructionTriviallyDead(I, &TLI)) 3621 eraseInstFromFunction(*I); 3622 MadeIRChange = true; 3623 continue; 3624 } 3625 } 3626 3627 // See if we can trivially sink this instruction to its user if we can 3628 // prove that the successor is not executed more frequently than our block. 3629 if (EnableCodeSinking) 3630 if (Use *SingleUse = I->getSingleUndroppableUse()) { 3631 BasicBlock *BB = I->getParent(); 3632 Instruction *UserInst = cast<Instruction>(SingleUse->getUser()); 3633 BasicBlock *UserParent; 3634 3635 // Get the block the use occurs in. 3636 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 3637 UserParent = PN->getIncomingBlock(*SingleUse); 3638 else 3639 UserParent = UserInst->getParent(); 3640 3641 if (UserParent != BB) { 3642 // See if the user is one of our successors that has only one 3643 // predecessor, so that we don't have to split the critical edge. 3644 bool ShouldSink = UserParent->getUniquePredecessor() == BB; 3645 // Another option where we can sink is a block that ends with a 3646 // terminator that does not pass control to other block (such as 3647 // return or unreachable). In this case: 3648 // - I dominates the User (by SSA form); 3649 // - the User will be executed at most once. 3650 // So sinking I down to User is always profitable or neutral. 3651 if (!ShouldSink) { 3652 auto *Term = UserParent->getTerminator(); 3653 ShouldSink = isa<ReturnInst>(Term) || isa<UnreachableInst>(Term); 3654 } 3655 if (ShouldSink) { 3656 assert(DT.dominates(BB, UserParent) && 3657 "Dominance relation broken?"); 3658 // Okay, the CFG is simple enough, try to sink this instruction. 3659 if (TryToSinkInstruction(I, UserParent)) { 3660 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n'); 3661 MadeIRChange = true; 3662 // We'll add uses of the sunk instruction below, but since sinking 3663 // can expose opportunities for it's *operands* add them to the 3664 // worklist 3665 for (Use &U : I->operands()) 3666 if (Instruction *OpI = dyn_cast<Instruction>(U.get())) 3667 Worklist.push(OpI); 3668 } 3669 } 3670 } 3671 } 3672 3673 // Now that we have an instruction, try combining it to simplify it. 3674 Builder.SetInsertPoint(I); 3675 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 3676 3677 #ifndef NDEBUG 3678 std::string OrigI; 3679 #endif 3680 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 3681 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n'); 3682 3683 if (Instruction *Result = visit(*I)) { 3684 ++NumCombined; 3685 // Should we replace the old instruction with a new one? 3686 if (Result != I) { 3687 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n' 3688 << " New = " << *Result << '\n'); 3689 3690 if (I->getDebugLoc()) 3691 Result->setDebugLoc(I->getDebugLoc()); 3692 // Everything uses the new instruction now. 3693 I->replaceAllUsesWith(Result); 3694 3695 // Move the name to the new instruction first. 3696 Result->takeName(I); 3697 3698 // Insert the new instruction into the basic block... 3699 BasicBlock *InstParent = I->getParent(); 3700 BasicBlock::iterator InsertPos = I->getIterator(); 3701 3702 // Are we replace a PHI with something that isn't a PHI, or vice versa? 3703 if (isa<PHINode>(Result) != isa<PHINode>(I)) { 3704 // We need to fix up the insertion point. 3705 if (isa<PHINode>(I)) // PHI -> Non-PHI 3706 InsertPos = InstParent->getFirstInsertionPt(); 3707 else // Non-PHI -> PHI 3708 InsertPos = InstParent->getFirstNonPHI()->getIterator(); 3709 } 3710 3711 InstParent->getInstList().insert(InsertPos, Result); 3712 3713 // Push the new instruction and any users onto the worklist. 3714 Worklist.pushUsersToWorkList(*Result); 3715 Worklist.push(Result); 3716 3717 eraseInstFromFunction(*I); 3718 } else { 3719 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n' 3720 << " New = " << *I << '\n'); 3721 3722 // If the instruction was modified, it's possible that it is now dead. 3723 // if so, remove it. 3724 if (isInstructionTriviallyDead(I, &TLI)) { 3725 eraseInstFromFunction(*I); 3726 } else { 3727 Worklist.pushUsersToWorkList(*I); 3728 Worklist.push(I); 3729 } 3730 } 3731 MadeIRChange = true; 3732 } 3733 } 3734 3735 Worklist.zap(); 3736 return MadeIRChange; 3737 } 3738 3739 /// Populate the IC worklist from a function, by walking it in depth-first 3740 /// order and adding all reachable code to the worklist. 3741 /// 3742 /// This has a couple of tricks to make the code faster and more powerful. In 3743 /// particular, we constant fold and DCE instructions as we go, to avoid adding 3744 /// them to the worklist (this significantly speeds up instcombine on code where 3745 /// many instructions are dead or constant). Additionally, if we find a branch 3746 /// whose condition is a known constant, we only visit the reachable successors. 3747 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL, 3748 const TargetLibraryInfo *TLI, 3749 InstCombineWorklist &ICWorklist) { 3750 bool MadeIRChange = false; 3751 SmallPtrSet<BasicBlock *, 32> Visited; 3752 SmallVector<BasicBlock*, 256> Worklist; 3753 Worklist.push_back(&F.front()); 3754 3755 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; 3756 DenseMap<Constant *, Constant *> FoldedConstants; 3757 3758 do { 3759 BasicBlock *BB = Worklist.pop_back_val(); 3760 3761 // We have now visited this block! If we've already been here, ignore it. 3762 if (!Visited.insert(BB).second) 3763 continue; 3764 3765 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 3766 Instruction *Inst = &*BBI++; 3767 3768 // ConstantProp instruction if trivially constant. 3769 if (!Inst->use_empty() && 3770 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0)))) 3771 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) { 3772 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst 3773 << '\n'); 3774 Inst->replaceAllUsesWith(C); 3775 ++NumConstProp; 3776 if (isInstructionTriviallyDead(Inst, TLI)) 3777 Inst->eraseFromParent(); 3778 MadeIRChange = true; 3779 continue; 3780 } 3781 3782 // See if we can constant fold its operands. 3783 for (Use &U : Inst->operands()) { 3784 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U)) 3785 continue; 3786 3787 auto *C = cast<Constant>(U); 3788 Constant *&FoldRes = FoldedConstants[C]; 3789 if (!FoldRes) 3790 FoldRes = ConstantFoldConstant(C, DL, TLI); 3791 3792 if (FoldRes != C) { 3793 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst 3794 << "\n Old = " << *C 3795 << "\n New = " << *FoldRes << '\n'); 3796 U = FoldRes; 3797 MadeIRChange = true; 3798 } 3799 } 3800 3801 // Skip processing debug intrinsics in InstCombine. Processing these call instructions 3802 // consumes non-trivial amount of time and provides no value for the optimization. 3803 if (!isa<DbgInfoIntrinsic>(Inst)) 3804 InstrsForInstCombineWorklist.push_back(Inst); 3805 } 3806 3807 // Recursively visit successors. If this is a branch or switch on a 3808 // constant, only visit the reachable successor. 3809 Instruction *TI = BB->getTerminator(); 3810 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 3811 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { 3812 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); 3813 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); 3814 Worklist.push_back(ReachableBB); 3815 continue; 3816 } 3817 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 3818 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 3819 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor()); 3820 continue; 3821 } 3822 } 3823 3824 for (BasicBlock *SuccBB : successors(TI)) 3825 Worklist.push_back(SuccBB); 3826 } while (!Worklist.empty()); 3827 3828 // Remove instructions inside unreachable blocks. This prevents the 3829 // instcombine code from having to deal with some bad special cases, and 3830 // reduces use counts of instructions. 3831 for (BasicBlock &BB : F) { 3832 if (Visited.count(&BB)) 3833 continue; 3834 3835 unsigned NumDeadInstInBB; 3836 unsigned NumDeadDbgInstInBB; 3837 std::tie(NumDeadInstInBB, NumDeadDbgInstInBB) = 3838 removeAllNonTerminatorAndEHPadInstructions(&BB); 3839 3840 MadeIRChange |= NumDeadInstInBB + NumDeadDbgInstInBB > 0; 3841 NumDeadInst += NumDeadInstInBB; 3842 } 3843 3844 // Once we've found all of the instructions to add to instcombine's worklist, 3845 // add them in reverse order. This way instcombine will visit from the top 3846 // of the function down. This jives well with the way that it adds all uses 3847 // of instructions to the worklist after doing a transformation, thus avoiding 3848 // some N^2 behavior in pathological cases. 3849 ICWorklist.reserve(InstrsForInstCombineWorklist.size()); 3850 for (Instruction *Inst : reverse(InstrsForInstCombineWorklist)) { 3851 // DCE instruction if trivially dead. As we iterate in reverse program 3852 // order here, we will clean up whole chains of dead instructions. 3853 if (isInstructionTriviallyDead(Inst, TLI)) { 3854 ++NumDeadInst; 3855 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n'); 3856 salvageDebugInfo(*Inst); 3857 Inst->eraseFromParent(); 3858 MadeIRChange = true; 3859 continue; 3860 } 3861 3862 ICWorklist.push(Inst); 3863 } 3864 3865 return MadeIRChange; 3866 } 3867 3868 static bool combineInstructionsOverFunction( 3869 Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, 3870 AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, 3871 DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, 3872 ProfileSummaryInfo *PSI, unsigned MaxIterations, LoopInfo *LI) { 3873 auto &DL = F.getParent()->getDataLayout(); 3874 MaxIterations = std::min(MaxIterations, LimitMaxIterations.getValue()); 3875 3876 /// Builder - This is an IRBuilder that automatically inserts new 3877 /// instructions into the worklist when they are created. 3878 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder( 3879 F.getContext(), TargetFolder(DL), 3880 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) { 3881 Worklist.add(I); 3882 if (match(I, m_Intrinsic<Intrinsic::assume>())) 3883 AC.registerAssumption(cast<CallInst>(I)); 3884 })); 3885 3886 // Lower dbg.declare intrinsics otherwise their value may be clobbered 3887 // by instcombiner. 3888 bool MadeIRChange = false; 3889 if (ShouldLowerDbgDeclare) 3890 MadeIRChange = LowerDbgDeclare(F); 3891 3892 // Iterate while there is work to do. 3893 unsigned Iteration = 0; 3894 while (true) { 3895 ++NumWorklistIterations; 3896 ++Iteration; 3897 3898 if (Iteration > InfiniteLoopDetectionThreshold) { 3899 report_fatal_error( 3900 "Instruction Combining seems stuck in an infinite loop after " + 3901 Twine(InfiniteLoopDetectionThreshold) + " iterations."); 3902 } 3903 3904 if (Iteration > MaxIterations) { 3905 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterations 3906 << " on " << F.getName() 3907 << " reached; stopping before reaching a fixpoint\n"); 3908 break; 3909 } 3910 3911 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 3912 << F.getName() << "\n"); 3913 3914 MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist); 3915 3916 InstCombinerImpl IC(Worklist, Builder, F.hasMinSize(), AA, AC, TLI, TTI, DT, 3917 ORE, BFI, PSI, DL, LI); 3918 IC.MaxArraySizeForCombine = MaxArraySize; 3919 3920 if (!IC.run()) 3921 break; 3922 3923 MadeIRChange = true; 3924 } 3925 3926 return MadeIRChange; 3927 } 3928 3929 InstCombinePass::InstCombinePass() : MaxIterations(LimitMaxIterations) {} 3930 3931 InstCombinePass::InstCombinePass(unsigned MaxIterations) 3932 : MaxIterations(MaxIterations) {} 3933 3934 PreservedAnalyses InstCombinePass::run(Function &F, 3935 FunctionAnalysisManager &AM) { 3936 auto &AC = AM.getResult<AssumptionAnalysis>(F); 3937 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 3938 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 3939 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 3940 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 3941 3942 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 3943 3944 auto *AA = &AM.getResult<AAManager>(F); 3945 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 3946 ProfileSummaryInfo *PSI = 3947 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 3948 auto *BFI = (PSI && PSI->hasProfileSummary()) ? 3949 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr; 3950 3951 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE, 3952 BFI, PSI, MaxIterations, LI)) 3953 // No changes, all analyses are preserved. 3954 return PreservedAnalyses::all(); 3955 3956 // Mark all the analyses that instcombine updates as preserved. 3957 PreservedAnalyses PA; 3958 PA.preserveSet<CFGAnalyses>(); 3959 PA.preserve<AAManager>(); 3960 PA.preserve<BasicAA>(); 3961 PA.preserve<GlobalsAA>(); 3962 return PA; 3963 } 3964 3965 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const { 3966 AU.setPreservesCFG(); 3967 AU.addRequired<AAResultsWrapperPass>(); 3968 AU.addRequired<AssumptionCacheTracker>(); 3969 AU.addRequired<TargetLibraryInfoWrapperPass>(); 3970 AU.addRequired<TargetTransformInfoWrapperPass>(); 3971 AU.addRequired<DominatorTreeWrapperPass>(); 3972 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 3973 AU.addPreserved<DominatorTreeWrapperPass>(); 3974 AU.addPreserved<AAResultsWrapperPass>(); 3975 AU.addPreserved<BasicAAWrapperPass>(); 3976 AU.addPreserved<GlobalsAAWrapperPass>(); 3977 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 3978 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU); 3979 } 3980 3981 bool InstructionCombiningPass::runOnFunction(Function &F) { 3982 if (skipFunction(F)) 3983 return false; 3984 3985 // Required analyses. 3986 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 3987 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 3988 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 3989 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 3990 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3991 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 3992 3993 // Optional analyses. 3994 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 3995 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; 3996 ProfileSummaryInfo *PSI = 3997 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 3998 BlockFrequencyInfo *BFI = 3999 (PSI && PSI->hasProfileSummary()) ? 4000 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() : 4001 nullptr; 4002 4003 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE, 4004 BFI, PSI, MaxIterations, LI); 4005 } 4006 4007 char InstructionCombiningPass::ID = 0; 4008 4009 InstructionCombiningPass::InstructionCombiningPass() 4010 : FunctionPass(ID), MaxIterations(InstCombineDefaultMaxIterations) { 4011 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); 4012 } 4013 4014 InstructionCombiningPass::InstructionCombiningPass(unsigned MaxIterations) 4015 : FunctionPass(ID), MaxIterations(MaxIterations) { 4016 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); 4017 } 4018 4019 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", 4020 "Combine redundant instructions", false, false) 4021 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 4022 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 4023 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 4024 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 4025 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 4026 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 4027 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 4028 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass) 4029 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 4030 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine", 4031 "Combine redundant instructions", false, false) 4032 4033 // Initialization Routines 4034 void llvm::initializeInstCombine(PassRegistry &Registry) { 4035 initializeInstructionCombiningPassPass(Registry); 4036 } 4037 4038 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { 4039 initializeInstructionCombiningPassPass(*unwrap(R)); 4040 } 4041 4042 FunctionPass *llvm::createInstructionCombiningPass() { 4043 return new InstructionCombiningPass(); 4044 } 4045 4046 FunctionPass *llvm::createInstructionCombiningPass(unsigned MaxIterations) { 4047 return new InstructionCombiningPass(MaxIterations); 4048 } 4049 4050 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) { 4051 unwrap(PM)->add(createInstructionCombiningPass()); 4052 } 4053