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