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