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