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