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