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