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