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