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