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