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