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