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