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