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