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