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