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