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 /// Thread a GEP operation with constant indices through the constant true/false 1807 /// arms of a select. 1808 static Instruction *foldSelectGEP(GetElementPtrInst &GEP, 1809 InstCombiner::BuilderTy &Builder) { 1810 if (!GEP.hasAllConstantIndices()) 1811 return nullptr; 1812 1813 Instruction *Sel; 1814 Value *Cond; 1815 Constant *TrueC, *FalseC; 1816 if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) || 1817 !match(Sel, 1818 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC)))) 1819 return nullptr; 1820 1821 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC' 1822 // Propagate 'inbounds' and metadata from existing instructions. 1823 // Note: using IRBuilder to create the constants for efficiency. 1824 SmallVector<Value *, 4> IndexC(GEP.idx_begin(), GEP.idx_end()); 1825 bool IsInBounds = GEP.isInBounds(); 1826 Value *NewTrueC = IsInBounds ? Builder.CreateInBoundsGEP(TrueC, IndexC) 1827 : Builder.CreateGEP(TrueC, IndexC); 1828 Value *NewFalseC = IsInBounds ? Builder.CreateInBoundsGEP(FalseC, IndexC) 1829 : Builder.CreateGEP(FalseC, IndexC); 1830 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel); 1831 } 1832 1833 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) { 1834 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end()); 1835 Type *GEPType = GEP.getType(); 1836 Type *GEPEltType = GEP.getSourceElementType(); 1837 if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP))) 1838 return replaceInstUsesWith(GEP, V); 1839 1840 // For vector geps, use the generic demanded vector support. 1841 if (GEP.getType()->isVectorTy()) { 1842 auto VWidth = GEP.getType()->getVectorNumElements(); 1843 APInt UndefElts(VWidth, 0); 1844 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1845 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask, 1846 UndefElts)) { 1847 if (V != &GEP) 1848 return replaceInstUsesWith(GEP, V); 1849 return &GEP; 1850 } 1851 1852 // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if 1853 // possible (decide on canonical form for pointer broadcast), 3) exploit 1854 // undef elements to decrease demanded bits 1855 } 1856 1857 Value *PtrOp = GEP.getOperand(0); 1858 1859 // Eliminate unneeded casts for indices, and replace indices which displace 1860 // by multiples of a zero size type with zero. 1861 bool MadeChange = false; 1862 1863 // Index width may not be the same width as pointer width. 1864 // Data layout chooses the right type based on supported integer types. 1865 Type *NewScalarIndexTy = 1866 DL.getIndexType(GEP.getPointerOperandType()->getScalarType()); 1867 1868 gep_type_iterator GTI = gep_type_begin(GEP); 1869 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E; 1870 ++I, ++GTI) { 1871 // Skip indices into struct types. 1872 if (GTI.isStruct()) 1873 continue; 1874 1875 Type *IndexTy = (*I)->getType(); 1876 Type *NewIndexType = 1877 IndexTy->isVectorTy() 1878 ? VectorType::get(NewScalarIndexTy, IndexTy->getVectorNumElements()) 1879 : NewScalarIndexTy; 1880 1881 // If the element type has zero size then any index over it is equivalent 1882 // to an index of zero, so replace it with zero if it is not zero already. 1883 Type *EltTy = GTI.getIndexedType(); 1884 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0) 1885 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) { 1886 *I = Constant::getNullValue(NewIndexType); 1887 MadeChange = true; 1888 } 1889 1890 if (IndexTy != NewIndexType) { 1891 // If we are using a wider index than needed for this platform, shrink 1892 // it to what we need. If narrower, sign-extend it to what we need. 1893 // This explicit cast can make subsequent optimizations more obvious. 1894 *I = Builder.CreateIntCast(*I, NewIndexType, true); 1895 MadeChange = true; 1896 } 1897 } 1898 if (MadeChange) 1899 return &GEP; 1900 1901 // Check to see if the inputs to the PHI node are getelementptr instructions. 1902 if (auto *PN = dyn_cast<PHINode>(PtrOp)) { 1903 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0)); 1904 if (!Op1) 1905 return nullptr; 1906 1907 // Don't fold a GEP into itself through a PHI node. This can only happen 1908 // through the back-edge of a loop. Folding a GEP into itself means that 1909 // the value of the previous iteration needs to be stored in the meantime, 1910 // thus requiring an additional register variable to be live, but not 1911 // actually achieving anything (the GEP still needs to be executed once per 1912 // loop iteration). 1913 if (Op1 == &GEP) 1914 return nullptr; 1915 1916 int DI = -1; 1917 1918 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) { 1919 auto *Op2 = dyn_cast<GetElementPtrInst>(*I); 1920 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands()) 1921 return nullptr; 1922 1923 // As for Op1 above, don't try to fold a GEP into itself. 1924 if (Op2 == &GEP) 1925 return nullptr; 1926 1927 // Keep track of the type as we walk the GEP. 1928 Type *CurTy = nullptr; 1929 1930 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) { 1931 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType()) 1932 return nullptr; 1933 1934 if (Op1->getOperand(J) != Op2->getOperand(J)) { 1935 if (DI == -1) { 1936 // We have not seen any differences yet in the GEPs feeding the 1937 // PHI yet, so we record this one if it is allowed to be a 1938 // variable. 1939 1940 // The first two arguments can vary for any GEP, the rest have to be 1941 // static for struct slots 1942 if (J > 1) { 1943 assert(CurTy && "No current type?"); 1944 if (CurTy->isStructTy()) 1945 return nullptr; 1946 } 1947 1948 DI = J; 1949 } else { 1950 // The GEP is different by more than one input. While this could be 1951 // extended to support GEPs that vary by more than one variable it 1952 // doesn't make sense since it greatly increases the complexity and 1953 // would result in an R+R+R addressing mode which no backend 1954 // directly supports and would need to be broken into several 1955 // simpler instructions anyway. 1956 return nullptr; 1957 } 1958 } 1959 1960 // Sink down a layer of the type for the next iteration. 1961 if (J > 0) { 1962 if (J == 1) { 1963 CurTy = Op1->getSourceElementType(); 1964 } else { 1965 CurTy = 1966 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J)); 1967 } 1968 } 1969 } 1970 } 1971 1972 // If not all GEPs are identical we'll have to create a new PHI node. 1973 // Check that the old PHI node has only one use so that it will get 1974 // removed. 1975 if (DI != -1 && !PN->hasOneUse()) 1976 return nullptr; 1977 1978 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone()); 1979 if (DI == -1) { 1980 // All the GEPs feeding the PHI are identical. Clone one down into our 1981 // BB so that it can be merged with the current GEP. 1982 GEP.getParent()->getInstList().insert( 1983 GEP.getParent()->getFirstInsertionPt(), NewGEP); 1984 } else { 1985 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP 1986 // into the current block so it can be merged, and create a new PHI to 1987 // set that index. 1988 PHINode *NewPN; 1989 { 1990 IRBuilderBase::InsertPointGuard Guard(Builder); 1991 Builder.SetInsertPoint(PN); 1992 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(), 1993 PN->getNumOperands()); 1994 } 1995 1996 for (auto &I : PN->operands()) 1997 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI), 1998 PN->getIncomingBlock(I)); 1999 2000 NewGEP->setOperand(DI, NewPN); 2001 GEP.getParent()->getInstList().insert( 2002 GEP.getParent()->getFirstInsertionPt(), NewGEP); 2003 NewGEP->setOperand(DI, NewPN); 2004 } 2005 2006 GEP.setOperand(0, NewGEP); 2007 PtrOp = NewGEP; 2008 } 2009 2010 // Combine Indices - If the source pointer to this getelementptr instruction 2011 // is a getelementptr instruction, combine the indices of the two 2012 // getelementptr instructions into a single instruction. 2013 if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) { 2014 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src)) 2015 return nullptr; 2016 2017 // Try to reassociate loop invariant GEP chains to enable LICM. 2018 if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 && 2019 Src->hasOneUse()) { 2020 if (Loop *L = LI->getLoopFor(GEP.getParent())) { 2021 Value *GO1 = GEP.getOperand(1); 2022 Value *SO1 = Src->getOperand(1); 2023 // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is 2024 // invariant: this breaks the dependence between GEPs and allows LICM 2025 // to hoist the invariant part out of the loop. 2026 if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) { 2027 // We have to be careful here. 2028 // We have something like: 2029 // %src = getelementptr <ty>, <ty>* %base, <ty> %idx 2030 // %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2 2031 // If we just swap idx & idx2 then we could inadvertantly 2032 // change %src from a vector to a scalar, or vice versa. 2033 // Cases: 2034 // 1) %base a scalar & idx a scalar & idx2 a vector 2035 // => Swapping idx & idx2 turns %src into a vector type. 2036 // 2) %base a scalar & idx a vector & idx2 a scalar 2037 // => Swapping idx & idx2 turns %src in a scalar type 2038 // 3) %base, %idx, and %idx2 are scalars 2039 // => %src & %gep are scalars 2040 // => swapping idx & idx2 is safe 2041 // 4) %base a vector 2042 // => %src is a vector 2043 // => swapping idx & idx2 is safe. 2044 auto *SO0 = Src->getOperand(0); 2045 auto *SO0Ty = SO0->getType(); 2046 if (!isa<VectorType>(GEPType) || // case 3 2047 isa<VectorType>(SO0Ty)) { // case 4 2048 Src->setOperand(1, GO1); 2049 GEP.setOperand(1, SO1); 2050 return &GEP; 2051 } else { 2052 // Case 1 or 2 2053 // -- have to recreate %src & %gep 2054 // put NewSrc at same location as %src 2055 Builder.SetInsertPoint(cast<Instruction>(PtrOp)); 2056 auto *NewSrc = cast<GetElementPtrInst>( 2057 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName())); 2058 NewSrc->setIsInBounds(Src->isInBounds()); 2059 auto *NewGEP = GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1}); 2060 NewGEP->setIsInBounds(GEP.isInBounds()); 2061 return NewGEP; 2062 } 2063 } 2064 } 2065 } 2066 2067 // Note that if our source is a gep chain itself then we wait for that 2068 // chain to be resolved before we perform this transformation. This 2069 // avoids us creating a TON of code in some cases. 2070 if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0))) 2071 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) 2072 return nullptr; // Wait until our source is folded to completion. 2073 2074 SmallVector<Value*, 8> Indices; 2075 2076 // Find out whether the last index in the source GEP is a sequential idx. 2077 bool EndsWithSequential = false; 2078 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 2079 I != E; ++I) 2080 EndsWithSequential = I.isSequential(); 2081 2082 // Can we combine the two pointer arithmetics offsets? 2083 if (EndsWithSequential) { 2084 // Replace: gep (gep %P, long B), long A, ... 2085 // With: T = long A+B; gep %P, T, ... 2086 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 2087 Value *GO1 = GEP.getOperand(1); 2088 2089 // If they aren't the same type, then the input hasn't been processed 2090 // by the loop above yet (which canonicalizes sequential index types to 2091 // intptr_t). Just avoid transforming this until the input has been 2092 // normalized. 2093 if (SO1->getType() != GO1->getType()) 2094 return nullptr; 2095 2096 Value *Sum = 2097 SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP)); 2098 // Only do the combine when we are sure the cost after the 2099 // merge is never more than that before the merge. 2100 if (Sum == nullptr) 2101 return nullptr; 2102 2103 // Update the GEP in place if possible. 2104 if (Src->getNumOperands() == 2) { 2105 GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))); 2106 GEP.setOperand(0, Src->getOperand(0)); 2107 GEP.setOperand(1, Sum); 2108 return &GEP; 2109 } 2110 Indices.append(Src->op_begin()+1, Src->op_end()-1); 2111 Indices.push_back(Sum); 2112 Indices.append(GEP.op_begin()+2, GEP.op_end()); 2113 } else if (isa<Constant>(*GEP.idx_begin()) && 2114 cast<Constant>(*GEP.idx_begin())->isNullValue() && 2115 Src->getNumOperands() != 1) { 2116 // Otherwise we can do the fold if the first index of the GEP is a zero 2117 Indices.append(Src->op_begin()+1, Src->op_end()); 2118 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 2119 } 2120 2121 if (!Indices.empty()) 2122 return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)) 2123 ? GetElementPtrInst::CreateInBounds( 2124 Src->getSourceElementType(), Src->getOperand(0), Indices, 2125 GEP.getName()) 2126 : GetElementPtrInst::Create(Src->getSourceElementType(), 2127 Src->getOperand(0), Indices, 2128 GEP.getName()); 2129 } 2130 2131 if (GEP.getNumIndices() == 1) { 2132 unsigned AS = GEP.getPointerAddressSpace(); 2133 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() == 2134 DL.getIndexSizeInBits(AS)) { 2135 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType); 2136 2137 bool Matched = false; 2138 uint64_t C; 2139 Value *V = nullptr; 2140 if (TyAllocSize == 1) { 2141 V = GEP.getOperand(1); 2142 Matched = true; 2143 } else if (match(GEP.getOperand(1), 2144 m_AShr(m_Value(V), m_ConstantInt(C)))) { 2145 if (TyAllocSize == 1ULL << C) 2146 Matched = true; 2147 } else if (match(GEP.getOperand(1), 2148 m_SDiv(m_Value(V), m_ConstantInt(C)))) { 2149 if (TyAllocSize == C) 2150 Matched = true; 2151 } 2152 2153 if (Matched) { 2154 // Canonicalize (gep i8* X, -(ptrtoint Y)) 2155 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y))) 2156 // The GEP pattern is emitted by the SCEV expander for certain kinds of 2157 // pointer arithmetic. 2158 if (match(V, m_Neg(m_PtrToInt(m_Value())))) { 2159 Operator *Index = cast<Operator>(V); 2160 Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType()); 2161 Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1)); 2162 return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType); 2163 } 2164 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) 2165 // to (bitcast Y) 2166 Value *Y; 2167 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)), 2168 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) 2169 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType); 2170 } 2171 } 2172 } 2173 2174 // We do not handle pointer-vector geps here. 2175 if (GEPType->isVectorTy()) 2176 return nullptr; 2177 2178 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). 2179 Value *StrippedPtr = PtrOp->stripPointerCasts(); 2180 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType()); 2181 2182 if (StrippedPtr != PtrOp) { 2183 bool HasZeroPointerIndex = false; 2184 Type *StrippedPtrEltTy = StrippedPtrTy->getElementType(); 2185 2186 if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) 2187 HasZeroPointerIndex = C->isZero(); 2188 2189 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... 2190 // into : GEP [10 x i8]* X, i32 0, ... 2191 // 2192 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... 2193 // into : GEP i8* X, ... 2194 // 2195 // This occurs when the program declares an array extern like "int X[];" 2196 if (HasZeroPointerIndex) { 2197 if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) { 2198 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? 2199 if (CATy->getElementType() == StrippedPtrEltTy) { 2200 // -> GEP i8* X, ... 2201 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); 2202 GetElementPtrInst *Res = GetElementPtrInst::Create( 2203 StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName()); 2204 Res->setIsInBounds(GEP.isInBounds()); 2205 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) 2206 return Res; 2207 // Insert Res, and create an addrspacecast. 2208 // e.g., 2209 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ... 2210 // -> 2211 // %0 = GEP i8 addrspace(1)* X, ... 2212 // addrspacecast i8 addrspace(1)* %0 to i8* 2213 return new AddrSpaceCastInst(Builder.Insert(Res), GEPType); 2214 } 2215 2216 if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) { 2217 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? 2218 if (CATy->getElementType() == XATy->getElementType()) { 2219 // -> GEP [10 x i8]* X, i32 0, ... 2220 // At this point, we know that the cast source type is a pointer 2221 // to an array of the same type as the destination pointer 2222 // array. Because the array type is never stepped over (there 2223 // is a leading zero) we can fold the cast into this GEP. 2224 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) { 2225 GEP.setOperand(0, StrippedPtr); 2226 GEP.setSourceElementType(XATy); 2227 return &GEP; 2228 } 2229 // Cannot replace the base pointer directly because StrippedPtr's 2230 // address space is different. Instead, create a new GEP followed by 2231 // an addrspacecast. 2232 // e.g., 2233 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*), 2234 // i32 0, ... 2235 // -> 2236 // %0 = GEP [10 x i8] addrspace(1)* X, ... 2237 // addrspacecast i8 addrspace(1)* %0 to i8* 2238 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end()); 2239 Value *NewGEP = 2240 GEP.isInBounds() 2241 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2242 Idx, GEP.getName()) 2243 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2244 GEP.getName()); 2245 return new AddrSpaceCastInst(NewGEP, GEPType); 2246 } 2247 } 2248 } 2249 } else if (GEP.getNumOperands() == 2) { 2250 // Transform things like: 2251 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V 2252 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast 2253 if (StrippedPtrEltTy->isArrayTy() && 2254 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) == 2255 DL.getTypeAllocSize(GEPEltType)) { 2256 Type *IdxType = DL.getIndexType(GEPType); 2257 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) }; 2258 Value *NewGEP = 2259 GEP.isInBounds() 2260 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2261 GEP.getName()) 2262 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2263 GEP.getName()); 2264 2265 // V and GEP are both pointer types --> BitCast 2266 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType); 2267 } 2268 2269 // Transform things like: 2270 // %V = mul i64 %N, 4 2271 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V 2272 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast 2273 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) { 2274 // Check that changing the type amounts to dividing the index by a scale 2275 // factor. 2276 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType); 2277 uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy); 2278 if (ResSize && SrcSize % ResSize == 0) { 2279 Value *Idx = GEP.getOperand(1); 2280 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2281 uint64_t Scale = SrcSize / ResSize; 2282 2283 // Earlier transforms ensure that the index has the right type 2284 // according to Data Layout, which considerably simplifies the 2285 // logic by eliminating implicit casts. 2286 assert(Idx->getType() == DL.getIndexType(GEPType) && 2287 "Index type does not match the Data Layout preferences"); 2288 2289 bool NSW; 2290 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2291 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2292 // If the multiplication NewIdx * Scale may overflow then the new 2293 // GEP may not be "inbounds". 2294 Value *NewGEP = 2295 GEP.isInBounds() && NSW 2296 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2297 NewIdx, GEP.getName()) 2298 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx, 2299 GEP.getName()); 2300 2301 // The NewGEP must be pointer typed, so must the old one -> BitCast 2302 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2303 GEPType); 2304 } 2305 } 2306 } 2307 2308 // Similarly, transform things like: 2309 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp 2310 // (where tmp = 8*tmp2) into: 2311 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast 2312 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() && 2313 StrippedPtrEltTy->isArrayTy()) { 2314 // Check that changing to the array element type amounts to dividing the 2315 // index by a scale factor. 2316 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType); 2317 uint64_t ArrayEltSize = 2318 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()); 2319 if (ResSize && ArrayEltSize % ResSize == 0) { 2320 Value *Idx = GEP.getOperand(1); 2321 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2322 uint64_t Scale = ArrayEltSize / ResSize; 2323 2324 // Earlier transforms ensure that the index has the right type 2325 // according to the Data Layout, which considerably simplifies 2326 // the logic by eliminating implicit casts. 2327 assert(Idx->getType() == DL.getIndexType(GEPType) && 2328 "Index type does not match the Data Layout preferences"); 2329 2330 bool NSW; 2331 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2332 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2333 // If the multiplication NewIdx * Scale may overflow then the new 2334 // GEP may not be "inbounds". 2335 Type *IndTy = DL.getIndexType(GEPType); 2336 Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx}; 2337 2338 Value *NewGEP = 2339 GEP.isInBounds() && NSW 2340 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2341 Off, GEP.getName()) 2342 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off, 2343 GEP.getName()); 2344 // The NewGEP must be pointer typed, so must the old one -> BitCast 2345 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2346 GEPType); 2347 } 2348 } 2349 } 2350 } 2351 } 2352 2353 // addrspacecast between types is canonicalized as a bitcast, then an 2354 // addrspacecast. To take advantage of the below bitcast + struct GEP, look 2355 // through the addrspacecast. 2356 Value *ASCStrippedPtrOp = PtrOp; 2357 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) { 2358 // X = bitcast A addrspace(1)* to B addrspace(1)* 2359 // Y = addrspacecast A addrspace(1)* to B addrspace(2)* 2360 // Z = gep Y, <...constant indices...> 2361 // Into an addrspacecasted GEP of the struct. 2362 if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0))) 2363 ASCStrippedPtrOp = BC; 2364 } 2365 2366 if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) { 2367 Value *SrcOp = BCI->getOperand(0); 2368 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy()); 2369 Type *SrcEltType = SrcType->getElementType(); 2370 2371 // GEP directly using the source operand if this GEP is accessing an element 2372 // of a bitcasted pointer to vector or array of the same dimensions: 2373 // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z 2374 // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z 2375 auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy, 2376 const DataLayout &DL) { 2377 return ArrTy->getArrayElementType() == VecTy->getVectorElementType() && 2378 ArrTy->getArrayNumElements() == VecTy->getVectorNumElements() && 2379 DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy); 2380 }; 2381 if (GEP.getNumOperands() == 3 && 2382 ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() && 2383 areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) || 2384 (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() && 2385 areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) { 2386 2387 // Create a new GEP here, as using `setOperand()` followed by 2388 // `setSourceElementType()` won't actually update the type of the 2389 // existing GEP Value. Causing issues if this Value is accessed when 2390 // constructing an AddrSpaceCastInst 2391 Value *NGEP = 2392 GEP.isInBounds() 2393 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}) 2394 : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}); 2395 NGEP->takeName(&GEP); 2396 2397 // Preserve GEP address space to satisfy users 2398 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2399 return new AddrSpaceCastInst(NGEP, GEPType); 2400 2401 return replaceInstUsesWith(GEP, NGEP); 2402 } 2403 2404 // See if we can simplify: 2405 // X = bitcast A* to B* 2406 // Y = gep X, <...constant indices...> 2407 // into a gep of the original struct. This is important for SROA and alias 2408 // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. 2409 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType); 2410 APInt Offset(OffsetBits, 0); 2411 if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) { 2412 // If this GEP instruction doesn't move the pointer, just replace the GEP 2413 // with a bitcast of the real input to the dest type. 2414 if (!Offset) { 2415 // If the bitcast is of an allocation, and the allocation will be 2416 // converted to match the type of the cast, don't touch this. 2417 if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) { 2418 // See if the bitcast simplifies, if so, don't nuke this GEP yet. 2419 if (Instruction *I = visitBitCast(*BCI)) { 2420 if (I != BCI) { 2421 I->takeName(BCI); 2422 BCI->getParent()->getInstList().insert(BCI->getIterator(), I); 2423 replaceInstUsesWith(*BCI, I); 2424 } 2425 return &GEP; 2426 } 2427 } 2428 2429 if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace()) 2430 return new AddrSpaceCastInst(SrcOp, GEPType); 2431 return new BitCastInst(SrcOp, GEPType); 2432 } 2433 2434 // Otherwise, if the offset is non-zero, we need to find out if there is a 2435 // field at Offset in 'A's type. If so, we can pull the cast through the 2436 // GEP. 2437 SmallVector<Value*, 8> NewIndices; 2438 if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) { 2439 Value *NGEP = 2440 GEP.isInBounds() 2441 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices) 2442 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices); 2443 2444 if (NGEP->getType() == GEPType) 2445 return replaceInstUsesWith(GEP, NGEP); 2446 NGEP->takeName(&GEP); 2447 2448 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2449 return new AddrSpaceCastInst(NGEP, GEPType); 2450 return new BitCastInst(NGEP, GEPType); 2451 } 2452 } 2453 } 2454 2455 if (!GEP.isInBounds()) { 2456 unsigned IdxWidth = 2457 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace()); 2458 APInt BasePtrOffset(IdxWidth, 0); 2459 Value *UnderlyingPtrOp = 2460 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, 2461 BasePtrOffset); 2462 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) { 2463 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) && 2464 BasePtrOffset.isNonNegative()) { 2465 APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType())); 2466 if (BasePtrOffset.ule(AllocSize)) { 2467 return GetElementPtrInst::CreateInBounds( 2468 GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1), 2469 GEP.getName()); 2470 } 2471 } 2472 } 2473 } 2474 2475 if (Instruction *R = foldSelectGEP(GEP, Builder)) 2476 return R; 2477 2478 return nullptr; 2479 } 2480 2481 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI, 2482 Instruction *AI) { 2483 if (isa<ConstantPointerNull>(V)) 2484 return true; 2485 if (auto *LI = dyn_cast<LoadInst>(V)) 2486 return isa<GlobalVariable>(LI->getPointerOperand()); 2487 // Two distinct allocations will never be equal. 2488 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking 2489 // through bitcasts of V can cause 2490 // the result statement below to be true, even when AI and V (ex: 2491 // i8* ->i32* ->i8* of AI) are the same allocations. 2492 return isAllocLikeFn(V, TLI) && V != AI; 2493 } 2494 2495 static bool isAllocSiteRemovable(Instruction *AI, 2496 SmallVectorImpl<WeakTrackingVH> &Users, 2497 const TargetLibraryInfo *TLI) { 2498 SmallVector<Instruction*, 4> Worklist; 2499 Worklist.push_back(AI); 2500 2501 do { 2502 Instruction *PI = Worklist.pop_back_val(); 2503 for (User *U : PI->users()) { 2504 Instruction *I = cast<Instruction>(U); 2505 switch (I->getOpcode()) { 2506 default: 2507 // Give up the moment we see something we can't handle. 2508 return false; 2509 2510 case Instruction::AddrSpaceCast: 2511 case Instruction::BitCast: 2512 case Instruction::GetElementPtr: 2513 Users.emplace_back(I); 2514 Worklist.push_back(I); 2515 continue; 2516 2517 case Instruction::ICmp: { 2518 ICmpInst *ICI = cast<ICmpInst>(I); 2519 // We can fold eq/ne comparisons with null to false/true, respectively. 2520 // We also fold comparisons in some conditions provided the alloc has 2521 // not escaped (see isNeverEqualToUnescapedAlloc). 2522 if (!ICI->isEquality()) 2523 return false; 2524 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0; 2525 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI)) 2526 return false; 2527 Users.emplace_back(I); 2528 continue; 2529 } 2530 2531 case Instruction::Call: 2532 // Ignore no-op and store intrinsics. 2533 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2534 switch (II->getIntrinsicID()) { 2535 default: 2536 return false; 2537 2538 case Intrinsic::memmove: 2539 case Intrinsic::memcpy: 2540 case Intrinsic::memset: { 2541 MemIntrinsic *MI = cast<MemIntrinsic>(II); 2542 if (MI->isVolatile() || MI->getRawDest() != PI) 2543 return false; 2544 LLVM_FALLTHROUGH; 2545 } 2546 case Intrinsic::invariant_start: 2547 case Intrinsic::invariant_end: 2548 case Intrinsic::lifetime_start: 2549 case Intrinsic::lifetime_end: 2550 case Intrinsic::objectsize: 2551 Users.emplace_back(I); 2552 continue; 2553 } 2554 } 2555 2556 if (isFreeCall(I, TLI)) { 2557 Users.emplace_back(I); 2558 continue; 2559 } 2560 return false; 2561 2562 case Instruction::Store: { 2563 StoreInst *SI = cast<StoreInst>(I); 2564 if (SI->isVolatile() || SI->getPointerOperand() != PI) 2565 return false; 2566 Users.emplace_back(I); 2567 continue; 2568 } 2569 } 2570 llvm_unreachable("missing a return?"); 2571 } 2572 } while (!Worklist.empty()); 2573 return true; 2574 } 2575 2576 Instruction *InstCombiner::visitAllocSite(Instruction &MI) { 2577 // If we have a malloc call which is only used in any amount of comparisons to 2578 // null and free calls, delete the calls and replace the comparisons with true 2579 // or false as appropriate. 2580 2581 // This is based on the principle that we can substitute our own allocation 2582 // function (which will never return null) rather than knowledge of the 2583 // specific function being called. In some sense this can change the permitted 2584 // outputs of a program (when we convert a malloc to an alloca, the fact that 2585 // the allocation is now on the stack is potentially visible, for example), 2586 // but we believe in a permissible manner. 2587 SmallVector<WeakTrackingVH, 64> Users; 2588 2589 // If we are removing an alloca with a dbg.declare, insert dbg.value calls 2590 // before each store. 2591 TinyPtrVector<DbgVariableIntrinsic *> DIIs; 2592 std::unique_ptr<DIBuilder> DIB; 2593 if (isa<AllocaInst>(MI)) { 2594 DIIs = FindDbgAddrUses(&MI); 2595 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false)); 2596 } 2597 2598 if (isAllocSiteRemovable(&MI, Users, &TLI)) { 2599 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2600 // Lowering all @llvm.objectsize calls first because they may 2601 // use a bitcast/GEP of the alloca we are removing. 2602 if (!Users[i]) 2603 continue; 2604 2605 Instruction *I = cast<Instruction>(&*Users[i]); 2606 2607 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2608 if (II->getIntrinsicID() == Intrinsic::objectsize) { 2609 Value *Result = 2610 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true); 2611 replaceInstUsesWith(*I, Result); 2612 eraseInstFromFunction(*I); 2613 Users[i] = nullptr; // Skip examining in the next loop. 2614 } 2615 } 2616 } 2617 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2618 if (!Users[i]) 2619 continue; 2620 2621 Instruction *I = cast<Instruction>(&*Users[i]); 2622 2623 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) { 2624 replaceInstUsesWith(*C, 2625 ConstantInt::get(Type::getInt1Ty(C->getContext()), 2626 C->isFalseWhenEqual())); 2627 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 2628 for (auto *DII : DIIs) 2629 ConvertDebugDeclareToDebugValue(DII, SI, *DIB); 2630 } else { 2631 // Casts, GEP, or anything else: we're about to delete this instruction, 2632 // so it can not have any valid uses. 2633 replaceInstUsesWith(*I, UndefValue::get(I->getType())); 2634 } 2635 eraseInstFromFunction(*I); 2636 } 2637 2638 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) { 2639 // Replace invoke with a NOP intrinsic to maintain the original CFG 2640 Module *M = II->getModule(); 2641 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing); 2642 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(), 2643 None, "", II->getParent()); 2644 } 2645 2646 for (auto *DII : DIIs) 2647 eraseInstFromFunction(*DII); 2648 2649 return eraseInstFromFunction(MI); 2650 } 2651 return nullptr; 2652 } 2653 2654 /// Move the call to free before a NULL test. 2655 /// 2656 /// Check if this free is accessed after its argument has been test 2657 /// against NULL (property 0). 2658 /// If yes, it is legal to move this call in its predecessor block. 2659 /// 2660 /// The move is performed only if the block containing the call to free 2661 /// will be removed, i.e.: 2662 /// 1. it has only one predecessor P, and P has two successors 2663 /// 2. it contains the call, noops, and an unconditional branch 2664 /// 3. its successor is the same as its predecessor's successor 2665 /// 2666 /// The profitability is out-of concern here and this function should 2667 /// be called only if the caller knows this transformation would be 2668 /// profitable (e.g., for code size). 2669 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI, 2670 const DataLayout &DL) { 2671 Value *Op = FI.getArgOperand(0); 2672 BasicBlock *FreeInstrBB = FI.getParent(); 2673 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor(); 2674 2675 // Validate part of constraint #1: Only one predecessor 2676 // FIXME: We can extend the number of predecessor, but in that case, we 2677 // would duplicate the call to free in each predecessor and it may 2678 // not be profitable even for code size. 2679 if (!PredBB) 2680 return nullptr; 2681 2682 // Validate constraint #2: Does this block contains only the call to 2683 // free, noops, and an unconditional branch? 2684 BasicBlock *SuccBB; 2685 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator(); 2686 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB))) 2687 return nullptr; 2688 2689 // If there are only 2 instructions in the block, at this point, 2690 // this is the call to free and unconditional. 2691 // If there are more than 2 instructions, check that they are noops 2692 // i.e., they won't hurt the performance of the generated code. 2693 if (FreeInstrBB->size() != 2) { 2694 for (const Instruction &Inst : *FreeInstrBB) { 2695 if (&Inst == &FI || &Inst == FreeInstrBBTerminator) 2696 continue; 2697 auto *Cast = dyn_cast<CastInst>(&Inst); 2698 if (!Cast || !Cast->isNoopCast(DL)) 2699 return nullptr; 2700 } 2701 } 2702 // Validate the rest of constraint #1 by matching on the pred branch. 2703 Instruction *TI = PredBB->getTerminator(); 2704 BasicBlock *TrueBB, *FalseBB; 2705 ICmpInst::Predicate Pred; 2706 if (!match(TI, m_Br(m_ICmp(Pred, 2707 m_CombineOr(m_Specific(Op), 2708 m_Specific(Op->stripPointerCasts())), 2709 m_Zero()), 2710 TrueBB, FalseBB))) 2711 return nullptr; 2712 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE) 2713 return nullptr; 2714 2715 // Validate constraint #3: Ensure the null case just falls through. 2716 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB)) 2717 return nullptr; 2718 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && 2719 "Broken CFG: missing edge from predecessor to successor"); 2720 2721 // At this point, we know that everything in FreeInstrBB can be moved 2722 // before TI. 2723 for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end(); 2724 It != End;) { 2725 Instruction &Instr = *It++; 2726 if (&Instr == FreeInstrBBTerminator) 2727 break; 2728 Instr.moveBefore(TI); 2729 } 2730 assert(FreeInstrBB->size() == 1 && 2731 "Only the branch instruction should remain"); 2732 return &FI; 2733 } 2734 2735 Instruction *InstCombiner::visitFree(CallInst &FI) { 2736 Value *Op = FI.getArgOperand(0); 2737 2738 // free undef -> unreachable. 2739 if (isa<UndefValue>(Op)) { 2740 // Leave a marker since we can't modify the CFG here. 2741 CreateNonTerminatorUnreachable(&FI); 2742 return eraseInstFromFunction(FI); 2743 } 2744 2745 // If we have 'free null' delete the instruction. This can happen in stl code 2746 // when lots of inlining happens. 2747 if (isa<ConstantPointerNull>(Op)) 2748 return eraseInstFromFunction(FI); 2749 2750 // If we optimize for code size, try to move the call to free before the null 2751 // test so that simplify cfg can remove the empty block and dead code 2752 // elimination the branch. I.e., helps to turn something like: 2753 // if (foo) free(foo); 2754 // into 2755 // free(foo); 2756 if (MinimizeSize) 2757 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL)) 2758 return I; 2759 2760 return nullptr; 2761 } 2762 2763 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) { 2764 if (RI.getNumOperands() == 0) // ret void 2765 return nullptr; 2766 2767 Value *ResultOp = RI.getOperand(0); 2768 Type *VTy = ResultOp->getType(); 2769 if (!VTy->isIntegerTy() || isa<Constant>(ResultOp)) 2770 return nullptr; 2771 2772 // There might be assume intrinsics dominating this return that completely 2773 // determine the value. If so, constant fold it. 2774 KnownBits Known = computeKnownBits(ResultOp, 0, &RI); 2775 if (Known.isConstant()) 2776 return replaceOperand(RI, 0, 2777 Constant::getIntegerValue(VTy, Known.getConstant())); 2778 2779 return nullptr; 2780 } 2781 2782 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { 2783 // Change br (not X), label True, label False to: br X, label False, True 2784 Value *X = nullptr; 2785 if (match(&BI, m_Br(m_Not(m_Value(X)), m_BasicBlock(), m_BasicBlock())) && 2786 !isa<Constant>(X)) { 2787 // Swap Destinations and condition... 2788 BI.swapSuccessors(); 2789 return replaceOperand(BI, 0, X); 2790 } 2791 2792 // If the condition is irrelevant, remove the use so that other 2793 // transforms on the condition become more effective. 2794 if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) && 2795 BI.getSuccessor(0) == BI.getSuccessor(1)) 2796 return replaceOperand( 2797 BI, 0, ConstantInt::getFalse(BI.getCondition()->getType())); 2798 2799 // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq. 2800 CmpInst::Predicate Pred; 2801 if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), 2802 m_BasicBlock(), m_BasicBlock())) && 2803 !isCanonicalPredicate(Pred)) { 2804 // Swap destinations and condition. 2805 CmpInst *Cond = cast<CmpInst>(BI.getCondition()); 2806 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 2807 BI.swapSuccessors(); 2808 Worklist.push(Cond); 2809 return &BI; 2810 } 2811 2812 return nullptr; 2813 } 2814 2815 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { 2816 Value *Cond = SI.getCondition(); 2817 Value *Op0; 2818 ConstantInt *AddRHS; 2819 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) { 2820 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'. 2821 for (auto Case : SI.cases()) { 2822 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS); 2823 assert(isa<ConstantInt>(NewCase) && 2824 "Result of expression should be constant"); 2825 Case.setValue(cast<ConstantInt>(NewCase)); 2826 } 2827 return replaceOperand(SI, 0, Op0); 2828 } 2829 2830 KnownBits Known = computeKnownBits(Cond, 0, &SI); 2831 unsigned LeadingKnownZeros = Known.countMinLeadingZeros(); 2832 unsigned LeadingKnownOnes = Known.countMinLeadingOnes(); 2833 2834 // Compute the number of leading bits we can ignore. 2835 // TODO: A better way to determine this would use ComputeNumSignBits(). 2836 for (auto &C : SI.cases()) { 2837 LeadingKnownZeros = std::min( 2838 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros()); 2839 LeadingKnownOnes = std::min( 2840 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes()); 2841 } 2842 2843 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes); 2844 2845 // Shrink the condition operand if the new type is smaller than the old type. 2846 // But do not shrink to a non-standard type, because backend can't generate 2847 // good code for that yet. 2848 // TODO: We can make it aggressive again after fixing PR39569. 2849 if (NewWidth > 0 && NewWidth < Known.getBitWidth() && 2850 shouldChangeType(Known.getBitWidth(), NewWidth)) { 2851 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth); 2852 Builder.SetInsertPoint(&SI); 2853 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc"); 2854 2855 for (auto Case : SI.cases()) { 2856 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth); 2857 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase)); 2858 } 2859 return replaceOperand(SI, 0, NewCond); 2860 } 2861 2862 return nullptr; 2863 } 2864 2865 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) { 2866 Value *Agg = EV.getAggregateOperand(); 2867 2868 if (!EV.hasIndices()) 2869 return replaceInstUsesWith(EV, Agg); 2870 2871 if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(), 2872 SQ.getWithInstruction(&EV))) 2873 return replaceInstUsesWith(EV, V); 2874 2875 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 2876 // We're extracting from an insertvalue instruction, compare the indices 2877 const unsigned *exti, *exte, *insi, *inse; 2878 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 2879 exte = EV.idx_end(), inse = IV->idx_end(); 2880 exti != exte && insi != inse; 2881 ++exti, ++insi) { 2882 if (*insi != *exti) 2883 // The insert and extract both reference distinctly different elements. 2884 // This means the extract is not influenced by the insert, and we can 2885 // replace the aggregate operand of the extract with the aggregate 2886 // operand of the insert. i.e., replace 2887 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 2888 // %E = extractvalue { i32, { i32 } } %I, 0 2889 // with 2890 // %E = extractvalue { i32, { i32 } } %A, 0 2891 return ExtractValueInst::Create(IV->getAggregateOperand(), 2892 EV.getIndices()); 2893 } 2894 if (exti == exte && insi == inse) 2895 // Both iterators are at the end: Index lists are identical. Replace 2896 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 2897 // %C = extractvalue { i32, { i32 } } %B, 1, 0 2898 // with "i32 42" 2899 return replaceInstUsesWith(EV, IV->getInsertedValueOperand()); 2900 if (exti == exte) { 2901 // The extract list is a prefix of the insert list. i.e. replace 2902 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 2903 // %E = extractvalue { i32, { i32 } } %I, 1 2904 // with 2905 // %X = extractvalue { i32, { i32 } } %A, 1 2906 // %E = insertvalue { i32 } %X, i32 42, 0 2907 // by switching the order of the insert and extract (though the 2908 // insertvalue should be left in, since it may have other uses). 2909 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(), 2910 EV.getIndices()); 2911 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 2912 makeArrayRef(insi, inse)); 2913 } 2914 if (insi == inse) 2915 // The insert list is a prefix of the extract list 2916 // We can simply remove the common indices from the extract and make it 2917 // operate on the inserted value instead of the insertvalue result. 2918 // i.e., replace 2919 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 2920 // %E = extractvalue { i32, { i32 } } %I, 1, 0 2921 // with 2922 // %E extractvalue { i32 } { i32 42 }, 0 2923 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 2924 makeArrayRef(exti, exte)); 2925 } 2926 if (WithOverflowInst *WO = dyn_cast<WithOverflowInst>(Agg)) { 2927 // We're extracting from an overflow intrinsic, see if we're the only user, 2928 // which allows us to simplify multiple result intrinsics to simpler 2929 // things that just get one value. 2930 if (WO->hasOneUse()) { 2931 // Check if we're grabbing only the result of a 'with overflow' intrinsic 2932 // and replace it with a traditional binary instruction. 2933 if (*EV.idx_begin() == 0) { 2934 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 2935 Value *LHS = WO->getLHS(), *RHS = WO->getRHS(); 2936 replaceInstUsesWith(*WO, UndefValue::get(WO->getType())); 2937 eraseInstFromFunction(*WO); 2938 return BinaryOperator::Create(BinOp, LHS, RHS); 2939 } 2940 2941 // If the normal result of the add is dead, and the RHS is a constant, 2942 // we can transform this into a range comparison. 2943 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 2944 if (WO->getIntrinsicID() == Intrinsic::uadd_with_overflow) 2945 if (ConstantInt *CI = dyn_cast<ConstantInt>(WO->getRHS())) 2946 return new ICmpInst(ICmpInst::ICMP_UGT, WO->getLHS(), 2947 ConstantExpr::getNot(CI)); 2948 } 2949 } 2950 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) 2951 // If the (non-volatile) load only has one use, we can rewrite this to a 2952 // load from a GEP. This reduces the size of the load. If a load is used 2953 // only by extractvalue instructions then this either must have been 2954 // optimized before, or it is a struct with padding, in which case we 2955 // don't want to do the transformation as it loses padding knowledge. 2956 if (L->isSimple() && L->hasOneUse()) { 2957 // extractvalue has integer indices, getelementptr has Value*s. Convert. 2958 SmallVector<Value*, 4> Indices; 2959 // Prefix an i32 0 since we need the first element. 2960 Indices.push_back(Builder.getInt32(0)); 2961 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); 2962 I != E; ++I) 2963 Indices.push_back(Builder.getInt32(*I)); 2964 2965 // We need to insert these at the location of the old load, not at that of 2966 // the extractvalue. 2967 Builder.SetInsertPoint(L); 2968 Value *GEP = Builder.CreateInBoundsGEP(L->getType(), 2969 L->getPointerOperand(), Indices); 2970 Instruction *NL = Builder.CreateLoad(EV.getType(), GEP); 2971 // Whatever aliasing information we had for the orignal load must also 2972 // hold for the smaller load, so propagate the annotations. 2973 AAMDNodes Nodes; 2974 L->getAAMetadata(Nodes); 2975 NL->setAAMetadata(Nodes); 2976 // Returning the load directly will cause the main loop to insert it in 2977 // the wrong spot, so use replaceInstUsesWith(). 2978 return replaceInstUsesWith(EV, NL); 2979 } 2980 // We could simplify extracts from other values. Note that nested extracts may 2981 // already be simplified implicitly by the above: extract (extract (insert) ) 2982 // will be translated into extract ( insert ( extract ) ) first and then just 2983 // the value inserted, if appropriate. Similarly for extracts from single-use 2984 // loads: extract (extract (load)) will be translated to extract (load (gep)) 2985 // and if again single-use then via load (gep (gep)) to load (gep). 2986 // However, double extracts from e.g. function arguments or return values 2987 // aren't handled yet. 2988 return nullptr; 2989 } 2990 2991 /// Return 'true' if the given typeinfo will match anything. 2992 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) { 2993 switch (Personality) { 2994 case EHPersonality::GNU_C: 2995 case EHPersonality::GNU_C_SjLj: 2996 case EHPersonality::Rust: 2997 // The GCC C EH and Rust personality only exists to support cleanups, so 2998 // it's not clear what the semantics of catch clauses are. 2999 return false; 3000 case EHPersonality::Unknown: 3001 return false; 3002 case EHPersonality::GNU_Ada: 3003 // While __gnat_all_others_value will match any Ada exception, it doesn't 3004 // match foreign exceptions (or didn't, before gcc-4.7). 3005 return false; 3006 case EHPersonality::GNU_CXX: 3007 case EHPersonality::GNU_CXX_SjLj: 3008 case EHPersonality::GNU_ObjC: 3009 case EHPersonality::MSVC_X86SEH: 3010 case EHPersonality::MSVC_Win64SEH: 3011 case EHPersonality::MSVC_CXX: 3012 case EHPersonality::CoreCLR: 3013 case EHPersonality::Wasm_CXX: 3014 return TypeInfo->isNullValue(); 3015 } 3016 llvm_unreachable("invalid enum"); 3017 } 3018 3019 static bool shorter_filter(const Value *LHS, const Value *RHS) { 3020 return 3021 cast<ArrayType>(LHS->getType())->getNumElements() 3022 < 3023 cast<ArrayType>(RHS->getType())->getNumElements(); 3024 } 3025 3026 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) { 3027 // The logic here should be correct for any real-world personality function. 3028 // However if that turns out not to be true, the offending logic can always 3029 // be conditioned on the personality function, like the catch-all logic is. 3030 EHPersonality Personality = 3031 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn()); 3032 3033 // Simplify the list of clauses, eg by removing repeated catch clauses 3034 // (these are often created by inlining). 3035 bool MakeNewInstruction = false; // If true, recreate using the following: 3036 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction; 3037 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup. 3038 3039 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already. 3040 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) { 3041 bool isLastClause = i + 1 == e; 3042 if (LI.isCatch(i)) { 3043 // A catch clause. 3044 Constant *CatchClause = LI.getClause(i); 3045 Constant *TypeInfo = CatchClause->stripPointerCasts(); 3046 3047 // If we already saw this clause, there is no point in having a second 3048 // copy of it. 3049 if (AlreadyCaught.insert(TypeInfo).second) { 3050 // This catch clause was not already seen. 3051 NewClauses.push_back(CatchClause); 3052 } else { 3053 // Repeated catch clause - drop the redundant copy. 3054 MakeNewInstruction = true; 3055 } 3056 3057 // If this is a catch-all then there is no point in keeping any following 3058 // clauses or marking the landingpad as having a cleanup. 3059 if (isCatchAll(Personality, TypeInfo)) { 3060 if (!isLastClause) 3061 MakeNewInstruction = true; 3062 CleanupFlag = false; 3063 break; 3064 } 3065 } else { 3066 // A filter clause. If any of the filter elements were already caught 3067 // then they can be dropped from the filter. It is tempting to try to 3068 // exploit the filter further by saying that any typeinfo that does not 3069 // occur in the filter can't be caught later (and thus can be dropped). 3070 // However this would be wrong, since typeinfos can match without being 3071 // equal (for example if one represents a C++ class, and the other some 3072 // class derived from it). 3073 assert(LI.isFilter(i) && "Unsupported landingpad clause!"); 3074 Constant *FilterClause = LI.getClause(i); 3075 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType()); 3076 unsigned NumTypeInfos = FilterType->getNumElements(); 3077 3078 // An empty filter catches everything, so there is no point in keeping any 3079 // following clauses or marking the landingpad as having a cleanup. By 3080 // dealing with this case here the following code is made a bit simpler. 3081 if (!NumTypeInfos) { 3082 NewClauses.push_back(FilterClause); 3083 if (!isLastClause) 3084 MakeNewInstruction = true; 3085 CleanupFlag = false; 3086 break; 3087 } 3088 3089 bool MakeNewFilter = false; // If true, make a new filter. 3090 SmallVector<Constant *, 16> NewFilterElts; // New elements. 3091 if (isa<ConstantAggregateZero>(FilterClause)) { 3092 // Not an empty filter - it contains at least one null typeinfo. 3093 assert(NumTypeInfos > 0 && "Should have handled empty filter already!"); 3094 Constant *TypeInfo = 3095 Constant::getNullValue(FilterType->getElementType()); 3096 // If this typeinfo is a catch-all then the filter can never match. 3097 if (isCatchAll(Personality, TypeInfo)) { 3098 // Throw the filter away. 3099 MakeNewInstruction = true; 3100 continue; 3101 } 3102 3103 // There is no point in having multiple copies of this typeinfo, so 3104 // discard all but the first copy if there is more than one. 3105 NewFilterElts.push_back(TypeInfo); 3106 if (NumTypeInfos > 1) 3107 MakeNewFilter = true; 3108 } else { 3109 ConstantArray *Filter = cast<ConstantArray>(FilterClause); 3110 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements. 3111 NewFilterElts.reserve(NumTypeInfos); 3112 3113 // Remove any filter elements that were already caught or that already 3114 // occurred in the filter. While there, see if any of the elements are 3115 // catch-alls. If so, the filter can be discarded. 3116 bool SawCatchAll = false; 3117 for (unsigned j = 0; j != NumTypeInfos; ++j) { 3118 Constant *Elt = Filter->getOperand(j); 3119 Constant *TypeInfo = Elt->stripPointerCasts(); 3120 if (isCatchAll(Personality, TypeInfo)) { 3121 // This element is a catch-all. Bail out, noting this fact. 3122 SawCatchAll = true; 3123 break; 3124 } 3125 3126 // Even if we've seen a type in a catch clause, we don't want to 3127 // remove it from the filter. An unexpected type handler may be 3128 // set up for a call site which throws an exception of the same 3129 // type caught. In order for the exception thrown by the unexpected 3130 // handler to propagate correctly, the filter must be correctly 3131 // described for the call site. 3132 // 3133 // Example: 3134 // 3135 // void unexpected() { throw 1;} 3136 // void foo() throw (int) { 3137 // std::set_unexpected(unexpected); 3138 // try { 3139 // throw 2.0; 3140 // } catch (int i) {} 3141 // } 3142 3143 // There is no point in having multiple copies of the same typeinfo in 3144 // a filter, so only add it if we didn't already. 3145 if (SeenInFilter.insert(TypeInfo).second) 3146 NewFilterElts.push_back(cast<Constant>(Elt)); 3147 } 3148 // A filter containing a catch-all cannot match anything by definition. 3149 if (SawCatchAll) { 3150 // Throw the filter away. 3151 MakeNewInstruction = true; 3152 continue; 3153 } 3154 3155 // If we dropped something from the filter, make a new one. 3156 if (NewFilterElts.size() < NumTypeInfos) 3157 MakeNewFilter = true; 3158 } 3159 if (MakeNewFilter) { 3160 FilterType = ArrayType::get(FilterType->getElementType(), 3161 NewFilterElts.size()); 3162 FilterClause = ConstantArray::get(FilterType, NewFilterElts); 3163 MakeNewInstruction = true; 3164 } 3165 3166 NewClauses.push_back(FilterClause); 3167 3168 // If the new filter is empty then it will catch everything so there is 3169 // no point in keeping any following clauses or marking the landingpad 3170 // as having a cleanup. The case of the original filter being empty was 3171 // already handled above. 3172 if (MakeNewFilter && !NewFilterElts.size()) { 3173 assert(MakeNewInstruction && "New filter but not a new instruction!"); 3174 CleanupFlag = false; 3175 break; 3176 } 3177 } 3178 } 3179 3180 // If several filters occur in a row then reorder them so that the shortest 3181 // filters come first (those with the smallest number of elements). This is 3182 // advantageous because shorter filters are more likely to match, speeding up 3183 // unwinding, but mostly because it increases the effectiveness of the other 3184 // filter optimizations below. 3185 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) { 3186 unsigned j; 3187 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters. 3188 for (j = i; j != e; ++j) 3189 if (!isa<ArrayType>(NewClauses[j]->getType())) 3190 break; 3191 3192 // Check whether the filters are already sorted by length. We need to know 3193 // if sorting them is actually going to do anything so that we only make a 3194 // new landingpad instruction if it does. 3195 for (unsigned k = i; k + 1 < j; ++k) 3196 if (shorter_filter(NewClauses[k+1], NewClauses[k])) { 3197 // Not sorted, so sort the filters now. Doing an unstable sort would be 3198 // correct too but reordering filters pointlessly might confuse users. 3199 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j, 3200 shorter_filter); 3201 MakeNewInstruction = true; 3202 break; 3203 } 3204 3205 // Look for the next batch of filters. 3206 i = j + 1; 3207 } 3208 3209 // If typeinfos matched if and only if equal, then the elements of a filter L 3210 // that occurs later than a filter F could be replaced by the intersection of 3211 // the elements of F and L. In reality two typeinfos can match without being 3212 // equal (for example if one represents a C++ class, and the other some class 3213 // derived from it) so it would be wrong to perform this transform in general. 3214 // However the transform is correct and useful if F is a subset of L. In that 3215 // case L can be replaced by F, and thus removed altogether since repeating a 3216 // filter is pointless. So here we look at all pairs of filters F and L where 3217 // L follows F in the list of clauses, and remove L if every element of F is 3218 // an element of L. This can occur when inlining C++ functions with exception 3219 // specifications. 3220 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) { 3221 // Examine each filter in turn. 3222 Value *Filter = NewClauses[i]; 3223 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType()); 3224 if (!FTy) 3225 // Not a filter - skip it. 3226 continue; 3227 unsigned FElts = FTy->getNumElements(); 3228 // Examine each filter following this one. Doing this backwards means that 3229 // we don't have to worry about filters disappearing under us when removed. 3230 for (unsigned j = NewClauses.size() - 1; j != i; --j) { 3231 Value *LFilter = NewClauses[j]; 3232 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType()); 3233 if (!LTy) 3234 // Not a filter - skip it. 3235 continue; 3236 // If Filter is a subset of LFilter, i.e. every element of Filter is also 3237 // an element of LFilter, then discard LFilter. 3238 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j; 3239 // If Filter is empty then it is a subset of LFilter. 3240 if (!FElts) { 3241 // Discard LFilter. 3242 NewClauses.erase(J); 3243 MakeNewInstruction = true; 3244 // Move on to the next filter. 3245 continue; 3246 } 3247 unsigned LElts = LTy->getNumElements(); 3248 // If Filter is longer than LFilter then it cannot be a subset of it. 3249 if (FElts > LElts) 3250 // Move on to the next filter. 3251 continue; 3252 // At this point we know that LFilter has at least one element. 3253 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros. 3254 // Filter is a subset of LFilter iff Filter contains only zeros (as we 3255 // already know that Filter is not longer than LFilter). 3256 if (isa<ConstantAggregateZero>(Filter)) { 3257 assert(FElts <= LElts && "Should have handled this case earlier!"); 3258 // Discard LFilter. 3259 NewClauses.erase(J); 3260 MakeNewInstruction = true; 3261 } 3262 // Move on to the next filter. 3263 continue; 3264 } 3265 ConstantArray *LArray = cast<ConstantArray>(LFilter); 3266 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros. 3267 // Since Filter is non-empty and contains only zeros, it is a subset of 3268 // LFilter iff LFilter contains a zero. 3269 assert(FElts > 0 && "Should have eliminated the empty filter earlier!"); 3270 for (unsigned l = 0; l != LElts; ++l) 3271 if (LArray->getOperand(l)->isNullValue()) { 3272 // LFilter contains a zero - discard it. 3273 NewClauses.erase(J); 3274 MakeNewInstruction = true; 3275 break; 3276 } 3277 // Move on to the next filter. 3278 continue; 3279 } 3280 // At this point we know that both filters are ConstantArrays. Loop over 3281 // operands to see whether every element of Filter is also an element of 3282 // LFilter. Since filters tend to be short this is probably faster than 3283 // using a method that scales nicely. 3284 ConstantArray *FArray = cast<ConstantArray>(Filter); 3285 bool AllFound = true; 3286 for (unsigned f = 0; f != FElts; ++f) { 3287 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts(); 3288 AllFound = false; 3289 for (unsigned l = 0; l != LElts; ++l) { 3290 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts(); 3291 if (LTypeInfo == FTypeInfo) { 3292 AllFound = true; 3293 break; 3294 } 3295 } 3296 if (!AllFound) 3297 break; 3298 } 3299 if (AllFound) { 3300 // Discard LFilter. 3301 NewClauses.erase(J); 3302 MakeNewInstruction = true; 3303 } 3304 // Move on to the next filter. 3305 } 3306 } 3307 3308 // If we changed any of the clauses, replace the old landingpad instruction 3309 // with a new one. 3310 if (MakeNewInstruction) { 3311 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(), 3312 NewClauses.size()); 3313 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i) 3314 NLI->addClause(NewClauses[i]); 3315 // A landing pad with no clauses must have the cleanup flag set. It is 3316 // theoretically possible, though highly unlikely, that we eliminated all 3317 // clauses. If so, force the cleanup flag to true. 3318 if (NewClauses.empty()) 3319 CleanupFlag = true; 3320 NLI->setCleanup(CleanupFlag); 3321 return NLI; 3322 } 3323 3324 // Even if none of the clauses changed, we may nonetheless have understood 3325 // that the cleanup flag is pointless. Clear it if so. 3326 if (LI.isCleanup() != CleanupFlag) { 3327 assert(!CleanupFlag && "Adding a cleanup, not removing one?!"); 3328 LI.setCleanup(CleanupFlag); 3329 return &LI; 3330 } 3331 3332 return nullptr; 3333 } 3334 3335 Instruction *InstCombiner::visitFreeze(FreezeInst &I) { 3336 Value *Op0 = I.getOperand(0); 3337 3338 if (Value *V = SimplifyFreezeInst(Op0, SQ.getWithInstruction(&I))) 3339 return replaceInstUsesWith(I, V); 3340 3341 return nullptr; 3342 } 3343 3344 /// Try to move the specified instruction from its current block into the 3345 /// beginning of DestBlock, which can only happen if it's safe to move the 3346 /// instruction past all of the instructions between it and the end of its 3347 /// block. 3348 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 3349 assert(I->hasOneUse() && "Invariants didn't hold!"); 3350 BasicBlock *SrcBlock = I->getParent(); 3351 3352 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 3353 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() || 3354 I->isTerminator()) 3355 return false; 3356 3357 // Do not sink static or dynamic alloca instructions. Static allocas must 3358 // remain in the entry block, and dynamic allocas must not be sunk in between 3359 // a stacksave / stackrestore pair, which would incorrectly shorten its 3360 // lifetime. 3361 if (isa<AllocaInst>(I)) 3362 return false; 3363 3364 // Do not sink into catchswitch blocks. 3365 if (isa<CatchSwitchInst>(DestBlock->getTerminator())) 3366 return false; 3367 3368 // Do not sink convergent call instructions. 3369 if (auto *CI = dyn_cast<CallInst>(I)) { 3370 if (CI->isConvergent()) 3371 return false; 3372 } 3373 // We can only sink load instructions if there is nothing between the load and 3374 // the end of block that could change the value. 3375 if (I->mayReadFromMemory()) { 3376 for (BasicBlock::iterator Scan = I->getIterator(), 3377 E = I->getParent()->end(); 3378 Scan != E; ++Scan) 3379 if (Scan->mayWriteToMemory()) 3380 return false; 3381 } 3382 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); 3383 I->moveBefore(&*InsertPos); 3384 ++NumSunkInst; 3385 3386 // Also sink all related debug uses from the source basic block. Otherwise we 3387 // get debug use before the def. Attempt to salvage debug uses first, to 3388 // maximise the range variables have location for. If we cannot salvage, then 3389 // mark the location undef: we know it was supposed to receive a new location 3390 // here, but that computation has been sunk. 3391 SmallVector<DbgVariableIntrinsic *, 2> DbgUsers; 3392 findDbgUsers(DbgUsers, I); 3393 for (auto *DII : reverse(DbgUsers)) { 3394 if (DII->getParent() == SrcBlock) { 3395 if (isa<DbgDeclareInst>(DII)) { 3396 // A dbg.declare instruction should not be cloned, since there can only be 3397 // one per variable fragment. It should be left in the original place since 3398 // sunk instruction is not an alloca(otherwise we could not be here). 3399 // But we need to update arguments of dbg.declare instruction, so that it 3400 // would not point into sunk instruction. 3401 if (!isa<CastInst>(I)) 3402 continue; // dbg.declare points at something it shouldn't 3403 3404 DII->setOperand( 3405 0, MetadataAsValue::get(I->getContext(), 3406 ValueAsMetadata::get(I->getOperand(0)))); 3407 continue; 3408 } 3409 3410 // dbg.value is in the same basic block as the sunk inst, see if we can 3411 // salvage it. Clone a new copy of the instruction: on success we need 3412 // both salvaged and unsalvaged copies. 3413 SmallVector<DbgVariableIntrinsic *, 1> TmpUser{ 3414 cast<DbgVariableIntrinsic>(DII->clone())}; 3415 3416 if (!salvageDebugInfoForDbgValues(*I, TmpUser)) { 3417 // We are unable to salvage: sink the cloned dbg.value, and mark the 3418 // original as undef, terminating any earlier variable location. 3419 LLVM_DEBUG(dbgs() << "SINK: " << *DII << '\n'); 3420 TmpUser[0]->insertBefore(&*InsertPos); 3421 Value *Undef = UndefValue::get(I->getType()); 3422 DII->setOperand(0, MetadataAsValue::get(DII->getContext(), 3423 ValueAsMetadata::get(Undef))); 3424 } else { 3425 // We successfully salvaged: place the salvaged dbg.value in the 3426 // original location, and move the unmodified dbg.value to sink with 3427 // the sunk inst. 3428 TmpUser[0]->insertBefore(DII); 3429 DII->moveBefore(&*InsertPos); 3430 } 3431 } 3432 } 3433 return true; 3434 } 3435 3436 bool InstCombiner::run() { 3437 while (!Worklist.isEmpty()) { 3438 // Walk deferred instructions in reverse order, and push them to the 3439 // worklist, which means they'll end up popped from the worklist in-order. 3440 while (Instruction *I = Worklist.popDeferred()) { 3441 // Check to see if we can DCE the instruction. We do this already here to 3442 // reduce the number of uses and thus allow other folds to trigger. 3443 // Note that eraseInstFromFunction() may push additional instructions on 3444 // the deferred worklist, so this will DCE whole instruction chains. 3445 if (isInstructionTriviallyDead(I, &TLI)) { 3446 eraseInstFromFunction(*I); 3447 ++NumDeadInst; 3448 continue; 3449 } 3450 3451 Worklist.push(I); 3452 } 3453 3454 Instruction *I = Worklist.removeOne(); 3455 if (I == nullptr) continue; // skip null values. 3456 3457 // Check to see if we can DCE the instruction. 3458 if (isInstructionTriviallyDead(I, &TLI)) { 3459 eraseInstFromFunction(*I); 3460 ++NumDeadInst; 3461 continue; 3462 } 3463 3464 if (!DebugCounter::shouldExecute(VisitCounter)) 3465 continue; 3466 3467 // Instruction isn't dead, see if we can constant propagate it. 3468 if (!I->use_empty() && 3469 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) { 3470 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) { 3471 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I 3472 << '\n'); 3473 3474 // Add operands to the worklist. 3475 replaceInstUsesWith(*I, C); 3476 ++NumConstProp; 3477 if (isInstructionTriviallyDead(I, &TLI)) 3478 eraseInstFromFunction(*I); 3479 MadeIRChange = true; 3480 continue; 3481 } 3482 } 3483 3484 // In general, it is possible for computeKnownBits to determine all bits in 3485 // a value even when the operands are not all constants. 3486 Type *Ty = I->getType(); 3487 if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) { 3488 KnownBits Known = computeKnownBits(I, /*Depth*/0, I); 3489 if (Known.isConstant()) { 3490 Constant *C = ConstantInt::get(Ty, Known.getConstant()); 3491 LLVM_DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C 3492 << " from: " << *I << '\n'); 3493 3494 // Add operands to the worklist. 3495 replaceInstUsesWith(*I, C); 3496 ++NumConstProp; 3497 if (isInstructionTriviallyDead(I, &TLI)) 3498 eraseInstFromFunction(*I); 3499 MadeIRChange = true; 3500 continue; 3501 } 3502 } 3503 3504 // See if we can trivially sink this instruction to a successor basic block. 3505 if (EnableCodeSinking && I->hasOneUse()) { 3506 BasicBlock *BB = I->getParent(); 3507 Instruction *UserInst = cast<Instruction>(*I->user_begin()); 3508 BasicBlock *UserParent; 3509 3510 // Get the block the use occurs in. 3511 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 3512 UserParent = PN->getIncomingBlock(*I->use_begin()); 3513 else 3514 UserParent = UserInst->getParent(); 3515 3516 if (UserParent != BB) { 3517 bool UserIsSuccessor = false; 3518 // See if the user is one of our successors. 3519 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) 3520 if (*SI == UserParent) { 3521 UserIsSuccessor = true; 3522 break; 3523 } 3524 3525 // If the user is one of our immediate successors, and if that successor 3526 // only has us as a predecessors (we'd have to split the critical edge 3527 // otherwise), we can keep going. 3528 if (UserIsSuccessor && UserParent->getUniquePredecessor()) { 3529 // Okay, the CFG is simple enough, try to sink this instruction. 3530 if (TryToSinkInstruction(I, UserParent)) { 3531 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n'); 3532 MadeIRChange = true; 3533 // We'll add uses of the sunk instruction below, but since sinking 3534 // can expose opportunities for it's *operands* add them to the 3535 // worklist 3536 for (Use &U : I->operands()) 3537 if (Instruction *OpI = dyn_cast<Instruction>(U.get())) 3538 Worklist.push(OpI); 3539 } 3540 } 3541 } 3542 } 3543 3544 // Now that we have an instruction, try combining it to simplify it. 3545 Builder.SetInsertPoint(I); 3546 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 3547 3548 #ifndef NDEBUG 3549 std::string OrigI; 3550 #endif 3551 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 3552 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n'); 3553 3554 if (Instruction *Result = visit(*I)) { 3555 ++NumCombined; 3556 // Should we replace the old instruction with a new one? 3557 if (Result != I) { 3558 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n' 3559 << " New = " << *Result << '\n'); 3560 3561 if (I->getDebugLoc()) 3562 Result->setDebugLoc(I->getDebugLoc()); 3563 // Everything uses the new instruction now. 3564 I->replaceAllUsesWith(Result); 3565 3566 // Move the name to the new instruction first. 3567 Result->takeName(I); 3568 3569 // Insert the new instruction into the basic block... 3570 BasicBlock *InstParent = I->getParent(); 3571 BasicBlock::iterator InsertPos = I->getIterator(); 3572 3573 // If we replace a PHI with something that isn't a PHI, fix up the 3574 // insertion point. 3575 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos)) 3576 InsertPos = InstParent->getFirstInsertionPt(); 3577 3578 InstParent->getInstList().insert(InsertPos, Result); 3579 3580 // Push the new instruction and any users onto the worklist. 3581 Worklist.pushUsersToWorkList(*Result); 3582 Worklist.push(Result); 3583 3584 eraseInstFromFunction(*I); 3585 } else { 3586 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n' 3587 << " New = " << *I << '\n'); 3588 3589 // If the instruction was modified, it's possible that it is now dead. 3590 // if so, remove it. 3591 if (isInstructionTriviallyDead(I, &TLI)) { 3592 eraseInstFromFunction(*I); 3593 } else { 3594 Worklist.pushUsersToWorkList(*I); 3595 Worklist.push(I); 3596 } 3597 } 3598 MadeIRChange = true; 3599 } 3600 } 3601 3602 Worklist.zap(); 3603 return MadeIRChange; 3604 } 3605 3606 /// Walk the function in depth-first order, adding all reachable code to the 3607 /// worklist. 3608 /// 3609 /// This has a couple of tricks to make the code faster and more powerful. In 3610 /// particular, we constant fold and DCE instructions as we go, to avoid adding 3611 /// them to the worklist (this significantly speeds up instcombine on code where 3612 /// many instructions are dead or constant). Additionally, if we find a branch 3613 /// whose condition is a known constant, we only visit the reachable successors. 3614 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL, 3615 SmallPtrSetImpl<BasicBlock *> &Visited, 3616 InstCombineWorklist &ICWorklist, 3617 const TargetLibraryInfo *TLI) { 3618 bool MadeIRChange = false; 3619 SmallVector<BasicBlock*, 256> Worklist; 3620 Worklist.push_back(BB); 3621 3622 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; 3623 DenseMap<Constant *, Constant *> FoldedConstants; 3624 3625 do { 3626 BB = Worklist.pop_back_val(); 3627 3628 // We have now visited this block! If we've already been here, ignore it. 3629 if (!Visited.insert(BB).second) 3630 continue; 3631 3632 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 3633 Instruction *Inst = &*BBI++; 3634 3635 // ConstantProp instruction if trivially constant. 3636 if (!Inst->use_empty() && 3637 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0)))) 3638 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) { 3639 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst 3640 << '\n'); 3641 Inst->replaceAllUsesWith(C); 3642 ++NumConstProp; 3643 if (isInstructionTriviallyDead(Inst, TLI)) 3644 Inst->eraseFromParent(); 3645 MadeIRChange = true; 3646 continue; 3647 } 3648 3649 // See if we can constant fold its operands. 3650 for (Use &U : Inst->operands()) { 3651 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U)) 3652 continue; 3653 3654 auto *C = cast<Constant>(U); 3655 Constant *&FoldRes = FoldedConstants[C]; 3656 if (!FoldRes) 3657 FoldRes = ConstantFoldConstant(C, DL, TLI); 3658 3659 if (FoldRes != C) { 3660 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst 3661 << "\n Old = " << *C 3662 << "\n New = " << *FoldRes << '\n'); 3663 U = FoldRes; 3664 MadeIRChange = true; 3665 } 3666 } 3667 3668 // Skip processing debug intrinsics in InstCombine. Processing these call instructions 3669 // consumes non-trivial amount of time and provides no value for the optimization. 3670 if (!isa<DbgInfoIntrinsic>(Inst)) 3671 InstrsForInstCombineWorklist.push_back(Inst); 3672 } 3673 3674 // Recursively visit successors. If this is a branch or switch on a 3675 // constant, only visit the reachable successor. 3676 Instruction *TI = BB->getTerminator(); 3677 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 3678 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { 3679 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); 3680 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); 3681 Worklist.push_back(ReachableBB); 3682 continue; 3683 } 3684 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 3685 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 3686 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor()); 3687 continue; 3688 } 3689 } 3690 3691 for (BasicBlock *SuccBB : successors(TI)) 3692 Worklist.push_back(SuccBB); 3693 } while (!Worklist.empty()); 3694 3695 // Once we've found all of the instructions to add to instcombine's worklist, 3696 // add them in reverse order. This way instcombine will visit from the top 3697 // of the function down. This jives well with the way that it adds all uses 3698 // of instructions to the worklist after doing a transformation, thus avoiding 3699 // some N^2 behavior in pathological cases. 3700 ICWorklist.reserve(InstrsForInstCombineWorklist.size()); 3701 for (Instruction *Inst : reverse(InstrsForInstCombineWorklist)) { 3702 // DCE instruction if trivially dead. As we iterate in reverse program 3703 // order here, we will clean up whole chains of dead instructions. 3704 if (isInstructionTriviallyDead(Inst, TLI)) { 3705 ++NumDeadInst; 3706 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n'); 3707 salvageDebugInfoOrMarkUndef(*Inst); 3708 Inst->eraseFromParent(); 3709 MadeIRChange = true; 3710 continue; 3711 } 3712 3713 ICWorklist.push(Inst); 3714 } 3715 3716 return MadeIRChange; 3717 } 3718 3719 /// Populate the IC worklist from a function, and prune any dead basic 3720 /// blocks discovered in the process. 3721 /// 3722 /// This also does basic constant propagation and other forward fixing to make 3723 /// the combiner itself run much faster. 3724 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL, 3725 TargetLibraryInfo *TLI, 3726 InstCombineWorklist &ICWorklist) { 3727 bool MadeIRChange = false; 3728 3729 // Do a depth-first traversal of the function, populate the worklist with 3730 // the reachable instructions. Ignore blocks that are not reachable. Keep 3731 // track of which blocks we visit. 3732 SmallPtrSet<BasicBlock *, 32> Visited; 3733 MadeIRChange |= 3734 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI); 3735 3736 // Do a quick scan over the function. If we find any blocks that are 3737 // unreachable, remove any instructions inside of them. This prevents 3738 // the instcombine code from having to deal with some bad special cases. 3739 for (BasicBlock &BB : F) { 3740 if (Visited.count(&BB)) 3741 continue; 3742 3743 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB); 3744 MadeIRChange |= NumDeadInstInBB > 0; 3745 NumDeadInst += NumDeadInstInBB; 3746 } 3747 3748 return MadeIRChange; 3749 } 3750 3751 static bool combineInstructionsOverFunction( 3752 Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, 3753 AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT, 3754 OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, 3755 ProfileSummaryInfo *PSI, bool ExpensiveCombines, unsigned MaxIterations, 3756 LoopInfo *LI) { 3757 auto &DL = F.getParent()->getDataLayout(); 3758 if (EnableExpensiveCombines.getNumOccurrences()) 3759 ExpensiveCombines = EnableExpensiveCombines; 3760 MaxIterations = std::min(MaxIterations, LimitMaxIterations.getValue()); 3761 3762 /// Builder - This is an IRBuilder that automatically inserts new 3763 /// instructions into the worklist when they are created. 3764 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder( 3765 F.getContext(), TargetFolder(DL), 3766 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) { 3767 Worklist.add(I); 3768 if (match(I, m_Intrinsic<Intrinsic::assume>())) 3769 AC.registerAssumption(cast<CallInst>(I)); 3770 })); 3771 3772 // Lower dbg.declare intrinsics otherwise their value may be clobbered 3773 // by instcombiner. 3774 bool MadeIRChange = false; 3775 if (ShouldLowerDbgDeclare) 3776 MadeIRChange = LowerDbgDeclare(F); 3777 3778 // Iterate while there is work to do. 3779 unsigned Iteration = 0; 3780 while (true) { 3781 ++Iteration; 3782 3783 if (Iteration > InfiniteLoopDetectionThreshold) { 3784 report_fatal_error( 3785 "Instruction Combining seems stuck in an infinite loop after " + 3786 Twine(InfiniteLoopDetectionThreshold) + " iterations."); 3787 } 3788 3789 if (Iteration > MaxIterations) { 3790 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterations 3791 << " on " << F.getName() 3792 << " reached; stopping before reaching a fixpoint\n"); 3793 break; 3794 } 3795 3796 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 3797 << F.getName() << "\n"); 3798 3799 MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist); 3800 3801 InstCombiner IC(Worklist, Builder, F.hasMinSize(), ExpensiveCombines, AA, 3802 AC, TLI, DT, ORE, BFI, PSI, DL, LI); 3803 IC.MaxArraySizeForCombine = MaxArraySize; 3804 3805 if (!IC.run()) 3806 break; 3807 3808 MadeIRChange = true; 3809 } 3810 3811 return MadeIRChange; 3812 } 3813 3814 InstCombinePass::InstCombinePass(bool ExpensiveCombines) 3815 : ExpensiveCombines(ExpensiveCombines), MaxIterations(LimitMaxIterations) {} 3816 3817 InstCombinePass::InstCombinePass(bool ExpensiveCombines, unsigned MaxIterations) 3818 : ExpensiveCombines(ExpensiveCombines), MaxIterations(MaxIterations) {} 3819 3820 PreservedAnalyses InstCombinePass::run(Function &F, 3821 FunctionAnalysisManager &AM) { 3822 auto &AC = AM.getResult<AssumptionAnalysis>(F); 3823 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 3824 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 3825 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 3826 3827 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 3828 3829 auto *AA = &AM.getResult<AAManager>(F); 3830 const ModuleAnalysisManager &MAM = 3831 AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager(); 3832 ProfileSummaryInfo *PSI = 3833 MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 3834 auto *BFI = (PSI && PSI->hasProfileSummary()) ? 3835 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr; 3836 3837 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, BFI, 3838 PSI, ExpensiveCombines, MaxIterations, 3839 LI)) 3840 // No changes, all analyses are preserved. 3841 return PreservedAnalyses::all(); 3842 3843 // Mark all the analyses that instcombine updates as preserved. 3844 PreservedAnalyses PA; 3845 PA.preserveSet<CFGAnalyses>(); 3846 PA.preserve<AAManager>(); 3847 PA.preserve<BasicAA>(); 3848 PA.preserve<GlobalsAA>(); 3849 return PA; 3850 } 3851 3852 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const { 3853 AU.setPreservesCFG(); 3854 AU.addRequired<AAResultsWrapperPass>(); 3855 AU.addRequired<AssumptionCacheTracker>(); 3856 AU.addRequired<TargetLibraryInfoWrapperPass>(); 3857 AU.addRequired<DominatorTreeWrapperPass>(); 3858 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 3859 AU.addPreserved<DominatorTreeWrapperPass>(); 3860 AU.addPreserved<AAResultsWrapperPass>(); 3861 AU.addPreserved<BasicAAWrapperPass>(); 3862 AU.addPreserved<GlobalsAAWrapperPass>(); 3863 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 3864 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU); 3865 } 3866 3867 bool InstructionCombiningPass::runOnFunction(Function &F) { 3868 if (skipFunction(F)) 3869 return false; 3870 3871 // Required analyses. 3872 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 3873 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 3874 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 3875 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3876 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 3877 3878 // Optional analyses. 3879 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 3880 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; 3881 ProfileSummaryInfo *PSI = 3882 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 3883 BlockFrequencyInfo *BFI = 3884 (PSI && PSI->hasProfileSummary()) ? 3885 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() : 3886 nullptr; 3887 3888 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, BFI, 3889 PSI, ExpensiveCombines, MaxIterations, 3890 LI); 3891 } 3892 3893 char InstructionCombiningPass::ID = 0; 3894 3895 InstructionCombiningPass::InstructionCombiningPass(bool ExpensiveCombines) 3896 : FunctionPass(ID), ExpensiveCombines(ExpensiveCombines), 3897 MaxIterations(InstCombineDefaultMaxIterations) { 3898 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); 3899 } 3900 3901 InstructionCombiningPass::InstructionCombiningPass(bool ExpensiveCombines, 3902 unsigned MaxIterations) 3903 : FunctionPass(ID), ExpensiveCombines(ExpensiveCombines), 3904 MaxIterations(MaxIterations) { 3905 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); 3906 } 3907 3908 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", 3909 "Combine redundant instructions", false, false) 3910 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 3911 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 3912 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 3913 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 3914 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 3915 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 3916 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass) 3917 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 3918 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine", 3919 "Combine redundant instructions", false, false) 3920 3921 // Initialization Routines 3922 void llvm::initializeInstCombine(PassRegistry &Registry) { 3923 initializeInstructionCombiningPassPass(Registry); 3924 } 3925 3926 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { 3927 initializeInstructionCombiningPassPass(*unwrap(R)); 3928 } 3929 3930 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) { 3931 return new InstructionCombiningPass(ExpensiveCombines); 3932 } 3933 3934 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines, 3935 unsigned MaxIterations) { 3936 return new InstructionCombiningPass(ExpensiveCombines, MaxIterations); 3937 } 3938 3939 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) { 3940 unwrap(PM)->add(createInstructionCombiningPass()); 3941 } 3942