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 // We have to be careful here. 1684 // We have something like: 1685 // %src = getelementptr <ty>, <ty>* %base, <ty> %idx 1686 // %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2 1687 // If we just swap idx & idx2 then we could inadvertantly 1688 // change %src from a vector to a scalar, or vice versa. 1689 // Cases: 1690 // 1) %base a scalar & idx a scalar & idx2 a vector 1691 // => Swapping idx & idx2 turns %src into a vector type. 1692 // 2) %base a scalar & idx a vector & idx2 a scalar 1693 // => Swapping idx & idx2 turns %src in a scalar type 1694 // 3) %base, %idx, and %idx2 are scalars 1695 // => %src & %gep are scalars 1696 // => swapping idx & idx2 is safe 1697 // 4) %base a vector 1698 // => %src is a vector 1699 // => swapping idx & idx2 is safe. 1700 auto *SO0 = Src->getOperand(0); 1701 auto *SO0Ty = SO0->getType(); 1702 if (!isa<VectorType>(GEPType) || // case 3 1703 isa<VectorType>(SO0Ty)) { // case 4 1704 Src->setOperand(1, GO1); 1705 GEP.setOperand(1, SO1); 1706 return &GEP; 1707 } else { 1708 // Case 1 or 2 1709 // -- have to recreate %src & %gep 1710 // put NewSrc at same location as %src 1711 Builder.SetInsertPoint(cast<Instruction>(PtrOp)); 1712 auto *NewSrc = cast<GetElementPtrInst>( 1713 Builder.CreateGEP(SO0, GO1, Src->getName())); 1714 NewSrc->setIsInBounds(Src->isInBounds()); 1715 auto *NewGEP = GetElementPtrInst::Create(nullptr, NewSrc, {SO1}); 1716 NewGEP->setIsInBounds(GEP.isInBounds()); 1717 return NewGEP; 1718 } 1719 } 1720 } 1721 } 1722 1723 // Note that if our source is a gep chain itself then we wait for that 1724 // chain to be resolved before we perform this transformation. This 1725 // avoids us creating a TON of code in some cases. 1726 if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0))) 1727 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) 1728 return nullptr; // Wait until our source is folded to completion. 1729 1730 SmallVector<Value*, 8> Indices; 1731 1732 // Find out whether the last index in the source GEP is a sequential idx. 1733 bool EndsWithSequential = false; 1734 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 1735 I != E; ++I) 1736 EndsWithSequential = I.isSequential(); 1737 1738 // Can we combine the two pointer arithmetics offsets? 1739 if (EndsWithSequential) { 1740 // Replace: gep (gep %P, long B), long A, ... 1741 // With: T = long A+B; gep %P, T, ... 1742 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 1743 Value *GO1 = GEP.getOperand(1); 1744 1745 // If they aren't the same type, then the input hasn't been processed 1746 // by the loop above yet (which canonicalizes sequential index types to 1747 // intptr_t). Just avoid transforming this until the input has been 1748 // normalized. 1749 if (SO1->getType() != GO1->getType()) 1750 return nullptr; 1751 1752 Value *Sum = 1753 SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP)); 1754 // Only do the combine when we are sure the cost after the 1755 // merge is never more than that before the merge. 1756 if (Sum == nullptr) 1757 return nullptr; 1758 1759 // Update the GEP in place if possible. 1760 if (Src->getNumOperands() == 2) { 1761 GEP.setOperand(0, Src->getOperand(0)); 1762 GEP.setOperand(1, Sum); 1763 return &GEP; 1764 } 1765 Indices.append(Src->op_begin()+1, Src->op_end()-1); 1766 Indices.push_back(Sum); 1767 Indices.append(GEP.op_begin()+2, GEP.op_end()); 1768 } else if (isa<Constant>(*GEP.idx_begin()) && 1769 cast<Constant>(*GEP.idx_begin())->isNullValue() && 1770 Src->getNumOperands() != 1) { 1771 // Otherwise we can do the fold if the first index of the GEP is a zero 1772 Indices.append(Src->op_begin()+1, Src->op_end()); 1773 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 1774 } 1775 1776 if (!Indices.empty()) 1777 return GEP.isInBounds() && Src->isInBounds() 1778 ? GetElementPtrInst::CreateInBounds( 1779 Src->getSourceElementType(), Src->getOperand(0), Indices, 1780 GEP.getName()) 1781 : GetElementPtrInst::Create(Src->getSourceElementType(), 1782 Src->getOperand(0), Indices, 1783 GEP.getName()); 1784 } 1785 1786 if (GEP.getNumIndices() == 1) { 1787 unsigned AS = GEP.getPointerAddressSpace(); 1788 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() == 1789 DL.getIndexSizeInBits(AS)) { 1790 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType); 1791 1792 bool Matched = false; 1793 uint64_t C; 1794 Value *V = nullptr; 1795 if (TyAllocSize == 1) { 1796 V = GEP.getOperand(1); 1797 Matched = true; 1798 } else if (match(GEP.getOperand(1), 1799 m_AShr(m_Value(V), m_ConstantInt(C)))) { 1800 if (TyAllocSize == 1ULL << C) 1801 Matched = true; 1802 } else if (match(GEP.getOperand(1), 1803 m_SDiv(m_Value(V), m_ConstantInt(C)))) { 1804 if (TyAllocSize == C) 1805 Matched = true; 1806 } 1807 1808 if (Matched) { 1809 // Canonicalize (gep i8* X, -(ptrtoint Y)) 1810 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y))) 1811 // The GEP pattern is emitted by the SCEV expander for certain kinds of 1812 // pointer arithmetic. 1813 if (match(V, m_Neg(m_PtrToInt(m_Value())))) { 1814 Operator *Index = cast<Operator>(V); 1815 Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType()); 1816 Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1)); 1817 return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType); 1818 } 1819 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) 1820 // to (bitcast Y) 1821 Value *Y; 1822 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)), 1823 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) 1824 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType); 1825 } 1826 } 1827 } 1828 1829 // We do not handle pointer-vector geps here. 1830 if (GEPType->isVectorTy()) 1831 return nullptr; 1832 1833 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). 1834 Value *StrippedPtr = PtrOp->stripPointerCasts(); 1835 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType()); 1836 1837 if (StrippedPtr != PtrOp) { 1838 bool HasZeroPointerIndex = false; 1839 if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) 1840 HasZeroPointerIndex = C->isZero(); 1841 1842 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... 1843 // into : GEP [10 x i8]* X, i32 0, ... 1844 // 1845 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... 1846 // into : GEP i8* X, ... 1847 // 1848 // This occurs when the program declares an array extern like "int X[];" 1849 if (HasZeroPointerIndex) { 1850 if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) { 1851 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? 1852 if (CATy->getElementType() == StrippedPtrTy->getElementType()) { 1853 // -> GEP i8* X, ... 1854 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); 1855 GetElementPtrInst *Res = GetElementPtrInst::Create( 1856 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName()); 1857 Res->setIsInBounds(GEP.isInBounds()); 1858 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) 1859 return Res; 1860 // Insert Res, and create an addrspacecast. 1861 // e.g., 1862 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ... 1863 // -> 1864 // %0 = GEP i8 addrspace(1)* X, ... 1865 // addrspacecast i8 addrspace(1)* %0 to i8* 1866 return new AddrSpaceCastInst(Builder.Insert(Res), GEPType); 1867 } 1868 1869 if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrTy->getElementType())) { 1870 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? 1871 if (CATy->getElementType() == XATy->getElementType()) { 1872 // -> GEP [10 x i8]* X, i32 0, ... 1873 // At this point, we know that the cast source type is a pointer 1874 // to an array of the same type as the destination pointer 1875 // array. Because the array type is never stepped over (there 1876 // is a leading zero) we can fold the cast into this GEP. 1877 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) { 1878 GEP.setOperand(0, StrippedPtr); 1879 GEP.setSourceElementType(XATy); 1880 return &GEP; 1881 } 1882 // Cannot replace the base pointer directly because StrippedPtr's 1883 // address space is different. Instead, create a new GEP followed by 1884 // an addrspacecast. 1885 // e.g., 1886 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*), 1887 // i32 0, ... 1888 // -> 1889 // %0 = GEP [10 x i8] addrspace(1)* X, ... 1890 // addrspacecast i8 addrspace(1)* %0 to i8* 1891 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end()); 1892 Value *NewGEP = GEP.isInBounds() 1893 ? Builder.CreateInBoundsGEP( 1894 nullptr, StrippedPtr, Idx, GEP.getName()) 1895 : Builder.CreateGEP(nullptr, StrippedPtr, Idx, 1896 GEP.getName()); 1897 return new AddrSpaceCastInst(NewGEP, GEPType); 1898 } 1899 } 1900 } 1901 } else if (GEP.getNumOperands() == 2) { 1902 // Transform things like: 1903 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V 1904 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast 1905 Type *SrcEltTy = StrippedPtrTy->getElementType(); 1906 if (SrcEltTy->isArrayTy() && 1907 DL.getTypeAllocSize(SrcEltTy->getArrayElementType()) == 1908 DL.getTypeAllocSize(GEPEltType)) { 1909 Type *IdxType = DL.getIndexType(GEPType); 1910 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) }; 1911 Value *NewGEP = 1912 GEP.isInBounds() 1913 ? Builder.CreateInBoundsGEP(nullptr, StrippedPtr, Idx, 1914 GEP.getName()) 1915 : Builder.CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName()); 1916 1917 // V and GEP are both pointer types --> BitCast 1918 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType); 1919 } 1920 1921 // Transform things like: 1922 // %V = mul i64 %N, 4 1923 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V 1924 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast 1925 if (GEPEltType->isSized() && SrcEltTy->isSized()) { 1926 // Check that changing the type amounts to dividing the index by a scale 1927 // factor. 1928 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType); 1929 uint64_t SrcSize = DL.getTypeAllocSize(SrcEltTy); 1930 if (ResSize && SrcSize % ResSize == 0) { 1931 Value *Idx = GEP.getOperand(1); 1932 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 1933 uint64_t Scale = SrcSize / ResSize; 1934 1935 // Earlier transforms ensure that the index has the right type 1936 // according to Data Layout, which considerably simplifies the 1937 // logic by eliminating implicit casts. 1938 assert(Idx->getType() == DL.getIndexType(GEPType) && 1939 "Index type does not match the Data Layout preferences"); 1940 1941 bool NSW; 1942 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 1943 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 1944 // If the multiplication NewIdx * Scale may overflow then the new 1945 // GEP may not be "inbounds". 1946 Value *NewGEP = 1947 GEP.isInBounds() && NSW 1948 ? Builder.CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx, 1949 GEP.getName()) 1950 : Builder.CreateGEP(nullptr, StrippedPtr, NewIdx, 1951 GEP.getName()); 1952 1953 // The NewGEP must be pointer typed, so must the old one -> BitCast 1954 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 1955 GEPType); 1956 } 1957 } 1958 } 1959 1960 // Similarly, transform things like: 1961 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp 1962 // (where tmp = 8*tmp2) into: 1963 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast 1964 if (GEPEltType->isSized() && SrcEltTy->isSized() && 1965 SrcEltTy->isArrayTy()) { 1966 // Check that changing to the array element type amounts to dividing the 1967 // index by a scale factor. 1968 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType); 1969 uint64_t ArrayEltSize = 1970 DL.getTypeAllocSize(SrcEltTy->getArrayElementType()); 1971 if (ResSize && ArrayEltSize % ResSize == 0) { 1972 Value *Idx = GEP.getOperand(1); 1973 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 1974 uint64_t Scale = ArrayEltSize / ResSize; 1975 1976 // Earlier transforms ensure that the index has the right type 1977 // according to the Data Layout, which considerably simplifies 1978 // the logic by eliminating implicit casts. 1979 assert(Idx->getType() == DL.getIndexType(GEPType) && 1980 "Index type does not match the Data Layout preferences"); 1981 1982 bool NSW; 1983 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 1984 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 1985 // If the multiplication NewIdx * Scale may overflow then the new 1986 // GEP may not be "inbounds". 1987 Type *IndTy = DL.getIndexType(GEPType); 1988 Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx}; 1989 1990 Value *NewGEP = GEP.isInBounds() && NSW 1991 ? Builder.CreateInBoundsGEP( 1992 SrcEltTy, StrippedPtr, Off, GEP.getName()) 1993 : Builder.CreateGEP(SrcEltTy, StrippedPtr, Off, 1994 GEP.getName()); 1995 // The NewGEP must be pointer typed, so must the old one -> BitCast 1996 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 1997 GEPType); 1998 } 1999 } 2000 } 2001 } 2002 } 2003 2004 // addrspacecast between types is canonicalized as a bitcast, then an 2005 // addrspacecast. To take advantage of the below bitcast + struct GEP, look 2006 // through the addrspacecast. 2007 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) { 2008 // X = bitcast A addrspace(1)* to B addrspace(1)* 2009 // Y = addrspacecast A addrspace(1)* to B addrspace(2)* 2010 // Z = gep Y, <...constant indices...> 2011 // Into an addrspacecasted GEP of the struct. 2012 if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0))) 2013 PtrOp = BC; 2014 } 2015 2016 /// See if we can simplify: 2017 /// X = bitcast A* to B* 2018 /// Y = gep X, <...constant indices...> 2019 /// into a gep of the original struct. This is important for SROA and alias 2020 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. 2021 if (auto *BCI = dyn_cast<BitCastInst>(PtrOp)) { 2022 Value *SrcOp = BCI->getOperand(0); 2023 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy()); 2024 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType); 2025 APInt Offset(OffsetBits, 0); 2026 if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) { 2027 // If this GEP instruction doesn't move the pointer, just replace the GEP 2028 // with a bitcast of the real input to the dest type. 2029 if (!Offset) { 2030 // If the bitcast is of an allocation, and the allocation will be 2031 // converted to match the type of the cast, don't touch this. 2032 if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) { 2033 // See if the bitcast simplifies, if so, don't nuke this GEP yet. 2034 if (Instruction *I = visitBitCast(*BCI)) { 2035 if (I != BCI) { 2036 I->takeName(BCI); 2037 BCI->getParent()->getInstList().insert(BCI->getIterator(), I); 2038 replaceInstUsesWith(*BCI, I); 2039 } 2040 return &GEP; 2041 } 2042 } 2043 2044 if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace()) 2045 return new AddrSpaceCastInst(SrcOp, GEPType); 2046 return new BitCastInst(SrcOp, GEPType); 2047 } 2048 2049 // Otherwise, if the offset is non-zero, we need to find out if there is a 2050 // field at Offset in 'A's type. If so, we can pull the cast through the 2051 // GEP. 2052 SmallVector<Value*, 8> NewIndices; 2053 if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) { 2054 Value *NGEP = 2055 GEP.isInBounds() 2056 ? Builder.CreateInBoundsGEP(nullptr, SrcOp, NewIndices) 2057 : Builder.CreateGEP(nullptr, SrcOp, NewIndices); 2058 2059 if (NGEP->getType() == GEPType) 2060 return replaceInstUsesWith(GEP, NGEP); 2061 NGEP->takeName(&GEP); 2062 2063 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2064 return new AddrSpaceCastInst(NGEP, GEPType); 2065 return new BitCastInst(NGEP, GEPType); 2066 } 2067 } 2068 } 2069 2070 if (!GEP.isInBounds()) { 2071 unsigned IdxWidth = 2072 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace()); 2073 APInt BasePtrOffset(IdxWidth, 0); 2074 Value *UnderlyingPtrOp = 2075 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, 2076 BasePtrOffset); 2077 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) { 2078 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) && 2079 BasePtrOffset.isNonNegative()) { 2080 APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType())); 2081 if (BasePtrOffset.ule(AllocSize)) { 2082 return GetElementPtrInst::CreateInBounds( 2083 PtrOp, makeArrayRef(Ops).slice(1), GEP.getName()); 2084 } 2085 } 2086 } 2087 } 2088 2089 return nullptr; 2090 } 2091 2092 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI, 2093 Instruction *AI) { 2094 if (isa<ConstantPointerNull>(V)) 2095 return true; 2096 if (auto *LI = dyn_cast<LoadInst>(V)) 2097 return isa<GlobalVariable>(LI->getPointerOperand()); 2098 // Two distinct allocations will never be equal. 2099 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking 2100 // through bitcasts of V can cause 2101 // the result statement below to be true, even when AI and V (ex: 2102 // i8* ->i32* ->i8* of AI) are the same allocations. 2103 return isAllocLikeFn(V, TLI) && V != AI; 2104 } 2105 2106 static bool isAllocSiteRemovable(Instruction *AI, 2107 SmallVectorImpl<WeakTrackingVH> &Users, 2108 const TargetLibraryInfo *TLI) { 2109 SmallVector<Instruction*, 4> Worklist; 2110 Worklist.push_back(AI); 2111 2112 do { 2113 Instruction *PI = Worklist.pop_back_val(); 2114 for (User *U : PI->users()) { 2115 Instruction *I = cast<Instruction>(U); 2116 switch (I->getOpcode()) { 2117 default: 2118 // Give up the moment we see something we can't handle. 2119 return false; 2120 2121 case Instruction::AddrSpaceCast: 2122 case Instruction::BitCast: 2123 case Instruction::GetElementPtr: 2124 Users.emplace_back(I); 2125 Worklist.push_back(I); 2126 continue; 2127 2128 case Instruction::ICmp: { 2129 ICmpInst *ICI = cast<ICmpInst>(I); 2130 // We can fold eq/ne comparisons with null to false/true, respectively. 2131 // We also fold comparisons in some conditions provided the alloc has 2132 // not escaped (see isNeverEqualToUnescapedAlloc). 2133 if (!ICI->isEquality()) 2134 return false; 2135 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0; 2136 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI)) 2137 return false; 2138 Users.emplace_back(I); 2139 continue; 2140 } 2141 2142 case Instruction::Call: 2143 // Ignore no-op and store intrinsics. 2144 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2145 switch (II->getIntrinsicID()) { 2146 default: 2147 return false; 2148 2149 case Intrinsic::memmove: 2150 case Intrinsic::memcpy: 2151 case Intrinsic::memset: { 2152 MemIntrinsic *MI = cast<MemIntrinsic>(II); 2153 if (MI->isVolatile() || MI->getRawDest() != PI) 2154 return false; 2155 LLVM_FALLTHROUGH; 2156 } 2157 case Intrinsic::invariant_start: 2158 case Intrinsic::invariant_end: 2159 case Intrinsic::lifetime_start: 2160 case Intrinsic::lifetime_end: 2161 case Intrinsic::objectsize: 2162 Users.emplace_back(I); 2163 continue; 2164 } 2165 } 2166 2167 if (isFreeCall(I, TLI)) { 2168 Users.emplace_back(I); 2169 continue; 2170 } 2171 return false; 2172 2173 case Instruction::Store: { 2174 StoreInst *SI = cast<StoreInst>(I); 2175 if (SI->isVolatile() || SI->getPointerOperand() != PI) 2176 return false; 2177 Users.emplace_back(I); 2178 continue; 2179 } 2180 } 2181 llvm_unreachable("missing a return?"); 2182 } 2183 } while (!Worklist.empty()); 2184 return true; 2185 } 2186 2187 Instruction *InstCombiner::visitAllocSite(Instruction &MI) { 2188 // If we have a malloc call which is only used in any amount of comparisons 2189 // to null and free calls, delete the calls and replace the comparisons with 2190 // true or false as appropriate. 2191 SmallVector<WeakTrackingVH, 64> Users; 2192 2193 // If we are removing an alloca with a dbg.declare, insert dbg.value calls 2194 // before each store. 2195 TinyPtrVector<DbgInfoIntrinsic *> DIIs; 2196 std::unique_ptr<DIBuilder> DIB; 2197 if (isa<AllocaInst>(MI)) { 2198 DIIs = FindDbgAddrUses(&MI); 2199 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false)); 2200 } 2201 2202 if (isAllocSiteRemovable(&MI, Users, &TLI)) { 2203 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2204 // Lowering all @llvm.objectsize calls first because they may 2205 // use a bitcast/GEP of the alloca we are removing. 2206 if (!Users[i]) 2207 continue; 2208 2209 Instruction *I = cast<Instruction>(&*Users[i]); 2210 2211 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2212 if (II->getIntrinsicID() == Intrinsic::objectsize) { 2213 ConstantInt *Result = lowerObjectSizeCall(II, DL, &TLI, 2214 /*MustSucceed=*/true); 2215 replaceInstUsesWith(*I, Result); 2216 eraseInstFromFunction(*I); 2217 Users[i] = nullptr; // Skip examining in the next loop. 2218 } 2219 } 2220 } 2221 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2222 if (!Users[i]) 2223 continue; 2224 2225 Instruction *I = cast<Instruction>(&*Users[i]); 2226 2227 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) { 2228 replaceInstUsesWith(*C, 2229 ConstantInt::get(Type::getInt1Ty(C->getContext()), 2230 C->isFalseWhenEqual())); 2231 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) || 2232 isa<AddrSpaceCastInst>(I)) { 2233 replaceInstUsesWith(*I, UndefValue::get(I->getType())); 2234 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 2235 for (auto *DII : DIIs) 2236 ConvertDebugDeclareToDebugValue(DII, SI, *DIB); 2237 } 2238 eraseInstFromFunction(*I); 2239 } 2240 2241 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) { 2242 // Replace invoke with a NOP intrinsic to maintain the original CFG 2243 Module *M = II->getModule(); 2244 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing); 2245 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(), 2246 None, "", II->getParent()); 2247 } 2248 2249 for (auto *DII : DIIs) 2250 eraseInstFromFunction(*DII); 2251 2252 return eraseInstFromFunction(MI); 2253 } 2254 return nullptr; 2255 } 2256 2257 /// \brief Move the call to free before a NULL test. 2258 /// 2259 /// Check if this free is accessed after its argument has been test 2260 /// against NULL (property 0). 2261 /// If yes, it is legal to move this call in its predecessor block. 2262 /// 2263 /// The move is performed only if the block containing the call to free 2264 /// will be removed, i.e.: 2265 /// 1. it has only one predecessor P, and P has two successors 2266 /// 2. it contains the call and an unconditional branch 2267 /// 3. its successor is the same as its predecessor's successor 2268 /// 2269 /// The profitability is out-of concern here and this function should 2270 /// be called only if the caller knows this transformation would be 2271 /// profitable (e.g., for code size). 2272 static Instruction * 2273 tryToMoveFreeBeforeNullTest(CallInst &FI) { 2274 Value *Op = FI.getArgOperand(0); 2275 BasicBlock *FreeInstrBB = FI.getParent(); 2276 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor(); 2277 2278 // Validate part of constraint #1: Only one predecessor 2279 // FIXME: We can extend the number of predecessor, but in that case, we 2280 // would duplicate the call to free in each predecessor and it may 2281 // not be profitable even for code size. 2282 if (!PredBB) 2283 return nullptr; 2284 2285 // Validate constraint #2: Does this block contains only the call to 2286 // free and an unconditional branch? 2287 // FIXME: We could check if we can speculate everything in the 2288 // predecessor block 2289 if (FreeInstrBB->size() != 2) 2290 return nullptr; 2291 BasicBlock *SuccBB; 2292 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB))) 2293 return nullptr; 2294 2295 // Validate the rest of constraint #1 by matching on the pred branch. 2296 TerminatorInst *TI = PredBB->getTerminator(); 2297 BasicBlock *TrueBB, *FalseBB; 2298 ICmpInst::Predicate Pred; 2299 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB))) 2300 return nullptr; 2301 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE) 2302 return nullptr; 2303 2304 // Validate constraint #3: Ensure the null case just falls through. 2305 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB)) 2306 return nullptr; 2307 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && 2308 "Broken CFG: missing edge from predecessor to successor"); 2309 2310 FI.moveBefore(TI); 2311 return &FI; 2312 } 2313 2314 Instruction *InstCombiner::visitFree(CallInst &FI) { 2315 Value *Op = FI.getArgOperand(0); 2316 2317 // free undef -> unreachable. 2318 if (isa<UndefValue>(Op)) { 2319 // Insert a new store to null because we cannot modify the CFG here. 2320 Builder.CreateStore(ConstantInt::getTrue(FI.getContext()), 2321 UndefValue::get(Type::getInt1PtrTy(FI.getContext()))); 2322 return eraseInstFromFunction(FI); 2323 } 2324 2325 // If we have 'free null' delete the instruction. This can happen in stl code 2326 // when lots of inlining happens. 2327 if (isa<ConstantPointerNull>(Op)) 2328 return eraseInstFromFunction(FI); 2329 2330 // If we optimize for code size, try to move the call to free before the null 2331 // test so that simplify cfg can remove the empty block and dead code 2332 // elimination the branch. I.e., helps to turn something like: 2333 // if (foo) free(foo); 2334 // into 2335 // free(foo); 2336 if (MinimizeSize) 2337 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI)) 2338 return I; 2339 2340 return nullptr; 2341 } 2342 2343 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) { 2344 if (RI.getNumOperands() == 0) // ret void 2345 return nullptr; 2346 2347 Value *ResultOp = RI.getOperand(0); 2348 Type *VTy = ResultOp->getType(); 2349 if (!VTy->isIntegerTy()) 2350 return nullptr; 2351 2352 // There might be assume intrinsics dominating this return that completely 2353 // determine the value. If so, constant fold it. 2354 KnownBits Known = computeKnownBits(ResultOp, 0, &RI); 2355 if (Known.isConstant()) 2356 RI.setOperand(0, Constant::getIntegerValue(VTy, Known.getConstant())); 2357 2358 return nullptr; 2359 } 2360 2361 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { 2362 // Change br (not X), label True, label False to: br X, label False, True 2363 Value *X = nullptr; 2364 BasicBlock *TrueDest; 2365 BasicBlock *FalseDest; 2366 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) && 2367 !isa<Constant>(X)) { 2368 // Swap Destinations and condition... 2369 BI.setCondition(X); 2370 BI.swapSuccessors(); 2371 return &BI; 2372 } 2373 2374 // If the condition is irrelevant, remove the use so that other 2375 // transforms on the condition become more effective. 2376 if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) && 2377 BI.getSuccessor(0) == BI.getSuccessor(1)) { 2378 BI.setCondition(ConstantInt::getFalse(BI.getCondition()->getType())); 2379 return &BI; 2380 } 2381 2382 // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq. 2383 CmpInst::Predicate Pred; 2384 if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), TrueDest, 2385 FalseDest)) && 2386 !isCanonicalPredicate(Pred)) { 2387 // Swap destinations and condition. 2388 CmpInst *Cond = cast<CmpInst>(BI.getCondition()); 2389 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 2390 BI.swapSuccessors(); 2391 Worklist.Add(Cond); 2392 return &BI; 2393 } 2394 2395 return nullptr; 2396 } 2397 2398 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { 2399 Value *Cond = SI.getCondition(); 2400 Value *Op0; 2401 ConstantInt *AddRHS; 2402 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) { 2403 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'. 2404 for (auto Case : SI.cases()) { 2405 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS); 2406 assert(isa<ConstantInt>(NewCase) && 2407 "Result of expression should be constant"); 2408 Case.setValue(cast<ConstantInt>(NewCase)); 2409 } 2410 SI.setCondition(Op0); 2411 return &SI; 2412 } 2413 2414 KnownBits Known = computeKnownBits(Cond, 0, &SI); 2415 unsigned LeadingKnownZeros = Known.countMinLeadingZeros(); 2416 unsigned LeadingKnownOnes = Known.countMinLeadingOnes(); 2417 2418 // Compute the number of leading bits we can ignore. 2419 // TODO: A better way to determine this would use ComputeNumSignBits(). 2420 for (auto &C : SI.cases()) { 2421 LeadingKnownZeros = std::min( 2422 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros()); 2423 LeadingKnownOnes = std::min( 2424 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes()); 2425 } 2426 2427 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes); 2428 2429 // Shrink the condition operand if the new type is smaller than the old type. 2430 // This may produce a non-standard type for the switch, but that's ok because 2431 // the backend should extend back to a legal type for the target. 2432 if (NewWidth > 0 && NewWidth < Known.getBitWidth()) { 2433 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth); 2434 Builder.SetInsertPoint(&SI); 2435 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc"); 2436 SI.setCondition(NewCond); 2437 2438 for (auto Case : SI.cases()) { 2439 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth); 2440 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase)); 2441 } 2442 return &SI; 2443 } 2444 2445 return nullptr; 2446 } 2447 2448 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) { 2449 Value *Agg = EV.getAggregateOperand(); 2450 2451 if (!EV.hasIndices()) 2452 return replaceInstUsesWith(EV, Agg); 2453 2454 if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(), 2455 SQ.getWithInstruction(&EV))) 2456 return replaceInstUsesWith(EV, V); 2457 2458 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 2459 // We're extracting from an insertvalue instruction, compare the indices 2460 const unsigned *exti, *exte, *insi, *inse; 2461 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 2462 exte = EV.idx_end(), inse = IV->idx_end(); 2463 exti != exte && insi != inse; 2464 ++exti, ++insi) { 2465 if (*insi != *exti) 2466 // The insert and extract both reference distinctly different elements. 2467 // This means the extract is not influenced by the insert, and we can 2468 // replace the aggregate operand of the extract with the aggregate 2469 // operand of the insert. i.e., replace 2470 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 2471 // %E = extractvalue { i32, { i32 } } %I, 0 2472 // with 2473 // %E = extractvalue { i32, { i32 } } %A, 0 2474 return ExtractValueInst::Create(IV->getAggregateOperand(), 2475 EV.getIndices()); 2476 } 2477 if (exti == exte && insi == inse) 2478 // Both iterators are at the end: Index lists are identical. Replace 2479 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 2480 // %C = extractvalue { i32, { i32 } } %B, 1, 0 2481 // with "i32 42" 2482 return replaceInstUsesWith(EV, IV->getInsertedValueOperand()); 2483 if (exti == exte) { 2484 // The extract list is a prefix of the insert list. i.e. replace 2485 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 2486 // %E = extractvalue { i32, { i32 } } %I, 1 2487 // with 2488 // %X = extractvalue { i32, { i32 } } %A, 1 2489 // %E = insertvalue { i32 } %X, i32 42, 0 2490 // by switching the order of the insert and extract (though the 2491 // insertvalue should be left in, since it may have other uses). 2492 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(), 2493 EV.getIndices()); 2494 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 2495 makeArrayRef(insi, inse)); 2496 } 2497 if (insi == inse) 2498 // The insert list is a prefix of the extract list 2499 // We can simply remove the common indices from the extract and make it 2500 // operate on the inserted value instead of the insertvalue result. 2501 // i.e., replace 2502 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 2503 // %E = extractvalue { i32, { i32 } } %I, 1, 0 2504 // with 2505 // %E extractvalue { i32 } { i32 42 }, 0 2506 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 2507 makeArrayRef(exti, exte)); 2508 } 2509 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) { 2510 // We're extracting from an intrinsic, see if we're the only user, which 2511 // allows us to simplify multiple result intrinsics to simpler things that 2512 // just get one value. 2513 if (II->hasOneUse()) { 2514 // Check if we're grabbing the overflow bit or the result of a 'with 2515 // overflow' intrinsic. If it's the latter we can remove the intrinsic 2516 // and replace it with a traditional binary instruction. 2517 switch (II->getIntrinsicID()) { 2518 case Intrinsic::uadd_with_overflow: 2519 case Intrinsic::sadd_with_overflow: 2520 if (*EV.idx_begin() == 0) { // Normal result. 2521 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 2522 replaceInstUsesWith(*II, UndefValue::get(II->getType())); 2523 eraseInstFromFunction(*II); 2524 return BinaryOperator::CreateAdd(LHS, RHS); 2525 } 2526 2527 // If the normal result of the add is dead, and the RHS is a constant, 2528 // we can transform this into a range comparison. 2529 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 2530 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow) 2531 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1))) 2532 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0), 2533 ConstantExpr::getNot(CI)); 2534 break; 2535 case Intrinsic::usub_with_overflow: 2536 case Intrinsic::ssub_with_overflow: 2537 if (*EV.idx_begin() == 0) { // Normal result. 2538 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 2539 replaceInstUsesWith(*II, UndefValue::get(II->getType())); 2540 eraseInstFromFunction(*II); 2541 return BinaryOperator::CreateSub(LHS, RHS); 2542 } 2543 break; 2544 case Intrinsic::umul_with_overflow: 2545 case Intrinsic::smul_with_overflow: 2546 if (*EV.idx_begin() == 0) { // Normal result. 2547 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 2548 replaceInstUsesWith(*II, UndefValue::get(II->getType())); 2549 eraseInstFromFunction(*II); 2550 return BinaryOperator::CreateMul(LHS, RHS); 2551 } 2552 break; 2553 default: 2554 break; 2555 } 2556 } 2557 } 2558 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) 2559 // If the (non-volatile) load only has one use, we can rewrite this to a 2560 // load from a GEP. This reduces the size of the load. If a load is used 2561 // only by extractvalue instructions then this either must have been 2562 // optimized before, or it is a struct with padding, in which case we 2563 // don't want to do the transformation as it loses padding knowledge. 2564 if (L->isSimple() && L->hasOneUse()) { 2565 // extractvalue has integer indices, getelementptr has Value*s. Convert. 2566 SmallVector<Value*, 4> Indices; 2567 // Prefix an i32 0 since we need the first element. 2568 Indices.push_back(Builder.getInt32(0)); 2569 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); 2570 I != E; ++I) 2571 Indices.push_back(Builder.getInt32(*I)); 2572 2573 // We need to insert these at the location of the old load, not at that of 2574 // the extractvalue. 2575 Builder.SetInsertPoint(L); 2576 Value *GEP = Builder.CreateInBoundsGEP(L->getType(), 2577 L->getPointerOperand(), Indices); 2578 Instruction *NL = Builder.CreateLoad(GEP); 2579 // Whatever aliasing information we had for the orignal load must also 2580 // hold for the smaller load, so propagate the annotations. 2581 AAMDNodes Nodes; 2582 L->getAAMetadata(Nodes); 2583 NL->setAAMetadata(Nodes); 2584 // Returning the load directly will cause the main loop to insert it in 2585 // the wrong spot, so use replaceInstUsesWith(). 2586 return replaceInstUsesWith(EV, NL); 2587 } 2588 // We could simplify extracts from other values. Note that nested extracts may 2589 // already be simplified implicitly by the above: extract (extract (insert) ) 2590 // will be translated into extract ( insert ( extract ) ) first and then just 2591 // the value inserted, if appropriate. Similarly for extracts from single-use 2592 // loads: extract (extract (load)) will be translated to extract (load (gep)) 2593 // and if again single-use then via load (gep (gep)) to load (gep). 2594 // However, double extracts from e.g. function arguments or return values 2595 // aren't handled yet. 2596 return nullptr; 2597 } 2598 2599 /// Return 'true' if the given typeinfo will match anything. 2600 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) { 2601 switch (Personality) { 2602 case EHPersonality::GNU_C: 2603 case EHPersonality::GNU_C_SjLj: 2604 case EHPersonality::Rust: 2605 // The GCC C EH and Rust personality only exists to support cleanups, so 2606 // it's not clear what the semantics of catch clauses are. 2607 return false; 2608 case EHPersonality::Unknown: 2609 return false; 2610 case EHPersonality::GNU_Ada: 2611 // While __gnat_all_others_value will match any Ada exception, it doesn't 2612 // match foreign exceptions (or didn't, before gcc-4.7). 2613 return false; 2614 case EHPersonality::GNU_CXX: 2615 case EHPersonality::GNU_CXX_SjLj: 2616 case EHPersonality::GNU_ObjC: 2617 case EHPersonality::MSVC_X86SEH: 2618 case EHPersonality::MSVC_Win64SEH: 2619 case EHPersonality::MSVC_CXX: 2620 case EHPersonality::CoreCLR: 2621 return TypeInfo->isNullValue(); 2622 } 2623 llvm_unreachable("invalid enum"); 2624 } 2625 2626 static bool shorter_filter(const Value *LHS, const Value *RHS) { 2627 return 2628 cast<ArrayType>(LHS->getType())->getNumElements() 2629 < 2630 cast<ArrayType>(RHS->getType())->getNumElements(); 2631 } 2632 2633 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) { 2634 // The logic here should be correct for any real-world personality function. 2635 // However if that turns out not to be true, the offending logic can always 2636 // be conditioned on the personality function, like the catch-all logic is. 2637 EHPersonality Personality = 2638 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn()); 2639 2640 // Simplify the list of clauses, eg by removing repeated catch clauses 2641 // (these are often created by inlining). 2642 bool MakeNewInstruction = false; // If true, recreate using the following: 2643 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction; 2644 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup. 2645 2646 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already. 2647 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) { 2648 bool isLastClause = i + 1 == e; 2649 if (LI.isCatch(i)) { 2650 // A catch clause. 2651 Constant *CatchClause = LI.getClause(i); 2652 Constant *TypeInfo = CatchClause->stripPointerCasts(); 2653 2654 // If we already saw this clause, there is no point in having a second 2655 // copy of it. 2656 if (AlreadyCaught.insert(TypeInfo).second) { 2657 // This catch clause was not already seen. 2658 NewClauses.push_back(CatchClause); 2659 } else { 2660 // Repeated catch clause - drop the redundant copy. 2661 MakeNewInstruction = true; 2662 } 2663 2664 // If this is a catch-all then there is no point in keeping any following 2665 // clauses or marking the landingpad as having a cleanup. 2666 if (isCatchAll(Personality, TypeInfo)) { 2667 if (!isLastClause) 2668 MakeNewInstruction = true; 2669 CleanupFlag = false; 2670 break; 2671 } 2672 } else { 2673 // A filter clause. If any of the filter elements were already caught 2674 // then they can be dropped from the filter. It is tempting to try to 2675 // exploit the filter further by saying that any typeinfo that does not 2676 // occur in the filter can't be caught later (and thus can be dropped). 2677 // However this would be wrong, since typeinfos can match without being 2678 // equal (for example if one represents a C++ class, and the other some 2679 // class derived from it). 2680 assert(LI.isFilter(i) && "Unsupported landingpad clause!"); 2681 Constant *FilterClause = LI.getClause(i); 2682 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType()); 2683 unsigned NumTypeInfos = FilterType->getNumElements(); 2684 2685 // An empty filter catches everything, so there is no point in keeping any 2686 // following clauses or marking the landingpad as having a cleanup. By 2687 // dealing with this case here the following code is made a bit simpler. 2688 if (!NumTypeInfos) { 2689 NewClauses.push_back(FilterClause); 2690 if (!isLastClause) 2691 MakeNewInstruction = true; 2692 CleanupFlag = false; 2693 break; 2694 } 2695 2696 bool MakeNewFilter = false; // If true, make a new filter. 2697 SmallVector<Constant *, 16> NewFilterElts; // New elements. 2698 if (isa<ConstantAggregateZero>(FilterClause)) { 2699 // Not an empty filter - it contains at least one null typeinfo. 2700 assert(NumTypeInfos > 0 && "Should have handled empty filter already!"); 2701 Constant *TypeInfo = 2702 Constant::getNullValue(FilterType->getElementType()); 2703 // If this typeinfo is a catch-all then the filter can never match. 2704 if (isCatchAll(Personality, TypeInfo)) { 2705 // Throw the filter away. 2706 MakeNewInstruction = true; 2707 continue; 2708 } 2709 2710 // There is no point in having multiple copies of this typeinfo, so 2711 // discard all but the first copy if there is more than one. 2712 NewFilterElts.push_back(TypeInfo); 2713 if (NumTypeInfos > 1) 2714 MakeNewFilter = true; 2715 } else { 2716 ConstantArray *Filter = cast<ConstantArray>(FilterClause); 2717 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements. 2718 NewFilterElts.reserve(NumTypeInfos); 2719 2720 // Remove any filter elements that were already caught or that already 2721 // occurred in the filter. While there, see if any of the elements are 2722 // catch-alls. If so, the filter can be discarded. 2723 bool SawCatchAll = false; 2724 for (unsigned j = 0; j != NumTypeInfos; ++j) { 2725 Constant *Elt = Filter->getOperand(j); 2726 Constant *TypeInfo = Elt->stripPointerCasts(); 2727 if (isCatchAll(Personality, TypeInfo)) { 2728 // This element is a catch-all. Bail out, noting this fact. 2729 SawCatchAll = true; 2730 break; 2731 } 2732 2733 // Even if we've seen a type in a catch clause, we don't want to 2734 // remove it from the filter. An unexpected type handler may be 2735 // set up for a call site which throws an exception of the same 2736 // type caught. In order for the exception thrown by the unexpected 2737 // handler to propagate correctly, the filter must be correctly 2738 // described for the call site. 2739 // 2740 // Example: 2741 // 2742 // void unexpected() { throw 1;} 2743 // void foo() throw (int) { 2744 // std::set_unexpected(unexpected); 2745 // try { 2746 // throw 2.0; 2747 // } catch (int i) {} 2748 // } 2749 2750 // There is no point in having multiple copies of the same typeinfo in 2751 // a filter, so only add it if we didn't already. 2752 if (SeenInFilter.insert(TypeInfo).second) 2753 NewFilterElts.push_back(cast<Constant>(Elt)); 2754 } 2755 // A filter containing a catch-all cannot match anything by definition. 2756 if (SawCatchAll) { 2757 // Throw the filter away. 2758 MakeNewInstruction = true; 2759 continue; 2760 } 2761 2762 // If we dropped something from the filter, make a new one. 2763 if (NewFilterElts.size() < NumTypeInfos) 2764 MakeNewFilter = true; 2765 } 2766 if (MakeNewFilter) { 2767 FilterType = ArrayType::get(FilterType->getElementType(), 2768 NewFilterElts.size()); 2769 FilterClause = ConstantArray::get(FilterType, NewFilterElts); 2770 MakeNewInstruction = true; 2771 } 2772 2773 NewClauses.push_back(FilterClause); 2774 2775 // If the new filter is empty then it will catch everything so there is 2776 // no point in keeping any following clauses or marking the landingpad 2777 // as having a cleanup. The case of the original filter being empty was 2778 // already handled above. 2779 if (MakeNewFilter && !NewFilterElts.size()) { 2780 assert(MakeNewInstruction && "New filter but not a new instruction!"); 2781 CleanupFlag = false; 2782 break; 2783 } 2784 } 2785 } 2786 2787 // If several filters occur in a row then reorder them so that the shortest 2788 // filters come first (those with the smallest number of elements). This is 2789 // advantageous because shorter filters are more likely to match, speeding up 2790 // unwinding, but mostly because it increases the effectiveness of the other 2791 // filter optimizations below. 2792 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) { 2793 unsigned j; 2794 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters. 2795 for (j = i; j != e; ++j) 2796 if (!isa<ArrayType>(NewClauses[j]->getType())) 2797 break; 2798 2799 // Check whether the filters are already sorted by length. We need to know 2800 // if sorting them is actually going to do anything so that we only make a 2801 // new landingpad instruction if it does. 2802 for (unsigned k = i; k + 1 < j; ++k) 2803 if (shorter_filter(NewClauses[k+1], NewClauses[k])) { 2804 // Not sorted, so sort the filters now. Doing an unstable sort would be 2805 // correct too but reordering filters pointlessly might confuse users. 2806 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j, 2807 shorter_filter); 2808 MakeNewInstruction = true; 2809 break; 2810 } 2811 2812 // Look for the next batch of filters. 2813 i = j + 1; 2814 } 2815 2816 // If typeinfos matched if and only if equal, then the elements of a filter L 2817 // that occurs later than a filter F could be replaced by the intersection of 2818 // the elements of F and L. In reality two typeinfos can match without being 2819 // equal (for example if one represents a C++ class, and the other some class 2820 // derived from it) so it would be wrong to perform this transform in general. 2821 // However the transform is correct and useful if F is a subset of L. In that 2822 // case L can be replaced by F, and thus removed altogether since repeating a 2823 // filter is pointless. So here we look at all pairs of filters F and L where 2824 // L follows F in the list of clauses, and remove L if every element of F is 2825 // an element of L. This can occur when inlining C++ functions with exception 2826 // specifications. 2827 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) { 2828 // Examine each filter in turn. 2829 Value *Filter = NewClauses[i]; 2830 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType()); 2831 if (!FTy) 2832 // Not a filter - skip it. 2833 continue; 2834 unsigned FElts = FTy->getNumElements(); 2835 // Examine each filter following this one. Doing this backwards means that 2836 // we don't have to worry about filters disappearing under us when removed. 2837 for (unsigned j = NewClauses.size() - 1; j != i; --j) { 2838 Value *LFilter = NewClauses[j]; 2839 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType()); 2840 if (!LTy) 2841 // Not a filter - skip it. 2842 continue; 2843 // If Filter is a subset of LFilter, i.e. every element of Filter is also 2844 // an element of LFilter, then discard LFilter. 2845 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j; 2846 // If Filter is empty then it is a subset of LFilter. 2847 if (!FElts) { 2848 // Discard LFilter. 2849 NewClauses.erase(J); 2850 MakeNewInstruction = true; 2851 // Move on to the next filter. 2852 continue; 2853 } 2854 unsigned LElts = LTy->getNumElements(); 2855 // If Filter is longer than LFilter then it cannot be a subset of it. 2856 if (FElts > LElts) 2857 // Move on to the next filter. 2858 continue; 2859 // At this point we know that LFilter has at least one element. 2860 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros. 2861 // Filter is a subset of LFilter iff Filter contains only zeros (as we 2862 // already know that Filter is not longer than LFilter). 2863 if (isa<ConstantAggregateZero>(Filter)) { 2864 assert(FElts <= LElts && "Should have handled this case earlier!"); 2865 // Discard LFilter. 2866 NewClauses.erase(J); 2867 MakeNewInstruction = true; 2868 } 2869 // Move on to the next filter. 2870 continue; 2871 } 2872 ConstantArray *LArray = cast<ConstantArray>(LFilter); 2873 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros. 2874 // Since Filter is non-empty and contains only zeros, it is a subset of 2875 // LFilter iff LFilter contains a zero. 2876 assert(FElts > 0 && "Should have eliminated the empty filter earlier!"); 2877 for (unsigned l = 0; l != LElts; ++l) 2878 if (LArray->getOperand(l)->isNullValue()) { 2879 // LFilter contains a zero - discard it. 2880 NewClauses.erase(J); 2881 MakeNewInstruction = true; 2882 break; 2883 } 2884 // Move on to the next filter. 2885 continue; 2886 } 2887 // At this point we know that both filters are ConstantArrays. Loop over 2888 // operands to see whether every element of Filter is also an element of 2889 // LFilter. Since filters tend to be short this is probably faster than 2890 // using a method that scales nicely. 2891 ConstantArray *FArray = cast<ConstantArray>(Filter); 2892 bool AllFound = true; 2893 for (unsigned f = 0; f != FElts; ++f) { 2894 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts(); 2895 AllFound = false; 2896 for (unsigned l = 0; l != LElts; ++l) { 2897 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts(); 2898 if (LTypeInfo == FTypeInfo) { 2899 AllFound = true; 2900 break; 2901 } 2902 } 2903 if (!AllFound) 2904 break; 2905 } 2906 if (AllFound) { 2907 // Discard LFilter. 2908 NewClauses.erase(J); 2909 MakeNewInstruction = true; 2910 } 2911 // Move on to the next filter. 2912 } 2913 } 2914 2915 // If we changed any of the clauses, replace the old landingpad instruction 2916 // with a new one. 2917 if (MakeNewInstruction) { 2918 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(), 2919 NewClauses.size()); 2920 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i) 2921 NLI->addClause(NewClauses[i]); 2922 // A landing pad with no clauses must have the cleanup flag set. It is 2923 // theoretically possible, though highly unlikely, that we eliminated all 2924 // clauses. If so, force the cleanup flag to true. 2925 if (NewClauses.empty()) 2926 CleanupFlag = true; 2927 NLI->setCleanup(CleanupFlag); 2928 return NLI; 2929 } 2930 2931 // Even if none of the clauses changed, we may nonetheless have understood 2932 // that the cleanup flag is pointless. Clear it if so. 2933 if (LI.isCleanup() != CleanupFlag) { 2934 assert(!CleanupFlag && "Adding a cleanup, not removing one?!"); 2935 LI.setCleanup(CleanupFlag); 2936 return &LI; 2937 } 2938 2939 return nullptr; 2940 } 2941 2942 /// Try to move the specified instruction from its current block into the 2943 /// beginning of DestBlock, which can only happen if it's safe to move the 2944 /// instruction past all of the instructions between it and the end of its 2945 /// block. 2946 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 2947 assert(I->hasOneUse() && "Invariants didn't hold!"); 2948 2949 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 2950 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() || 2951 isa<TerminatorInst>(I)) 2952 return false; 2953 2954 // Do not sink alloca instructions out of the entry block. 2955 if (isa<AllocaInst>(I) && I->getParent() == 2956 &DestBlock->getParent()->getEntryBlock()) 2957 return false; 2958 2959 // Do not sink into catchswitch blocks. 2960 if (isa<CatchSwitchInst>(DestBlock->getTerminator())) 2961 return false; 2962 2963 // Do not sink convergent call instructions. 2964 if (auto *CI = dyn_cast<CallInst>(I)) { 2965 if (CI->isConvergent()) 2966 return false; 2967 } 2968 // We can only sink load instructions if there is nothing between the load and 2969 // the end of block that could change the value. 2970 if (I->mayReadFromMemory()) { 2971 for (BasicBlock::iterator Scan = I->getIterator(), 2972 E = I->getParent()->end(); 2973 Scan != E; ++Scan) 2974 if (Scan->mayWriteToMemory()) 2975 return false; 2976 } 2977 2978 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); 2979 I->moveBefore(&*InsertPos); 2980 ++NumSunkInst; 2981 return true; 2982 } 2983 2984 bool InstCombiner::run() { 2985 while (!Worklist.isEmpty()) { 2986 Instruction *I = Worklist.RemoveOne(); 2987 if (I == nullptr) continue; // skip null values. 2988 2989 // Check to see if we can DCE the instruction. 2990 if (isInstructionTriviallyDead(I, &TLI)) { 2991 DEBUG(dbgs() << "IC: DCE: " << *I << '\n'); 2992 eraseInstFromFunction(*I); 2993 ++NumDeadInst; 2994 MadeIRChange = true; 2995 continue; 2996 } 2997 2998 if (!DebugCounter::shouldExecute(VisitCounter)) 2999 continue; 3000 3001 // Instruction isn't dead, see if we can constant propagate it. 3002 if (!I->use_empty() && 3003 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) { 3004 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) { 3005 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n'); 3006 3007 // Add operands to the worklist. 3008 replaceInstUsesWith(*I, C); 3009 ++NumConstProp; 3010 if (isInstructionTriviallyDead(I, &TLI)) 3011 eraseInstFromFunction(*I); 3012 MadeIRChange = true; 3013 continue; 3014 } 3015 } 3016 3017 // In general, it is possible for computeKnownBits to determine all bits in 3018 // a value even when the operands are not all constants. 3019 Type *Ty = I->getType(); 3020 if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) { 3021 KnownBits Known = computeKnownBits(I, /*Depth*/0, I); 3022 if (Known.isConstant()) { 3023 Constant *C = ConstantInt::get(Ty, Known.getConstant()); 3024 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C << 3025 " from: " << *I << '\n'); 3026 3027 // Add operands to the worklist. 3028 replaceInstUsesWith(*I, C); 3029 ++NumConstProp; 3030 if (isInstructionTriviallyDead(I, &TLI)) 3031 eraseInstFromFunction(*I); 3032 MadeIRChange = true; 3033 continue; 3034 } 3035 } 3036 3037 // See if we can trivially sink this instruction to a successor basic block. 3038 if (I->hasOneUse()) { 3039 BasicBlock *BB = I->getParent(); 3040 Instruction *UserInst = cast<Instruction>(*I->user_begin()); 3041 BasicBlock *UserParent; 3042 3043 // Get the block the use occurs in. 3044 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 3045 UserParent = PN->getIncomingBlock(*I->use_begin()); 3046 else 3047 UserParent = UserInst->getParent(); 3048 3049 if (UserParent != BB) { 3050 bool UserIsSuccessor = false; 3051 // See if the user is one of our successors. 3052 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) 3053 if (*SI == UserParent) { 3054 UserIsSuccessor = true; 3055 break; 3056 } 3057 3058 // If the user is one of our immediate successors, and if that successor 3059 // only has us as a predecessors (we'd have to split the critical edge 3060 // otherwise), we can keep going. 3061 if (UserIsSuccessor && UserParent->getUniquePredecessor()) { 3062 // Okay, the CFG is simple enough, try to sink this instruction. 3063 if (TryToSinkInstruction(I, UserParent)) { 3064 DEBUG(dbgs() << "IC: Sink: " << *I << '\n'); 3065 MadeIRChange = true; 3066 // We'll add uses of the sunk instruction below, but since sinking 3067 // can expose opportunities for it's *operands* add them to the 3068 // worklist 3069 for (Use &U : I->operands()) 3070 if (Instruction *OpI = dyn_cast<Instruction>(U.get())) 3071 Worklist.Add(OpI); 3072 } 3073 } 3074 } 3075 } 3076 3077 // Now that we have an instruction, try combining it to simplify it. 3078 Builder.SetInsertPoint(I); 3079 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 3080 3081 #ifndef NDEBUG 3082 std::string OrigI; 3083 #endif 3084 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 3085 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n'); 3086 3087 if (Instruction *Result = visit(*I)) { 3088 ++NumCombined; 3089 // Should we replace the old instruction with a new one? 3090 if (Result != I) { 3091 DEBUG(dbgs() << "IC: Old = " << *I << '\n' 3092 << " New = " << *Result << '\n'); 3093 3094 if (I->getDebugLoc()) 3095 Result->setDebugLoc(I->getDebugLoc()); 3096 // Everything uses the new instruction now. 3097 I->replaceAllUsesWith(Result); 3098 3099 // Move the name to the new instruction first. 3100 Result->takeName(I); 3101 3102 // Push the new instruction and any users onto the worklist. 3103 Worklist.AddUsersToWorkList(*Result); 3104 Worklist.Add(Result); 3105 3106 // Insert the new instruction into the basic block... 3107 BasicBlock *InstParent = I->getParent(); 3108 BasicBlock::iterator InsertPos = I->getIterator(); 3109 3110 // If we replace a PHI with something that isn't a PHI, fix up the 3111 // insertion point. 3112 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos)) 3113 InsertPos = InstParent->getFirstInsertionPt(); 3114 3115 InstParent->getInstList().insert(InsertPos, Result); 3116 3117 eraseInstFromFunction(*I); 3118 } else { 3119 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n' 3120 << " New = " << *I << '\n'); 3121 3122 // If the instruction was modified, it's possible that it is now dead. 3123 // if so, remove it. 3124 if (isInstructionTriviallyDead(I, &TLI)) { 3125 eraseInstFromFunction(*I); 3126 } else { 3127 Worklist.AddUsersToWorkList(*I); 3128 Worklist.Add(I); 3129 } 3130 } 3131 MadeIRChange = true; 3132 } 3133 } 3134 3135 Worklist.Zap(); 3136 return MadeIRChange; 3137 } 3138 3139 /// Walk the function in depth-first order, adding all reachable code to the 3140 /// worklist. 3141 /// 3142 /// This has a couple of tricks to make the code faster and more powerful. In 3143 /// particular, we constant fold and DCE instructions as we go, to avoid adding 3144 /// them to the worklist (this significantly speeds up instcombine on code where 3145 /// many instructions are dead or constant). Additionally, if we find a branch 3146 /// whose condition is a known constant, we only visit the reachable successors. 3147 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL, 3148 SmallPtrSetImpl<BasicBlock *> &Visited, 3149 InstCombineWorklist &ICWorklist, 3150 const TargetLibraryInfo *TLI) { 3151 bool MadeIRChange = false; 3152 SmallVector<BasicBlock*, 256> Worklist; 3153 Worklist.push_back(BB); 3154 3155 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; 3156 DenseMap<Constant *, Constant *> FoldedConstants; 3157 3158 do { 3159 BB = Worklist.pop_back_val(); 3160 3161 // We have now visited this block! If we've already been here, ignore it. 3162 if (!Visited.insert(BB).second) 3163 continue; 3164 3165 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 3166 Instruction *Inst = &*BBI++; 3167 3168 // DCE instruction if trivially dead. 3169 if (isInstructionTriviallyDead(Inst, TLI)) { 3170 ++NumDeadInst; 3171 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n'); 3172 salvageDebugInfo(*Inst); 3173 Inst->eraseFromParent(); 3174 MadeIRChange = true; 3175 continue; 3176 } 3177 3178 // ConstantProp instruction if trivially constant. 3179 if (!Inst->use_empty() && 3180 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0)))) 3181 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) { 3182 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " 3183 << *Inst << '\n'); 3184 Inst->replaceAllUsesWith(C); 3185 ++NumConstProp; 3186 if (isInstructionTriviallyDead(Inst, TLI)) 3187 Inst->eraseFromParent(); 3188 MadeIRChange = true; 3189 continue; 3190 } 3191 3192 // See if we can constant fold its operands. 3193 for (Use &U : Inst->operands()) { 3194 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U)) 3195 continue; 3196 3197 auto *C = cast<Constant>(U); 3198 Constant *&FoldRes = FoldedConstants[C]; 3199 if (!FoldRes) 3200 FoldRes = ConstantFoldConstant(C, DL, TLI); 3201 if (!FoldRes) 3202 FoldRes = C; 3203 3204 if (FoldRes != C) { 3205 DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst 3206 << "\n Old = " << *C 3207 << "\n New = " << *FoldRes << '\n'); 3208 U = FoldRes; 3209 MadeIRChange = true; 3210 } 3211 } 3212 3213 // Skip processing debug intrinsics in InstCombine. Processing these call instructions 3214 // consumes non-trivial amount of time and provides no value for the optimization. 3215 if (!isa<DbgInfoIntrinsic>(Inst)) 3216 InstrsForInstCombineWorklist.push_back(Inst); 3217 } 3218 3219 // Recursively visit successors. If this is a branch or switch on a 3220 // constant, only visit the reachable successor. 3221 TerminatorInst *TI = BB->getTerminator(); 3222 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 3223 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { 3224 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); 3225 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); 3226 Worklist.push_back(ReachableBB); 3227 continue; 3228 } 3229 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 3230 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 3231 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor()); 3232 continue; 3233 } 3234 } 3235 3236 for (BasicBlock *SuccBB : TI->successors()) 3237 Worklist.push_back(SuccBB); 3238 } while (!Worklist.empty()); 3239 3240 // Once we've found all of the instructions to add to instcombine's worklist, 3241 // add them in reverse order. This way instcombine will visit from the top 3242 // of the function down. This jives well with the way that it adds all uses 3243 // of instructions to the worklist after doing a transformation, thus avoiding 3244 // some N^2 behavior in pathological cases. 3245 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist); 3246 3247 return MadeIRChange; 3248 } 3249 3250 /// \brief Populate the IC worklist from a function, and prune any dead basic 3251 /// blocks discovered in the process. 3252 /// 3253 /// This also does basic constant propagation and other forward fixing to make 3254 /// the combiner itself run much faster. 3255 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL, 3256 TargetLibraryInfo *TLI, 3257 InstCombineWorklist &ICWorklist) { 3258 bool MadeIRChange = false; 3259 3260 // Do a depth-first traversal of the function, populate the worklist with 3261 // the reachable instructions. Ignore blocks that are not reachable. Keep 3262 // track of which blocks we visit. 3263 SmallPtrSet<BasicBlock *, 32> Visited; 3264 MadeIRChange |= 3265 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI); 3266 3267 // Do a quick scan over the function. If we find any blocks that are 3268 // unreachable, remove any instructions inside of them. This prevents 3269 // the instcombine code from having to deal with some bad special cases. 3270 for (BasicBlock &BB : F) { 3271 if (Visited.count(&BB)) 3272 continue; 3273 3274 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB); 3275 MadeIRChange |= NumDeadInstInBB > 0; 3276 NumDeadInst += NumDeadInstInBB; 3277 } 3278 3279 return MadeIRChange; 3280 } 3281 3282 static bool combineInstructionsOverFunction( 3283 Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, 3284 AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT, 3285 OptimizationRemarkEmitter &ORE, bool ExpensiveCombines = true, 3286 LoopInfo *LI = nullptr) { 3287 auto &DL = F.getParent()->getDataLayout(); 3288 ExpensiveCombines |= EnableExpensiveCombines; 3289 3290 /// Builder - This is an IRBuilder that automatically inserts new 3291 /// instructions into the worklist when they are created. 3292 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder( 3293 F.getContext(), TargetFolder(DL), 3294 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) { 3295 Worklist.Add(I); 3296 if (match(I, m_Intrinsic<Intrinsic::assume>())) 3297 AC.registerAssumption(cast<CallInst>(I)); 3298 })); 3299 3300 // Lower dbg.declare intrinsics otherwise their value may be clobbered 3301 // by instcombiner. 3302 bool MadeIRChange = false; 3303 if (ShouldLowerDbgDeclare) 3304 MadeIRChange = LowerDbgDeclare(F); 3305 3306 // Iterate while there is work to do. 3307 int Iteration = 0; 3308 while (true) { 3309 ++Iteration; 3310 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 3311 << F.getName() << "\n"); 3312 3313 MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist); 3314 3315 InstCombiner IC(Worklist, Builder, F.optForMinSize(), ExpensiveCombines, AA, 3316 AC, TLI, DT, ORE, DL, LI); 3317 IC.MaxArraySizeForCombine = MaxArraySize; 3318 3319 if (!IC.run()) 3320 break; 3321 } 3322 3323 return MadeIRChange || Iteration > 1; 3324 } 3325 3326 PreservedAnalyses InstCombinePass::run(Function &F, 3327 FunctionAnalysisManager &AM) { 3328 auto &AC = AM.getResult<AssumptionAnalysis>(F); 3329 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 3330 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 3331 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 3332 3333 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 3334 3335 auto *AA = &AM.getResult<AAManager>(F); 3336 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, 3337 ExpensiveCombines, LI)) 3338 // No changes, all analyses are preserved. 3339 return PreservedAnalyses::all(); 3340 3341 // Mark all the analyses that instcombine updates as preserved. 3342 PreservedAnalyses PA; 3343 PA.preserveSet<CFGAnalyses>(); 3344 PA.preserve<AAManager>(); 3345 PA.preserve<BasicAA>(); 3346 PA.preserve<GlobalsAA>(); 3347 return PA; 3348 } 3349 3350 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const { 3351 AU.setPreservesCFG(); 3352 AU.addRequired<AAResultsWrapperPass>(); 3353 AU.addRequired<AssumptionCacheTracker>(); 3354 AU.addRequired<TargetLibraryInfoWrapperPass>(); 3355 AU.addRequired<DominatorTreeWrapperPass>(); 3356 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 3357 AU.addPreserved<DominatorTreeWrapperPass>(); 3358 AU.addPreserved<AAResultsWrapperPass>(); 3359 AU.addPreserved<BasicAAWrapperPass>(); 3360 AU.addPreserved<GlobalsAAWrapperPass>(); 3361 } 3362 3363 bool InstructionCombiningPass::runOnFunction(Function &F) { 3364 if (skipFunction(F)) 3365 return false; 3366 3367 // Required analyses. 3368 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 3369 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 3370 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 3371 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3372 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 3373 3374 // Optional analyses. 3375 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 3376 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; 3377 3378 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, 3379 ExpensiveCombines, LI); 3380 } 3381 3382 char InstructionCombiningPass::ID = 0; 3383 3384 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", 3385 "Combine redundant instructions", false, false) 3386 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 3387 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 3388 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 3389 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 3390 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 3391 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 3392 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine", 3393 "Combine redundant instructions", false, false) 3394 3395 // Initialization Routines 3396 void llvm::initializeInstCombine(PassRegistry &Registry) { 3397 initializeInstructionCombiningPassPass(Registry); 3398 } 3399 3400 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { 3401 initializeInstructionCombiningPassPass(*unwrap(R)); 3402 } 3403 3404 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) { 3405 return new InstructionCombiningPass(ExpensiveCombines); 3406 } 3407