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