1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Peephole optimize the CFG. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/APInt.h" 14 #include "llvm/ADT/ArrayRef.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/Optional.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SetOperations.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/Analysis/AssumptionCache.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/EHPersonalities.h" 27 #include "llvm/Analysis/GuardUtils.h" 28 #include "llvm/Analysis/InstructionSimplify.h" 29 #include "llvm/Analysis/MemorySSA.h" 30 #include "llvm/Analysis/MemorySSAUpdater.h" 31 #include "llvm/Analysis/TargetTransformInfo.h" 32 #include "llvm/Analysis/ValueTracking.h" 33 #include "llvm/IR/Attributes.h" 34 #include "llvm/IR/BasicBlock.h" 35 #include "llvm/IR/CFG.h" 36 #include "llvm/IR/CallSite.h" 37 #include "llvm/IR/Constant.h" 38 #include "llvm/IR/ConstantRange.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/DerivedTypes.h" 42 #include "llvm/IR/Function.h" 43 #include "llvm/IR/GlobalValue.h" 44 #include "llvm/IR/GlobalVariable.h" 45 #include "llvm/IR/IRBuilder.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Instruction.h" 48 #include "llvm/IR/Instructions.h" 49 #include "llvm/IR/IntrinsicInst.h" 50 #include "llvm/IR/Intrinsics.h" 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/MDBuilder.h" 53 #include "llvm/IR/Metadata.h" 54 #include "llvm/IR/Module.h" 55 #include "llvm/IR/NoFolder.h" 56 #include "llvm/IR/Operator.h" 57 #include "llvm/IR/PatternMatch.h" 58 #include "llvm/IR/Type.h" 59 #include "llvm/IR/Use.h" 60 #include "llvm/IR/User.h" 61 #include "llvm/IR/Value.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/CommandLine.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/KnownBits.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 70 #include "llvm/Transforms/Utils/Local.h" 71 #include "llvm/Transforms/Utils/ValueMapper.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <climits> 75 #include <cstddef> 76 #include <cstdint> 77 #include <iterator> 78 #include <map> 79 #include <set> 80 #include <tuple> 81 #include <utility> 82 #include <vector> 83 84 using namespace llvm; 85 using namespace PatternMatch; 86 87 #define DEBUG_TYPE "simplifycfg" 88 89 // Chosen as 2 so as to be cheap, but still to have enough power to fold 90 // a select, so the "clamp" idiom (of a min followed by a max) will be caught. 91 // To catch this, we need to fold a compare and a select, hence '2' being the 92 // minimum reasonable default. 93 static cl::opt<unsigned> PHINodeFoldingThreshold( 94 "phi-node-folding-threshold", cl::Hidden, cl::init(2), 95 cl::desc( 96 "Control the amount of phi node folding to perform (default = 2)")); 97 98 static cl::opt<unsigned> TwoEntryPHINodeFoldingThreshold( 99 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4), 100 cl::desc("Control the maximal total instruction cost that we are willing " 101 "to speculatively execute to fold a 2-entry PHI node into a " 102 "select (default = 4)")); 103 104 static cl::opt<bool> DupRet( 105 "simplifycfg-dup-ret", cl::Hidden, cl::init(false), 106 cl::desc("Duplicate return instructions into unconditional branches")); 107 108 static cl::opt<bool> 109 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), 110 cl::desc("Sink common instructions down to the end block")); 111 112 static cl::opt<bool> HoistCondStores( 113 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), 114 cl::desc("Hoist conditional stores if an unconditional store precedes")); 115 116 static cl::opt<bool> MergeCondStores( 117 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), 118 cl::desc("Hoist conditional stores even if an unconditional store does not " 119 "precede - hoist multiple conditional stores into a single " 120 "predicated store")); 121 122 static cl::opt<bool> MergeCondStoresAggressively( 123 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), 124 cl::desc("When merging conditional stores, do so even if the resultant " 125 "basic blocks are unlikely to be if-converted as a result")); 126 127 static cl::opt<bool> SpeculateOneExpensiveInst( 128 "speculate-one-expensive-inst", cl::Hidden, cl::init(true), 129 cl::desc("Allow exactly one expensive instruction to be speculatively " 130 "executed")); 131 132 static cl::opt<unsigned> MaxSpeculationDepth( 133 "max-speculation-depth", cl::Hidden, cl::init(10), 134 cl::desc("Limit maximum recursion depth when calculating costs of " 135 "speculatively executed instructions")); 136 137 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); 138 STATISTIC(NumLinearMaps, 139 "Number of switch instructions turned into linear mapping"); 140 STATISTIC(NumLookupTables, 141 "Number of switch instructions turned into lookup tables"); 142 STATISTIC( 143 NumLookupTablesHoles, 144 "Number of switch instructions turned into lookup tables (holes checked)"); 145 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares"); 146 STATISTIC(NumSinkCommons, 147 "Number of common instructions sunk down to the end block"); 148 STATISTIC(NumSpeculations, "Number of speculative executed instructions"); 149 150 namespace { 151 152 // The first field contains the value that the switch produces when a certain 153 // case group is selected, and the second field is a vector containing the 154 // cases composing the case group. 155 using SwitchCaseResultVectorTy = 156 SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>; 157 158 // The first field contains the phi node that generates a result of the switch 159 // and the second field contains the value generated for a certain case in the 160 // switch for that PHI. 161 using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; 162 163 /// ValueEqualityComparisonCase - Represents a case of a switch. 164 struct ValueEqualityComparisonCase { 165 ConstantInt *Value; 166 BasicBlock *Dest; 167 168 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) 169 : Value(Value), Dest(Dest) {} 170 171 bool operator<(ValueEqualityComparisonCase RHS) const { 172 // Comparing pointers is ok as we only rely on the order for uniquing. 173 return Value < RHS.Value; 174 } 175 176 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } 177 }; 178 179 class SimplifyCFGOpt { 180 const TargetTransformInfo &TTI; 181 const DataLayout &DL; 182 SmallPtrSetImpl<BasicBlock *> *LoopHeaders; 183 const SimplifyCFGOptions &Options; 184 bool Resimplify; 185 186 Value *isValueEqualityComparison(Instruction *TI); 187 BasicBlock *GetValueEqualityComparisonCases( 188 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases); 189 bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI, 190 BasicBlock *Pred, 191 IRBuilder<> &Builder); 192 bool FoldValueComparisonIntoPredecessors(Instruction *TI, 193 IRBuilder<> &Builder); 194 195 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); 196 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); 197 bool SimplifySingleResume(ResumeInst *RI); 198 bool SimplifyCommonResume(ResumeInst *RI); 199 bool SimplifyCleanupReturn(CleanupReturnInst *RI); 200 bool SimplifyUnreachable(UnreachableInst *UI); 201 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); 202 bool SimplifyIndirectBr(IndirectBrInst *IBI); 203 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder); 204 bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder); 205 206 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI, 207 IRBuilder<> &Builder); 208 209 public: 210 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL, 211 SmallPtrSetImpl<BasicBlock *> *LoopHeaders, 212 const SimplifyCFGOptions &Opts) 213 : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {} 214 215 bool run(BasicBlock *BB); 216 bool simplifyOnce(BasicBlock *BB); 217 218 // Helper to set Resimplify and return change indication. 219 bool requestResimplify() { 220 Resimplify = true; 221 return true; 222 } 223 }; 224 225 } // end anonymous namespace 226 227 /// Return true if it is safe to merge these two 228 /// terminator instructions together. 229 static bool 230 SafeToMergeTerminators(Instruction *SI1, Instruction *SI2, 231 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) { 232 if (SI1 == SI2) 233 return false; // Can't merge with self! 234 235 // It is not safe to merge these two switch instructions if they have a common 236 // successor, and if that successor has a PHI node, and if *that* PHI node has 237 // conflicting incoming values from the two switch blocks. 238 BasicBlock *SI1BB = SI1->getParent(); 239 BasicBlock *SI2BB = SI2->getParent(); 240 241 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 242 bool Fail = false; 243 for (BasicBlock *Succ : successors(SI2BB)) 244 if (SI1Succs.count(Succ)) 245 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { 246 PHINode *PN = cast<PHINode>(BBI); 247 if (PN->getIncomingValueForBlock(SI1BB) != 248 PN->getIncomingValueForBlock(SI2BB)) { 249 if (FailBlocks) 250 FailBlocks->insert(Succ); 251 Fail = true; 252 } 253 } 254 255 return !Fail; 256 } 257 258 /// Return true if it is safe and profitable to merge these two terminator 259 /// instructions together, where SI1 is an unconditional branch. PhiNodes will 260 /// store all PHI nodes in common successors. 261 static bool 262 isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2, 263 Instruction *Cond, 264 SmallVectorImpl<PHINode *> &PhiNodes) { 265 if (SI1 == SI2) 266 return false; // Can't merge with self! 267 assert(SI1->isUnconditional() && SI2->isConditional()); 268 269 // We fold the unconditional branch if we can easily update all PHI nodes in 270 // common successors: 271 // 1> We have a constant incoming value for the conditional branch; 272 // 2> We have "Cond" as the incoming value for the unconditional branch; 273 // 3> SI2->getCondition() and Cond have same operands. 274 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); 275 if (!Ci2) 276 return false; 277 if (!(Cond->getOperand(0) == Ci2->getOperand(0) && 278 Cond->getOperand(1) == Ci2->getOperand(1)) && 279 !(Cond->getOperand(0) == Ci2->getOperand(1) && 280 Cond->getOperand(1) == Ci2->getOperand(0))) 281 return false; 282 283 BasicBlock *SI1BB = SI1->getParent(); 284 BasicBlock *SI2BB = SI2->getParent(); 285 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 286 for (BasicBlock *Succ : successors(SI2BB)) 287 if (SI1Succs.count(Succ)) 288 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { 289 PHINode *PN = cast<PHINode>(BBI); 290 if (PN->getIncomingValueForBlock(SI1BB) != Cond || 291 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) 292 return false; 293 PhiNodes.push_back(PN); 294 } 295 return true; 296 } 297 298 /// Update PHI nodes in Succ to indicate that there will now be entries in it 299 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes 300 /// will be the same as those coming in from ExistPred, an existing predecessor 301 /// of Succ. 302 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, 303 BasicBlock *ExistPred, 304 MemorySSAUpdater *MSSAU = nullptr) { 305 for (PHINode &PN : Succ->phis()) 306 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred); 307 if (MSSAU) 308 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ)) 309 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred); 310 } 311 312 /// Compute an abstract "cost" of speculating the given instruction, 313 /// which is assumed to be safe to speculate. TCC_Free means cheap, 314 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively 315 /// expensive. 316 static unsigned ComputeSpeculationCost(const User *I, 317 const TargetTransformInfo &TTI) { 318 assert(isSafeToSpeculativelyExecute(I) && 319 "Instruction is not safe to speculatively execute!"); 320 return TTI.getUserCost(I); 321 } 322 323 /// If we have a merge point of an "if condition" as accepted above, 324 /// return true if the specified value dominates the block. We 325 /// don't handle the true generality of domination here, just a special case 326 /// which works well enough for us. 327 /// 328 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to 329 /// see if V (which must be an instruction) and its recursive operands 330 /// that do not dominate BB have a combined cost lower than CostRemaining and 331 /// are non-trapping. If both are true, the instruction is inserted into the 332 /// set and true is returned. 333 /// 334 /// The cost for most non-trapping instructions is defined as 1 except for 335 /// Select whose cost is 2. 336 /// 337 /// After this function returns, CostRemaining is decreased by the cost of 338 /// V plus its non-dominating operands. If that cost is greater than 339 /// CostRemaining, false is returned and CostRemaining is undefined. 340 static bool DominatesMergePoint(Value *V, BasicBlock *BB, 341 SmallPtrSetImpl<Instruction *> &AggressiveInsts, 342 int &BudgetRemaining, 343 const TargetTransformInfo &TTI, 344 unsigned Depth = 0) { 345 // It is possible to hit a zero-cost cycle (phi/gep instructions for example), 346 // so limit the recursion depth. 347 // TODO: While this recursion limit does prevent pathological behavior, it 348 // would be better to track visited instructions to avoid cycles. 349 if (Depth == MaxSpeculationDepth) 350 return false; 351 352 Instruction *I = dyn_cast<Instruction>(V); 353 if (!I) { 354 // Non-instructions all dominate instructions, but not all constantexprs 355 // can be executed unconditionally. 356 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) 357 if (C->canTrap()) 358 return false; 359 return true; 360 } 361 BasicBlock *PBB = I->getParent(); 362 363 // We don't want to allow weird loops that might have the "if condition" in 364 // the bottom of this block. 365 if (PBB == BB) 366 return false; 367 368 // If this instruction is defined in a block that contains an unconditional 369 // branch to BB, then it must be in the 'conditional' part of the "if 370 // statement". If not, it definitely dominates the region. 371 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); 372 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB) 373 return true; 374 375 // If we have seen this instruction before, don't count it again. 376 if (AggressiveInsts.count(I)) 377 return true; 378 379 // Okay, it looks like the instruction IS in the "condition". Check to 380 // see if it's a cheap instruction to unconditionally compute, and if it 381 // only uses stuff defined outside of the condition. If so, hoist it out. 382 if (!isSafeToSpeculativelyExecute(I)) 383 return false; 384 385 BudgetRemaining -= ComputeSpeculationCost(I, TTI); 386 387 // Allow exactly one instruction to be speculated regardless of its cost 388 // (as long as it is safe to do so). 389 // This is intended to flatten the CFG even if the instruction is a division 390 // or other expensive operation. The speculation of an expensive instruction 391 // is expected to be undone in CodeGenPrepare if the speculation has not 392 // enabled further IR optimizations. 393 if (BudgetRemaining < 0 && 394 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0)) 395 return false; 396 397 // Okay, we can only really hoist these out if their operands do 398 // not take us over the cost threshold. 399 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) 400 if (!DominatesMergePoint(*i, BB, AggressiveInsts, BudgetRemaining, TTI, 401 Depth + 1)) 402 return false; 403 // Okay, it's safe to do this! Remember this instruction. 404 AggressiveInsts.insert(I); 405 return true; 406 } 407 408 /// Extract ConstantInt from value, looking through IntToPtr 409 /// and PointerNullValue. Return NULL if value is not a constant int. 410 static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) { 411 // Normal constant int. 412 ConstantInt *CI = dyn_cast<ConstantInt>(V); 413 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy()) 414 return CI; 415 416 // This is some kind of pointer constant. Turn it into a pointer-sized 417 // ConstantInt if possible. 418 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType())); 419 420 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). 421 if (isa<ConstantPointerNull>(V)) 422 return ConstantInt::get(PtrTy, 0); 423 424 // IntToPtr const int. 425 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 426 if (CE->getOpcode() == Instruction::IntToPtr) 427 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { 428 // The constant is very likely to have the right type already. 429 if (CI->getType() == PtrTy) 430 return CI; 431 else 432 return cast<ConstantInt>( 433 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); 434 } 435 return nullptr; 436 } 437 438 namespace { 439 440 /// Given a chain of or (||) or and (&&) comparison of a value against a 441 /// constant, this will try to recover the information required for a switch 442 /// structure. 443 /// It will depth-first traverse the chain of comparison, seeking for patterns 444 /// like %a == 12 or %a < 4 and combine them to produce a set of integer 445 /// representing the different cases for the switch. 446 /// Note that if the chain is composed of '||' it will build the set of elements 447 /// that matches the comparisons (i.e. any of this value validate the chain) 448 /// while for a chain of '&&' it will build the set elements that make the test 449 /// fail. 450 struct ConstantComparesGatherer { 451 const DataLayout &DL; 452 453 /// Value found for the switch comparison 454 Value *CompValue = nullptr; 455 456 /// Extra clause to be checked before the switch 457 Value *Extra = nullptr; 458 459 /// Set of integers to match in switch 460 SmallVector<ConstantInt *, 8> Vals; 461 462 /// Number of comparisons matched in the and/or chain 463 unsigned UsedICmps = 0; 464 465 /// Construct and compute the result for the comparison instruction Cond 466 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) { 467 gather(Cond); 468 } 469 470 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete; 471 ConstantComparesGatherer & 472 operator=(const ConstantComparesGatherer &) = delete; 473 474 private: 475 /// Try to set the current value used for the comparison, it succeeds only if 476 /// it wasn't set before or if the new value is the same as the old one 477 bool setValueOnce(Value *NewVal) { 478 if (CompValue && CompValue != NewVal) 479 return false; 480 CompValue = NewVal; 481 return (CompValue != nullptr); 482 } 483 484 /// Try to match Instruction "I" as a comparison against a constant and 485 /// populates the array Vals with the set of values that match (or do not 486 /// match depending on isEQ). 487 /// Return false on failure. On success, the Value the comparison matched 488 /// against is placed in CompValue. 489 /// If CompValue is already set, the function is expected to fail if a match 490 /// is found but the value compared to is different. 491 bool matchInstruction(Instruction *I, bool isEQ) { 492 // If this is an icmp against a constant, handle this as one of the cases. 493 ICmpInst *ICI; 494 ConstantInt *C; 495 if (!((ICI = dyn_cast<ICmpInst>(I)) && 496 (C = GetConstantInt(I->getOperand(1), DL)))) { 497 return false; 498 } 499 500 Value *RHSVal; 501 const APInt *RHSC; 502 503 // Pattern match a special case 504 // (x & ~2^z) == y --> x == y || x == y|2^z 505 // This undoes a transformation done by instcombine to fuse 2 compares. 506 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) { 507 // It's a little bit hard to see why the following transformations are 508 // correct. Here is a CVC3 program to verify them for 64-bit values: 509 510 /* 511 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63); 512 x : BITVECTOR(64); 513 y : BITVECTOR(64); 514 z : BITVECTOR(64); 515 mask : BITVECTOR(64) = BVSHL(ONE, z); 516 QUERY( (y & ~mask = y) => 517 ((x & ~mask = y) <=> (x = y OR x = (y | mask))) 518 ); 519 QUERY( (y | mask = y) => 520 ((x | mask = y) <=> (x = y OR x = (y & ~mask))) 521 ); 522 */ 523 524 // Please note that each pattern must be a dual implication (<--> or 525 // iff). One directional implication can create spurious matches. If the 526 // implication is only one-way, an unsatisfiable condition on the left 527 // side can imply a satisfiable condition on the right side. Dual 528 // implication ensures that satisfiable conditions are transformed to 529 // other satisfiable conditions and unsatisfiable conditions are 530 // transformed to other unsatisfiable conditions. 531 532 // Here is a concrete example of a unsatisfiable condition on the left 533 // implying a satisfiable condition on the right: 534 // 535 // mask = (1 << z) 536 // (x & ~mask) == y --> (x == y || x == (y | mask)) 537 // 538 // Substituting y = 3, z = 0 yields: 539 // (x & -2) == 3 --> (x == 3 || x == 2) 540 541 // Pattern match a special case: 542 /* 543 QUERY( (y & ~mask = y) => 544 ((x & ~mask = y) <=> (x = y OR x = (y | mask))) 545 ); 546 */ 547 if (match(ICI->getOperand(0), 548 m_And(m_Value(RHSVal), m_APInt(RHSC)))) { 549 APInt Mask = ~*RHSC; 550 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) { 551 // If we already have a value for the switch, it has to match! 552 if (!setValueOnce(RHSVal)) 553 return false; 554 555 Vals.push_back(C); 556 Vals.push_back( 557 ConstantInt::get(C->getContext(), 558 C->getValue() | Mask)); 559 UsedICmps++; 560 return true; 561 } 562 } 563 564 // Pattern match a special case: 565 /* 566 QUERY( (y | mask = y) => 567 ((x | mask = y) <=> (x = y OR x = (y & ~mask))) 568 ); 569 */ 570 if (match(ICI->getOperand(0), 571 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) { 572 APInt Mask = *RHSC; 573 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) { 574 // If we already have a value for the switch, it has to match! 575 if (!setValueOnce(RHSVal)) 576 return false; 577 578 Vals.push_back(C); 579 Vals.push_back(ConstantInt::get(C->getContext(), 580 C->getValue() & ~Mask)); 581 UsedICmps++; 582 return true; 583 } 584 } 585 586 // If we already have a value for the switch, it has to match! 587 if (!setValueOnce(ICI->getOperand(0))) 588 return false; 589 590 UsedICmps++; 591 Vals.push_back(C); 592 return ICI->getOperand(0); 593 } 594 595 // If we have "x ult 3", for example, then we can add 0,1,2 to the set. 596 ConstantRange Span = ConstantRange::makeAllowedICmpRegion( 597 ICI->getPredicate(), C->getValue()); 598 599 // Shift the range if the compare is fed by an add. This is the range 600 // compare idiom as emitted by instcombine. 601 Value *CandidateVal = I->getOperand(0); 602 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) { 603 Span = Span.subtract(*RHSC); 604 CandidateVal = RHSVal; 605 } 606 607 // If this is an and/!= check, then we are looking to build the set of 608 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into 609 // x != 0 && x != 1. 610 if (!isEQ) 611 Span = Span.inverse(); 612 613 // If there are a ton of values, we don't want to make a ginormous switch. 614 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) { 615 return false; 616 } 617 618 // If we already have a value for the switch, it has to match! 619 if (!setValueOnce(CandidateVal)) 620 return false; 621 622 // Add all values from the range to the set 623 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) 624 Vals.push_back(ConstantInt::get(I->getContext(), Tmp)); 625 626 UsedICmps++; 627 return true; 628 } 629 630 /// Given a potentially 'or'd or 'and'd together collection of icmp 631 /// eq/ne/lt/gt instructions that compare a value against a constant, extract 632 /// the value being compared, and stick the list constants into the Vals 633 /// vector. 634 /// One "Extra" case is allowed to differ from the other. 635 void gather(Value *V) { 636 bool isEQ = (cast<Instruction>(V)->getOpcode() == Instruction::Or); 637 638 // Keep a stack (SmallVector for efficiency) for depth-first traversal 639 SmallVector<Value *, 8> DFT; 640 SmallPtrSet<Value *, 8> Visited; 641 642 // Initialize 643 Visited.insert(V); 644 DFT.push_back(V); 645 646 while (!DFT.empty()) { 647 V = DFT.pop_back_val(); 648 649 if (Instruction *I = dyn_cast<Instruction>(V)) { 650 // If it is a || (or && depending on isEQ), process the operands. 651 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) { 652 if (Visited.insert(I->getOperand(1)).second) 653 DFT.push_back(I->getOperand(1)); 654 if (Visited.insert(I->getOperand(0)).second) 655 DFT.push_back(I->getOperand(0)); 656 continue; 657 } 658 659 // Try to match the current instruction 660 if (matchInstruction(I, isEQ)) 661 // Match succeed, continue the loop 662 continue; 663 } 664 665 // One element of the sequence of || (or &&) could not be match as a 666 // comparison against the same value as the others. 667 // We allow only one "Extra" case to be checked before the switch 668 if (!Extra) { 669 Extra = V; 670 continue; 671 } 672 // Failed to parse a proper sequence, abort now 673 CompValue = nullptr; 674 break; 675 } 676 } 677 }; 678 679 } // end anonymous namespace 680 681 static void EraseTerminatorAndDCECond(Instruction *TI, 682 MemorySSAUpdater *MSSAU = nullptr) { 683 Instruction *Cond = nullptr; 684 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 685 Cond = dyn_cast<Instruction>(SI->getCondition()); 686 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 687 if (BI->isConditional()) 688 Cond = dyn_cast<Instruction>(BI->getCondition()); 689 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { 690 Cond = dyn_cast<Instruction>(IBI->getAddress()); 691 } 692 693 TI->eraseFromParent(); 694 if (Cond) 695 RecursivelyDeleteTriviallyDeadInstructions(Cond, nullptr, MSSAU); 696 } 697 698 /// Return true if the specified terminator checks 699 /// to see if a value is equal to constant integer value. 700 Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) { 701 Value *CV = nullptr; 702 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 703 // Do not permit merging of large switch instructions into their 704 // predecessors unless there is only one predecessor. 705 if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors())) 706 CV = SI->getCondition(); 707 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) 708 if (BI->isConditional() && BI->getCondition()->hasOneUse()) 709 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) { 710 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL)) 711 CV = ICI->getOperand(0); 712 } 713 714 // Unwrap any lossless ptrtoint cast. 715 if (CV) { 716 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) { 717 Value *Ptr = PTII->getPointerOperand(); 718 if (PTII->getType() == DL.getIntPtrType(Ptr->getType())) 719 CV = Ptr; 720 } 721 } 722 return CV; 723 } 724 725 /// Given a value comparison instruction, 726 /// decode all of the 'cases' that it represents and return the 'default' block. 727 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases( 728 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) { 729 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 730 Cases.reserve(SI->getNumCases()); 731 for (auto Case : SI->cases()) 732 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(), 733 Case.getCaseSuccessor())); 734 return SI->getDefaultDest(); 735 } 736 737 BranchInst *BI = cast<BranchInst>(TI); 738 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); 739 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE); 740 Cases.push_back(ValueEqualityComparisonCase( 741 GetConstantInt(ICI->getOperand(1), DL), Succ)); 742 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); 743 } 744 745 /// Given a vector of bb/value pairs, remove any entries 746 /// in the list that match the specified block. 747 static void 748 EliminateBlockCases(BasicBlock *BB, 749 std::vector<ValueEqualityComparisonCase> &Cases) { 750 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end()); 751 } 752 753 /// Return true if there are any keys in C1 that exist in C2 as well. 754 static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1, 755 std::vector<ValueEqualityComparisonCase> &C2) { 756 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2; 757 758 // Make V1 be smaller than V2. 759 if (V1->size() > V2->size()) 760 std::swap(V1, V2); 761 762 if (V1->empty()) 763 return false; 764 if (V1->size() == 1) { 765 // Just scan V2. 766 ConstantInt *TheVal = (*V1)[0].Value; 767 for (unsigned i = 0, e = V2->size(); i != e; ++i) 768 if (TheVal == (*V2)[i].Value) 769 return true; 770 } 771 772 // Otherwise, just sort both lists and compare element by element. 773 array_pod_sort(V1->begin(), V1->end()); 774 array_pod_sort(V2->begin(), V2->end()); 775 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); 776 while (i1 != e1 && i2 != e2) { 777 if ((*V1)[i1].Value == (*V2)[i2].Value) 778 return true; 779 if ((*V1)[i1].Value < (*V2)[i2].Value) 780 ++i1; 781 else 782 ++i2; 783 } 784 return false; 785 } 786 787 // Set branch weights on SwitchInst. This sets the metadata if there is at 788 // least one non-zero weight. 789 static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) { 790 // Check that there is at least one non-zero weight. Otherwise, pass 791 // nullptr to setMetadata which will erase the existing metadata. 792 MDNode *N = nullptr; 793 if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; })) 794 N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights); 795 SI->setMetadata(LLVMContext::MD_prof, N); 796 } 797 798 // Similar to the above, but for branch and select instructions that take 799 // exactly 2 weights. 800 static void setBranchWeights(Instruction *I, uint32_t TrueWeight, 801 uint32_t FalseWeight) { 802 assert(isa<BranchInst>(I) || isa<SelectInst>(I)); 803 // Check that there is at least one non-zero weight. Otherwise, pass 804 // nullptr to setMetadata which will erase the existing metadata. 805 MDNode *N = nullptr; 806 if (TrueWeight || FalseWeight) 807 N = MDBuilder(I->getParent()->getContext()) 808 .createBranchWeights(TrueWeight, FalseWeight); 809 I->setMetadata(LLVMContext::MD_prof, N); 810 } 811 812 /// If TI is known to be a terminator instruction and its block is known to 813 /// only have a single predecessor block, check to see if that predecessor is 814 /// also a value comparison with the same value, and if that comparison 815 /// determines the outcome of this comparison. If so, simplify TI. This does a 816 /// very limited form of jump threading. 817 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor( 818 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) { 819 Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); 820 if (!PredVal) 821 return false; // Not a value comparison in predecessor. 822 823 Value *ThisVal = isValueEqualityComparison(TI); 824 assert(ThisVal && "This isn't a value comparison!!"); 825 if (ThisVal != PredVal) 826 return false; // Different predicates. 827 828 // TODO: Preserve branch weight metadata, similarly to how 829 // FoldValueComparisonIntoPredecessors preserves it. 830 831 // Find out information about when control will move from Pred to TI's block. 832 std::vector<ValueEqualityComparisonCase> PredCases; 833 BasicBlock *PredDef = 834 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases); 835 EliminateBlockCases(PredDef, PredCases); // Remove default from cases. 836 837 // Find information about how control leaves this block. 838 std::vector<ValueEqualityComparisonCase> ThisCases; 839 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); 840 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. 841 842 // If TI's block is the default block from Pred's comparison, potentially 843 // simplify TI based on this knowledge. 844 if (PredDef == TI->getParent()) { 845 // If we are here, we know that the value is none of those cases listed in 846 // PredCases. If there are any cases in ThisCases that are in PredCases, we 847 // can simplify TI. 848 if (!ValuesOverlap(PredCases, ThisCases)) 849 return false; 850 851 if (isa<BranchInst>(TI)) { 852 // Okay, one of the successors of this condbr is dead. Convert it to a 853 // uncond br. 854 assert(ThisCases.size() == 1 && "Branch can only have one case!"); 855 // Insert the new branch. 856 Instruction *NI = Builder.CreateBr(ThisDef); 857 (void)NI; 858 859 // Remove PHI node entries for the dead edge. 860 ThisCases[0].Dest->removePredecessor(TI->getParent()); 861 862 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 863 << "Through successor TI: " << *TI << "Leaving: " << *NI 864 << "\n"); 865 866 EraseTerminatorAndDCECond(TI); 867 return true; 868 } 869 870 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI); 871 // Okay, TI has cases that are statically dead, prune them away. 872 SmallPtrSet<Constant *, 16> DeadCases; 873 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 874 DeadCases.insert(PredCases[i].Value); 875 876 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 877 << "Through successor TI: " << *TI); 878 879 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) { 880 --i; 881 if (DeadCases.count(i->getCaseValue())) { 882 i->getCaseSuccessor()->removePredecessor(TI->getParent()); 883 SI.removeCase(i); 884 } 885 } 886 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n"); 887 return true; 888 } 889 890 // Otherwise, TI's block must correspond to some matched value. Find out 891 // which value (or set of values) this is. 892 ConstantInt *TIV = nullptr; 893 BasicBlock *TIBB = TI->getParent(); 894 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 895 if (PredCases[i].Dest == TIBB) { 896 if (TIV) 897 return false; // Cannot handle multiple values coming to this block. 898 TIV = PredCases[i].Value; 899 } 900 assert(TIV && "No edge from pred to succ?"); 901 902 // Okay, we found the one constant that our value can be if we get into TI's 903 // BB. Find out which successor will unconditionally be branched to. 904 BasicBlock *TheRealDest = nullptr; 905 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) 906 if (ThisCases[i].Value == TIV) { 907 TheRealDest = ThisCases[i].Dest; 908 break; 909 } 910 911 // If not handled by any explicit cases, it is handled by the default case. 912 if (!TheRealDest) 913 TheRealDest = ThisDef; 914 915 // Remove PHI node entries for dead edges. 916 BasicBlock *CheckEdge = TheRealDest; 917 for (BasicBlock *Succ : successors(TIBB)) 918 if (Succ != CheckEdge) 919 Succ->removePredecessor(TIBB); 920 else 921 CheckEdge = nullptr; 922 923 // Insert the new branch. 924 Instruction *NI = Builder.CreateBr(TheRealDest); 925 (void)NI; 926 927 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 928 << "Through successor TI: " << *TI << "Leaving: " << *NI 929 << "\n"); 930 931 EraseTerminatorAndDCECond(TI); 932 return true; 933 } 934 935 namespace { 936 937 /// This class implements a stable ordering of constant 938 /// integers that does not depend on their address. This is important for 939 /// applications that sort ConstantInt's to ensure uniqueness. 940 struct ConstantIntOrdering { 941 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { 942 return LHS->getValue().ult(RHS->getValue()); 943 } 944 }; 945 946 } // end anonymous namespace 947 948 static int ConstantIntSortPredicate(ConstantInt *const *P1, 949 ConstantInt *const *P2) { 950 const ConstantInt *LHS = *P1; 951 const ConstantInt *RHS = *P2; 952 if (LHS == RHS) 953 return 0; 954 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1; 955 } 956 957 static inline bool HasBranchWeights(const Instruction *I) { 958 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof); 959 if (ProfMD && ProfMD->getOperand(0)) 960 if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0))) 961 return MDS->getString().equals("branch_weights"); 962 963 return false; 964 } 965 966 /// Get Weights of a given terminator, the default weight is at the front 967 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight 968 /// metadata. 969 static void GetBranchWeights(Instruction *TI, 970 SmallVectorImpl<uint64_t> &Weights) { 971 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof); 972 assert(MD); 973 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) { 974 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i)); 975 Weights.push_back(CI->getValue().getZExtValue()); 976 } 977 978 // If TI is a conditional eq, the default case is the false case, 979 // and the corresponding branch-weight data is at index 2. We swap the 980 // default weight to be the first entry. 981 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 982 assert(Weights.size() == 2); 983 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); 984 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 985 std::swap(Weights.front(), Weights.back()); 986 } 987 } 988 989 /// Keep halving the weights until all can fit in uint32_t. 990 static void FitWeights(MutableArrayRef<uint64_t> Weights) { 991 uint64_t Max = *std::max_element(Weights.begin(), Weights.end()); 992 if (Max > UINT_MAX) { 993 unsigned Offset = 32 - countLeadingZeros(Max); 994 for (uint64_t &I : Weights) 995 I >>= Offset; 996 } 997 } 998 999 /// The specified terminator is a value equality comparison instruction 1000 /// (either a switch or a branch on "X == c"). 1001 /// See if any of the predecessors of the terminator block are value comparisons 1002 /// on the same value. If so, and if safe to do so, fold them together. 1003 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI, 1004 IRBuilder<> &Builder) { 1005 BasicBlock *BB = TI->getParent(); 1006 Value *CV = isValueEqualityComparison(TI); // CondVal 1007 assert(CV && "Not a comparison?"); 1008 bool Changed = false; 1009 1010 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB)); 1011 while (!Preds.empty()) { 1012 BasicBlock *Pred = Preds.pop_back_val(); 1013 1014 // See if the predecessor is a comparison with the same value. 1015 Instruction *PTI = Pred->getTerminator(); 1016 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal 1017 1018 if (PCV == CV && TI != PTI) { 1019 SmallSetVector<BasicBlock*, 4> FailBlocks; 1020 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) { 1021 for (auto *Succ : FailBlocks) { 1022 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split")) 1023 return false; 1024 } 1025 } 1026 1027 // Figure out which 'cases' to copy from SI to PSI. 1028 std::vector<ValueEqualityComparisonCase> BBCases; 1029 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); 1030 1031 std::vector<ValueEqualityComparisonCase> PredCases; 1032 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); 1033 1034 // Based on whether the default edge from PTI goes to BB or not, fill in 1035 // PredCases and PredDefault with the new switch cases we would like to 1036 // build. 1037 SmallVector<BasicBlock *, 8> NewSuccessors; 1038 1039 // Update the branch weight metadata along the way 1040 SmallVector<uint64_t, 8> Weights; 1041 bool PredHasWeights = HasBranchWeights(PTI); 1042 bool SuccHasWeights = HasBranchWeights(TI); 1043 1044 if (PredHasWeights) { 1045 GetBranchWeights(PTI, Weights); 1046 // branch-weight metadata is inconsistent here. 1047 if (Weights.size() != 1 + PredCases.size()) 1048 PredHasWeights = SuccHasWeights = false; 1049 } else if (SuccHasWeights) 1050 // If there are no predecessor weights but there are successor weights, 1051 // populate Weights with 1, which will later be scaled to the sum of 1052 // successor's weights 1053 Weights.assign(1 + PredCases.size(), 1); 1054 1055 SmallVector<uint64_t, 8> SuccWeights; 1056 if (SuccHasWeights) { 1057 GetBranchWeights(TI, SuccWeights); 1058 // branch-weight metadata is inconsistent here. 1059 if (SuccWeights.size() != 1 + BBCases.size()) 1060 PredHasWeights = SuccHasWeights = false; 1061 } else if (PredHasWeights) 1062 SuccWeights.assign(1 + BBCases.size(), 1); 1063 1064 if (PredDefault == BB) { 1065 // If this is the default destination from PTI, only the edges in TI 1066 // that don't occur in PTI, or that branch to BB will be activated. 1067 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled; 1068 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 1069 if (PredCases[i].Dest != BB) 1070 PTIHandled.insert(PredCases[i].Value); 1071 else { 1072 // The default destination is BB, we don't need explicit targets. 1073 std::swap(PredCases[i], PredCases.back()); 1074 1075 if (PredHasWeights || SuccHasWeights) { 1076 // Increase weight for the default case. 1077 Weights[0] += Weights[i + 1]; 1078 std::swap(Weights[i + 1], Weights.back()); 1079 Weights.pop_back(); 1080 } 1081 1082 PredCases.pop_back(); 1083 --i; 1084 --e; 1085 } 1086 1087 // Reconstruct the new switch statement we will be building. 1088 if (PredDefault != BBDefault) { 1089 PredDefault->removePredecessor(Pred); 1090 PredDefault = BBDefault; 1091 NewSuccessors.push_back(BBDefault); 1092 } 1093 1094 unsigned CasesFromPred = Weights.size(); 1095 uint64_t ValidTotalSuccWeight = 0; 1096 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 1097 if (!PTIHandled.count(BBCases[i].Value) && 1098 BBCases[i].Dest != BBDefault) { 1099 PredCases.push_back(BBCases[i]); 1100 NewSuccessors.push_back(BBCases[i].Dest); 1101 if (SuccHasWeights || PredHasWeights) { 1102 // The default weight is at index 0, so weight for the ith case 1103 // should be at index i+1. Scale the cases from successor by 1104 // PredDefaultWeight (Weights[0]). 1105 Weights.push_back(Weights[0] * SuccWeights[i + 1]); 1106 ValidTotalSuccWeight += SuccWeights[i + 1]; 1107 } 1108 } 1109 1110 if (SuccHasWeights || PredHasWeights) { 1111 ValidTotalSuccWeight += SuccWeights[0]; 1112 // Scale the cases from predecessor by ValidTotalSuccWeight. 1113 for (unsigned i = 1; i < CasesFromPred; ++i) 1114 Weights[i] *= ValidTotalSuccWeight; 1115 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]). 1116 Weights[0] *= SuccWeights[0]; 1117 } 1118 } else { 1119 // If this is not the default destination from PSI, only the edges 1120 // in SI that occur in PSI with a destination of BB will be 1121 // activated. 1122 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled; 1123 std::map<ConstantInt *, uint64_t> WeightsForHandled; 1124 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 1125 if (PredCases[i].Dest == BB) { 1126 PTIHandled.insert(PredCases[i].Value); 1127 1128 if (PredHasWeights || SuccHasWeights) { 1129 WeightsForHandled[PredCases[i].Value] = Weights[i + 1]; 1130 std::swap(Weights[i + 1], Weights.back()); 1131 Weights.pop_back(); 1132 } 1133 1134 std::swap(PredCases[i], PredCases.back()); 1135 PredCases.pop_back(); 1136 --i; 1137 --e; 1138 } 1139 1140 // Okay, now we know which constants were sent to BB from the 1141 // predecessor. Figure out where they will all go now. 1142 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 1143 if (PTIHandled.count(BBCases[i].Value)) { 1144 // If this is one we are capable of getting... 1145 if (PredHasWeights || SuccHasWeights) 1146 Weights.push_back(WeightsForHandled[BBCases[i].Value]); 1147 PredCases.push_back(BBCases[i]); 1148 NewSuccessors.push_back(BBCases[i].Dest); 1149 PTIHandled.erase( 1150 BBCases[i].Value); // This constant is taken care of 1151 } 1152 1153 // If there are any constants vectored to BB that TI doesn't handle, 1154 // they must go to the default destination of TI. 1155 for (ConstantInt *I : PTIHandled) { 1156 if (PredHasWeights || SuccHasWeights) 1157 Weights.push_back(WeightsForHandled[I]); 1158 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault)); 1159 NewSuccessors.push_back(BBDefault); 1160 } 1161 } 1162 1163 // Okay, at this point, we know which new successor Pred will get. Make 1164 // sure we update the number of entries in the PHI nodes for these 1165 // successors. 1166 for (BasicBlock *NewSuccessor : NewSuccessors) 1167 AddPredecessorToBlock(NewSuccessor, Pred, BB); 1168 1169 Builder.SetInsertPoint(PTI); 1170 // Convert pointer to int before we switch. 1171 if (CV->getType()->isPointerTy()) { 1172 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), 1173 "magicptr"); 1174 } 1175 1176 // Now that the successors are updated, create the new Switch instruction. 1177 SwitchInst *NewSI = 1178 Builder.CreateSwitch(CV, PredDefault, PredCases.size()); 1179 NewSI->setDebugLoc(PTI->getDebugLoc()); 1180 for (ValueEqualityComparisonCase &V : PredCases) 1181 NewSI->addCase(V.Value, V.Dest); 1182 1183 if (PredHasWeights || SuccHasWeights) { 1184 // Halve the weights if any of them cannot fit in an uint32_t 1185 FitWeights(Weights); 1186 1187 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 1188 1189 setBranchWeights(NewSI, MDWeights); 1190 } 1191 1192 EraseTerminatorAndDCECond(PTI); 1193 1194 // Okay, last check. If BB is still a successor of PSI, then we must 1195 // have an infinite loop case. If so, add an infinitely looping block 1196 // to handle the case to preserve the behavior of the code. 1197 BasicBlock *InfLoopBlock = nullptr; 1198 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) 1199 if (NewSI->getSuccessor(i) == BB) { 1200 if (!InfLoopBlock) { 1201 // Insert it at the end of the function, because it's either code, 1202 // or it won't matter if it's hot. :) 1203 InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop", 1204 BB->getParent()); 1205 BranchInst::Create(InfLoopBlock, InfLoopBlock); 1206 } 1207 NewSI->setSuccessor(i, InfLoopBlock); 1208 } 1209 1210 Changed = true; 1211 } 1212 } 1213 return Changed; 1214 } 1215 1216 // If we would need to insert a select that uses the value of this invoke 1217 // (comments in HoistThenElseCodeToIf explain why we would need to do this), we 1218 // can't hoist the invoke, as there is nowhere to put the select in this case. 1219 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, 1220 Instruction *I1, Instruction *I2) { 1221 for (BasicBlock *Succ : successors(BB1)) { 1222 for (const PHINode &PN : Succ->phis()) { 1223 Value *BB1V = PN.getIncomingValueForBlock(BB1); 1224 Value *BB2V = PN.getIncomingValueForBlock(BB2); 1225 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) { 1226 return false; 1227 } 1228 } 1229 } 1230 return true; 1231 } 1232 1233 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I); 1234 1235 /// Given a conditional branch that goes to BB1 and BB2, hoist any common code 1236 /// in the two blocks up into the branch block. The caller of this function 1237 /// guarantees that BI's block dominates BB1 and BB2. 1238 static bool HoistThenElseCodeToIf(BranchInst *BI, 1239 const TargetTransformInfo &TTI) { 1240 // This does very trivial matching, with limited scanning, to find identical 1241 // instructions in the two blocks. In particular, we don't want to get into 1242 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As 1243 // such, we currently just scan for obviously identical instructions in an 1244 // identical order. 1245 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. 1246 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination 1247 1248 BasicBlock::iterator BB1_Itr = BB1->begin(); 1249 BasicBlock::iterator BB2_Itr = BB2->begin(); 1250 1251 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++; 1252 // Skip debug info if it is not identical. 1253 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); 1254 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); 1255 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { 1256 while (isa<DbgInfoIntrinsic>(I1)) 1257 I1 = &*BB1_Itr++; 1258 while (isa<DbgInfoIntrinsic>(I2)) 1259 I2 = &*BB2_Itr++; 1260 } 1261 // FIXME: Can we define a safety predicate for CallBr? 1262 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) || 1263 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) || 1264 isa<CallBrInst>(I1)) 1265 return false; 1266 1267 BasicBlock *BIParent = BI->getParent(); 1268 1269 bool Changed = false; 1270 do { 1271 // If we are hoisting the terminator instruction, don't move one (making a 1272 // broken BB), instead clone it, and remove BI. 1273 if (I1->isTerminator()) 1274 goto HoistTerminator; 1275 1276 // If we're going to hoist a call, make sure that the two instructions we're 1277 // commoning/hoisting are both marked with musttail, or neither of them is 1278 // marked as such. Otherwise, we might end up in a situation where we hoist 1279 // from a block where the terminator is a `ret` to a block where the terminator 1280 // is a `br`, and `musttail` calls expect to be followed by a return. 1281 auto *C1 = dyn_cast<CallInst>(I1); 1282 auto *C2 = dyn_cast<CallInst>(I2); 1283 if (C1 && C2) 1284 if (C1->isMustTailCall() != C2->isMustTailCall()) 1285 return Changed; 1286 1287 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2)) 1288 return Changed; 1289 1290 if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) { 1291 assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2)); 1292 // The debug location is an integral part of a debug info intrinsic 1293 // and can't be separated from it or replaced. Instead of attempting 1294 // to merge locations, simply hoist both copies of the intrinsic. 1295 BIParent->getInstList().splice(BI->getIterator(), 1296 BB1->getInstList(), I1); 1297 BIParent->getInstList().splice(BI->getIterator(), 1298 BB2->getInstList(), I2); 1299 Changed = true; 1300 } else { 1301 // For a normal instruction, we just move one to right before the branch, 1302 // then replace all uses of the other with the first. Finally, we remove 1303 // the now redundant second instruction. 1304 BIParent->getInstList().splice(BI->getIterator(), 1305 BB1->getInstList(), I1); 1306 if (!I2->use_empty()) 1307 I2->replaceAllUsesWith(I1); 1308 I1->andIRFlags(I2); 1309 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, 1310 LLVMContext::MD_range, 1311 LLVMContext::MD_fpmath, 1312 LLVMContext::MD_invariant_load, 1313 LLVMContext::MD_nonnull, 1314 LLVMContext::MD_invariant_group, 1315 LLVMContext::MD_align, 1316 LLVMContext::MD_dereferenceable, 1317 LLVMContext::MD_dereferenceable_or_null, 1318 LLVMContext::MD_mem_parallel_loop_access, 1319 LLVMContext::MD_access_group, 1320 LLVMContext::MD_preserve_access_index}; 1321 combineMetadata(I1, I2, KnownIDs, true); 1322 1323 // I1 and I2 are being combined into a single instruction. Its debug 1324 // location is the merged locations of the original instructions. 1325 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc()); 1326 1327 I2->eraseFromParent(); 1328 Changed = true; 1329 } 1330 1331 I1 = &*BB1_Itr++; 1332 I2 = &*BB2_Itr++; 1333 // Skip debug info if it is not identical. 1334 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); 1335 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); 1336 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { 1337 while (isa<DbgInfoIntrinsic>(I1)) 1338 I1 = &*BB1_Itr++; 1339 while (isa<DbgInfoIntrinsic>(I2)) 1340 I2 = &*BB2_Itr++; 1341 } 1342 } while (I1->isIdenticalToWhenDefined(I2)); 1343 1344 return true; 1345 1346 HoistTerminator: 1347 // It may not be possible to hoist an invoke. 1348 // FIXME: Can we define a safety predicate for CallBr? 1349 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) 1350 return Changed; 1351 1352 // TODO: callbr hoisting currently disabled pending further study. 1353 if (isa<CallBrInst>(I1)) 1354 return Changed; 1355 1356 for (BasicBlock *Succ : successors(BB1)) { 1357 for (PHINode &PN : Succ->phis()) { 1358 Value *BB1V = PN.getIncomingValueForBlock(BB1); 1359 Value *BB2V = PN.getIncomingValueForBlock(BB2); 1360 if (BB1V == BB2V) 1361 continue; 1362 1363 // Check for passingValueIsAlwaysUndefined here because we would rather 1364 // eliminate undefined control flow then converting it to a select. 1365 if (passingValueIsAlwaysUndefined(BB1V, &PN) || 1366 passingValueIsAlwaysUndefined(BB2V, &PN)) 1367 return Changed; 1368 1369 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V)) 1370 return Changed; 1371 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V)) 1372 return Changed; 1373 } 1374 } 1375 1376 // Okay, it is safe to hoist the terminator. 1377 Instruction *NT = I1->clone(); 1378 BIParent->getInstList().insert(BI->getIterator(), NT); 1379 if (!NT->getType()->isVoidTy()) { 1380 I1->replaceAllUsesWith(NT); 1381 I2->replaceAllUsesWith(NT); 1382 NT->takeName(I1); 1383 } 1384 1385 // Ensure terminator gets a debug location, even an unknown one, in case 1386 // it involves inlinable calls. 1387 NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc()); 1388 1389 // PHIs created below will adopt NT's merged DebugLoc. 1390 IRBuilder<NoFolder> Builder(NT); 1391 1392 // Hoisting one of the terminators from our successor is a great thing. 1393 // Unfortunately, the successors of the if/else blocks may have PHI nodes in 1394 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI 1395 // nodes, so we insert select instruction to compute the final result. 1396 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects; 1397 for (BasicBlock *Succ : successors(BB1)) { 1398 for (PHINode &PN : Succ->phis()) { 1399 Value *BB1V = PN.getIncomingValueForBlock(BB1); 1400 Value *BB2V = PN.getIncomingValueForBlock(BB2); 1401 if (BB1V == BB2V) 1402 continue; 1403 1404 // These values do not agree. Insert a select instruction before NT 1405 // that determines the right value. 1406 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; 1407 if (!SI) { 1408 // Propagate fast-math-flags from phi node to its replacement select. 1409 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 1410 if (isa<FPMathOperator>(PN)) 1411 Builder.setFastMathFlags(PN.getFastMathFlags()); 1412 1413 SI = cast<SelectInst>( 1414 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V, 1415 BB1V->getName() + "." + BB2V->getName(), BI)); 1416 } 1417 1418 // Make the PHI node use the select for all incoming values for BB1/BB2 1419 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 1420 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2) 1421 PN.setIncomingValue(i, SI); 1422 } 1423 } 1424 1425 // Update any PHI nodes in our new successors. 1426 for (BasicBlock *Succ : successors(BB1)) 1427 AddPredecessorToBlock(Succ, BIParent, BB1); 1428 1429 EraseTerminatorAndDCECond(BI); 1430 return true; 1431 } 1432 1433 // Check lifetime markers. 1434 static bool isLifeTimeMarker(const Instruction *I) { 1435 if (auto II = dyn_cast<IntrinsicInst>(I)) { 1436 switch (II->getIntrinsicID()) { 1437 default: 1438 break; 1439 case Intrinsic::lifetime_start: 1440 case Intrinsic::lifetime_end: 1441 return true; 1442 } 1443 } 1444 return false; 1445 } 1446 1447 // All instructions in Insts belong to different blocks that all unconditionally 1448 // branch to a common successor. Analyze each instruction and return true if it 1449 // would be possible to sink them into their successor, creating one common 1450 // instruction instead. For every value that would be required to be provided by 1451 // PHI node (because an operand varies in each input block), add to PHIOperands. 1452 static bool canSinkInstructions( 1453 ArrayRef<Instruction *> Insts, 1454 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) { 1455 // Prune out obviously bad instructions to move. Each instruction must have 1456 // exactly zero or one use, and we check later that use is by a single, common 1457 // PHI instruction in the successor. 1458 bool HasUse = !Insts.front()->user_empty(); 1459 for (auto *I : Insts) { 1460 // These instructions may change or break semantics if moved. 1461 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) || 1462 I->getType()->isTokenTy()) 1463 return false; 1464 1465 // Conservatively return false if I is an inline-asm instruction. Sinking 1466 // and merging inline-asm instructions can potentially create arguments 1467 // that cannot satisfy the inline-asm constraints. 1468 if (const auto *C = dyn_cast<CallBase>(I)) 1469 if (C->isInlineAsm()) 1470 return false; 1471 1472 // Each instruction must have zero or one use. 1473 if (HasUse && !I->hasOneUse()) 1474 return false; 1475 if (!HasUse && !I->user_empty()) 1476 return false; 1477 } 1478 1479 const Instruction *I0 = Insts.front(); 1480 for (auto *I : Insts) 1481 if (!I->isSameOperationAs(I0)) 1482 return false; 1483 1484 // All instructions in Insts are known to be the same opcode. If they have a 1485 // use, check that the only user is a PHI or in the same block as the 1486 // instruction, because if a user is in the same block as an instruction we're 1487 // contemplating sinking, it must already be determined to be sinkable. 1488 if (HasUse) { 1489 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin()); 1490 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0); 1491 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool { 1492 auto *U = cast<Instruction>(*I->user_begin()); 1493 return (PNUse && 1494 PNUse->getParent() == Succ && 1495 PNUse->getIncomingValueForBlock(I->getParent()) == I) || 1496 U->getParent() == I->getParent(); 1497 })) 1498 return false; 1499 } 1500 1501 // Because SROA can't handle speculating stores of selects, try not to sink 1502 // loads, stores or lifetime markers of allocas when we'd have to create a 1503 // PHI for the address operand. Also, because it is likely that loads or 1504 // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink 1505 // them. 1506 // This can cause code churn which can have unintended consequences down 1507 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244. 1508 // FIXME: This is a workaround for a deficiency in SROA - see 1509 // https://llvm.org/bugs/show_bug.cgi?id=30188 1510 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) { 1511 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts()); 1512 })) 1513 return false; 1514 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) { 1515 return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts()); 1516 })) 1517 return false; 1518 if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) { 1519 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts()); 1520 })) 1521 return false; 1522 1523 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) { 1524 if (I0->getOperand(OI)->getType()->isTokenTy()) 1525 // Don't touch any operand of token type. 1526 return false; 1527 1528 auto SameAsI0 = [&I0, OI](const Instruction *I) { 1529 assert(I->getNumOperands() == I0->getNumOperands()); 1530 return I->getOperand(OI) == I0->getOperand(OI); 1531 }; 1532 if (!all_of(Insts, SameAsI0)) { 1533 if (!canReplaceOperandWithVariable(I0, OI)) 1534 // We can't create a PHI from this GEP. 1535 return false; 1536 // Don't create indirect calls! The called value is the final operand. 1537 if (isa<CallBase>(I0) && OI == OE - 1) { 1538 // FIXME: if the call was *already* indirect, we should do this. 1539 return false; 1540 } 1541 for (auto *I : Insts) 1542 PHIOperands[I].push_back(I->getOperand(OI)); 1543 } 1544 } 1545 return true; 1546 } 1547 1548 // Assuming canSinkLastInstruction(Blocks) has returned true, sink the last 1549 // instruction of every block in Blocks to their common successor, commoning 1550 // into one instruction. 1551 static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) { 1552 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0); 1553 1554 // canSinkLastInstruction returning true guarantees that every block has at 1555 // least one non-terminator instruction. 1556 SmallVector<Instruction*,4> Insts; 1557 for (auto *BB : Blocks) { 1558 Instruction *I = BB->getTerminator(); 1559 do { 1560 I = I->getPrevNode(); 1561 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front()); 1562 if (!isa<DbgInfoIntrinsic>(I)) 1563 Insts.push_back(I); 1564 } 1565 1566 // The only checking we need to do now is that all users of all instructions 1567 // are the same PHI node. canSinkLastInstruction should have checked this but 1568 // it is slightly over-aggressive - it gets confused by commutative instructions 1569 // so double-check it here. 1570 Instruction *I0 = Insts.front(); 1571 if (!I0->user_empty()) { 1572 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin()); 1573 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool { 1574 auto *U = cast<Instruction>(*I->user_begin()); 1575 return U == PNUse; 1576 })) 1577 return false; 1578 } 1579 1580 // We don't need to do any more checking here; canSinkLastInstruction should 1581 // have done it all for us. 1582 SmallVector<Value*, 4> NewOperands; 1583 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) { 1584 // This check is different to that in canSinkLastInstruction. There, we 1585 // cared about the global view once simplifycfg (and instcombine) have 1586 // completed - it takes into account PHIs that become trivially 1587 // simplifiable. However here we need a more local view; if an operand 1588 // differs we create a PHI and rely on instcombine to clean up the very 1589 // small mess we may make. 1590 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) { 1591 return I->getOperand(O) != I0->getOperand(O); 1592 }); 1593 if (!NeedPHI) { 1594 NewOperands.push_back(I0->getOperand(O)); 1595 continue; 1596 } 1597 1598 // Create a new PHI in the successor block and populate it. 1599 auto *Op = I0->getOperand(O); 1600 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!"); 1601 auto *PN = PHINode::Create(Op->getType(), Insts.size(), 1602 Op->getName() + ".sink", &BBEnd->front()); 1603 for (auto *I : Insts) 1604 PN->addIncoming(I->getOperand(O), I->getParent()); 1605 NewOperands.push_back(PN); 1606 } 1607 1608 // Arbitrarily use I0 as the new "common" instruction; remap its operands 1609 // and move it to the start of the successor block. 1610 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) 1611 I0->getOperandUse(O).set(NewOperands[O]); 1612 I0->moveBefore(&*BBEnd->getFirstInsertionPt()); 1613 1614 // Update metadata and IR flags, and merge debug locations. 1615 for (auto *I : Insts) 1616 if (I != I0) { 1617 // The debug location for the "common" instruction is the merged locations 1618 // of all the commoned instructions. We start with the original location 1619 // of the "common" instruction and iteratively merge each location in the 1620 // loop below. 1621 // This is an N-way merge, which will be inefficient if I0 is a CallInst. 1622 // However, as N-way merge for CallInst is rare, so we use simplified API 1623 // instead of using complex API for N-way merge. 1624 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc()); 1625 combineMetadataForCSE(I0, I, true); 1626 I0->andIRFlags(I); 1627 } 1628 1629 if (!I0->user_empty()) { 1630 // canSinkLastInstruction checked that all instructions were used by 1631 // one and only one PHI node. Find that now, RAUW it to our common 1632 // instruction and nuke it. 1633 auto *PN = cast<PHINode>(*I0->user_begin()); 1634 PN->replaceAllUsesWith(I0); 1635 PN->eraseFromParent(); 1636 } 1637 1638 // Finally nuke all instructions apart from the common instruction. 1639 for (auto *I : Insts) 1640 if (I != I0) 1641 I->eraseFromParent(); 1642 1643 return true; 1644 } 1645 1646 namespace { 1647 1648 // LockstepReverseIterator - Iterates through instructions 1649 // in a set of blocks in reverse order from the first non-terminator. 1650 // For example (assume all blocks have size n): 1651 // LockstepReverseIterator I([B1, B2, B3]); 1652 // *I-- = [B1[n], B2[n], B3[n]]; 1653 // *I-- = [B1[n-1], B2[n-1], B3[n-1]]; 1654 // *I-- = [B1[n-2], B2[n-2], B3[n-2]]; 1655 // ... 1656 class LockstepReverseIterator { 1657 ArrayRef<BasicBlock*> Blocks; 1658 SmallVector<Instruction*,4> Insts; 1659 bool Fail; 1660 1661 public: 1662 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) { 1663 reset(); 1664 } 1665 1666 void reset() { 1667 Fail = false; 1668 Insts.clear(); 1669 for (auto *BB : Blocks) { 1670 Instruction *Inst = BB->getTerminator(); 1671 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);) 1672 Inst = Inst->getPrevNode(); 1673 if (!Inst) { 1674 // Block wasn't big enough. 1675 Fail = true; 1676 return; 1677 } 1678 Insts.push_back(Inst); 1679 } 1680 } 1681 1682 bool isValid() const { 1683 return !Fail; 1684 } 1685 1686 void operator--() { 1687 if (Fail) 1688 return; 1689 for (auto *&Inst : Insts) { 1690 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);) 1691 Inst = Inst->getPrevNode(); 1692 // Already at beginning of block. 1693 if (!Inst) { 1694 Fail = true; 1695 return; 1696 } 1697 } 1698 } 1699 1700 ArrayRef<Instruction*> operator * () const { 1701 return Insts; 1702 } 1703 }; 1704 1705 } // end anonymous namespace 1706 1707 /// Check whether BB's predecessors end with unconditional branches. If it is 1708 /// true, sink any common code from the predecessors to BB. 1709 /// We also allow one predecessor to end with conditional branch (but no more 1710 /// than one). 1711 static bool SinkCommonCodeFromPredecessors(BasicBlock *BB) { 1712 // We support two situations: 1713 // (1) all incoming arcs are unconditional 1714 // (2) one incoming arc is conditional 1715 // 1716 // (2) is very common in switch defaults and 1717 // else-if patterns; 1718 // 1719 // if (a) f(1); 1720 // else if (b) f(2); 1721 // 1722 // produces: 1723 // 1724 // [if] 1725 // / \ 1726 // [f(1)] [if] 1727 // | | \ 1728 // | | | 1729 // | [f(2)]| 1730 // \ | / 1731 // [ end ] 1732 // 1733 // [end] has two unconditional predecessor arcs and one conditional. The 1734 // conditional refers to the implicit empty 'else' arc. This conditional 1735 // arc can also be caused by an empty default block in a switch. 1736 // 1737 // In this case, we attempt to sink code from all *unconditional* arcs. 1738 // If we can sink instructions from these arcs (determined during the scan 1739 // phase below) we insert a common successor for all unconditional arcs and 1740 // connect that to [end], to enable sinking: 1741 // 1742 // [if] 1743 // / \ 1744 // [x(1)] [if] 1745 // | | \ 1746 // | | \ 1747 // | [x(2)] | 1748 // \ / | 1749 // [sink.split] | 1750 // \ / 1751 // [ end ] 1752 // 1753 SmallVector<BasicBlock*,4> UnconditionalPreds; 1754 Instruction *Cond = nullptr; 1755 for (auto *B : predecessors(BB)) { 1756 auto *T = B->getTerminator(); 1757 if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional()) 1758 UnconditionalPreds.push_back(B); 1759 else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond) 1760 Cond = T; 1761 else 1762 return false; 1763 } 1764 if (UnconditionalPreds.size() < 2) 1765 return false; 1766 1767 bool Changed = false; 1768 // We take a two-step approach to tail sinking. First we scan from the end of 1769 // each block upwards in lockstep. If the n'th instruction from the end of each 1770 // block can be sunk, those instructions are added to ValuesToSink and we 1771 // carry on. If we can sink an instruction but need to PHI-merge some operands 1772 // (because they're not identical in each instruction) we add these to 1773 // PHIOperands. 1774 unsigned ScanIdx = 0; 1775 SmallPtrSet<Value*,4> InstructionsToSink; 1776 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands; 1777 LockstepReverseIterator LRI(UnconditionalPreds); 1778 while (LRI.isValid() && 1779 canSinkInstructions(*LRI, PHIOperands)) { 1780 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0] 1781 << "\n"); 1782 InstructionsToSink.insert((*LRI).begin(), (*LRI).end()); 1783 ++ScanIdx; 1784 --LRI; 1785 } 1786 1787 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) { 1788 unsigned NumPHIdValues = 0; 1789 for (auto *I : *LRI) 1790 for (auto *V : PHIOperands[I]) 1791 if (InstructionsToSink.count(V) == 0) 1792 ++NumPHIdValues; 1793 LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n"); 1794 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size(); 1795 if ((NumPHIdValues % UnconditionalPreds.size()) != 0) 1796 NumPHIInsts++; 1797 1798 return NumPHIInsts <= 1; 1799 }; 1800 1801 if (ScanIdx > 0 && Cond) { 1802 // Check if we would actually sink anything first! This mutates the CFG and 1803 // adds an extra block. The goal in doing this is to allow instructions that 1804 // couldn't be sunk before to be sunk - obviously, speculatable instructions 1805 // (such as trunc, add) can be sunk and predicated already. So we check that 1806 // we're going to sink at least one non-speculatable instruction. 1807 LRI.reset(); 1808 unsigned Idx = 0; 1809 bool Profitable = false; 1810 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) { 1811 if (!isSafeToSpeculativelyExecute((*LRI)[0])) { 1812 Profitable = true; 1813 break; 1814 } 1815 --LRI; 1816 ++Idx; 1817 } 1818 if (!Profitable) 1819 return false; 1820 1821 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n"); 1822 // We have a conditional edge and we're going to sink some instructions. 1823 // Insert a new block postdominating all blocks we're going to sink from. 1824 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split")) 1825 // Edges couldn't be split. 1826 return false; 1827 Changed = true; 1828 } 1829 1830 // Now that we've analyzed all potential sinking candidates, perform the 1831 // actual sink. We iteratively sink the last non-terminator of the source 1832 // blocks into their common successor unless doing so would require too 1833 // many PHI instructions to be generated (currently only one PHI is allowed 1834 // per sunk instruction). 1835 // 1836 // We can use InstructionsToSink to discount values needing PHI-merging that will 1837 // actually be sunk in a later iteration. This allows us to be more 1838 // aggressive in what we sink. This does allow a false positive where we 1839 // sink presuming a later value will also be sunk, but stop half way through 1840 // and never actually sink it which means we produce more PHIs than intended. 1841 // This is unlikely in practice though. 1842 for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) { 1843 LLVM_DEBUG(dbgs() << "SINK: Sink: " 1844 << *UnconditionalPreds[0]->getTerminator()->getPrevNode() 1845 << "\n"); 1846 1847 // Because we've sunk every instruction in turn, the current instruction to 1848 // sink is always at index 0. 1849 LRI.reset(); 1850 if (!ProfitableToSinkInstruction(LRI)) { 1851 // Too many PHIs would be created. 1852 LLVM_DEBUG( 1853 dbgs() << "SINK: stopping here, too many PHIs would be created!\n"); 1854 break; 1855 } 1856 1857 if (!sinkLastInstruction(UnconditionalPreds)) 1858 return Changed; 1859 NumSinkCommons++; 1860 Changed = true; 1861 } 1862 return Changed; 1863 } 1864 1865 /// Determine if we can hoist sink a sole store instruction out of a 1866 /// conditional block. 1867 /// 1868 /// We are looking for code like the following: 1869 /// BrBB: 1870 /// store i32 %add, i32* %arrayidx2 1871 /// ... // No other stores or function calls (we could be calling a memory 1872 /// ... // function). 1873 /// %cmp = icmp ult %x, %y 1874 /// br i1 %cmp, label %EndBB, label %ThenBB 1875 /// ThenBB: 1876 /// store i32 %add5, i32* %arrayidx2 1877 /// br label EndBB 1878 /// EndBB: 1879 /// ... 1880 /// We are going to transform this into: 1881 /// BrBB: 1882 /// store i32 %add, i32* %arrayidx2 1883 /// ... // 1884 /// %cmp = icmp ult %x, %y 1885 /// %add.add5 = select i1 %cmp, i32 %add, %add5 1886 /// store i32 %add.add5, i32* %arrayidx2 1887 /// ... 1888 /// 1889 /// \return The pointer to the value of the previous store if the store can be 1890 /// hoisted into the predecessor block. 0 otherwise. 1891 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, 1892 BasicBlock *StoreBB, BasicBlock *EndBB) { 1893 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); 1894 if (!StoreToHoist) 1895 return nullptr; 1896 1897 // Volatile or atomic. 1898 if (!StoreToHoist->isSimple()) 1899 return nullptr; 1900 1901 Value *StorePtr = StoreToHoist->getPointerOperand(); 1902 1903 // Look for a store to the same pointer in BrBB. 1904 unsigned MaxNumInstToLookAt = 9; 1905 for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug())) { 1906 if (!MaxNumInstToLookAt) 1907 break; 1908 --MaxNumInstToLookAt; 1909 1910 // Could be calling an instruction that affects memory like free(). 1911 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI)) 1912 return nullptr; 1913 1914 if (auto *SI = dyn_cast<StoreInst>(&CurI)) { 1915 // Found the previous store make sure it stores to the same location. 1916 if (SI->getPointerOperand() == StorePtr) 1917 // Found the previous store, return its value operand. 1918 return SI->getValueOperand(); 1919 return nullptr; // Unknown store. 1920 } 1921 } 1922 1923 return nullptr; 1924 } 1925 1926 /// Speculate a conditional basic block flattening the CFG. 1927 /// 1928 /// Note that this is a very risky transform currently. Speculating 1929 /// instructions like this is most often not desirable. Instead, there is an MI 1930 /// pass which can do it with full awareness of the resource constraints. 1931 /// However, some cases are "obvious" and we should do directly. An example of 1932 /// this is speculating a single, reasonably cheap instruction. 1933 /// 1934 /// There is only one distinct advantage to flattening the CFG at the IR level: 1935 /// it makes very common but simplistic optimizations such as are common in 1936 /// instcombine and the DAG combiner more powerful by removing CFG edges and 1937 /// modeling their effects with easier to reason about SSA value graphs. 1938 /// 1939 /// 1940 /// An illustration of this transform is turning this IR: 1941 /// \code 1942 /// BB: 1943 /// %cmp = icmp ult %x, %y 1944 /// br i1 %cmp, label %EndBB, label %ThenBB 1945 /// ThenBB: 1946 /// %sub = sub %x, %y 1947 /// br label BB2 1948 /// EndBB: 1949 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] 1950 /// ... 1951 /// \endcode 1952 /// 1953 /// Into this IR: 1954 /// \code 1955 /// BB: 1956 /// %cmp = icmp ult %x, %y 1957 /// %sub = sub %x, %y 1958 /// %cond = select i1 %cmp, 0, %sub 1959 /// ... 1960 /// \endcode 1961 /// 1962 /// \returns true if the conditional block is removed. 1963 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, 1964 const TargetTransformInfo &TTI) { 1965 // Be conservative for now. FP select instruction can often be expensive. 1966 Value *BrCond = BI->getCondition(); 1967 if (isa<FCmpInst>(BrCond)) 1968 return false; 1969 1970 BasicBlock *BB = BI->getParent(); 1971 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); 1972 1973 // If ThenBB is actually on the false edge of the conditional branch, remember 1974 // to swap the select operands later. 1975 bool Invert = false; 1976 if (ThenBB != BI->getSuccessor(0)) { 1977 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); 1978 Invert = true; 1979 } 1980 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); 1981 1982 // Keep a count of how many times instructions are used within ThenBB when 1983 // they are candidates for sinking into ThenBB. Specifically: 1984 // - They are defined in BB, and 1985 // - They have no side effects, and 1986 // - All of their uses are in ThenBB. 1987 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; 1988 1989 SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics; 1990 1991 unsigned SpeculatedInstructions = 0; 1992 Value *SpeculatedStoreValue = nullptr; 1993 StoreInst *SpeculatedStore = nullptr; 1994 for (BasicBlock::iterator BBI = ThenBB->begin(), 1995 BBE = std::prev(ThenBB->end()); 1996 BBI != BBE; ++BBI) { 1997 Instruction *I = &*BBI; 1998 // Skip debug info. 1999 if (isa<DbgInfoIntrinsic>(I)) { 2000 SpeculatedDbgIntrinsics.push_back(I); 2001 continue; 2002 } 2003 2004 // Only speculatively execute a single instruction (not counting the 2005 // terminator) for now. 2006 ++SpeculatedInstructions; 2007 if (SpeculatedInstructions > 1) 2008 return false; 2009 2010 // Don't hoist the instruction if it's unsafe or expensive. 2011 if (!isSafeToSpeculativelyExecute(I) && 2012 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore( 2013 I, BB, ThenBB, EndBB)))) 2014 return false; 2015 if (!SpeculatedStoreValue && 2016 ComputeSpeculationCost(I, TTI) > 2017 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic) 2018 return false; 2019 2020 // Store the store speculation candidate. 2021 if (SpeculatedStoreValue) 2022 SpeculatedStore = cast<StoreInst>(I); 2023 2024 // Do not hoist the instruction if any of its operands are defined but not 2025 // used in BB. The transformation will prevent the operand from 2026 // being sunk into the use block. 2027 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) { 2028 Instruction *OpI = dyn_cast<Instruction>(*i); 2029 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects()) 2030 continue; // Not a candidate for sinking. 2031 2032 ++SinkCandidateUseCounts[OpI]; 2033 } 2034 } 2035 2036 // Consider any sink candidates which are only used in ThenBB as costs for 2037 // speculation. Note, while we iterate over a DenseMap here, we are summing 2038 // and so iteration order isn't significant. 2039 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator 2040 I = SinkCandidateUseCounts.begin(), 2041 E = SinkCandidateUseCounts.end(); 2042 I != E; ++I) 2043 if (I->first->hasNUses(I->second)) { 2044 ++SpeculatedInstructions; 2045 if (SpeculatedInstructions > 1) 2046 return false; 2047 } 2048 2049 // Check that the PHI nodes can be converted to selects. 2050 bool HaveRewritablePHIs = false; 2051 for (PHINode &PN : EndBB->phis()) { 2052 Value *OrigV = PN.getIncomingValueForBlock(BB); 2053 Value *ThenV = PN.getIncomingValueForBlock(ThenBB); 2054 2055 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. 2056 // Skip PHIs which are trivial. 2057 if (ThenV == OrigV) 2058 continue; 2059 2060 // Don't convert to selects if we could remove undefined behavior instead. 2061 if (passingValueIsAlwaysUndefined(OrigV, &PN) || 2062 passingValueIsAlwaysUndefined(ThenV, &PN)) 2063 return false; 2064 2065 HaveRewritablePHIs = true; 2066 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); 2067 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); 2068 if (!OrigCE && !ThenCE) 2069 continue; // Known safe and cheap. 2070 2071 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) || 2072 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE))) 2073 return false; 2074 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0; 2075 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0; 2076 unsigned MaxCost = 2077 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 2078 if (OrigCost + ThenCost > MaxCost) 2079 return false; 2080 2081 // Account for the cost of an unfolded ConstantExpr which could end up 2082 // getting expanded into Instructions. 2083 // FIXME: This doesn't account for how many operations are combined in the 2084 // constant expression. 2085 ++SpeculatedInstructions; 2086 if (SpeculatedInstructions > 1) 2087 return false; 2088 } 2089 2090 // If there are no PHIs to process, bail early. This helps ensure idempotence 2091 // as well. 2092 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue)) 2093 return false; 2094 2095 // If we get here, we can hoist the instruction and if-convert. 2096 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); 2097 2098 // Insert a select of the value of the speculated store. 2099 if (SpeculatedStoreValue) { 2100 IRBuilder<NoFolder> Builder(BI); 2101 Value *TrueV = SpeculatedStore->getValueOperand(); 2102 Value *FalseV = SpeculatedStoreValue; 2103 if (Invert) 2104 std::swap(TrueV, FalseV); 2105 Value *S = Builder.CreateSelect( 2106 BrCond, TrueV, FalseV, "spec.store.select", BI); 2107 SpeculatedStore->setOperand(0, S); 2108 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(), 2109 SpeculatedStore->getDebugLoc()); 2110 } 2111 2112 // Metadata can be dependent on the condition we are hoisting above. 2113 // Conservatively strip all metadata on the instruction. 2114 for (auto &I : *ThenBB) 2115 I.dropUnknownNonDebugMetadata(); 2116 2117 // Hoist the instructions. 2118 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(), 2119 ThenBB->begin(), std::prev(ThenBB->end())); 2120 2121 // Insert selects and rewrite the PHI operands. 2122 IRBuilder<NoFolder> Builder(BI); 2123 for (PHINode &PN : EndBB->phis()) { 2124 unsigned OrigI = PN.getBasicBlockIndex(BB); 2125 unsigned ThenI = PN.getBasicBlockIndex(ThenBB); 2126 Value *OrigV = PN.getIncomingValue(OrigI); 2127 Value *ThenV = PN.getIncomingValue(ThenI); 2128 2129 // Skip PHIs which are trivial. 2130 if (OrigV == ThenV) 2131 continue; 2132 2133 // Create a select whose true value is the speculatively executed value and 2134 // false value is the preexisting value. Swap them if the branch 2135 // destinations were inverted. 2136 Value *TrueV = ThenV, *FalseV = OrigV; 2137 if (Invert) 2138 std::swap(TrueV, FalseV); 2139 Value *V = Builder.CreateSelect( 2140 BrCond, TrueV, FalseV, "spec.select", BI); 2141 PN.setIncomingValue(OrigI, V); 2142 PN.setIncomingValue(ThenI, V); 2143 } 2144 2145 // Remove speculated dbg intrinsics. 2146 // FIXME: Is it possible to do this in a more elegant way? Moving/merging the 2147 // dbg value for the different flows and inserting it after the select. 2148 for (Instruction *I : SpeculatedDbgIntrinsics) 2149 I->eraseFromParent(); 2150 2151 ++NumSpeculations; 2152 return true; 2153 } 2154 2155 /// Return true if we can thread a branch across this block. 2156 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { 2157 unsigned Size = 0; 2158 2159 for (Instruction &I : BB->instructionsWithoutDebug()) { 2160 if (Size > 10) 2161 return false; // Don't clone large BB's. 2162 ++Size; 2163 2164 // We can only support instructions that do not define values that are 2165 // live outside of the current basic block. 2166 for (User *U : I.users()) { 2167 Instruction *UI = cast<Instruction>(U); 2168 if (UI->getParent() != BB || isa<PHINode>(UI)) 2169 return false; 2170 } 2171 2172 // Looks ok, continue checking. 2173 } 2174 2175 return true; 2176 } 2177 2178 /// If we have a conditional branch on a PHI node value that is defined in the 2179 /// same block as the branch and if any PHI entries are constants, thread edges 2180 /// corresponding to that entry to be branches to their ultimate destination. 2181 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL, 2182 AssumptionCache *AC) { 2183 BasicBlock *BB = BI->getParent(); 2184 PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); 2185 // NOTE: we currently cannot transform this case if the PHI node is used 2186 // outside of the block. 2187 if (!PN || PN->getParent() != BB || !PN->hasOneUse()) 2188 return false; 2189 2190 // Degenerate case of a single entry PHI. 2191 if (PN->getNumIncomingValues() == 1) { 2192 FoldSingleEntryPHINodes(PN->getParent()); 2193 return true; 2194 } 2195 2196 // Now we know that this block has multiple preds and two succs. 2197 if (!BlockIsSimpleEnoughToThreadThrough(BB)) 2198 return false; 2199 2200 // Can't fold blocks that contain noduplicate or convergent calls. 2201 if (any_of(*BB, [](const Instruction &I) { 2202 const CallInst *CI = dyn_cast<CallInst>(&I); 2203 return CI && (CI->cannotDuplicate() || CI->isConvergent()); 2204 })) 2205 return false; 2206 2207 // Okay, this is a simple enough basic block. See if any phi values are 2208 // constants. 2209 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 2210 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); 2211 if (!CB || !CB->getType()->isIntegerTy(1)) 2212 continue; 2213 2214 // Okay, we now know that all edges from PredBB should be revectored to 2215 // branch to RealDest. 2216 BasicBlock *PredBB = PN->getIncomingBlock(i); 2217 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); 2218 2219 if (RealDest == BB) 2220 continue; // Skip self loops. 2221 // Skip if the predecessor's terminator is an indirect branch. 2222 if (isa<IndirectBrInst>(PredBB->getTerminator())) 2223 continue; 2224 2225 // The dest block might have PHI nodes, other predecessors and other 2226 // difficult cases. Instead of being smart about this, just insert a new 2227 // block that jumps to the destination block, effectively splitting 2228 // the edge we are about to create. 2229 BasicBlock *EdgeBB = 2230 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge", 2231 RealDest->getParent(), RealDest); 2232 BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB); 2233 CritEdgeBranch->setDebugLoc(BI->getDebugLoc()); 2234 2235 // Update PHI nodes. 2236 AddPredecessorToBlock(RealDest, EdgeBB, BB); 2237 2238 // BB may have instructions that are being threaded over. Clone these 2239 // instructions into EdgeBB. We know that there will be no uses of the 2240 // cloned instructions outside of EdgeBB. 2241 BasicBlock::iterator InsertPt = EdgeBB->begin(); 2242 DenseMap<Value *, Value *> TranslateMap; // Track translated values. 2243 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 2244 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 2245 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); 2246 continue; 2247 } 2248 // Clone the instruction. 2249 Instruction *N = BBI->clone(); 2250 if (BBI->hasName()) 2251 N->setName(BBI->getName() + ".c"); 2252 2253 // Update operands due to translation. 2254 for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) { 2255 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i); 2256 if (PI != TranslateMap.end()) 2257 *i = PI->second; 2258 } 2259 2260 // Check for trivial simplification. 2261 if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) { 2262 if (!BBI->use_empty()) 2263 TranslateMap[&*BBI] = V; 2264 if (!N->mayHaveSideEffects()) { 2265 N->deleteValue(); // Instruction folded away, don't need actual inst 2266 N = nullptr; 2267 } 2268 } else { 2269 if (!BBI->use_empty()) 2270 TranslateMap[&*BBI] = N; 2271 } 2272 if (N) { 2273 // Insert the new instruction into its new home. 2274 EdgeBB->getInstList().insert(InsertPt, N); 2275 2276 // Register the new instruction with the assumption cache if necessary. 2277 if (AC && match(N, m_Intrinsic<Intrinsic::assume>())) 2278 AC->registerAssumption(cast<IntrinsicInst>(N)); 2279 } 2280 } 2281 2282 // Loop over all of the edges from PredBB to BB, changing them to branch 2283 // to EdgeBB instead. 2284 Instruction *PredBBTI = PredBB->getTerminator(); 2285 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) 2286 if (PredBBTI->getSuccessor(i) == BB) { 2287 BB->removePredecessor(PredBB); 2288 PredBBTI->setSuccessor(i, EdgeBB); 2289 } 2290 2291 // Recurse, simplifying any other constants. 2292 return FoldCondBranchOnPHI(BI, DL, AC) || true; 2293 } 2294 2295 return false; 2296 } 2297 2298 /// Given a BB that starts with the specified two-entry PHI node, 2299 /// see if we can eliminate it. 2300 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, 2301 const DataLayout &DL) { 2302 // Ok, this is a two entry PHI node. Check to see if this is a simple "if 2303 // statement", which has a very simple dominance structure. Basically, we 2304 // are trying to find the condition that is being branched on, which 2305 // subsequently causes this merge to happen. We really want control 2306 // dependence information for this check, but simplifycfg can't keep it up 2307 // to date, and this catches most of the cases we care about anyway. 2308 BasicBlock *BB = PN->getParent(); 2309 const Function *Fn = BB->getParent(); 2310 if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing)) 2311 return false; 2312 2313 BasicBlock *IfTrue, *IfFalse; 2314 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); 2315 if (!IfCond || 2316 // Don't bother if the branch will be constant folded trivially. 2317 isa<ConstantInt>(IfCond)) 2318 return false; 2319 2320 // Okay, we found that we can merge this two-entry phi node into a select. 2321 // Doing so would require us to fold *all* two entry phi nodes in this block. 2322 // At some point this becomes non-profitable (particularly if the target 2323 // doesn't support cmov's). Only do this transformation if there are two or 2324 // fewer PHI nodes in this block. 2325 unsigned NumPhis = 0; 2326 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) 2327 if (NumPhis > 2) 2328 return false; 2329 2330 // Loop over the PHI's seeing if we can promote them all to select 2331 // instructions. While we are at it, keep track of the instructions 2332 // that need to be moved to the dominating block. 2333 SmallPtrSet<Instruction *, 4> AggressiveInsts; 2334 int BudgetRemaining = 2335 TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 2336 2337 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { 2338 PHINode *PN = cast<PHINode>(II++); 2339 if (Value *V = SimplifyInstruction(PN, {DL, PN})) { 2340 PN->replaceAllUsesWith(V); 2341 PN->eraseFromParent(); 2342 continue; 2343 } 2344 2345 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts, 2346 BudgetRemaining, TTI) || 2347 !DominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts, 2348 BudgetRemaining, TTI)) 2349 return false; 2350 } 2351 2352 // If we folded the first phi, PN dangles at this point. Refresh it. If 2353 // we ran out of PHIs then we simplified them all. 2354 PN = dyn_cast<PHINode>(BB->begin()); 2355 if (!PN) 2356 return true; 2357 2358 // Return true if at least one of these is a 'not', and another is either 2359 // a 'not' too, or a constant. 2360 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) { 2361 if (!match(V0, m_Not(m_Value()))) 2362 std::swap(V0, V1); 2363 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant()); 2364 return match(V0, m_Not(m_Value())) && match(V1, Invertible); 2365 }; 2366 2367 // Don't fold i1 branches on PHIs which contain binary operators, unless one 2368 // of the incoming values is an 'not' and another one is freely invertible. 2369 // These can often be turned into switches and other things. 2370 if (PN->getType()->isIntegerTy(1) && 2371 (isa<BinaryOperator>(PN->getIncomingValue(0)) || 2372 isa<BinaryOperator>(PN->getIncomingValue(1)) || 2373 isa<BinaryOperator>(IfCond)) && 2374 !CanHoistNotFromBothValues(PN->getIncomingValue(0), 2375 PN->getIncomingValue(1))) 2376 return false; 2377 2378 // If all PHI nodes are promotable, check to make sure that all instructions 2379 // in the predecessor blocks can be promoted as well. If not, we won't be able 2380 // to get rid of the control flow, so it's not worth promoting to select 2381 // instructions. 2382 BasicBlock *DomBlock = nullptr; 2383 BasicBlock *IfBlock1 = PN->getIncomingBlock(0); 2384 BasicBlock *IfBlock2 = PN->getIncomingBlock(1); 2385 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { 2386 IfBlock1 = nullptr; 2387 } else { 2388 DomBlock = *pred_begin(IfBlock1); 2389 for (BasicBlock::iterator I = IfBlock1->begin(); !I->isTerminator(); ++I) 2390 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { 2391 // This is not an aggressive instruction that we can promote. 2392 // Because of this, we won't be able to get rid of the control flow, so 2393 // the xform is not worth it. 2394 return false; 2395 } 2396 } 2397 2398 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { 2399 IfBlock2 = nullptr; 2400 } else { 2401 DomBlock = *pred_begin(IfBlock2); 2402 for (BasicBlock::iterator I = IfBlock2->begin(); !I->isTerminator(); ++I) 2403 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { 2404 // This is not an aggressive instruction that we can promote. 2405 // Because of this, we won't be able to get rid of the control flow, so 2406 // the xform is not worth it. 2407 return false; 2408 } 2409 } 2410 assert(DomBlock && "Failed to find root DomBlock"); 2411 2412 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond 2413 << " T: " << IfTrue->getName() 2414 << " F: " << IfFalse->getName() << "\n"); 2415 2416 // If we can still promote the PHI nodes after this gauntlet of tests, 2417 // do all of the PHI's now. 2418 Instruction *InsertPt = DomBlock->getTerminator(); 2419 IRBuilder<NoFolder> Builder(InsertPt); 2420 2421 // Move all 'aggressive' instructions, which are defined in the 2422 // conditional parts of the if's up to the dominating block. 2423 if (IfBlock1) 2424 hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1); 2425 if (IfBlock2) 2426 hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2); 2427 2428 // Propagate fast-math-flags from phi nodes to replacement selects. 2429 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 2430 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 2431 if (isa<FPMathOperator>(PN)) 2432 Builder.setFastMathFlags(PN->getFastMathFlags()); 2433 2434 // Change the PHI node into a select instruction. 2435 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); 2436 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); 2437 2438 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt); 2439 PN->replaceAllUsesWith(Sel); 2440 Sel->takeName(PN); 2441 PN->eraseFromParent(); 2442 } 2443 2444 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement 2445 // has been flattened. Change DomBlock to jump directly to our new block to 2446 // avoid other simplifycfg's kicking in on the diamond. 2447 Instruction *OldTI = DomBlock->getTerminator(); 2448 Builder.SetInsertPoint(OldTI); 2449 Builder.CreateBr(BB); 2450 OldTI->eraseFromParent(); 2451 return true; 2452 } 2453 2454 /// If we found a conditional branch that goes to two returning blocks, 2455 /// try to merge them together into one return, 2456 /// introducing a select if the return values disagree. 2457 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, 2458 IRBuilder<> &Builder) { 2459 assert(BI->isConditional() && "Must be a conditional branch"); 2460 BasicBlock *TrueSucc = BI->getSuccessor(0); 2461 BasicBlock *FalseSucc = BI->getSuccessor(1); 2462 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); 2463 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); 2464 2465 // Check to ensure both blocks are empty (just a return) or optionally empty 2466 // with PHI nodes. If there are other instructions, merging would cause extra 2467 // computation on one path or the other. 2468 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) 2469 return false; 2470 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) 2471 return false; 2472 2473 Builder.SetInsertPoint(BI); 2474 // Okay, we found a branch that is going to two return nodes. If 2475 // there is no return value for this function, just change the 2476 // branch into a return. 2477 if (FalseRet->getNumOperands() == 0) { 2478 TrueSucc->removePredecessor(BI->getParent()); 2479 FalseSucc->removePredecessor(BI->getParent()); 2480 Builder.CreateRetVoid(); 2481 EraseTerminatorAndDCECond(BI); 2482 return true; 2483 } 2484 2485 // Otherwise, figure out what the true and false return values are 2486 // so we can insert a new select instruction. 2487 Value *TrueValue = TrueRet->getReturnValue(); 2488 Value *FalseValue = FalseRet->getReturnValue(); 2489 2490 // Unwrap any PHI nodes in the return blocks. 2491 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) 2492 if (TVPN->getParent() == TrueSucc) 2493 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); 2494 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) 2495 if (FVPN->getParent() == FalseSucc) 2496 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); 2497 2498 // In order for this transformation to be safe, we must be able to 2499 // unconditionally execute both operands to the return. This is 2500 // normally the case, but we could have a potentially-trapping 2501 // constant expression that prevents this transformation from being 2502 // safe. 2503 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) 2504 if (TCV->canTrap()) 2505 return false; 2506 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) 2507 if (FCV->canTrap()) 2508 return false; 2509 2510 // Okay, we collected all the mapped values and checked them for sanity, and 2511 // defined to really do this transformation. First, update the CFG. 2512 TrueSucc->removePredecessor(BI->getParent()); 2513 FalseSucc->removePredecessor(BI->getParent()); 2514 2515 // Insert select instructions where needed. 2516 Value *BrCond = BI->getCondition(); 2517 if (TrueValue) { 2518 // Insert a select if the results differ. 2519 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { 2520 } else if (isa<UndefValue>(TrueValue)) { 2521 TrueValue = FalseValue; 2522 } else { 2523 TrueValue = 2524 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI); 2525 } 2526 } 2527 2528 Value *RI = 2529 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); 2530 2531 (void)RI; 2532 2533 LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 2534 << "\n " << *BI << "NewRet = " << *RI << "TRUEBLOCK: " 2535 << *TrueSucc << "FALSEBLOCK: " << *FalseSucc); 2536 2537 EraseTerminatorAndDCECond(BI); 2538 2539 return true; 2540 } 2541 2542 /// Return true if the given instruction is available 2543 /// in its predecessor block. If yes, the instruction will be removed. 2544 static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB) { 2545 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) 2546 return false; 2547 for (Instruction &I : *PB) { 2548 Instruction *PBI = &I; 2549 // Check whether Inst and PBI generate the same value. 2550 if (Inst->isIdenticalTo(PBI)) { 2551 Inst->replaceAllUsesWith(PBI); 2552 Inst->eraseFromParent(); 2553 return true; 2554 } 2555 } 2556 return false; 2557 } 2558 2559 /// Return true if either PBI or BI has branch weight available, and store 2560 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does 2561 /// not have branch weight, use 1:1 as its weight. 2562 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, 2563 uint64_t &PredTrueWeight, 2564 uint64_t &PredFalseWeight, 2565 uint64_t &SuccTrueWeight, 2566 uint64_t &SuccFalseWeight) { 2567 bool PredHasWeights = 2568 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight); 2569 bool SuccHasWeights = 2570 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight); 2571 if (PredHasWeights || SuccHasWeights) { 2572 if (!PredHasWeights) 2573 PredTrueWeight = PredFalseWeight = 1; 2574 if (!SuccHasWeights) 2575 SuccTrueWeight = SuccFalseWeight = 1; 2576 return true; 2577 } else { 2578 return false; 2579 } 2580 } 2581 2582 /// If this basic block is simple enough, and if a predecessor branches to us 2583 /// and one of our successors, fold the block into the predecessor and use 2584 /// logical operations to pick the right destination. 2585 bool llvm::FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU, 2586 unsigned BonusInstThreshold) { 2587 BasicBlock *BB = BI->getParent(); 2588 2589 const unsigned PredCount = pred_size(BB); 2590 2591 Instruction *Cond = nullptr; 2592 if (BI->isConditional()) 2593 Cond = dyn_cast<Instruction>(BI->getCondition()); 2594 else { 2595 // For unconditional branch, check for a simple CFG pattern, where 2596 // BB has a single predecessor and BB's successor is also its predecessor's 2597 // successor. If such pattern exists, check for CSE between BB and its 2598 // predecessor. 2599 if (BasicBlock *PB = BB->getSinglePredecessor()) 2600 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) 2601 if (PBI->isConditional() && 2602 (BI->getSuccessor(0) == PBI->getSuccessor(0) || 2603 BI->getSuccessor(0) == PBI->getSuccessor(1))) { 2604 for (auto I = BB->instructionsWithoutDebug().begin(), 2605 E = BB->instructionsWithoutDebug().end(); 2606 I != E;) { 2607 Instruction *Curr = &*I++; 2608 if (isa<CmpInst>(Curr)) { 2609 Cond = Curr; 2610 break; 2611 } 2612 // Quit if we can't remove this instruction. 2613 if (!tryCSEWithPredecessor(Curr, PB)) 2614 return false; 2615 } 2616 } 2617 2618 if (!Cond) 2619 return false; 2620 } 2621 2622 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || 2623 Cond->getParent() != BB || !Cond->hasOneUse()) 2624 return false; 2625 2626 // Make sure the instruction after the condition is the cond branch. 2627 BasicBlock::iterator CondIt = ++Cond->getIterator(); 2628 2629 // Ignore dbg intrinsics. 2630 while (isa<DbgInfoIntrinsic>(CondIt)) 2631 ++CondIt; 2632 2633 if (&*CondIt != BI) 2634 return false; 2635 2636 // Only allow this transformation if computing the condition doesn't involve 2637 // too many instructions and these involved instructions can be executed 2638 // unconditionally. We denote all involved instructions except the condition 2639 // as "bonus instructions", and only allow this transformation when the 2640 // number of the bonus instructions we'll need to create when cloning into 2641 // each predecessor does not exceed a certain threshold. 2642 unsigned NumBonusInsts = 0; 2643 for (auto I = BB->begin(); Cond != &*I; ++I) { 2644 // Ignore dbg intrinsics. 2645 if (isa<DbgInfoIntrinsic>(I)) 2646 continue; 2647 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I)) 2648 return false; 2649 // I has only one use and can be executed unconditionally. 2650 Instruction *User = dyn_cast<Instruction>(I->user_back()); 2651 if (User == nullptr || User->getParent() != BB) 2652 return false; 2653 // I is used in the same BB. Since BI uses Cond and doesn't have more slots 2654 // to use any other instruction, User must be an instruction between next(I) 2655 // and Cond. 2656 2657 // Account for the cost of duplicating this instruction into each 2658 // predecessor. 2659 NumBonusInsts += PredCount; 2660 // Early exits once we reach the limit. 2661 if (NumBonusInsts > BonusInstThreshold) 2662 return false; 2663 } 2664 2665 // Cond is known to be a compare or binary operator. Check to make sure that 2666 // neither operand is a potentially-trapping constant expression. 2667 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) 2668 if (CE->canTrap()) 2669 return false; 2670 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) 2671 if (CE->canTrap()) 2672 return false; 2673 2674 // Finally, don't infinitely unroll conditional loops. 2675 BasicBlock *TrueDest = BI->getSuccessor(0); 2676 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; 2677 if (TrueDest == BB || FalseDest == BB) 2678 return false; 2679 2680 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 2681 BasicBlock *PredBlock = *PI; 2682 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); 2683 2684 // Check that we have two conditional branches. If there is a PHI node in 2685 // the common successor, verify that the same value flows in from both 2686 // blocks. 2687 SmallVector<PHINode *, 4> PHIs; 2688 if (!PBI || PBI->isUnconditional() || 2689 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) || 2690 (!BI->isConditional() && 2691 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) 2692 continue; 2693 2694 // Determine if the two branches share a common destination. 2695 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; 2696 bool InvertPredCond = false; 2697 2698 if (BI->isConditional()) { 2699 if (PBI->getSuccessor(0) == TrueDest) { 2700 Opc = Instruction::Or; 2701 } else if (PBI->getSuccessor(1) == FalseDest) { 2702 Opc = Instruction::And; 2703 } else if (PBI->getSuccessor(0) == FalseDest) { 2704 Opc = Instruction::And; 2705 InvertPredCond = true; 2706 } else if (PBI->getSuccessor(1) == TrueDest) { 2707 Opc = Instruction::Or; 2708 InvertPredCond = true; 2709 } else { 2710 continue; 2711 } 2712 } else { 2713 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) 2714 continue; 2715 } 2716 2717 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); 2718 IRBuilder<> Builder(PBI); 2719 2720 // If we need to invert the condition in the pred block to match, do so now. 2721 if (InvertPredCond) { 2722 Value *NewCond = PBI->getCondition(); 2723 2724 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { 2725 CmpInst *CI = cast<CmpInst>(NewCond); 2726 CI->setPredicate(CI->getInversePredicate()); 2727 } else { 2728 NewCond = 2729 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not"); 2730 } 2731 2732 PBI->setCondition(NewCond); 2733 PBI->swapSuccessors(); 2734 } 2735 2736 // If we have bonus instructions, clone them into the predecessor block. 2737 // Note that there may be multiple predecessor blocks, so we cannot move 2738 // bonus instructions to a predecessor block. 2739 ValueToValueMapTy VMap; // maps original values to cloned values 2740 // We already make sure Cond is the last instruction before BI. Therefore, 2741 // all instructions before Cond other than DbgInfoIntrinsic are bonus 2742 // instructions. 2743 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) { 2744 if (isa<DbgInfoIntrinsic>(BonusInst)) 2745 continue; 2746 Instruction *NewBonusInst = BonusInst->clone(); 2747 RemapInstruction(NewBonusInst, VMap, 2748 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 2749 VMap[&*BonusInst] = NewBonusInst; 2750 2751 // If we moved a load, we cannot any longer claim any knowledge about 2752 // its potential value. The previous information might have been valid 2753 // only given the branch precondition. 2754 // For an analogous reason, we must also drop all the metadata whose 2755 // semantics we don't understand. 2756 NewBonusInst->dropUnknownNonDebugMetadata(); 2757 2758 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst); 2759 NewBonusInst->takeName(&*BonusInst); 2760 BonusInst->setName(BonusInst->getName() + ".old"); 2761 } 2762 2763 // Clone Cond into the predecessor basic block, and or/and the 2764 // two conditions together. 2765 Instruction *CondInPred = Cond->clone(); 2766 RemapInstruction(CondInPred, VMap, 2767 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 2768 PredBlock->getInstList().insert(PBI->getIterator(), CondInPred); 2769 CondInPred->takeName(Cond); 2770 Cond->setName(CondInPred->getName() + ".old"); 2771 2772 if (BI->isConditional()) { 2773 Instruction *NewCond = cast<Instruction>( 2774 Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond")); 2775 PBI->setCondition(NewCond); 2776 2777 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 2778 bool HasWeights = 2779 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 2780 SuccTrueWeight, SuccFalseWeight); 2781 SmallVector<uint64_t, 8> NewWeights; 2782 2783 if (PBI->getSuccessor(0) == BB) { 2784 if (HasWeights) { 2785 // PBI: br i1 %x, BB, FalseDest 2786 // BI: br i1 %y, TrueDest, FalseDest 2787 // TrueWeight is TrueWeight for PBI * TrueWeight for BI. 2788 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 2789 // FalseWeight is FalseWeight for PBI * TotalWeight for BI + 2790 // TrueWeight for PBI * FalseWeight for BI. 2791 // We assume that total weights of a BranchInst can fit into 32 bits. 2792 // Therefore, we will not have overflow using 64-bit arithmetic. 2793 NewWeights.push_back(PredFalseWeight * 2794 (SuccFalseWeight + SuccTrueWeight) + 2795 PredTrueWeight * SuccFalseWeight); 2796 } 2797 AddPredecessorToBlock(TrueDest, PredBlock, BB, MSSAU); 2798 PBI->setSuccessor(0, TrueDest); 2799 } 2800 if (PBI->getSuccessor(1) == BB) { 2801 if (HasWeights) { 2802 // PBI: br i1 %x, TrueDest, BB 2803 // BI: br i1 %y, TrueDest, FalseDest 2804 // TrueWeight is TrueWeight for PBI * TotalWeight for BI + 2805 // FalseWeight for PBI * TrueWeight for BI. 2806 NewWeights.push_back(PredTrueWeight * 2807 (SuccFalseWeight + SuccTrueWeight) + 2808 PredFalseWeight * SuccTrueWeight); 2809 // FalseWeight is FalseWeight for PBI * FalseWeight for BI. 2810 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 2811 } 2812 AddPredecessorToBlock(FalseDest, PredBlock, BB, MSSAU); 2813 PBI->setSuccessor(1, FalseDest); 2814 } 2815 if (NewWeights.size() == 2) { 2816 // Halve the weights if any of them cannot fit in an uint32_t 2817 FitWeights(NewWeights); 2818 2819 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), 2820 NewWeights.end()); 2821 setBranchWeights(PBI, MDWeights[0], MDWeights[1]); 2822 } else 2823 PBI->setMetadata(LLVMContext::MD_prof, nullptr); 2824 } else { 2825 // Update PHI nodes in the common successors. 2826 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { 2827 ConstantInt *PBI_C = cast<ConstantInt>( 2828 PHIs[i]->getIncomingValueForBlock(PBI->getParent())); 2829 assert(PBI_C->getType()->isIntegerTy(1)); 2830 Instruction *MergedCond = nullptr; 2831 if (PBI->getSuccessor(0) == TrueDest) { 2832 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) 2833 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) 2834 // is false: !PBI_Cond and BI_Value 2835 Instruction *NotCond = cast<Instruction>( 2836 Builder.CreateNot(PBI->getCondition(), "not.cond")); 2837 MergedCond = cast<Instruction>( 2838 Builder.CreateBinOp(Instruction::And, NotCond, CondInPred, 2839 "and.cond")); 2840 if (PBI_C->isOne()) 2841 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2842 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond")); 2843 } else { 2844 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) 2845 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) 2846 // is false: PBI_Cond and BI_Value 2847 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2848 Instruction::And, PBI->getCondition(), CondInPred, "and.cond")); 2849 if (PBI_C->isOne()) { 2850 Instruction *NotCond = cast<Instruction>( 2851 Builder.CreateNot(PBI->getCondition(), "not.cond")); 2852 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2853 Instruction::Or, NotCond, MergedCond, "or.cond")); 2854 } 2855 } 2856 // Update PHI Node. 2857 PHIs[i]->setIncomingValueForBlock(PBI->getParent(), MergedCond); 2858 } 2859 2860 // PBI is changed to branch to TrueDest below. Remove itself from 2861 // potential phis from all other successors. 2862 if (MSSAU) 2863 MSSAU->changeCondBranchToUnconditionalTo(PBI, TrueDest); 2864 2865 // Change PBI from Conditional to Unconditional. 2866 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); 2867 EraseTerminatorAndDCECond(PBI, MSSAU); 2868 PBI = New_PBI; 2869 } 2870 2871 // If BI was a loop latch, it may have had associated loop metadata. 2872 // We need to copy it to the new latch, that is, PBI. 2873 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop)) 2874 PBI->setMetadata(LLVMContext::MD_loop, LoopMD); 2875 2876 // TODO: If BB is reachable from all paths through PredBlock, then we 2877 // could replace PBI's branch probabilities with BI's. 2878 2879 // Copy any debug value intrinsics into the end of PredBlock. 2880 for (Instruction &I : *BB) 2881 if (isa<DbgInfoIntrinsic>(I)) 2882 I.clone()->insertBefore(PBI); 2883 2884 return true; 2885 } 2886 return false; 2887 } 2888 2889 // If there is only one store in BB1 and BB2, return it, otherwise return 2890 // nullptr. 2891 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { 2892 StoreInst *S = nullptr; 2893 for (auto *BB : {BB1, BB2}) { 2894 if (!BB) 2895 continue; 2896 for (auto &I : *BB) 2897 if (auto *SI = dyn_cast<StoreInst>(&I)) { 2898 if (S) 2899 // Multiple stores seen. 2900 return nullptr; 2901 else 2902 S = SI; 2903 } 2904 } 2905 return S; 2906 } 2907 2908 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, 2909 Value *AlternativeV = nullptr) { 2910 // PHI is going to be a PHI node that allows the value V that is defined in 2911 // BB to be referenced in BB's only successor. 2912 // 2913 // If AlternativeV is nullptr, the only value we care about in PHI is V. It 2914 // doesn't matter to us what the other operand is (it'll never get used). We 2915 // could just create a new PHI with an undef incoming value, but that could 2916 // increase register pressure if EarlyCSE/InstCombine can't fold it with some 2917 // other PHI. So here we directly look for some PHI in BB's successor with V 2918 // as an incoming operand. If we find one, we use it, else we create a new 2919 // one. 2920 // 2921 // If AlternativeV is not nullptr, we care about both incoming values in PHI. 2922 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] 2923 // where OtherBB is the single other predecessor of BB's only successor. 2924 PHINode *PHI = nullptr; 2925 BasicBlock *Succ = BB->getSingleSuccessor(); 2926 2927 for (auto I = Succ->begin(); isa<PHINode>(I); ++I) 2928 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { 2929 PHI = cast<PHINode>(I); 2930 if (!AlternativeV) 2931 break; 2932 2933 assert(Succ->hasNPredecessors(2)); 2934 auto PredI = pred_begin(Succ); 2935 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; 2936 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) 2937 break; 2938 PHI = nullptr; 2939 } 2940 if (PHI) 2941 return PHI; 2942 2943 // If V is not an instruction defined in BB, just return it. 2944 if (!AlternativeV && 2945 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB)) 2946 return V; 2947 2948 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front()); 2949 PHI->addIncoming(V, BB); 2950 for (BasicBlock *PredBB : predecessors(Succ)) 2951 if (PredBB != BB) 2952 PHI->addIncoming( 2953 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB); 2954 return PHI; 2955 } 2956 2957 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, 2958 BasicBlock *QTB, BasicBlock *QFB, 2959 BasicBlock *PostBB, Value *Address, 2960 bool InvertPCond, bool InvertQCond, 2961 const DataLayout &DL, 2962 const TargetTransformInfo &TTI) { 2963 // For every pointer, there must be exactly two stores, one coming from 2964 // PTB or PFB, and the other from QTB or QFB. We don't support more than one 2965 // store (to any address) in PTB,PFB or QTB,QFB. 2966 // FIXME: We could relax this restriction with a bit more work and performance 2967 // testing. 2968 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); 2969 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); 2970 if (!PStore || !QStore) 2971 return false; 2972 2973 // Now check the stores are compatible. 2974 if (!QStore->isUnordered() || !PStore->isUnordered()) 2975 return false; 2976 2977 // Check that sinking the store won't cause program behavior changes. Sinking 2978 // the store out of the Q blocks won't change any behavior as we're sinking 2979 // from a block to its unconditional successor. But we're moving a store from 2980 // the P blocks down through the middle block (QBI) and past both QFB and QTB. 2981 // So we need to check that there are no aliasing loads or stores in 2982 // QBI, QTB and QFB. We also need to check there are no conflicting memory 2983 // operations between PStore and the end of its parent block. 2984 // 2985 // The ideal way to do this is to query AliasAnalysis, but we don't 2986 // preserve AA currently so that is dangerous. Be super safe and just 2987 // check there are no other memory operations at all. 2988 for (auto &I : *QFB->getSinglePredecessor()) 2989 if (I.mayReadOrWriteMemory()) 2990 return false; 2991 for (auto &I : *QFB) 2992 if (&I != QStore && I.mayReadOrWriteMemory()) 2993 return false; 2994 if (QTB) 2995 for (auto &I : *QTB) 2996 if (&I != QStore && I.mayReadOrWriteMemory()) 2997 return false; 2998 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); 2999 I != E; ++I) 3000 if (&*I != PStore && I->mayReadOrWriteMemory()) 3001 return false; 3002 3003 // If we're not in aggressive mode, we only optimize if we have some 3004 // confidence that by optimizing we'll allow P and/or Q to be if-converted. 3005 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) { 3006 if (!BB) 3007 return true; 3008 // Heuristic: if the block can be if-converted/phi-folded and the 3009 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to 3010 // thread this store. 3011 int BudgetRemaining = 3012 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 3013 for (auto &I : BB->instructionsWithoutDebug()) { 3014 // Consider terminator instruction to be free. 3015 if (I.isTerminator()) 3016 continue; 3017 // If this is one the stores that we want to speculate out of this BB, 3018 // then don't count it's cost, consider it to be free. 3019 if (auto *S = dyn_cast<StoreInst>(&I)) 3020 if (llvm::find(FreeStores, S)) 3021 continue; 3022 // Else, we have a white-list of instructions that we are ak speculating. 3023 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I)) 3024 return false; // Not in white-list - not worthwhile folding. 3025 // And finally, if this is a non-free instruction that we are okay 3026 // speculating, ensure that we consider the speculation budget. 3027 BudgetRemaining -= TTI.getUserCost(&I); 3028 if (BudgetRemaining < 0) 3029 return false; // Eagerly refuse to fold as soon as we're out of budget. 3030 } 3031 assert(BudgetRemaining >= 0 && 3032 "When we run out of budget we will eagerly return from within the " 3033 "per-instruction loop."); 3034 return true; 3035 }; 3036 3037 const SmallVector<StoreInst *, 2> FreeStores = {PStore, QStore}; 3038 if (!MergeCondStoresAggressively && 3039 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) || 3040 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores))) 3041 return false; 3042 3043 // If PostBB has more than two predecessors, we need to split it so we can 3044 // sink the store. 3045 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) { 3046 // We know that QFB's only successor is PostBB. And QFB has a single 3047 // predecessor. If QTB exists, then its only successor is also PostBB. 3048 // If QTB does not exist, then QFB's only predecessor has a conditional 3049 // branch to QFB and PostBB. 3050 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor(); 3051 BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred}, 3052 "condstore.split"); 3053 if (!NewBB) 3054 return false; 3055 PostBB = NewBB; 3056 } 3057 3058 // OK, we're going to sink the stores to PostBB. The store has to be 3059 // conditional though, so first create the predicate. 3060 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) 3061 ->getCondition(); 3062 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) 3063 ->getCondition(); 3064 3065 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), 3066 PStore->getParent()); 3067 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), 3068 QStore->getParent(), PPHI); 3069 3070 IRBuilder<> QB(&*PostBB->getFirstInsertionPt()); 3071 3072 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); 3073 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); 3074 3075 if (InvertPCond) 3076 PPred = QB.CreateNot(PPred); 3077 if (InvertQCond) 3078 QPred = QB.CreateNot(QPred); 3079 Value *CombinedPred = QB.CreateOr(PPred, QPred); 3080 3081 auto *T = 3082 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false); 3083 QB.SetInsertPoint(T); 3084 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); 3085 AAMDNodes AAMD; 3086 PStore->getAAMetadata(AAMD, /*Merge=*/false); 3087 PStore->getAAMetadata(AAMD, /*Merge=*/true); 3088 SI->setAAMetadata(AAMD); 3089 unsigned PAlignment = PStore->getAlignment(); 3090 unsigned QAlignment = QStore->getAlignment(); 3091 unsigned TypeAlignment = 3092 DL.getABITypeAlignment(SI->getValueOperand()->getType()); 3093 unsigned MinAlignment; 3094 unsigned MaxAlignment; 3095 std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment); 3096 // Choose the minimum alignment. If we could prove both stores execute, we 3097 // could use biggest one. In this case, though, we only know that one of the 3098 // stores executes. And we don't know it's safe to take the alignment from a 3099 // store that doesn't execute. 3100 if (MinAlignment != 0) { 3101 // Choose the minimum of all non-zero alignments. 3102 SI->setAlignment(Align(MinAlignment)); 3103 } else if (MaxAlignment != 0) { 3104 // Choose the minimal alignment between the non-zero alignment and the ABI 3105 // default alignment for the type of the stored value. 3106 SI->setAlignment(Align(std::min(MaxAlignment, TypeAlignment))); 3107 } else { 3108 // If both alignments are zero, use ABI default alignment for the type of 3109 // the stored value. 3110 SI->setAlignment(Align(TypeAlignment)); 3111 } 3112 3113 QStore->eraseFromParent(); 3114 PStore->eraseFromParent(); 3115 3116 return true; 3117 } 3118 3119 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI, 3120 const DataLayout &DL, 3121 const TargetTransformInfo &TTI) { 3122 // The intention here is to find diamonds or triangles (see below) where each 3123 // conditional block contains a store to the same address. Both of these 3124 // stores are conditional, so they can't be unconditionally sunk. But it may 3125 // be profitable to speculatively sink the stores into one merged store at the 3126 // end, and predicate the merged store on the union of the two conditions of 3127 // PBI and QBI. 3128 // 3129 // This can reduce the number of stores executed if both of the conditions are 3130 // true, and can allow the blocks to become small enough to be if-converted. 3131 // This optimization will also chain, so that ladders of test-and-set 3132 // sequences can be if-converted away. 3133 // 3134 // We only deal with simple diamonds or triangles: 3135 // 3136 // PBI or PBI or a combination of the two 3137 // / \ | \ 3138 // PTB PFB | PFB 3139 // \ / | / 3140 // QBI QBI 3141 // / \ | \ 3142 // QTB QFB | QFB 3143 // \ / | / 3144 // PostBB PostBB 3145 // 3146 // We model triangles as a type of diamond with a nullptr "true" block. 3147 // Triangles are canonicalized so that the fallthrough edge is represented by 3148 // a true condition, as in the diagram above. 3149 BasicBlock *PTB = PBI->getSuccessor(0); 3150 BasicBlock *PFB = PBI->getSuccessor(1); 3151 BasicBlock *QTB = QBI->getSuccessor(0); 3152 BasicBlock *QFB = QBI->getSuccessor(1); 3153 BasicBlock *PostBB = QFB->getSingleSuccessor(); 3154 3155 // Make sure we have a good guess for PostBB. If QTB's only successor is 3156 // QFB, then QFB is a better PostBB. 3157 if (QTB->getSingleSuccessor() == QFB) 3158 PostBB = QFB; 3159 3160 // If we couldn't find a good PostBB, stop. 3161 if (!PostBB) 3162 return false; 3163 3164 bool InvertPCond = false, InvertQCond = false; 3165 // Canonicalize fallthroughs to the true branches. 3166 if (PFB == QBI->getParent()) { 3167 std::swap(PFB, PTB); 3168 InvertPCond = true; 3169 } 3170 if (QFB == PostBB) { 3171 std::swap(QFB, QTB); 3172 InvertQCond = true; 3173 } 3174 3175 // From this point on we can assume PTB or QTB may be fallthroughs but PFB 3176 // and QFB may not. Model fallthroughs as a nullptr block. 3177 if (PTB == QBI->getParent()) 3178 PTB = nullptr; 3179 if (QTB == PostBB) 3180 QTB = nullptr; 3181 3182 // Legality bailouts. We must have at least the non-fallthrough blocks and 3183 // the post-dominating block, and the non-fallthroughs must only have one 3184 // predecessor. 3185 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { 3186 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S; 3187 }; 3188 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || 3189 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) 3190 return false; 3191 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || 3192 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) 3193 return false; 3194 if (!QBI->getParent()->hasNUses(2)) 3195 return false; 3196 3197 // OK, this is a sequence of two diamonds or triangles. 3198 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. 3199 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses; 3200 for (auto *BB : {PTB, PFB}) { 3201 if (!BB) 3202 continue; 3203 for (auto &I : *BB) 3204 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3205 PStoreAddresses.insert(SI->getPointerOperand()); 3206 } 3207 for (auto *BB : {QTB, QFB}) { 3208 if (!BB) 3209 continue; 3210 for (auto &I : *BB) 3211 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3212 QStoreAddresses.insert(SI->getPointerOperand()); 3213 } 3214 3215 set_intersect(PStoreAddresses, QStoreAddresses); 3216 // set_intersect mutates PStoreAddresses in place. Rename it here to make it 3217 // clear what it contains. 3218 auto &CommonAddresses = PStoreAddresses; 3219 3220 bool Changed = false; 3221 for (auto *Address : CommonAddresses) 3222 Changed |= mergeConditionalStoreToAddress( 3223 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL, TTI); 3224 return Changed; 3225 } 3226 3227 3228 /// If the previous block ended with a widenable branch, determine if reusing 3229 /// the target block is profitable and legal. This will have the effect of 3230 /// "widening" PBI, but doesn't require us to reason about hosting safety. 3231 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) { 3232 // TODO: This can be generalized in two important ways: 3233 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input 3234 // values from the PBI edge. 3235 // 2) We can sink side effecting instructions into BI's fallthrough 3236 // successor provided they doesn't contribute to computation of 3237 // BI's condition. 3238 Value *CondWB, *WC; 3239 BasicBlock *IfTrueBB, *IfFalseBB; 3240 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) || 3241 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor()) 3242 return false; 3243 if (!IfFalseBB->phis().empty()) 3244 return false; // TODO 3245 // Use lambda to lazily compute expensive condition after cheap ones. 3246 auto NoSideEffects = [](BasicBlock &BB) { 3247 return !llvm::any_of(BB, [](const Instruction &I) { 3248 return I.mayWriteToMemory() || I.mayHaveSideEffects(); 3249 }); 3250 }; 3251 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping 3252 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability 3253 NoSideEffects(*BI->getParent())) { 3254 BI->getSuccessor(1)->removePredecessor(BI->getParent()); 3255 BI->setSuccessor(1, IfFalseBB); 3256 return true; 3257 } 3258 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping 3259 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability 3260 NoSideEffects(*BI->getParent())) { 3261 BI->getSuccessor(0)->removePredecessor(BI->getParent()); 3262 BI->setSuccessor(0, IfFalseBB); 3263 return true; 3264 } 3265 return false; 3266 } 3267 3268 /// If we have a conditional branch as a predecessor of another block, 3269 /// this function tries to simplify it. We know 3270 /// that PBI and BI are both conditional branches, and BI is in one of the 3271 /// successor blocks of PBI - PBI branches to BI. 3272 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 3273 const DataLayout &DL, 3274 const TargetTransformInfo &TTI) { 3275 assert(PBI->isConditional() && BI->isConditional()); 3276 BasicBlock *BB = BI->getParent(); 3277 3278 // If this block ends with a branch instruction, and if there is a 3279 // predecessor that ends on a branch of the same condition, make 3280 // this conditional branch redundant. 3281 if (PBI->getCondition() == BI->getCondition() && 3282 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3283 // Okay, the outcome of this conditional branch is statically 3284 // knowable. If this block had a single pred, handle specially. 3285 if (BB->getSinglePredecessor()) { 3286 // Turn this into a branch on constant. 3287 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3288 BI->setCondition( 3289 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue)); 3290 return true; // Nuke the branch on constant. 3291 } 3292 3293 // Otherwise, if there are multiple predecessors, insert a PHI that merges 3294 // in the constant and simplify the block result. Subsequent passes of 3295 // simplifycfg will thread the block. 3296 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 3297 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 3298 PHINode *NewPN = PHINode::Create( 3299 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE), 3300 BI->getCondition()->getName() + ".pr", &BB->front()); 3301 // Okay, we're going to insert the PHI node. Since PBI is not the only 3302 // predecessor, compute the PHI'd conditional value for all of the preds. 3303 // Any predecessor where the condition is not computable we keep symbolic. 3304 for (pred_iterator PI = PB; PI != PE; ++PI) { 3305 BasicBlock *P = *PI; 3306 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI && 3307 PBI->isConditional() && PBI->getCondition() == BI->getCondition() && 3308 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3309 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3310 NewPN->addIncoming( 3311 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue), 3312 P); 3313 } else { 3314 NewPN->addIncoming(BI->getCondition(), P); 3315 } 3316 } 3317 3318 BI->setCondition(NewPN); 3319 return true; 3320 } 3321 } 3322 3323 // If the previous block ended with a widenable branch, determine if reusing 3324 // the target block is profitable and legal. This will have the effect of 3325 // "widening" PBI, but doesn't require us to reason about hosting safety. 3326 if (tryWidenCondBranchToCondBranch(PBI, BI)) 3327 return true; 3328 3329 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition())) 3330 if (CE->canTrap()) 3331 return false; 3332 3333 // If both branches are conditional and both contain stores to the same 3334 // address, remove the stores from the conditionals and create a conditional 3335 // merged store at the end. 3336 if (MergeCondStores && mergeConditionalStores(PBI, BI, DL, TTI)) 3337 return true; 3338 3339 // If this is a conditional branch in an empty block, and if any 3340 // predecessors are a conditional branch to one of our destinations, 3341 // fold the conditions into logical ops and one cond br. 3342 3343 // Ignore dbg intrinsics. 3344 if (&*BB->instructionsWithoutDebug().begin() != BI) 3345 return false; 3346 3347 int PBIOp, BIOp; 3348 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3349 PBIOp = 0; 3350 BIOp = 0; 3351 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3352 PBIOp = 0; 3353 BIOp = 1; 3354 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3355 PBIOp = 1; 3356 BIOp = 0; 3357 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3358 PBIOp = 1; 3359 BIOp = 1; 3360 } else { 3361 return false; 3362 } 3363 3364 // Check to make sure that the other destination of this branch 3365 // isn't BB itself. If so, this is an infinite loop that will 3366 // keep getting unwound. 3367 if (PBI->getSuccessor(PBIOp) == BB) 3368 return false; 3369 3370 // Do not perform this transformation if it would require 3371 // insertion of a large number of select instructions. For targets 3372 // without predication/cmovs, this is a big pessimization. 3373 3374 // Also do not perform this transformation if any phi node in the common 3375 // destination block can trap when reached by BB or PBB (PR17073). In that 3376 // case, it would be unsafe to hoist the operation into a select instruction. 3377 3378 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 3379 unsigned NumPhis = 0; 3380 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II); 3381 ++II, ++NumPhis) { 3382 if (NumPhis > 2) // Disable this xform. 3383 return false; 3384 3385 PHINode *PN = cast<PHINode>(II); 3386 Value *BIV = PN->getIncomingValueForBlock(BB); 3387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) 3388 if (CE->canTrap()) 3389 return false; 3390 3391 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 3392 Value *PBIV = PN->getIncomingValue(PBBIdx); 3393 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) 3394 if (CE->canTrap()) 3395 return false; 3396 } 3397 3398 // Finally, if everything is ok, fold the branches to logical ops. 3399 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 3400 3401 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 3402 << "AND: " << *BI->getParent()); 3403 3404 // If OtherDest *is* BB, then BB is a basic block with a single conditional 3405 // branch in it, where one edge (OtherDest) goes back to itself but the other 3406 // exits. We don't *know* that the program avoids the infinite loop 3407 // (even though that seems likely). If we do this xform naively, we'll end up 3408 // recursively unpeeling the loop. Since we know that (after the xform is 3409 // done) that the block *is* infinite if reached, we just make it an obviously 3410 // infinite loop with no cond branch. 3411 if (OtherDest == BB) { 3412 // Insert it at the end of the function, because it's either code, 3413 // or it won't matter if it's hot. :) 3414 BasicBlock *InfLoopBlock = 3415 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent()); 3416 BranchInst::Create(InfLoopBlock, InfLoopBlock); 3417 OtherDest = InfLoopBlock; 3418 } 3419 3420 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3421 3422 // BI may have other predecessors. Because of this, we leave 3423 // it alone, but modify PBI. 3424 3425 // Make sure we get to CommonDest on True&True directions. 3426 Value *PBICond = PBI->getCondition(); 3427 IRBuilder<NoFolder> Builder(PBI); 3428 if (PBIOp) 3429 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not"); 3430 3431 Value *BICond = BI->getCondition(); 3432 if (BIOp) 3433 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not"); 3434 3435 // Merge the conditions. 3436 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); 3437 3438 // Modify PBI to branch on the new condition to the new dests. 3439 PBI->setCondition(Cond); 3440 PBI->setSuccessor(0, CommonDest); 3441 PBI->setSuccessor(1, OtherDest); 3442 3443 // Update branch weight for PBI. 3444 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3445 uint64_t PredCommon, PredOther, SuccCommon, SuccOther; 3446 bool HasWeights = 3447 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3448 SuccTrueWeight, SuccFalseWeight); 3449 if (HasWeights) { 3450 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3451 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3452 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3453 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3454 // The weight to CommonDest should be PredCommon * SuccTotal + 3455 // PredOther * SuccCommon. 3456 // The weight to OtherDest should be PredOther * SuccOther. 3457 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + 3458 PredOther * SuccCommon, 3459 PredOther * SuccOther}; 3460 // Halve the weights if any of them cannot fit in an uint32_t 3461 FitWeights(NewWeights); 3462 3463 setBranchWeights(PBI, NewWeights[0], NewWeights[1]); 3464 } 3465 3466 // OtherDest may have phi nodes. If so, add an entry from PBI's 3467 // block that are identical to the entries for BI's block. 3468 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 3469 3470 // We know that the CommonDest already had an edge from PBI to 3471 // it. If it has PHIs though, the PHIs may have different 3472 // entries for BB and PBI's BB. If so, insert a select to make 3473 // them agree. 3474 for (PHINode &PN : CommonDest->phis()) { 3475 Value *BIV = PN.getIncomingValueForBlock(BB); 3476 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent()); 3477 Value *PBIV = PN.getIncomingValue(PBBIdx); 3478 if (BIV != PBIV) { 3479 // Insert a select in PBI to pick the right value. 3480 SelectInst *NV = cast<SelectInst>( 3481 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux")); 3482 PN.setIncomingValue(PBBIdx, NV); 3483 // Although the select has the same condition as PBI, the original branch 3484 // weights for PBI do not apply to the new select because the select's 3485 // 'logical' edges are incoming edges of the phi that is eliminated, not 3486 // the outgoing edges of PBI. 3487 if (HasWeights) { 3488 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3489 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3490 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3491 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3492 // The weight to PredCommonDest should be PredCommon * SuccTotal. 3493 // The weight to PredOtherDest should be PredOther * SuccCommon. 3494 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther), 3495 PredOther * SuccCommon}; 3496 3497 FitWeights(NewWeights); 3498 3499 setBranchWeights(NV, NewWeights[0], NewWeights[1]); 3500 } 3501 } 3502 } 3503 3504 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 3505 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3506 3507 // This basic block is probably dead. We know it has at least 3508 // one fewer predecessor. 3509 return true; 3510 } 3511 3512 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is 3513 // true or to FalseBB if Cond is false. 3514 // Takes care of updating the successors and removing the old terminator. 3515 // Also makes sure not to introduce new successors by assuming that edges to 3516 // non-successor TrueBBs and FalseBBs aren't reachable. 3517 static bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond, 3518 BasicBlock *TrueBB, BasicBlock *FalseBB, 3519 uint32_t TrueWeight, 3520 uint32_t FalseWeight) { 3521 // Remove any superfluous successor edges from the CFG. 3522 // First, figure out which successors to preserve. 3523 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 3524 // successor. 3525 BasicBlock *KeepEdge1 = TrueBB; 3526 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; 3527 3528 // Then remove the rest. 3529 for (BasicBlock *Succ : successors(OldTerm)) { 3530 // Make sure only to keep exactly one copy of each edge. 3531 if (Succ == KeepEdge1) 3532 KeepEdge1 = nullptr; 3533 else if (Succ == KeepEdge2) 3534 KeepEdge2 = nullptr; 3535 else 3536 Succ->removePredecessor(OldTerm->getParent(), 3537 /*KeepOneInputPHIs=*/true); 3538 } 3539 3540 IRBuilder<> Builder(OldTerm); 3541 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 3542 3543 // Insert an appropriate new terminator. 3544 if (!KeepEdge1 && !KeepEdge2) { 3545 if (TrueBB == FalseBB) 3546 // We were only looking for one successor, and it was present. 3547 // Create an unconditional branch to it. 3548 Builder.CreateBr(TrueBB); 3549 else { 3550 // We found both of the successors we were looking for. 3551 // Create a conditional branch sharing the condition of the select. 3552 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 3553 if (TrueWeight != FalseWeight) 3554 setBranchWeights(NewBI, TrueWeight, FalseWeight); 3555 } 3556 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 3557 // Neither of the selected blocks were successors, so this 3558 // terminator must be unreachable. 3559 new UnreachableInst(OldTerm->getContext(), OldTerm); 3560 } else { 3561 // One of the selected values was a successor, but the other wasn't. 3562 // Insert an unconditional branch to the one that was found; 3563 // the edge to the one that wasn't must be unreachable. 3564 if (!KeepEdge1) 3565 // Only TrueBB was found. 3566 Builder.CreateBr(TrueBB); 3567 else 3568 // Only FalseBB was found. 3569 Builder.CreateBr(FalseBB); 3570 } 3571 3572 EraseTerminatorAndDCECond(OldTerm); 3573 return true; 3574 } 3575 3576 // Replaces 3577 // (switch (select cond, X, Y)) on constant X, Y 3578 // with a branch - conditional if X and Y lead to distinct BBs, 3579 // unconditional otherwise. 3580 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) { 3581 // Check for constant integer values in the select. 3582 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 3583 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 3584 if (!TrueVal || !FalseVal) 3585 return false; 3586 3587 // Find the relevant condition and destinations. 3588 Value *Condition = Select->getCondition(); 3589 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor(); 3590 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor(); 3591 3592 // Get weight for TrueBB and FalseBB. 3593 uint32_t TrueWeight = 0, FalseWeight = 0; 3594 SmallVector<uint64_t, 8> Weights; 3595 bool HasWeights = HasBranchWeights(SI); 3596 if (HasWeights) { 3597 GetBranchWeights(SI, Weights); 3598 if (Weights.size() == 1 + SI->getNumCases()) { 3599 TrueWeight = 3600 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()]; 3601 FalseWeight = 3602 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()]; 3603 } 3604 } 3605 3606 // Perform the actual simplification. 3607 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight, 3608 FalseWeight); 3609 } 3610 3611 // Replaces 3612 // (indirectbr (select cond, blockaddress(@fn, BlockA), 3613 // blockaddress(@fn, BlockB))) 3614 // with 3615 // (br cond, BlockA, BlockB). 3616 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) { 3617 // Check that both operands of the select are block addresses. 3618 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 3619 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 3620 if (!TBA || !FBA) 3621 return false; 3622 3623 // Extract the actual blocks. 3624 BasicBlock *TrueBB = TBA->getBasicBlock(); 3625 BasicBlock *FalseBB = FBA->getBasicBlock(); 3626 3627 // Perform the actual simplification. 3628 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0, 3629 0); 3630 } 3631 3632 /// This is called when we find an icmp instruction 3633 /// (a seteq/setne with a constant) as the only instruction in a 3634 /// block that ends with an uncond branch. We are looking for a very specific 3635 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 3636 /// this case, we merge the first two "or's of icmp" into a switch, but then the 3637 /// default value goes to an uncond block with a seteq in it, we get something 3638 /// like: 3639 /// 3640 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 3641 /// DEFAULT: 3642 /// %tmp = icmp eq i8 %A, 92 3643 /// br label %end 3644 /// end: 3645 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 3646 /// 3647 /// We prefer to split the edge to 'end' so that there is a true/false entry to 3648 /// the PHI, merging the third icmp into the switch. 3649 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( 3650 ICmpInst *ICI, IRBuilder<> &Builder) { 3651 BasicBlock *BB = ICI->getParent(); 3652 3653 // If the block has any PHIs in it or the icmp has multiple uses, it is too 3654 // complex. 3655 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) 3656 return false; 3657 3658 Value *V = ICI->getOperand(0); 3659 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 3660 3661 // The pattern we're looking for is where our only predecessor is a switch on 3662 // 'V' and this block is the default case for the switch. In this case we can 3663 // fold the compared value into the switch to simplify things. 3664 BasicBlock *Pred = BB->getSinglePredecessor(); 3665 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) 3666 return false; 3667 3668 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 3669 if (SI->getCondition() != V) 3670 return false; 3671 3672 // If BB is reachable on a non-default case, then we simply know the value of 3673 // V in this block. Substitute it and constant fold the icmp instruction 3674 // away. 3675 if (SI->getDefaultDest() != BB) { 3676 ConstantInt *VVal = SI->findCaseDest(BB); 3677 assert(VVal && "Should have a unique destination value"); 3678 ICI->setOperand(0, VVal); 3679 3680 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) { 3681 ICI->replaceAllUsesWith(V); 3682 ICI->eraseFromParent(); 3683 } 3684 // BB is now empty, so it is likely to simplify away. 3685 return requestResimplify(); 3686 } 3687 3688 // Ok, the block is reachable from the default dest. If the constant we're 3689 // comparing exists in one of the other edges, then we can constant fold ICI 3690 // and zap it. 3691 if (SI->findCaseValue(Cst) != SI->case_default()) { 3692 Value *V; 3693 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3694 V = ConstantInt::getFalse(BB->getContext()); 3695 else 3696 V = ConstantInt::getTrue(BB->getContext()); 3697 3698 ICI->replaceAllUsesWith(V); 3699 ICI->eraseFromParent(); 3700 // BB is now empty, so it is likely to simplify away. 3701 return requestResimplify(); 3702 } 3703 3704 // The use of the icmp has to be in the 'end' block, by the only PHI node in 3705 // the block. 3706 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 3707 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); 3708 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || 3709 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 3710 return false; 3711 3712 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 3713 // true in the PHI. 3714 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 3715 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 3716 3717 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3718 std::swap(DefaultCst, NewCst); 3719 3720 // Replace ICI (which is used by the PHI for the default value) with true or 3721 // false depending on if it is EQ or NE. 3722 ICI->replaceAllUsesWith(DefaultCst); 3723 ICI->eraseFromParent(); 3724 3725 // Okay, the switch goes to this block on a default value. Add an edge from 3726 // the switch to the merge point on the compared value. 3727 BasicBlock *NewBB = 3728 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB); 3729 { 3730 SwitchInstProfUpdateWrapper SIW(*SI); 3731 auto W0 = SIW.getSuccessorWeight(0); 3732 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW; 3733 if (W0) { 3734 NewW = ((uint64_t(*W0) + 1) >> 1); 3735 SIW.setSuccessorWeight(0, *NewW); 3736 } 3737 SIW.addCase(Cst, NewBB, NewW); 3738 } 3739 3740 // NewBB branches to the phi block, add the uncond branch and the phi entry. 3741 Builder.SetInsertPoint(NewBB); 3742 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 3743 Builder.CreateBr(SuccBlock); 3744 PHIUse->addIncoming(NewCst, NewBB); 3745 return true; 3746 } 3747 3748 /// The specified branch is a conditional branch. 3749 /// Check to see if it is branching on an or/and chain of icmp instructions, and 3750 /// fold it into a switch instruction if so. 3751 static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder, 3752 const DataLayout &DL) { 3753 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 3754 if (!Cond) 3755 return false; 3756 3757 // Change br (X == 0 | X == 1), T, F into a switch instruction. 3758 // If this is a bunch of seteq's or'd together, or if it's a bunch of 3759 // 'setne's and'ed together, collect them. 3760 3761 // Try to gather values from a chain of and/or to be turned into a switch 3762 ConstantComparesGatherer ConstantCompare(Cond, DL); 3763 // Unpack the result 3764 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals; 3765 Value *CompVal = ConstantCompare.CompValue; 3766 unsigned UsedICmps = ConstantCompare.UsedICmps; 3767 Value *ExtraCase = ConstantCompare.Extra; 3768 3769 // If we didn't have a multiply compared value, fail. 3770 if (!CompVal) 3771 return false; 3772 3773 // Avoid turning single icmps into a switch. 3774 if (UsedICmps <= 1) 3775 return false; 3776 3777 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or); 3778 3779 // There might be duplicate constants in the list, which the switch 3780 // instruction can't handle, remove them now. 3781 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 3782 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 3783 3784 // If Extra was used, we require at least two switch values to do the 3785 // transformation. A switch with one value is just a conditional branch. 3786 if (ExtraCase && Values.size() < 2) 3787 return false; 3788 3789 // TODO: Preserve branch weight metadata, similarly to how 3790 // FoldValueComparisonIntoPredecessors preserves it. 3791 3792 // Figure out which block is which destination. 3793 BasicBlock *DefaultBB = BI->getSuccessor(1); 3794 BasicBlock *EdgeBB = BI->getSuccessor(0); 3795 if (!TrueWhenEqual) 3796 std::swap(DefaultBB, EdgeBB); 3797 3798 BasicBlock *BB = BI->getParent(); 3799 3800 // MSAN does not like undefs as branch condition which can be introduced 3801 // with "explicit branch". 3802 if (ExtraCase && BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory)) 3803 return false; 3804 3805 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 3806 << " cases into SWITCH. BB is:\n" 3807 << *BB); 3808 3809 // If there are any extra values that couldn't be folded into the switch 3810 // then we evaluate them with an explicit branch first. Split the block 3811 // right before the condbr to handle it. 3812 if (ExtraCase) { 3813 BasicBlock *NewBB = 3814 BB->splitBasicBlock(BI->getIterator(), "switch.early.test"); 3815 // Remove the uncond branch added to the old block. 3816 Instruction *OldTI = BB->getTerminator(); 3817 Builder.SetInsertPoint(OldTI); 3818 3819 if (TrueWhenEqual) 3820 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 3821 else 3822 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 3823 3824 OldTI->eraseFromParent(); 3825 3826 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 3827 // for the edge we just added. 3828 AddPredecessorToBlock(EdgeBB, BB, NewBB); 3829 3830 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 3831 << "\nEXTRABB = " << *BB); 3832 BB = NewBB; 3833 } 3834 3835 Builder.SetInsertPoint(BI); 3836 // Convert pointer to int before we switch. 3837 if (CompVal->getType()->isPointerTy()) { 3838 CompVal = Builder.CreatePtrToInt( 3839 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); 3840 } 3841 3842 // Create the new switch instruction now. 3843 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 3844 3845 // Add all of the 'cases' to the switch instruction. 3846 for (unsigned i = 0, e = Values.size(); i != e; ++i) 3847 New->addCase(Values[i], EdgeBB); 3848 3849 // We added edges from PI to the EdgeBB. As such, if there were any 3850 // PHI nodes in EdgeBB, they need entries to be added corresponding to 3851 // the number of edges added. 3852 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) { 3853 PHINode *PN = cast<PHINode>(BBI); 3854 Value *InVal = PN->getIncomingValueForBlock(BB); 3855 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i) 3856 PN->addIncoming(InVal, BB); 3857 } 3858 3859 // Erase the old branch instruction. 3860 EraseTerminatorAndDCECond(BI); 3861 3862 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 3863 return true; 3864 } 3865 3866 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 3867 if (isa<PHINode>(RI->getValue())) 3868 return SimplifyCommonResume(RI); 3869 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) && 3870 RI->getValue() == RI->getParent()->getFirstNonPHI()) 3871 // The resume must unwind the exception that caused control to branch here. 3872 return SimplifySingleResume(RI); 3873 3874 return false; 3875 } 3876 3877 // Simplify resume that is shared by several landing pads (phi of landing pad). 3878 bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) { 3879 BasicBlock *BB = RI->getParent(); 3880 3881 // Check that there are no other instructions except for debug intrinsics 3882 // between the phi of landing pads (RI->getValue()) and resume instruction. 3883 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(), 3884 E = RI->getIterator(); 3885 while (++I != E) 3886 if (!isa<DbgInfoIntrinsic>(I)) 3887 return false; 3888 3889 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks; 3890 auto *PhiLPInst = cast<PHINode>(RI->getValue()); 3891 3892 // Check incoming blocks to see if any of them are trivial. 3893 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End; 3894 Idx++) { 3895 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx); 3896 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx); 3897 3898 // If the block has other successors, we can not delete it because 3899 // it has other dependents. 3900 if (IncomingBB->getUniqueSuccessor() != BB) 3901 continue; 3902 3903 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI()); 3904 // Not the landing pad that caused the control to branch here. 3905 if (IncomingValue != LandingPad) 3906 continue; 3907 3908 bool isTrivial = true; 3909 3910 I = IncomingBB->getFirstNonPHI()->getIterator(); 3911 E = IncomingBB->getTerminator()->getIterator(); 3912 while (++I != E) 3913 if (!isa<DbgInfoIntrinsic>(I)) { 3914 isTrivial = false; 3915 break; 3916 } 3917 3918 if (isTrivial) 3919 TrivialUnwindBlocks.insert(IncomingBB); 3920 } 3921 3922 // If no trivial unwind blocks, don't do any simplifications. 3923 if (TrivialUnwindBlocks.empty()) 3924 return false; 3925 3926 // Turn all invokes that unwind here into calls. 3927 for (auto *TrivialBB : TrivialUnwindBlocks) { 3928 // Blocks that will be simplified should be removed from the phi node. 3929 // Note there could be multiple edges to the resume block, and we need 3930 // to remove them all. 3931 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1) 3932 BB->removePredecessor(TrivialBB, true); 3933 3934 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB); 3935 PI != PE;) { 3936 BasicBlock *Pred = *PI++; 3937 removeUnwindEdge(Pred); 3938 } 3939 3940 // In each SimplifyCFG run, only the current processed block can be erased. 3941 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead 3942 // of erasing TrivialBB, we only remove the branch to the common resume 3943 // block so that we can later erase the resume block since it has no 3944 // predecessors. 3945 TrivialBB->getTerminator()->eraseFromParent(); 3946 new UnreachableInst(RI->getContext(), TrivialBB); 3947 } 3948 3949 // Delete the resume block if all its predecessors have been removed. 3950 if (pred_empty(BB)) 3951 BB->eraseFromParent(); 3952 3953 return !TrivialUnwindBlocks.empty(); 3954 } 3955 3956 // Simplify resume that is only used by a single (non-phi) landing pad. 3957 bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) { 3958 BasicBlock *BB = RI->getParent(); 3959 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI()); 3960 assert(RI->getValue() == LPInst && 3961 "Resume must unwind the exception that caused control to here"); 3962 3963 // Check that there are no other instructions except for debug intrinsics. 3964 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator(); 3965 while (++I != E) 3966 if (!isa<DbgInfoIntrinsic>(I)) 3967 return false; 3968 3969 // Turn all invokes that unwind here into calls and delete the basic block. 3970 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 3971 BasicBlock *Pred = *PI++; 3972 removeUnwindEdge(Pred); 3973 } 3974 3975 // The landingpad is now unreachable. Zap it. 3976 if (LoopHeaders) 3977 LoopHeaders->erase(BB); 3978 BB->eraseFromParent(); 3979 return true; 3980 } 3981 3982 static bool removeEmptyCleanup(CleanupReturnInst *RI) { 3983 // If this is a trivial cleanup pad that executes no instructions, it can be 3984 // eliminated. If the cleanup pad continues to the caller, any predecessor 3985 // that is an EH pad will be updated to continue to the caller and any 3986 // predecessor that terminates with an invoke instruction will have its invoke 3987 // instruction converted to a call instruction. If the cleanup pad being 3988 // simplified does not continue to the caller, each predecessor will be 3989 // updated to continue to the unwind destination of the cleanup pad being 3990 // simplified. 3991 BasicBlock *BB = RI->getParent(); 3992 CleanupPadInst *CPInst = RI->getCleanupPad(); 3993 if (CPInst->getParent() != BB) 3994 // This isn't an empty cleanup. 3995 return false; 3996 3997 // We cannot kill the pad if it has multiple uses. This typically arises 3998 // from unreachable basic blocks. 3999 if (!CPInst->hasOneUse()) 4000 return false; 4001 4002 // Check that there are no other instructions except for benign intrinsics. 4003 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator(); 4004 while (++I != E) { 4005 auto *II = dyn_cast<IntrinsicInst>(I); 4006 if (!II) 4007 return false; 4008 4009 Intrinsic::ID IntrinsicID = II->getIntrinsicID(); 4010 switch (IntrinsicID) { 4011 case Intrinsic::dbg_declare: 4012 case Intrinsic::dbg_value: 4013 case Intrinsic::dbg_label: 4014 case Intrinsic::lifetime_end: 4015 break; 4016 default: 4017 return false; 4018 } 4019 } 4020 4021 // If the cleanup return we are simplifying unwinds to the caller, this will 4022 // set UnwindDest to nullptr. 4023 BasicBlock *UnwindDest = RI->getUnwindDest(); 4024 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr; 4025 4026 // We're about to remove BB from the control flow. Before we do, sink any 4027 // PHINodes into the unwind destination. Doing this before changing the 4028 // control flow avoids some potentially slow checks, since we can currently 4029 // be certain that UnwindDest and BB have no common predecessors (since they 4030 // are both EH pads). 4031 if (UnwindDest) { 4032 // First, go through the PHI nodes in UnwindDest and update any nodes that 4033 // reference the block we are removing 4034 for (BasicBlock::iterator I = UnwindDest->begin(), 4035 IE = DestEHPad->getIterator(); 4036 I != IE; ++I) { 4037 PHINode *DestPN = cast<PHINode>(I); 4038 4039 int Idx = DestPN->getBasicBlockIndex(BB); 4040 // Since BB unwinds to UnwindDest, it has to be in the PHI node. 4041 assert(Idx != -1); 4042 // This PHI node has an incoming value that corresponds to a control 4043 // path through the cleanup pad we are removing. If the incoming 4044 // value is in the cleanup pad, it must be a PHINode (because we 4045 // verified above that the block is otherwise empty). Otherwise, the 4046 // value is either a constant or a value that dominates the cleanup 4047 // pad being removed. 4048 // 4049 // Because BB and UnwindDest are both EH pads, all of their 4050 // predecessors must unwind to these blocks, and since no instruction 4051 // can have multiple unwind destinations, there will be no overlap in 4052 // incoming blocks between SrcPN and DestPN. 4053 Value *SrcVal = DestPN->getIncomingValue(Idx); 4054 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); 4055 4056 // Remove the entry for the block we are deleting. 4057 DestPN->removeIncomingValue(Idx, false); 4058 4059 if (SrcPN && SrcPN->getParent() == BB) { 4060 // If the incoming value was a PHI node in the cleanup pad we are 4061 // removing, we need to merge that PHI node's incoming values into 4062 // DestPN. 4063 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues(); 4064 SrcIdx != SrcE; ++SrcIdx) { 4065 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx), 4066 SrcPN->getIncomingBlock(SrcIdx)); 4067 } 4068 } else { 4069 // Otherwise, the incoming value came from above BB and 4070 // so we can just reuse it. We must associate all of BB's 4071 // predecessors with this value. 4072 for (auto *pred : predecessors(BB)) { 4073 DestPN->addIncoming(SrcVal, pred); 4074 } 4075 } 4076 } 4077 4078 // Sink any remaining PHI nodes directly into UnwindDest. 4079 Instruction *InsertPt = DestEHPad; 4080 for (BasicBlock::iterator I = BB->begin(), 4081 IE = BB->getFirstNonPHI()->getIterator(); 4082 I != IE;) { 4083 // The iterator must be incremented here because the instructions are 4084 // being moved to another block. 4085 PHINode *PN = cast<PHINode>(I++); 4086 if (PN->use_empty() || !PN->isUsedOutsideOfBlock(BB)) 4087 // If the PHI node has no uses or all of its uses are in this basic 4088 // block (meaning they are debug or lifetime intrinsics), just leave 4089 // it. It will be erased when we erase BB below. 4090 continue; 4091 4092 // Otherwise, sink this PHI node into UnwindDest. 4093 // Any predecessors to UnwindDest which are not already represented 4094 // must be back edges which inherit the value from the path through 4095 // BB. In this case, the PHI value must reference itself. 4096 for (auto *pred : predecessors(UnwindDest)) 4097 if (pred != BB) 4098 PN->addIncoming(PN, pred); 4099 PN->moveBefore(InsertPt); 4100 } 4101 } 4102 4103 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 4104 // The iterator must be updated here because we are removing this pred. 4105 BasicBlock *PredBB = *PI++; 4106 if (UnwindDest == nullptr) { 4107 removeUnwindEdge(PredBB); 4108 } else { 4109 Instruction *TI = PredBB->getTerminator(); 4110 TI->replaceUsesOfWith(BB, UnwindDest); 4111 } 4112 } 4113 4114 // The cleanup pad is now unreachable. Zap it. 4115 BB->eraseFromParent(); 4116 return true; 4117 } 4118 4119 // Try to merge two cleanuppads together. 4120 static bool mergeCleanupPad(CleanupReturnInst *RI) { 4121 // Skip any cleanuprets which unwind to caller, there is nothing to merge 4122 // with. 4123 BasicBlock *UnwindDest = RI->getUnwindDest(); 4124 if (!UnwindDest) 4125 return false; 4126 4127 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't 4128 // be safe to merge without code duplication. 4129 if (UnwindDest->getSinglePredecessor() != RI->getParent()) 4130 return false; 4131 4132 // Verify that our cleanuppad's unwind destination is another cleanuppad. 4133 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front()); 4134 if (!SuccessorCleanupPad) 4135 return false; 4136 4137 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad(); 4138 // Replace any uses of the successor cleanupad with the predecessor pad 4139 // The only cleanuppad uses should be this cleanupret, it's cleanupret and 4140 // funclet bundle operands. 4141 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad); 4142 // Remove the old cleanuppad. 4143 SuccessorCleanupPad->eraseFromParent(); 4144 // Now, we simply replace the cleanupret with a branch to the unwind 4145 // destination. 4146 BranchInst::Create(UnwindDest, RI->getParent()); 4147 RI->eraseFromParent(); 4148 4149 return true; 4150 } 4151 4152 bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) { 4153 // It is possible to transiantly have an undef cleanuppad operand because we 4154 // have deleted some, but not all, dead blocks. 4155 // Eventually, this block will be deleted. 4156 if (isa<UndefValue>(RI->getOperand(0))) 4157 return false; 4158 4159 if (mergeCleanupPad(RI)) 4160 return true; 4161 4162 if (removeEmptyCleanup(RI)) 4163 return true; 4164 4165 return false; 4166 } 4167 4168 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { 4169 BasicBlock *BB = RI->getParent(); 4170 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) 4171 return false; 4172 4173 // Find predecessors that end with branches. 4174 SmallVector<BasicBlock *, 8> UncondBranchPreds; 4175 SmallVector<BranchInst *, 8> CondBranchPreds; 4176 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 4177 BasicBlock *P = *PI; 4178 Instruction *PTI = P->getTerminator(); 4179 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { 4180 if (BI->isUnconditional()) 4181 UncondBranchPreds.push_back(P); 4182 else 4183 CondBranchPreds.push_back(BI); 4184 } 4185 } 4186 4187 // If we found some, do the transformation! 4188 if (!UncondBranchPreds.empty() && DupRet) { 4189 while (!UncondBranchPreds.empty()) { 4190 BasicBlock *Pred = UncondBranchPreds.pop_back_val(); 4191 LLVM_DEBUG(dbgs() << "FOLDING: " << *BB 4192 << "INTO UNCOND BRANCH PRED: " << *Pred); 4193 (void)FoldReturnIntoUncondBranch(RI, BB, Pred); 4194 } 4195 4196 // If we eliminated all predecessors of the block, delete the block now. 4197 if (pred_empty(BB)) { 4198 // We know there are no successors, so just nuke the block. 4199 if (LoopHeaders) 4200 LoopHeaders->erase(BB); 4201 BB->eraseFromParent(); 4202 } 4203 4204 return true; 4205 } 4206 4207 // Check out all of the conditional branches going to this return 4208 // instruction. If any of them just select between returns, change the 4209 // branch itself into a select/return pair. 4210 while (!CondBranchPreds.empty()) { 4211 BranchInst *BI = CondBranchPreds.pop_back_val(); 4212 4213 // Check to see if the non-BB successor is also a return block. 4214 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && 4215 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && 4216 SimplifyCondBranchToTwoReturns(BI, Builder)) 4217 return true; 4218 } 4219 return false; 4220 } 4221 4222 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) { 4223 BasicBlock *BB = UI->getParent(); 4224 4225 bool Changed = false; 4226 4227 // If there are any instructions immediately before the unreachable that can 4228 // be removed, do so. 4229 while (UI->getIterator() != BB->begin()) { 4230 BasicBlock::iterator BBI = UI->getIterator(); 4231 --BBI; 4232 // Do not delete instructions that can have side effects which might cause 4233 // the unreachable to not be reachable; specifically, calls and volatile 4234 // operations may have this effect. 4235 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) 4236 break; 4237 4238 if (BBI->mayHaveSideEffects()) { 4239 if (auto *SI = dyn_cast<StoreInst>(BBI)) { 4240 if (SI->isVolatile()) 4241 break; 4242 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) { 4243 if (LI->isVolatile()) 4244 break; 4245 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { 4246 if (RMWI->isVolatile()) 4247 break; 4248 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { 4249 if (CXI->isVolatile()) 4250 break; 4251 } else if (isa<CatchPadInst>(BBI)) { 4252 // A catchpad may invoke exception object constructors and such, which 4253 // in some languages can be arbitrary code, so be conservative by 4254 // default. 4255 // For CoreCLR, it just involves a type test, so can be removed. 4256 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) != 4257 EHPersonality::CoreCLR) 4258 break; 4259 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && 4260 !isa<LandingPadInst>(BBI)) { 4261 break; 4262 } 4263 // Note that deleting LandingPad's here is in fact okay, although it 4264 // involves a bit of subtle reasoning. If this inst is a LandingPad, 4265 // all the predecessors of this block will be the unwind edges of Invokes, 4266 // and we can therefore guarantee this block will be erased. 4267 } 4268 4269 // Delete this instruction (any uses are guaranteed to be dead) 4270 if (!BBI->use_empty()) 4271 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 4272 BBI->eraseFromParent(); 4273 Changed = true; 4274 } 4275 4276 // If the unreachable instruction is the first in the block, take a gander 4277 // at all of the predecessors of this instruction, and simplify them. 4278 if (&BB->front() != UI) 4279 return Changed; 4280 4281 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB)); 4282 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 4283 Instruction *TI = Preds[i]->getTerminator(); 4284 IRBuilder<> Builder(TI); 4285 if (auto *BI = dyn_cast<BranchInst>(TI)) { 4286 if (BI->isUnconditional()) { 4287 assert(BI->getSuccessor(0) == BB && "Incorrect CFG"); 4288 new UnreachableInst(TI->getContext(), TI); 4289 TI->eraseFromParent(); 4290 Changed = true; 4291 } else { 4292 Value* Cond = BI->getCondition(); 4293 if (BI->getSuccessor(0) == BB) { 4294 Builder.CreateAssumption(Builder.CreateNot(Cond)); 4295 Builder.CreateBr(BI->getSuccessor(1)); 4296 } else { 4297 assert(BI->getSuccessor(1) == BB && "Incorrect CFG"); 4298 Builder.CreateAssumption(Cond); 4299 Builder.CreateBr(BI->getSuccessor(0)); 4300 } 4301 EraseTerminatorAndDCECond(BI); 4302 Changed = true; 4303 } 4304 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { 4305 SwitchInstProfUpdateWrapper SU(*SI); 4306 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) { 4307 if (i->getCaseSuccessor() != BB) { 4308 ++i; 4309 continue; 4310 } 4311 BB->removePredecessor(SU->getParent()); 4312 i = SU.removeCase(i); 4313 e = SU->case_end(); 4314 Changed = true; 4315 } 4316 } else if (auto *II = dyn_cast<InvokeInst>(TI)) { 4317 if (II->getUnwindDest() == BB) { 4318 removeUnwindEdge(TI->getParent()); 4319 Changed = true; 4320 } 4321 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 4322 if (CSI->getUnwindDest() == BB) { 4323 removeUnwindEdge(TI->getParent()); 4324 Changed = true; 4325 continue; 4326 } 4327 4328 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(), 4329 E = CSI->handler_end(); 4330 I != E; ++I) { 4331 if (*I == BB) { 4332 CSI->removeHandler(I); 4333 --I; 4334 --E; 4335 Changed = true; 4336 } 4337 } 4338 if (CSI->getNumHandlers() == 0) { 4339 BasicBlock *CatchSwitchBB = CSI->getParent(); 4340 if (CSI->hasUnwindDest()) { 4341 // Redirect preds to the unwind dest 4342 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest()); 4343 } else { 4344 // Rewrite all preds to unwind to caller (or from invoke to call). 4345 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB)); 4346 for (BasicBlock *EHPred : EHPreds) 4347 removeUnwindEdge(EHPred); 4348 } 4349 // The catchswitch is no longer reachable. 4350 new UnreachableInst(CSI->getContext(), CSI); 4351 CSI->eraseFromParent(); 4352 Changed = true; 4353 } 4354 } else if (isa<CleanupReturnInst>(TI)) { 4355 new UnreachableInst(TI->getContext(), TI); 4356 TI->eraseFromParent(); 4357 Changed = true; 4358 } 4359 } 4360 4361 // If this block is now dead, remove it. 4362 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) { 4363 // We know there are no successors, so just nuke the block. 4364 if (LoopHeaders) 4365 LoopHeaders->erase(BB); 4366 BB->eraseFromParent(); 4367 return true; 4368 } 4369 4370 return Changed; 4371 } 4372 4373 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { 4374 assert(Cases.size() >= 1); 4375 4376 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 4377 for (size_t I = 1, E = Cases.size(); I != E; ++I) { 4378 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) 4379 return false; 4380 } 4381 return true; 4382 } 4383 4384 static void createUnreachableSwitchDefault(SwitchInst *Switch) { 4385 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); 4386 BasicBlock *NewDefaultBlock = 4387 SplitBlockPredecessors(Switch->getDefaultDest(), Switch->getParent(), ""); 4388 Switch->setDefaultDest(&*NewDefaultBlock); 4389 SplitBlock(&*NewDefaultBlock, &NewDefaultBlock->front()); 4390 auto *NewTerminator = NewDefaultBlock->getTerminator(); 4391 new UnreachableInst(Switch->getContext(), NewTerminator); 4392 EraseTerminatorAndDCECond(NewTerminator); 4393 } 4394 4395 /// Turn a switch with two reachable destinations into an integer range 4396 /// comparison and branch. 4397 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) { 4398 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 4399 4400 bool HasDefault = 4401 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4402 4403 // Partition the cases into two sets with different destinations. 4404 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; 4405 BasicBlock *DestB = nullptr; 4406 SmallVector<ConstantInt *, 16> CasesA; 4407 SmallVector<ConstantInt *, 16> CasesB; 4408 4409 for (auto Case : SI->cases()) { 4410 BasicBlock *Dest = Case.getCaseSuccessor(); 4411 if (!DestA) 4412 DestA = Dest; 4413 if (Dest == DestA) { 4414 CasesA.push_back(Case.getCaseValue()); 4415 continue; 4416 } 4417 if (!DestB) 4418 DestB = Dest; 4419 if (Dest == DestB) { 4420 CasesB.push_back(Case.getCaseValue()); 4421 continue; 4422 } 4423 return false; // More than two destinations. 4424 } 4425 4426 assert(DestA && DestB && 4427 "Single-destination switch should have been folded."); 4428 assert(DestA != DestB); 4429 assert(DestB != SI->getDefaultDest()); 4430 assert(!CasesB.empty() && "There must be non-default cases."); 4431 assert(!CasesA.empty() || HasDefault); 4432 4433 // Figure out if one of the sets of cases form a contiguous range. 4434 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; 4435 BasicBlock *ContiguousDest = nullptr; 4436 BasicBlock *OtherDest = nullptr; 4437 if (!CasesA.empty() && CasesAreContiguous(CasesA)) { 4438 ContiguousCases = &CasesA; 4439 ContiguousDest = DestA; 4440 OtherDest = DestB; 4441 } else if (CasesAreContiguous(CasesB)) { 4442 ContiguousCases = &CasesB; 4443 ContiguousDest = DestB; 4444 OtherDest = DestA; 4445 } else 4446 return false; 4447 4448 // Start building the compare and branch. 4449 4450 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); 4451 Constant *NumCases = 4452 ConstantInt::get(Offset->getType(), ContiguousCases->size()); 4453 4454 Value *Sub = SI->getCondition(); 4455 if (!Offset->isNullValue()) 4456 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); 4457 4458 Value *Cmp; 4459 // If NumCases overflowed, then all possible values jump to the successor. 4460 if (NumCases->isNullValue() && !ContiguousCases->empty()) 4461 Cmp = ConstantInt::getTrue(SI->getContext()); 4462 else 4463 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 4464 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); 4465 4466 // Update weight for the newly-created conditional branch. 4467 if (HasBranchWeights(SI)) { 4468 SmallVector<uint64_t, 8> Weights; 4469 GetBranchWeights(SI, Weights); 4470 if (Weights.size() == 1 + SI->getNumCases()) { 4471 uint64_t TrueWeight = 0; 4472 uint64_t FalseWeight = 0; 4473 for (size_t I = 0, E = Weights.size(); I != E; ++I) { 4474 if (SI->getSuccessor(I) == ContiguousDest) 4475 TrueWeight += Weights[I]; 4476 else 4477 FalseWeight += Weights[I]; 4478 } 4479 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { 4480 TrueWeight /= 2; 4481 FalseWeight /= 2; 4482 } 4483 setBranchWeights(NewBI, TrueWeight, FalseWeight); 4484 } 4485 } 4486 4487 // Prune obsolete incoming values off the successors' PHI nodes. 4488 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { 4489 unsigned PreviousEdges = ContiguousCases->size(); 4490 if (ContiguousDest == SI->getDefaultDest()) 4491 ++PreviousEdges; 4492 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4493 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4494 } 4495 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { 4496 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); 4497 if (OtherDest == SI->getDefaultDest()) 4498 ++PreviousEdges; 4499 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4500 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4501 } 4502 4503 // Clean up the default block - it may have phis or other instructions before 4504 // the unreachable terminator. 4505 if (!HasDefault) 4506 createUnreachableSwitchDefault(SI); 4507 4508 // Drop the switch. 4509 SI->eraseFromParent(); 4510 4511 return true; 4512 } 4513 4514 /// Compute masked bits for the condition of a switch 4515 /// and use it to remove dead cases. 4516 static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, 4517 const DataLayout &DL) { 4518 Value *Cond = SI->getCondition(); 4519 unsigned Bits = Cond->getType()->getIntegerBitWidth(); 4520 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI); 4521 4522 // We can also eliminate cases by determining that their values are outside of 4523 // the limited range of the condition based on how many significant (non-sign) 4524 // bits are in the condition value. 4525 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1; 4526 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits; 4527 4528 // Gather dead cases. 4529 SmallVector<ConstantInt *, 8> DeadCases; 4530 for (auto &Case : SI->cases()) { 4531 const APInt &CaseVal = Case.getCaseValue()->getValue(); 4532 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) || 4533 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) { 4534 DeadCases.push_back(Case.getCaseValue()); 4535 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal 4536 << " is dead.\n"); 4537 } 4538 } 4539 4540 // If we can prove that the cases must cover all possible values, the 4541 // default destination becomes dead and we can remove it. If we know some 4542 // of the bits in the value, we can use that to more precisely compute the 4543 // number of possible unique case values. 4544 bool HasDefault = 4545 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4546 const unsigned NumUnknownBits = 4547 Bits - (Known.Zero | Known.One).countPopulation(); 4548 assert(NumUnknownBits <= Bits); 4549 if (HasDefault && DeadCases.empty() && 4550 NumUnknownBits < 64 /* avoid overflow */ && 4551 SI->getNumCases() == (1ULL << NumUnknownBits)) { 4552 createUnreachableSwitchDefault(SI); 4553 return true; 4554 } 4555 4556 if (DeadCases.empty()) 4557 return false; 4558 4559 SwitchInstProfUpdateWrapper SIW(*SI); 4560 for (ConstantInt *DeadCase : DeadCases) { 4561 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase); 4562 assert(CaseI != SI->case_default() && 4563 "Case was not found. Probably mistake in DeadCases forming."); 4564 // Prune unused values from PHI nodes. 4565 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent()); 4566 SIW.removeCase(CaseI); 4567 } 4568 4569 return true; 4570 } 4571 4572 /// If BB would be eligible for simplification by 4573 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 4574 /// by an unconditional branch), look at the phi node for BB in the successor 4575 /// block and see if the incoming value is equal to CaseValue. If so, return 4576 /// the phi node, and set PhiIndex to BB's index in the phi node. 4577 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 4578 BasicBlock *BB, int *PhiIndex) { 4579 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 4580 return nullptr; // BB must be empty to be a candidate for simplification. 4581 if (!BB->getSinglePredecessor()) 4582 return nullptr; // BB must be dominated by the switch. 4583 4584 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 4585 if (!Branch || !Branch->isUnconditional()) 4586 return nullptr; // Terminator must be unconditional branch. 4587 4588 BasicBlock *Succ = Branch->getSuccessor(0); 4589 4590 for (PHINode &PHI : Succ->phis()) { 4591 int Idx = PHI.getBasicBlockIndex(BB); 4592 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 4593 4594 Value *InValue = PHI.getIncomingValue(Idx); 4595 if (InValue != CaseValue) 4596 continue; 4597 4598 *PhiIndex = Idx; 4599 return &PHI; 4600 } 4601 4602 return nullptr; 4603 } 4604 4605 /// Try to forward the condition of a switch instruction to a phi node 4606 /// dominated by the switch, if that would mean that some of the destination 4607 /// blocks of the switch can be folded away. Return true if a change is made. 4608 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 4609 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>; 4610 4611 ForwardingNodesMap ForwardingNodes; 4612 BasicBlock *SwitchBlock = SI->getParent(); 4613 bool Changed = false; 4614 for (auto &Case : SI->cases()) { 4615 ConstantInt *CaseValue = Case.getCaseValue(); 4616 BasicBlock *CaseDest = Case.getCaseSuccessor(); 4617 4618 // Replace phi operands in successor blocks that are using the constant case 4619 // value rather than the switch condition variable: 4620 // switchbb: 4621 // switch i32 %x, label %default [ 4622 // i32 17, label %succ 4623 // ... 4624 // succ: 4625 // %r = phi i32 ... [ 17, %switchbb ] ... 4626 // --> 4627 // %r = phi i32 ... [ %x, %switchbb ] ... 4628 4629 for (PHINode &Phi : CaseDest->phis()) { 4630 // This only works if there is exactly 1 incoming edge from the switch to 4631 // a phi. If there is >1, that means multiple cases of the switch map to 1 4632 // value in the phi, and that phi value is not the switch condition. Thus, 4633 // this transform would not make sense (the phi would be invalid because 4634 // a phi can't have different incoming values from the same block). 4635 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock); 4636 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue && 4637 count(Phi.blocks(), SwitchBlock) == 1) { 4638 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition()); 4639 Changed = true; 4640 } 4641 } 4642 4643 // Collect phi nodes that are indirectly using this switch's case constants. 4644 int PhiIdx; 4645 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx)) 4646 ForwardingNodes[Phi].push_back(PhiIdx); 4647 } 4648 4649 for (auto &ForwardingNode : ForwardingNodes) { 4650 PHINode *Phi = ForwardingNode.first; 4651 SmallVectorImpl<int> &Indexes = ForwardingNode.second; 4652 if (Indexes.size() < 2) 4653 continue; 4654 4655 for (int Index : Indexes) 4656 Phi->setIncomingValue(Index, SI->getCondition()); 4657 Changed = true; 4658 } 4659 4660 return Changed; 4661 } 4662 4663 /// Return true if the backend will be able to handle 4664 /// initializing an array of constants like C. 4665 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) { 4666 if (C->isThreadDependent()) 4667 return false; 4668 if (C->isDLLImportDependent()) 4669 return false; 4670 4671 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) && 4672 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) && 4673 !isa<UndefValue>(C) && !isa<ConstantExpr>(C)) 4674 return false; 4675 4676 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 4677 if (!CE->isGEPWithNoNotionalOverIndexing()) 4678 return false; 4679 if (!ValidLookupTableConstant(CE->getOperand(0), TTI)) 4680 return false; 4681 } 4682 4683 if (!TTI.shouldBuildLookupTablesForConstant(C)) 4684 return false; 4685 4686 return true; 4687 } 4688 4689 /// If V is a Constant, return it. Otherwise, try to look up 4690 /// its constant value in ConstantPool, returning 0 if it's not there. 4691 static Constant * 4692 LookupConstant(Value *V, 4693 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 4694 if (Constant *C = dyn_cast<Constant>(V)) 4695 return C; 4696 return ConstantPool.lookup(V); 4697 } 4698 4699 /// Try to fold instruction I into a constant. This works for 4700 /// simple instructions such as binary operations where both operands are 4701 /// constant or can be replaced by constants from the ConstantPool. Returns the 4702 /// resulting constant on success, 0 otherwise. 4703 static Constant * 4704 ConstantFold(Instruction *I, const DataLayout &DL, 4705 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 4706 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 4707 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 4708 if (!A) 4709 return nullptr; 4710 if (A->isAllOnesValue()) 4711 return LookupConstant(Select->getTrueValue(), ConstantPool); 4712 if (A->isNullValue()) 4713 return LookupConstant(Select->getFalseValue(), ConstantPool); 4714 return nullptr; 4715 } 4716 4717 SmallVector<Constant *, 4> COps; 4718 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { 4719 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) 4720 COps.push_back(A); 4721 else 4722 return nullptr; 4723 } 4724 4725 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 4726 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], 4727 COps[1], DL); 4728 } 4729 4730 return ConstantFoldInstOperands(I, COps, DL); 4731 } 4732 4733 /// Try to determine the resulting constant values in phi nodes 4734 /// at the common destination basic block, *CommonDest, for one of the case 4735 /// destionations CaseDest corresponding to value CaseVal (0 for the default 4736 /// case), of a switch instruction SI. 4737 static bool 4738 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, 4739 BasicBlock **CommonDest, 4740 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, 4741 const DataLayout &DL, const TargetTransformInfo &TTI) { 4742 // The block from which we enter the common destination. 4743 BasicBlock *Pred = SI->getParent(); 4744 4745 // If CaseDest is empty except for some side-effect free instructions through 4746 // which we can constant-propagate the CaseVal, continue to its successor. 4747 SmallDenseMap<Value *, Constant *> ConstantPool; 4748 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 4749 for (Instruction &I :CaseDest->instructionsWithoutDebug()) { 4750 if (I.isTerminator()) { 4751 // If the terminator is a simple branch, continue to the next block. 4752 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator()) 4753 return false; 4754 Pred = CaseDest; 4755 CaseDest = I.getSuccessor(0); 4756 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) { 4757 // Instruction is side-effect free and constant. 4758 4759 // If the instruction has uses outside this block or a phi node slot for 4760 // the block, it is not safe to bypass the instruction since it would then 4761 // no longer dominate all its uses. 4762 for (auto &Use : I.uses()) { 4763 User *User = Use.getUser(); 4764 if (Instruction *I = dyn_cast<Instruction>(User)) 4765 if (I->getParent() == CaseDest) 4766 continue; 4767 if (PHINode *Phi = dyn_cast<PHINode>(User)) 4768 if (Phi->getIncomingBlock(Use) == CaseDest) 4769 continue; 4770 return false; 4771 } 4772 4773 ConstantPool.insert(std::make_pair(&I, C)); 4774 } else { 4775 break; 4776 } 4777 } 4778 4779 // If we did not have a CommonDest before, use the current one. 4780 if (!*CommonDest) 4781 *CommonDest = CaseDest; 4782 // If the destination isn't the common one, abort. 4783 if (CaseDest != *CommonDest) 4784 return false; 4785 4786 // Get the values for this case from phi nodes in the destination block. 4787 for (PHINode &PHI : (*CommonDest)->phis()) { 4788 int Idx = PHI.getBasicBlockIndex(Pred); 4789 if (Idx == -1) 4790 continue; 4791 4792 Constant *ConstVal = 4793 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool); 4794 if (!ConstVal) 4795 return false; 4796 4797 // Be conservative about which kinds of constants we support. 4798 if (!ValidLookupTableConstant(ConstVal, TTI)) 4799 return false; 4800 4801 Res.push_back(std::make_pair(&PHI, ConstVal)); 4802 } 4803 4804 return Res.size() > 0; 4805 } 4806 4807 // Helper function used to add CaseVal to the list of cases that generate 4808 // Result. Returns the updated number of cases that generate this result. 4809 static uintptr_t MapCaseToResult(ConstantInt *CaseVal, 4810 SwitchCaseResultVectorTy &UniqueResults, 4811 Constant *Result) { 4812 for (auto &I : UniqueResults) { 4813 if (I.first == Result) { 4814 I.second.push_back(CaseVal); 4815 return I.second.size(); 4816 } 4817 } 4818 UniqueResults.push_back( 4819 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal))); 4820 return 1; 4821 } 4822 4823 // Helper function that initializes a map containing 4824 // results for the PHI node of the common destination block for a switch 4825 // instruction. Returns false if multiple PHI nodes have been found or if 4826 // there is not a common destination block for the switch. 4827 static bool 4828 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, 4829 SwitchCaseResultVectorTy &UniqueResults, 4830 Constant *&DefaultResult, const DataLayout &DL, 4831 const TargetTransformInfo &TTI, 4832 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) { 4833 for (auto &I : SI->cases()) { 4834 ConstantInt *CaseVal = I.getCaseValue(); 4835 4836 // Resulting value at phi nodes for this case value. 4837 SwitchCaseResultsTy Results; 4838 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, 4839 DL, TTI)) 4840 return false; 4841 4842 // Only one value per case is permitted. 4843 if (Results.size() > 1) 4844 return false; 4845 4846 // Add the case->result mapping to UniqueResults. 4847 const uintptr_t NumCasesForResult = 4848 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); 4849 4850 // Early out if there are too many cases for this result. 4851 if (NumCasesForResult > MaxCasesPerResult) 4852 return false; 4853 4854 // Early out if there are too many unique results. 4855 if (UniqueResults.size() > MaxUniqueResults) 4856 return false; 4857 4858 // Check the PHI consistency. 4859 if (!PHI) 4860 PHI = Results[0].first; 4861 else if (PHI != Results[0].first) 4862 return false; 4863 } 4864 // Find the default result value. 4865 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; 4866 BasicBlock *DefaultDest = SI->getDefaultDest(); 4867 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, 4868 DL, TTI); 4869 // If the default value is not found abort unless the default destination 4870 // is unreachable. 4871 DefaultResult = 4872 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; 4873 if ((!DefaultResult && 4874 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) 4875 return false; 4876 4877 return true; 4878 } 4879 4880 // Helper function that checks if it is possible to transform a switch with only 4881 // two cases (or two cases + default) that produces a result into a select. 4882 // Example: 4883 // switch (a) { 4884 // case 10: %0 = icmp eq i32 %a, 10 4885 // return 10; %1 = select i1 %0, i32 10, i32 4 4886 // case 20: ----> %2 = icmp eq i32 %a, 20 4887 // return 2; %3 = select i1 %2, i32 2, i32 %1 4888 // default: 4889 // return 4; 4890 // } 4891 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, 4892 Constant *DefaultResult, Value *Condition, 4893 IRBuilder<> &Builder) { 4894 assert(ResultVector.size() == 2 && 4895 "We should have exactly two unique results at this point"); 4896 // If we are selecting between only two cases transform into a simple 4897 // select or a two-way select if default is possible. 4898 if (ResultVector[0].second.size() == 1 && 4899 ResultVector[1].second.size() == 1) { 4900 ConstantInt *const FirstCase = ResultVector[0].second[0]; 4901 ConstantInt *const SecondCase = ResultVector[1].second[0]; 4902 4903 bool DefaultCanTrigger = DefaultResult; 4904 Value *SelectValue = ResultVector[1].first; 4905 if (DefaultCanTrigger) { 4906 Value *const ValueCompare = 4907 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); 4908 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, 4909 DefaultResult, "switch.select"); 4910 } 4911 Value *const ValueCompare = 4912 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); 4913 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, 4914 SelectValue, "switch.select"); 4915 } 4916 4917 return nullptr; 4918 } 4919 4920 // Helper function to cleanup a switch instruction that has been converted into 4921 // a select, fixing up PHI nodes and basic blocks. 4922 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, 4923 Value *SelectValue, 4924 IRBuilder<> &Builder) { 4925 BasicBlock *SelectBB = SI->getParent(); 4926 while (PHI->getBasicBlockIndex(SelectBB) >= 0) 4927 PHI->removeIncomingValue(SelectBB); 4928 PHI->addIncoming(SelectValue, SelectBB); 4929 4930 Builder.CreateBr(PHI->getParent()); 4931 4932 // Remove the switch. 4933 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 4934 BasicBlock *Succ = SI->getSuccessor(i); 4935 4936 if (Succ == PHI->getParent()) 4937 continue; 4938 Succ->removePredecessor(SelectBB); 4939 } 4940 SI->eraseFromParent(); 4941 } 4942 4943 /// If the switch is only used to initialize one or more 4944 /// phi nodes in a common successor block with only two different 4945 /// constant values, replace the switch with select. 4946 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder, 4947 const DataLayout &DL, 4948 const TargetTransformInfo &TTI) { 4949 Value *const Cond = SI->getCondition(); 4950 PHINode *PHI = nullptr; 4951 BasicBlock *CommonDest = nullptr; 4952 Constant *DefaultResult; 4953 SwitchCaseResultVectorTy UniqueResults; 4954 // Collect all the cases that will deliver the same value from the switch. 4955 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, 4956 DL, TTI, 2, 1)) 4957 return false; 4958 // Selects choose between maximum two values. 4959 if (UniqueResults.size() != 2) 4960 return false; 4961 assert(PHI != nullptr && "PHI for value select not found"); 4962 4963 Builder.SetInsertPoint(SI); 4964 Value *SelectValue = 4965 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder); 4966 if (SelectValue) { 4967 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder); 4968 return true; 4969 } 4970 // The switch couldn't be converted into a select. 4971 return false; 4972 } 4973 4974 namespace { 4975 4976 /// This class represents a lookup table that can be used to replace a switch. 4977 class SwitchLookupTable { 4978 public: 4979 /// Create a lookup table to use as a switch replacement with the contents 4980 /// of Values, using DefaultValue to fill any holes in the table. 4981 SwitchLookupTable( 4982 Module &M, uint64_t TableSize, ConstantInt *Offset, 4983 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 4984 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName); 4985 4986 /// Build instructions with Builder to retrieve the value at 4987 /// the position given by Index in the lookup table. 4988 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 4989 4990 /// Return true if a table with TableSize elements of 4991 /// type ElementType would fit in a target-legal register. 4992 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, 4993 Type *ElementType); 4994 4995 private: 4996 // Depending on the contents of the table, it can be represented in 4997 // different ways. 4998 enum { 4999 // For tables where each element contains the same value, we just have to 5000 // store that single value and return it for each lookup. 5001 SingleValueKind, 5002 5003 // For tables where there is a linear relationship between table index 5004 // and values. We calculate the result with a simple multiplication 5005 // and addition instead of a table lookup. 5006 LinearMapKind, 5007 5008 // For small tables with integer elements, we can pack them into a bitmap 5009 // that fits into a target-legal register. Values are retrieved by 5010 // shift and mask operations. 5011 BitMapKind, 5012 5013 // The table is stored as an array of values. Values are retrieved by load 5014 // instructions from the table. 5015 ArrayKind 5016 } Kind; 5017 5018 // For SingleValueKind, this is the single value. 5019 Constant *SingleValue = nullptr; 5020 5021 // For BitMapKind, this is the bitmap. 5022 ConstantInt *BitMap = nullptr; 5023 IntegerType *BitMapElementTy = nullptr; 5024 5025 // For LinearMapKind, these are the constants used to derive the value. 5026 ConstantInt *LinearOffset = nullptr; 5027 ConstantInt *LinearMultiplier = nullptr; 5028 5029 // For ArrayKind, this is the array. 5030 GlobalVariable *Array = nullptr; 5031 }; 5032 5033 } // end anonymous namespace 5034 5035 SwitchLookupTable::SwitchLookupTable( 5036 Module &M, uint64_t TableSize, ConstantInt *Offset, 5037 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5038 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) { 5039 assert(Values.size() && "Can't build lookup table without values!"); 5040 assert(TableSize >= Values.size() && "Can't fit values in table!"); 5041 5042 // If all values in the table are equal, this is that value. 5043 SingleValue = Values.begin()->second; 5044 5045 Type *ValueType = Values.begin()->second->getType(); 5046 5047 // Build up the table contents. 5048 SmallVector<Constant *, 64> TableContents(TableSize); 5049 for (size_t I = 0, E = Values.size(); I != E; ++I) { 5050 ConstantInt *CaseVal = Values[I].first; 5051 Constant *CaseRes = Values[I].second; 5052 assert(CaseRes->getType() == ValueType); 5053 5054 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue(); 5055 TableContents[Idx] = CaseRes; 5056 5057 if (CaseRes != SingleValue) 5058 SingleValue = nullptr; 5059 } 5060 5061 // Fill in any holes in the table with the default result. 5062 if (Values.size() < TableSize) { 5063 assert(DefaultValue && 5064 "Need a default value to fill the lookup table holes."); 5065 assert(DefaultValue->getType() == ValueType); 5066 for (uint64_t I = 0; I < TableSize; ++I) { 5067 if (!TableContents[I]) 5068 TableContents[I] = DefaultValue; 5069 } 5070 5071 if (DefaultValue != SingleValue) 5072 SingleValue = nullptr; 5073 } 5074 5075 // If each element in the table contains the same value, we only need to store 5076 // that single value. 5077 if (SingleValue) { 5078 Kind = SingleValueKind; 5079 return; 5080 } 5081 5082 // Check if we can derive the value with a linear transformation from the 5083 // table index. 5084 if (isa<IntegerType>(ValueType)) { 5085 bool LinearMappingPossible = true; 5086 APInt PrevVal; 5087 APInt DistToPrev; 5088 assert(TableSize >= 2 && "Should be a SingleValue table."); 5089 // Check if there is the same distance between two consecutive values. 5090 for (uint64_t I = 0; I < TableSize; ++I) { 5091 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); 5092 if (!ConstVal) { 5093 // This is an undef. We could deal with it, but undefs in lookup tables 5094 // are very seldom. It's probably not worth the additional complexity. 5095 LinearMappingPossible = false; 5096 break; 5097 } 5098 const APInt &Val = ConstVal->getValue(); 5099 if (I != 0) { 5100 APInt Dist = Val - PrevVal; 5101 if (I == 1) { 5102 DistToPrev = Dist; 5103 } else if (Dist != DistToPrev) { 5104 LinearMappingPossible = false; 5105 break; 5106 } 5107 } 5108 PrevVal = Val; 5109 } 5110 if (LinearMappingPossible) { 5111 LinearOffset = cast<ConstantInt>(TableContents[0]); 5112 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); 5113 Kind = LinearMapKind; 5114 ++NumLinearMaps; 5115 return; 5116 } 5117 } 5118 5119 // If the type is integer and the table fits in a register, build a bitmap. 5120 if (WouldFitInRegister(DL, TableSize, ValueType)) { 5121 IntegerType *IT = cast<IntegerType>(ValueType); 5122 APInt TableInt(TableSize * IT->getBitWidth(), 0); 5123 for (uint64_t I = TableSize; I > 0; --I) { 5124 TableInt <<= IT->getBitWidth(); 5125 // Insert values into the bitmap. Undef values are set to zero. 5126 if (!isa<UndefValue>(TableContents[I - 1])) { 5127 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 5128 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 5129 } 5130 } 5131 BitMap = ConstantInt::get(M.getContext(), TableInt); 5132 BitMapElementTy = IT; 5133 Kind = BitMapKind; 5134 ++NumBitMaps; 5135 return; 5136 } 5137 5138 // Store the table in an array. 5139 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); 5140 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 5141 5142 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true, 5143 GlobalVariable::PrivateLinkage, Initializer, 5144 "switch.table." + FuncName); 5145 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 5146 // Set the alignment to that of an array items. We will be only loading one 5147 // value out of it. 5148 Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType))); 5149 Kind = ArrayKind; 5150 } 5151 5152 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 5153 switch (Kind) { 5154 case SingleValueKind: 5155 return SingleValue; 5156 case LinearMapKind: { 5157 // Derive the result value from the input value. 5158 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), 5159 false, "switch.idx.cast"); 5160 if (!LinearMultiplier->isOne()) 5161 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); 5162 if (!LinearOffset->isZero()) 5163 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); 5164 return Result; 5165 } 5166 case BitMapKind: { 5167 // Type of the bitmap (e.g. i59). 5168 IntegerType *MapTy = BitMap->getType(); 5169 5170 // Cast Index to the same type as the bitmap. 5171 // Note: The Index is <= the number of elements in the table, so 5172 // truncating it to the width of the bitmask is safe. 5173 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 5174 5175 // Multiply the shift amount by the element width. 5176 ShiftAmt = Builder.CreateMul( 5177 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 5178 "switch.shiftamt"); 5179 5180 // Shift down. 5181 Value *DownShifted = 5182 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift"); 5183 // Mask off. 5184 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked"); 5185 } 5186 case ArrayKind: { 5187 // Make sure the table index will not overflow when treated as signed. 5188 IntegerType *IT = cast<IntegerType>(Index->getType()); 5189 uint64_t TableSize = 5190 Array->getInitializer()->getType()->getArrayNumElements(); 5191 if (TableSize > (1ULL << (IT->getBitWidth() - 1))) 5192 Index = Builder.CreateZExt( 5193 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1), 5194 "switch.tableidx.zext"); 5195 5196 Value *GEPIndices[] = {Builder.getInt32(0), Index}; 5197 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, 5198 GEPIndices, "switch.gep"); 5199 return Builder.CreateLoad( 5200 cast<ArrayType>(Array->getValueType())->getElementType(), GEP, 5201 "switch.load"); 5202 } 5203 } 5204 llvm_unreachable("Unknown lookup table kind!"); 5205 } 5206 5207 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, 5208 uint64_t TableSize, 5209 Type *ElementType) { 5210 auto *IT = dyn_cast<IntegerType>(ElementType); 5211 if (!IT) 5212 return false; 5213 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 5214 // are <= 15, we could try to narrow the type. 5215 5216 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 5217 if (TableSize >= UINT_MAX / IT->getBitWidth()) 5218 return false; 5219 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); 5220 } 5221 5222 /// Determine whether a lookup table should be built for this switch, based on 5223 /// the number of cases, size of the table, and the types of the results. 5224 static bool 5225 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, 5226 const TargetTransformInfo &TTI, const DataLayout &DL, 5227 const SmallDenseMap<PHINode *, Type *> &ResultTypes) { 5228 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) 5229 return false; // TableSize overflowed, or mul below might overflow. 5230 5231 bool AllTablesFitInRegister = true; 5232 bool HasIllegalType = false; 5233 for (const auto &I : ResultTypes) { 5234 Type *Ty = I.second; 5235 5236 // Saturate this flag to true. 5237 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); 5238 5239 // Saturate this flag to false. 5240 AllTablesFitInRegister = 5241 AllTablesFitInRegister && 5242 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); 5243 5244 // If both flags saturate, we're done. NOTE: This *only* works with 5245 // saturating flags, and all flags have to saturate first due to the 5246 // non-deterministic behavior of iterating over a dense map. 5247 if (HasIllegalType && !AllTablesFitInRegister) 5248 break; 5249 } 5250 5251 // If each table would fit in a register, we should build it anyway. 5252 if (AllTablesFitInRegister) 5253 return true; 5254 5255 // Don't build a table that doesn't fit in-register if it has illegal types. 5256 if (HasIllegalType) 5257 return false; 5258 5259 // The table density should be at least 40%. This is the same criterion as for 5260 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. 5261 // FIXME: Find the best cut-off. 5262 return SI->getNumCases() * 10 >= TableSize * 4; 5263 } 5264 5265 /// Try to reuse the switch table index compare. Following pattern: 5266 /// \code 5267 /// if (idx < tablesize) 5268 /// r = table[idx]; // table does not contain default_value 5269 /// else 5270 /// r = default_value; 5271 /// if (r != default_value) 5272 /// ... 5273 /// \endcode 5274 /// Is optimized to: 5275 /// \code 5276 /// cond = idx < tablesize; 5277 /// if (cond) 5278 /// r = table[idx]; 5279 /// else 5280 /// r = default_value; 5281 /// if (cond) 5282 /// ... 5283 /// \endcode 5284 /// Jump threading will then eliminate the second if(cond). 5285 static void reuseTableCompare( 5286 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, 5287 Constant *DefaultValue, 5288 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) { 5289 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); 5290 if (!CmpInst) 5291 return; 5292 5293 // We require that the compare is in the same block as the phi so that jump 5294 // threading can do its work afterwards. 5295 if (CmpInst->getParent() != PhiBlock) 5296 return; 5297 5298 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); 5299 if (!CmpOp1) 5300 return; 5301 5302 Value *RangeCmp = RangeCheckBranch->getCondition(); 5303 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); 5304 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); 5305 5306 // Check if the compare with the default value is constant true or false. 5307 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5308 DefaultValue, CmpOp1, true); 5309 if (DefaultConst != TrueConst && DefaultConst != FalseConst) 5310 return; 5311 5312 // Check if the compare with the case values is distinct from the default 5313 // compare result. 5314 for (auto ValuePair : Values) { 5315 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5316 ValuePair.second, CmpOp1, true); 5317 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst)) 5318 return; 5319 assert((CaseConst == TrueConst || CaseConst == FalseConst) && 5320 "Expect true or false as compare result."); 5321 } 5322 5323 // Check if the branch instruction dominates the phi node. It's a simple 5324 // dominance check, but sufficient for our needs. 5325 // Although this check is invariant in the calling loops, it's better to do it 5326 // at this late stage. Practically we do it at most once for a switch. 5327 BasicBlock *BranchBlock = RangeCheckBranch->getParent(); 5328 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) { 5329 BasicBlock *Pred = *PI; 5330 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) 5331 return; 5332 } 5333 5334 if (DefaultConst == FalseConst) { 5335 // The compare yields the same result. We can replace it. 5336 CmpInst->replaceAllUsesWith(RangeCmp); 5337 ++NumTableCmpReuses; 5338 } else { 5339 // The compare yields the same result, just inverted. We can replace it. 5340 Value *InvertedTableCmp = BinaryOperator::CreateXor( 5341 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", 5342 RangeCheckBranch); 5343 CmpInst->replaceAllUsesWith(InvertedTableCmp); 5344 ++NumTableCmpReuses; 5345 } 5346 } 5347 5348 /// If the switch is only used to initialize one or more phi nodes in a common 5349 /// successor block with different constant values, replace the switch with 5350 /// lookup tables. 5351 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, 5352 const DataLayout &DL, 5353 const TargetTransformInfo &TTI) { 5354 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 5355 5356 Function *Fn = SI->getParent()->getParent(); 5357 // Only build lookup table when we have a target that supports it or the 5358 // attribute is not set. 5359 if (!TTI.shouldBuildLookupTables() || 5360 (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")) 5361 return false; 5362 5363 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 5364 // split off a dense part and build a lookup table for that. 5365 5366 // FIXME: This creates arrays of GEPs to constant strings, which means each 5367 // GEP needs a runtime relocation in PIC code. We should just build one big 5368 // string and lookup indices into that. 5369 5370 // Ignore switches with less than three cases. Lookup tables will not make 5371 // them faster, so we don't analyze them. 5372 if (SI->getNumCases() < 3) 5373 return false; 5374 5375 // Figure out the corresponding result for each case value and phi node in the 5376 // common destination, as well as the min and max case values. 5377 assert(!SI->cases().empty()); 5378 SwitchInst::CaseIt CI = SI->case_begin(); 5379 ConstantInt *MinCaseVal = CI->getCaseValue(); 5380 ConstantInt *MaxCaseVal = CI->getCaseValue(); 5381 5382 BasicBlock *CommonDest = nullptr; 5383 5384 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>; 5385 SmallDenseMap<PHINode *, ResultListTy> ResultLists; 5386 5387 SmallDenseMap<PHINode *, Constant *> DefaultResults; 5388 SmallDenseMap<PHINode *, Type *> ResultTypes; 5389 SmallVector<PHINode *, 4> PHIs; 5390 5391 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 5392 ConstantInt *CaseVal = CI->getCaseValue(); 5393 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 5394 MinCaseVal = CaseVal; 5395 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 5396 MaxCaseVal = CaseVal; 5397 5398 // Resulting value at phi nodes for this case value. 5399 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; 5400 ResultsTy Results; 5401 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest, 5402 Results, DL, TTI)) 5403 return false; 5404 5405 // Append the result from this case to the list for each phi. 5406 for (const auto &I : Results) { 5407 PHINode *PHI = I.first; 5408 Constant *Value = I.second; 5409 if (!ResultLists.count(PHI)) 5410 PHIs.push_back(PHI); 5411 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); 5412 } 5413 } 5414 5415 // Keep track of the result types. 5416 for (PHINode *PHI : PHIs) { 5417 ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); 5418 } 5419 5420 uint64_t NumResults = ResultLists[PHIs[0]].size(); 5421 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); 5422 uint64_t TableSize = RangeSpread.getLimitedValue() + 1; 5423 bool TableHasHoles = (NumResults < TableSize); 5424 5425 // If the table has holes, we need a constant result for the default case 5426 // or a bitmask that fits in a register. 5427 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList; 5428 bool HasDefaultResults = 5429 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, 5430 DefaultResultsList, DL, TTI); 5431 5432 bool NeedMask = (TableHasHoles && !HasDefaultResults); 5433 if (NeedMask) { 5434 // As an extra penalty for the validity test we require more cases. 5435 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). 5436 return false; 5437 if (!DL.fitsInLegalInteger(TableSize)) 5438 return false; 5439 } 5440 5441 for (const auto &I : DefaultResultsList) { 5442 PHINode *PHI = I.first; 5443 Constant *Result = I.second; 5444 DefaultResults[PHI] = Result; 5445 } 5446 5447 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) 5448 return false; 5449 5450 // Create the BB that does the lookups. 5451 Module &Mod = *CommonDest->getParent()->getParent(); 5452 BasicBlock *LookupBB = BasicBlock::Create( 5453 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest); 5454 5455 // Compute the table index value. 5456 Builder.SetInsertPoint(SI); 5457 Value *TableIndex; 5458 if (MinCaseVal->isNullValue()) 5459 TableIndex = SI->getCondition(); 5460 else 5461 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, 5462 "switch.tableidx"); 5463 5464 // Compute the maximum table size representable by the integer type we are 5465 // switching upon. 5466 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); 5467 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; 5468 assert(MaxTableSize >= TableSize && 5469 "It is impossible for a switch to have more entries than the max " 5470 "representable value of its input integer type's size."); 5471 5472 // If the default destination is unreachable, or if the lookup table covers 5473 // all values of the conditional variable, branch directly to the lookup table 5474 // BB. Otherwise, check that the condition is within the case range. 5475 const bool DefaultIsReachable = 5476 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 5477 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); 5478 BranchInst *RangeCheckBranch = nullptr; 5479 5480 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5481 Builder.CreateBr(LookupBB); 5482 // Note: We call removeProdecessor later since we need to be able to get the 5483 // PHI value for the default case in case we're using a bit mask. 5484 } else { 5485 Value *Cmp = Builder.CreateICmpULT( 5486 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize)); 5487 RangeCheckBranch = 5488 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 5489 } 5490 5491 // Populate the BB that does the lookups. 5492 Builder.SetInsertPoint(LookupBB); 5493 5494 if (NeedMask) { 5495 // Before doing the lookup, we do the hole check. The LookupBB is therefore 5496 // re-purposed to do the hole check, and we create a new LookupBB. 5497 BasicBlock *MaskBB = LookupBB; 5498 MaskBB->setName("switch.hole_check"); 5499 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup", 5500 CommonDest->getParent(), CommonDest); 5501 5502 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid 5503 // unnecessary illegal types. 5504 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); 5505 APInt MaskInt(TableSizePowOf2, 0); 5506 APInt One(TableSizePowOf2, 1); 5507 // Build bitmask; fill in a 1 bit for every case. 5508 const ResultListTy &ResultList = ResultLists[PHIs[0]]; 5509 for (size_t I = 0, E = ResultList.size(); I != E; ++I) { 5510 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue()) 5511 .getLimitedValue(); 5512 MaskInt |= One << Idx; 5513 } 5514 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); 5515 5516 // Get the TableIndex'th bit of the bitmask. 5517 // If this bit is 0 (meaning hole) jump to the default destination, 5518 // else continue with table lookup. 5519 IntegerType *MapTy = TableMask->getType(); 5520 Value *MaskIndex = 5521 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex"); 5522 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted"); 5523 Value *LoBit = Builder.CreateTrunc( 5524 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit"); 5525 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); 5526 5527 Builder.SetInsertPoint(LookupBB); 5528 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); 5529 } 5530 5531 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5532 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later, 5533 // do not delete PHINodes here. 5534 SI->getDefaultDest()->removePredecessor(SI->getParent(), 5535 /*KeepOneInputPHIs=*/true); 5536 } 5537 5538 bool ReturnedEarly = false; 5539 for (PHINode *PHI : PHIs) { 5540 const ResultListTy &ResultList = ResultLists[PHI]; 5541 5542 // If using a bitmask, use any value to fill the lookup table holes. 5543 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; 5544 StringRef FuncName = Fn->getName(); 5545 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL, 5546 FuncName); 5547 5548 Value *Result = Table.BuildLookup(TableIndex, Builder); 5549 5550 // If the result is used to return immediately from the function, we want to 5551 // do that right here. 5552 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && 5553 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { 5554 Builder.CreateRet(Result); 5555 ReturnedEarly = true; 5556 break; 5557 } 5558 5559 // Do a small peephole optimization: re-use the switch table compare if 5560 // possible. 5561 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { 5562 BasicBlock *PhiBlock = PHI->getParent(); 5563 // Search for compare instructions which use the phi. 5564 for (auto *User : PHI->users()) { 5565 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); 5566 } 5567 } 5568 5569 PHI->addIncoming(Result, LookupBB); 5570 } 5571 5572 if (!ReturnedEarly) 5573 Builder.CreateBr(CommonDest); 5574 5575 // Remove the switch. 5576 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5577 BasicBlock *Succ = SI->getSuccessor(i); 5578 5579 if (Succ == SI->getDefaultDest()) 5580 continue; 5581 Succ->removePredecessor(SI->getParent()); 5582 } 5583 SI->eraseFromParent(); 5584 5585 ++NumLookupTables; 5586 if (NeedMask) 5587 ++NumLookupTablesHoles; 5588 return true; 5589 } 5590 5591 static bool isSwitchDense(ArrayRef<int64_t> Values) { 5592 // See also SelectionDAGBuilder::isDense(), which this function was based on. 5593 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front(); 5594 uint64_t Range = Diff + 1; 5595 uint64_t NumCases = Values.size(); 5596 // 40% is the default density for building a jump table in optsize/minsize mode. 5597 uint64_t MinDensity = 40; 5598 5599 return NumCases * 100 >= Range * MinDensity; 5600 } 5601 5602 /// Try to transform a switch that has "holes" in it to a contiguous sequence 5603 /// of cases. 5604 /// 5605 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be 5606 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}. 5607 /// 5608 /// This converts a sparse switch into a dense switch which allows better 5609 /// lowering and could also allow transforming into a lookup table. 5610 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, 5611 const DataLayout &DL, 5612 const TargetTransformInfo &TTI) { 5613 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType()); 5614 if (CondTy->getIntegerBitWidth() > 64 || 5615 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth())) 5616 return false; 5617 // Only bother with this optimization if there are more than 3 switch cases; 5618 // SDAG will only bother creating jump tables for 4 or more cases. 5619 if (SI->getNumCases() < 4) 5620 return false; 5621 5622 // This transform is agnostic to the signedness of the input or case values. We 5623 // can treat the case values as signed or unsigned. We can optimize more common 5624 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values 5625 // as signed. 5626 SmallVector<int64_t,4> Values; 5627 for (auto &C : SI->cases()) 5628 Values.push_back(C.getCaseValue()->getValue().getSExtValue()); 5629 llvm::sort(Values); 5630 5631 // If the switch is already dense, there's nothing useful to do here. 5632 if (isSwitchDense(Values)) 5633 return false; 5634 5635 // First, transform the values such that they start at zero and ascend. 5636 int64_t Base = Values[0]; 5637 for (auto &V : Values) 5638 V -= (uint64_t)(Base); 5639 5640 // Now we have signed numbers that have been shifted so that, given enough 5641 // precision, there are no negative values. Since the rest of the transform 5642 // is bitwise only, we switch now to an unsigned representation. 5643 5644 // This transform can be done speculatively because it is so cheap - it 5645 // results in a single rotate operation being inserted. 5646 // FIXME: It's possible that optimizing a switch on powers of two might also 5647 // be beneficial - flag values are often powers of two and we could use a CLZ 5648 // as the key function. 5649 5650 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than 5651 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be 5652 // less than 64. 5653 unsigned Shift = 64; 5654 for (auto &V : Values) 5655 Shift = std::min(Shift, countTrailingZeros((uint64_t)V)); 5656 assert(Shift < 64); 5657 if (Shift > 0) 5658 for (auto &V : Values) 5659 V = (int64_t)((uint64_t)V >> Shift); 5660 5661 if (!isSwitchDense(Values)) 5662 // Transform didn't create a dense switch. 5663 return false; 5664 5665 // The obvious transform is to shift the switch condition right and emit a 5666 // check that the condition actually cleanly divided by GCD, i.e. 5667 // C & (1 << Shift - 1) == 0 5668 // inserting a new CFG edge to handle the case where it didn't divide cleanly. 5669 // 5670 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the 5671 // shift and puts the shifted-off bits in the uppermost bits. If any of these 5672 // are nonzero then the switch condition will be very large and will hit the 5673 // default case. 5674 5675 auto *Ty = cast<IntegerType>(SI->getCondition()->getType()); 5676 Builder.SetInsertPoint(SI); 5677 auto *ShiftC = ConstantInt::get(Ty, Shift); 5678 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base)); 5679 auto *LShr = Builder.CreateLShr(Sub, ShiftC); 5680 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift); 5681 auto *Rot = Builder.CreateOr(LShr, Shl); 5682 SI->replaceUsesOfWith(SI->getCondition(), Rot); 5683 5684 for (auto Case : SI->cases()) { 5685 auto *Orig = Case.getCaseValue(); 5686 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base); 5687 Case.setValue( 5688 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue())))); 5689 } 5690 return true; 5691 } 5692 5693 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 5694 BasicBlock *BB = SI->getParent(); 5695 5696 if (isValueEqualityComparison(SI)) { 5697 // If we only have one predecessor, and if it is a branch on this value, 5698 // see if that predecessor totally determines the outcome of this switch. 5699 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 5700 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 5701 return requestResimplify(); 5702 5703 Value *Cond = SI->getCondition(); 5704 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 5705 if (SimplifySwitchOnSelect(SI, Select)) 5706 return requestResimplify(); 5707 5708 // If the block only contains the switch, see if we can fold the block 5709 // away into any preds. 5710 if (SI == &*BB->instructionsWithoutDebug().begin()) 5711 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 5712 return requestResimplify(); 5713 } 5714 5715 // Try to transform the switch into an icmp and a branch. 5716 if (TurnSwitchRangeIntoICmp(SI, Builder)) 5717 return requestResimplify(); 5718 5719 // Remove unreachable cases. 5720 if (eliminateDeadSwitchCases(SI, Options.AC, DL)) 5721 return requestResimplify(); 5722 5723 if (switchToSelect(SI, Builder, DL, TTI)) 5724 return requestResimplify(); 5725 5726 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI)) 5727 return requestResimplify(); 5728 5729 // The conversion from switch to lookup tables results in difficult-to-analyze 5730 // code and makes pruning branches much harder. This is a problem if the 5731 // switch expression itself can still be restricted as a result of inlining or 5732 // CVP. Therefore, only apply this transformation during late stages of the 5733 // optimisation pipeline. 5734 if (Options.ConvertSwitchToLookupTable && 5735 SwitchToLookupTable(SI, Builder, DL, TTI)) 5736 return requestResimplify(); 5737 5738 if (ReduceSwitchRange(SI, Builder, DL, TTI)) 5739 return requestResimplify(); 5740 5741 return false; 5742 } 5743 5744 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) { 5745 BasicBlock *BB = IBI->getParent(); 5746 bool Changed = false; 5747 5748 // Eliminate redundant destinations. 5749 SmallPtrSet<Value *, 8> Succs; 5750 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 5751 BasicBlock *Dest = IBI->getDestination(i); 5752 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { 5753 Dest->removePredecessor(BB); 5754 IBI->removeDestination(i); 5755 --i; 5756 --e; 5757 Changed = true; 5758 } 5759 } 5760 5761 if (IBI->getNumDestinations() == 0) { 5762 // If the indirectbr has no successors, change it to unreachable. 5763 new UnreachableInst(IBI->getContext(), IBI); 5764 EraseTerminatorAndDCECond(IBI); 5765 return true; 5766 } 5767 5768 if (IBI->getNumDestinations() == 1) { 5769 // If the indirectbr has one successor, change it to a direct branch. 5770 BranchInst::Create(IBI->getDestination(0), IBI); 5771 EraseTerminatorAndDCECond(IBI); 5772 return true; 5773 } 5774 5775 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 5776 if (SimplifyIndirectBrOnSelect(IBI, SI)) 5777 return requestResimplify(); 5778 } 5779 return Changed; 5780 } 5781 5782 /// Given an block with only a single landing pad and a unconditional branch 5783 /// try to find another basic block which this one can be merged with. This 5784 /// handles cases where we have multiple invokes with unique landing pads, but 5785 /// a shared handler. 5786 /// 5787 /// We specifically choose to not worry about merging non-empty blocks 5788 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In 5789 /// practice, the optimizer produces empty landing pad blocks quite frequently 5790 /// when dealing with exception dense code. (see: instcombine, gvn, if-else 5791 /// sinking in this file) 5792 /// 5793 /// This is primarily a code size optimization. We need to avoid performing 5794 /// any transform which might inhibit optimization (such as our ability to 5795 /// specialize a particular handler via tail commoning). We do this by not 5796 /// merging any blocks which require us to introduce a phi. Since the same 5797 /// values are flowing through both blocks, we don't lose any ability to 5798 /// specialize. If anything, we make such specialization more likely. 5799 /// 5800 /// TODO - This transformation could remove entries from a phi in the target 5801 /// block when the inputs in the phi are the same for the two blocks being 5802 /// merged. In some cases, this could result in removal of the PHI entirely. 5803 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, 5804 BasicBlock *BB) { 5805 auto Succ = BB->getUniqueSuccessor(); 5806 assert(Succ); 5807 // If there's a phi in the successor block, we'd likely have to introduce 5808 // a phi into the merged landing pad block. 5809 if (isa<PHINode>(*Succ->begin())) 5810 return false; 5811 5812 for (BasicBlock *OtherPred : predecessors(Succ)) { 5813 if (BB == OtherPred) 5814 continue; 5815 BasicBlock::iterator I = OtherPred->begin(); 5816 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); 5817 if (!LPad2 || !LPad2->isIdenticalTo(LPad)) 5818 continue; 5819 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5820 ; 5821 BranchInst *BI2 = dyn_cast<BranchInst>(I); 5822 if (!BI2 || !BI2->isIdenticalTo(BI)) 5823 continue; 5824 5825 // We've found an identical block. Update our predecessors to take that 5826 // path instead and make ourselves dead. 5827 SmallPtrSet<BasicBlock *, 16> Preds; 5828 Preds.insert(pred_begin(BB), pred_end(BB)); 5829 for (BasicBlock *Pred : Preds) { 5830 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); 5831 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB && 5832 "unexpected successor"); 5833 II->setUnwindDest(OtherPred); 5834 } 5835 5836 // The debug info in OtherPred doesn't cover the merged control flow that 5837 // used to go through BB. We need to delete it or update it. 5838 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) { 5839 Instruction &Inst = *I; 5840 I++; 5841 if (isa<DbgInfoIntrinsic>(Inst)) 5842 Inst.eraseFromParent(); 5843 } 5844 5845 SmallPtrSet<BasicBlock *, 16> Succs; 5846 Succs.insert(succ_begin(BB), succ_end(BB)); 5847 for (BasicBlock *Succ : Succs) { 5848 Succ->removePredecessor(BB); 5849 } 5850 5851 IRBuilder<> Builder(BI); 5852 Builder.CreateUnreachable(); 5853 BI->eraseFromParent(); 5854 return true; 5855 } 5856 return false; 5857 } 5858 5859 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, 5860 IRBuilder<> &Builder) { 5861 BasicBlock *BB = BI->getParent(); 5862 BasicBlock *Succ = BI->getSuccessor(0); 5863 5864 // If the Terminator is the only non-phi instruction, simplify the block. 5865 // If LoopHeader is provided, check if the block or its successor is a loop 5866 // header. (This is for early invocations before loop simplify and 5867 // vectorization to keep canonical loop forms for nested loops. These blocks 5868 // can be eliminated when the pass is invoked later in the back-end.) 5869 // Note that if BB has only one predecessor then we do not introduce new 5870 // backedge, so we can eliminate BB. 5871 bool NeedCanonicalLoop = 5872 Options.NeedCanonicalLoop && 5873 (LoopHeaders && BB->hasNPredecessorsOrMore(2) && 5874 (LoopHeaders->count(BB) || LoopHeaders->count(Succ))); 5875 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator(); 5876 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 5877 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB)) 5878 return true; 5879 5880 // If the only instruction in the block is a seteq/setne comparison against a 5881 // constant, try to simplify the block. 5882 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 5883 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 5884 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5885 ; 5886 if (I->isTerminator() && 5887 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder)) 5888 return true; 5889 } 5890 5891 // See if we can merge an empty landing pad block with another which is 5892 // equivalent. 5893 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { 5894 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5895 ; 5896 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB)) 5897 return true; 5898 } 5899 5900 // If this basic block is ONLY a compare and a branch, and if a predecessor 5901 // branches to us and our successor, fold the comparison into the 5902 // predecessor and use logical operations to update the incoming value 5903 // for PHI nodes in common successor. 5904 if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold)) 5905 return requestResimplify(); 5906 return false; 5907 } 5908 5909 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { 5910 BasicBlock *PredPred = nullptr; 5911 for (auto *P : predecessors(BB)) { 5912 BasicBlock *PPred = P->getSinglePredecessor(); 5913 if (!PPred || (PredPred && PredPred != PPred)) 5914 return nullptr; 5915 PredPred = PPred; 5916 } 5917 return PredPred; 5918 } 5919 5920 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 5921 BasicBlock *BB = BI->getParent(); 5922 const Function *Fn = BB->getParent(); 5923 if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing)) 5924 return false; 5925 5926 // Conditional branch 5927 if (isValueEqualityComparison(BI)) { 5928 // If we only have one predecessor, and if it is a branch on this value, 5929 // see if that predecessor totally determines the outcome of this 5930 // switch. 5931 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 5932 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 5933 return requestResimplify(); 5934 5935 // This block must be empty, except for the setcond inst, if it exists. 5936 // Ignore dbg intrinsics. 5937 auto I = BB->instructionsWithoutDebug().begin(); 5938 if (&*I == BI) { 5939 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 5940 return requestResimplify(); 5941 } else if (&*I == cast<Instruction>(BI->getCondition())) { 5942 ++I; 5943 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 5944 return requestResimplify(); 5945 } 5946 } 5947 5948 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 5949 if (SimplifyBranchOnICmpChain(BI, Builder, DL)) 5950 return true; 5951 5952 // If this basic block has dominating predecessor blocks and the dominating 5953 // blocks' conditions imply BI's condition, we know the direction of BI. 5954 Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL); 5955 if (Imp) { 5956 // Turn this into a branch on constant. 5957 auto *OldCond = BI->getCondition(); 5958 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext()) 5959 : ConstantInt::getFalse(BB->getContext()); 5960 BI->setCondition(TorF); 5961 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 5962 return requestResimplify(); 5963 } 5964 5965 // If this basic block is ONLY a compare and a branch, and if a predecessor 5966 // branches to us and one of our successors, fold the comparison into the 5967 // predecessor and use logical operations to pick the right destination. 5968 if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold)) 5969 return requestResimplify(); 5970 5971 // We have a conditional branch to two blocks that are only reachable 5972 // from BI. We know that the condbr dominates the two blocks, so see if 5973 // there is any identical code in the "then" and "else" blocks. If so, we 5974 // can hoist it up to the branching block. 5975 if (BI->getSuccessor(0)->getSinglePredecessor()) { 5976 if (BI->getSuccessor(1)->getSinglePredecessor()) { 5977 if (HoistThenElseCodeToIf(BI, TTI)) 5978 return requestResimplify(); 5979 } else { 5980 // If Successor #1 has multiple preds, we may be able to conditionally 5981 // execute Successor #0 if it branches to Successor #1. 5982 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator(); 5983 if (Succ0TI->getNumSuccessors() == 1 && 5984 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 5985 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) 5986 return requestResimplify(); 5987 } 5988 } else if (BI->getSuccessor(1)->getSinglePredecessor()) { 5989 // If Successor #0 has multiple preds, we may be able to conditionally 5990 // execute Successor #1 if it branches to Successor #0. 5991 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator(); 5992 if (Succ1TI->getNumSuccessors() == 1 && 5993 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 5994 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) 5995 return requestResimplify(); 5996 } 5997 5998 // If this is a branch on a phi node in the current block, thread control 5999 // through this block if any PHI node entries are constants. 6000 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 6001 if (PN->getParent() == BI->getParent()) 6002 if (FoldCondBranchOnPHI(BI, DL, Options.AC)) 6003 return requestResimplify(); 6004 6005 // Scan predecessor blocks for conditional branches. 6006 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 6007 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 6008 if (PBI != BI && PBI->isConditional()) 6009 if (SimplifyCondBranchToCondBranch(PBI, BI, DL, TTI)) 6010 return requestResimplify(); 6011 6012 // Look for diamond patterns. 6013 if (MergeCondStores) 6014 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) 6015 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) 6016 if (PBI != BI && PBI->isConditional()) 6017 if (mergeConditionalStores(PBI, BI, DL, TTI)) 6018 return requestResimplify(); 6019 6020 return false; 6021 } 6022 6023 /// Check if passing a value to an instruction will cause undefined behavior. 6024 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { 6025 Constant *C = dyn_cast<Constant>(V); 6026 if (!C) 6027 return false; 6028 6029 if (I->use_empty()) 6030 return false; 6031 6032 if (C->isNullValue() || isa<UndefValue>(C)) { 6033 // Only look at the first use, avoid hurting compile time with long uselists 6034 User *Use = *I->user_begin(); 6035 6036 // Now make sure that there are no instructions in between that can alter 6037 // control flow (eg. calls) 6038 for (BasicBlock::iterator 6039 i = ++BasicBlock::iterator(I), 6040 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use)); 6041 i != UI; ++i) 6042 if (i == I->getParent()->end() || i->mayHaveSideEffects()) 6043 return false; 6044 6045 // Look through GEPs. A load from a GEP derived from NULL is still undefined 6046 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 6047 if (GEP->getPointerOperand() == I) 6048 return passingValueIsAlwaysUndefined(V, GEP); 6049 6050 // Look through bitcasts. 6051 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 6052 return passingValueIsAlwaysUndefined(V, BC); 6053 6054 // Load from null is undefined. 6055 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 6056 if (!LI->isVolatile()) 6057 return !NullPointerIsDefined(LI->getFunction(), 6058 LI->getPointerAddressSpace()); 6059 6060 // Store to null is undefined. 6061 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 6062 if (!SI->isVolatile()) 6063 return (!NullPointerIsDefined(SI->getFunction(), 6064 SI->getPointerAddressSpace())) && 6065 SI->getPointerOperand() == I; 6066 6067 // A call to null is undefined. 6068 if (auto CS = CallSite(Use)) 6069 return !NullPointerIsDefined(CS->getFunction()) && 6070 CS.getCalledValue() == I; 6071 } 6072 return false; 6073 } 6074 6075 /// If BB has an incoming value that will always trigger undefined behavior 6076 /// (eg. null pointer dereference), remove the branch leading here. 6077 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { 6078 for (PHINode &PHI : BB->phis()) 6079 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) 6080 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) { 6081 Instruction *T = PHI.getIncomingBlock(i)->getTerminator(); 6082 IRBuilder<> Builder(T); 6083 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 6084 BB->removePredecessor(PHI.getIncomingBlock(i)); 6085 // Turn uncoditional branches into unreachables and remove the dead 6086 // destination from conditional branches. 6087 if (BI->isUnconditional()) 6088 Builder.CreateUnreachable(); 6089 else 6090 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) 6091 : BI->getSuccessor(0)); 6092 BI->eraseFromParent(); 6093 return true; 6094 } 6095 // TODO: SwitchInst. 6096 } 6097 6098 return false; 6099 } 6100 6101 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) { 6102 bool Changed = false; 6103 6104 assert(BB && BB->getParent() && "Block not embedded in function!"); 6105 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 6106 6107 // Remove basic blocks that have no predecessors (except the entry block)... 6108 // or that just have themself as a predecessor. These are unreachable. 6109 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) || 6110 BB->getSinglePredecessor() == BB) { 6111 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB); 6112 DeleteDeadBlock(BB); 6113 return true; 6114 } 6115 6116 // Check to see if we can constant propagate this terminator instruction 6117 // away... 6118 Changed |= ConstantFoldTerminator(BB, true); 6119 6120 // Check for and eliminate duplicate PHI nodes in this block. 6121 Changed |= EliminateDuplicatePHINodes(BB); 6122 6123 // Check for and remove branches that will always cause undefined behavior. 6124 Changed |= removeUndefIntroducingPredecessor(BB); 6125 6126 // Merge basic blocks into their predecessor if there is only one distinct 6127 // pred, and if there is only one distinct successor of the predecessor, and 6128 // if there are no PHI nodes. 6129 if (MergeBlockIntoPredecessor(BB)) 6130 return true; 6131 6132 if (SinkCommon && Options.SinkCommonInsts) 6133 Changed |= SinkCommonCodeFromPredecessors(BB); 6134 6135 IRBuilder<> Builder(BB); 6136 6137 // If there is a trivial two-entry PHI node in this basic block, and we can 6138 // eliminate it, do so now. 6139 if (auto *PN = dyn_cast<PHINode>(BB->begin())) 6140 if (PN->getNumIncomingValues() == 2) 6141 Changed |= FoldTwoEntryPHINode(PN, TTI, DL); 6142 6143 Builder.SetInsertPoint(BB->getTerminator()); 6144 if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 6145 if (BI->isUnconditional()) { 6146 if (SimplifyUncondBranch(BI, Builder)) 6147 return true; 6148 } else { 6149 if (SimplifyCondBranch(BI, Builder)) 6150 return true; 6151 } 6152 } else if (auto *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 6153 if (SimplifyReturn(RI, Builder)) 6154 return true; 6155 } else if (auto *RI = dyn_cast<ResumeInst>(BB->getTerminator())) { 6156 if (SimplifyResume(RI, Builder)) 6157 return true; 6158 } else if (auto *RI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) { 6159 if (SimplifyCleanupReturn(RI)) 6160 return true; 6161 } else if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 6162 if (SimplifySwitch(SI, Builder)) 6163 return true; 6164 } else if (auto *UI = dyn_cast<UnreachableInst>(BB->getTerminator())) { 6165 if (SimplifyUnreachable(UI)) 6166 return true; 6167 } else if (auto *IBI = dyn_cast<IndirectBrInst>(BB->getTerminator())) { 6168 if (SimplifyIndirectBr(IBI)) 6169 return true; 6170 } 6171 6172 return Changed; 6173 } 6174 6175 bool SimplifyCFGOpt::run(BasicBlock *BB) { 6176 bool Changed = false; 6177 6178 // Repeated simplify BB as long as resimplification is requested. 6179 do { 6180 Resimplify = false; 6181 6182 // Perform one round of simplifcation. Resimplify flag will be set if 6183 // another iteration is requested. 6184 Changed |= simplifyOnce(BB); 6185 } while (Resimplify); 6186 6187 return Changed; 6188 } 6189 6190 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 6191 const SimplifyCFGOptions &Options, 6192 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) { 6193 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders, 6194 Options) 6195 .run(BB); 6196 } 6197