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 Type *Ty = std::get<0>(Ops)->getType(); 2459 assert(Ty == std::get<1>(Ops)->getType() && "Incompatible types?"); 2460 return Ty->isTokenTy() && std::get<0>(Ops) != std::get<1>(Ops); 2461 }; 2462 assert(Invokes.size() == 2 && "Always called with exactly two candidates."); 2463 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()), 2464 IsIllegalToMergeArguments)) 2465 return false; 2466 2467 return true; 2468 } 2469 2470 } // namespace 2471 2472 // Merge all invokes in the provided set, all of which are compatible 2473 // as per the `CompatibleSets::shouldBelongToSameSet()`. 2474 static void MergeCompatibleInvokesImpl(ArrayRef<InvokeInst *> Invokes, 2475 DomTreeUpdater *DTU) { 2476 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge."); 2477 2478 SmallVector<DominatorTree::UpdateType, 8> Updates; 2479 if (DTU) 2480 Updates.reserve(2 + 3 * Invokes.size()); 2481 2482 bool HasNormalDest = 2483 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg()); 2484 2485 // Clone one of the invokes into a new basic block. 2486 // Since they are all compatible, it doesn't matter which invoke is cloned. 2487 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() { 2488 InvokeInst *II0 = Invokes.front(); 2489 BasicBlock *II0BB = II0->getParent(); 2490 BasicBlock *InsertBeforeBlock = 2491 II0->getParent()->getIterator()->getNextNode(); 2492 Function *Func = II0BB->getParent(); 2493 LLVMContext &Ctx = II0->getContext(); 2494 2495 BasicBlock *MergedInvokeBB = BasicBlock::Create( 2496 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock); 2497 2498 auto *MergedInvoke = cast<InvokeInst>(II0->clone()); 2499 // NOTE: all invokes have the same attributes, so no handling needed. 2500 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end()); 2501 2502 if (!HasNormalDest) { 2503 // This set does not have a normal destination, 2504 // so just form a new block with unreachable terminator. 2505 BasicBlock *MergedNormalDest = BasicBlock::Create( 2506 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock); 2507 new UnreachableInst(Ctx, MergedNormalDest); 2508 MergedInvoke->setNormalDest(MergedNormalDest); 2509 } 2510 2511 // The unwind destination, however, remainds identical for all invokes here. 2512 2513 return MergedInvoke; 2514 }(); 2515 2516 if (DTU) { 2517 // Predecessor blocks that contained these invokes will now branch to 2518 // the new block that contains the merged invoke, ... 2519 for (InvokeInst *II : Invokes) 2520 Updates.push_back( 2521 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()}); 2522 2523 // ... which has the new `unreachable` block as normal destination, 2524 // or unwinds to the (same for all `invoke`s in this set) `landingpad`, 2525 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke)) 2526 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(), 2527 SuccBBOfMergedInvoke}); 2528 2529 // Since predecessor blocks now unconditionally branch to a new block, 2530 // they no longer branch to their original successors. 2531 for (InvokeInst *II : Invokes) 2532 for (BasicBlock *SuccOfPredBB : successors(II->getParent())) 2533 Updates.push_back( 2534 {DominatorTree::Delete, II->getParent(), SuccOfPredBB}); 2535 } 2536 2537 bool IsIndirectCall = Invokes[0]->isIndirectCall(); 2538 2539 // Form the merged operands for the merged invoke. 2540 for (Use &U : MergedInvoke->operands()) { 2541 // Only PHI together the indirect callees and data operands. 2542 if (MergedInvoke->isCallee(&U)) { 2543 if (!IsIndirectCall) 2544 continue; 2545 } else if (!MergedInvoke->isDataOperand(&U)) 2546 continue; 2547 2548 // Don't create trivial PHI's with all-identical incoming values. 2549 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) { 2550 return II->getOperand(U.getOperandNo()) != U.get(); 2551 }); 2552 if (!NeedPHI) 2553 continue; 2554 2555 // Form a PHI out of all the data ops under this index. 2556 PHINode *PN = PHINode::Create( 2557 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke); 2558 for (InvokeInst *II : Invokes) 2559 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent()); 2560 2561 U.set(PN); 2562 } 2563 2564 // We've ensured that each PHI node has compatible (identical) incoming values 2565 // when coming from each of the `invoke`s in the current merge set, 2566 // so update the PHI nodes accordingly. 2567 for (BasicBlock *Succ : successors(MergedInvoke)) 2568 AddPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(), 2569 /*ExistPred=*/Invokes.front()->getParent()); 2570 2571 // And finally, replace the original `invoke`s with an unconditional branch 2572 // to the block with the merged `invoke`. Also, give that merged `invoke` 2573 // the merged debugloc of all the original `invoke`s. 2574 const DILocation *MergedDebugLoc = nullptr; 2575 for (InvokeInst *II : Invokes) { 2576 // Compute the debug location common to all the original `invoke`s. 2577 if (!MergedDebugLoc) 2578 MergedDebugLoc = II->getDebugLoc(); 2579 else 2580 MergedDebugLoc = 2581 DILocation::getMergedLocation(MergedDebugLoc, II->getDebugLoc()); 2582 2583 // And replace the old `invoke` with an unconditionally branch 2584 // to the block with the merged `invoke`. 2585 for (BasicBlock *OrigSuccBB : successors(II->getParent())) 2586 OrigSuccBB->removePredecessor(II->getParent()); 2587 BranchInst::Create(MergedInvoke->getParent(), II->getParent()); 2588 II->replaceAllUsesWith(MergedInvoke); 2589 II->eraseFromParent(); 2590 ++NumInvokesMerged; 2591 } 2592 MergedInvoke->setDebugLoc(MergedDebugLoc); 2593 ++NumInvokeSetsFormed; 2594 2595 if (DTU) 2596 DTU->applyUpdates(Updates); 2597 } 2598 2599 /// If this block is a `landingpad` exception handling block, categorize all 2600 /// the predecessor `invoke`s into sets, with all `invoke`s in each set 2601 /// being "mergeable" together, and then merge invokes in each set together. 2602 /// 2603 /// This is a weird mix of hoisting and sinking. Visually, it goes from: 2604 /// [...] [...] 2605 /// | | 2606 /// [invoke0] [invoke1] 2607 /// / \ / \ 2608 /// [cont0] [landingpad] [cont1] 2609 /// to: 2610 /// [...] [...] 2611 /// \ / 2612 /// [invoke] 2613 /// / \ 2614 /// [cont] [landingpad] 2615 /// 2616 /// But of course we can only do that if the invokes share the `landingpad`, 2617 /// edges invoke0->cont0 and invoke1->cont1 are "compatible", 2618 /// and the invoked functions are "compatible". 2619 static bool MergeCompatibleInvokes(BasicBlock *BB, DomTreeUpdater *DTU) { 2620 if (!EnableMergeCompatibleInvokes) 2621 return false; 2622 2623 bool Changed = false; 2624 2625 // FIXME: generalize to all exception handling blocks? 2626 if (!BB->isLandingPad()) 2627 return Changed; 2628 2629 CompatibleSets Grouper; 2630 2631 // Record all the predecessors of this `landingpad`. As per verifier, 2632 // the only allowed predecessor is the unwind edge of an `invoke`. 2633 // We want to group "compatible" `invokes` into the same set to be merged. 2634 for (BasicBlock *PredBB : predecessors(BB)) 2635 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator())); 2636 2637 // And now, merge `invoke`s that were grouped togeter. 2638 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) { 2639 if (Invokes.size() < 2) 2640 continue; 2641 Changed = true; 2642 MergeCompatibleInvokesImpl(Invokes, DTU); 2643 } 2644 2645 return Changed; 2646 } 2647 2648 namespace { 2649 /// Track ephemeral values, which should be ignored for cost-modelling 2650 /// purposes. Requires walking instructions in reverse order. 2651 class EphemeralValueTracker { 2652 SmallPtrSet<const Instruction *, 32> EphValues; 2653 2654 bool isEphemeral(const Instruction *I) { 2655 if (isa<AssumeInst>(I)) 2656 return true; 2657 return !I->mayHaveSideEffects() && !I->isTerminator() && 2658 all_of(I->users(), [&](const User *U) { 2659 return EphValues.count(cast<Instruction>(U)); 2660 }); 2661 } 2662 2663 public: 2664 bool track(const Instruction *I) { 2665 if (isEphemeral(I)) { 2666 EphValues.insert(I); 2667 return true; 2668 } 2669 return false; 2670 } 2671 2672 bool contains(const Instruction *I) const { return EphValues.contains(I); } 2673 }; 2674 } // namespace 2675 2676 /// Determine if we can hoist sink a sole store instruction out of a 2677 /// conditional block. 2678 /// 2679 /// We are looking for code like the following: 2680 /// BrBB: 2681 /// store i32 %add, i32* %arrayidx2 2682 /// ... // No other stores or function calls (we could be calling a memory 2683 /// ... // function). 2684 /// %cmp = icmp ult %x, %y 2685 /// br i1 %cmp, label %EndBB, label %ThenBB 2686 /// ThenBB: 2687 /// store i32 %add5, i32* %arrayidx2 2688 /// br label EndBB 2689 /// EndBB: 2690 /// ... 2691 /// We are going to transform this into: 2692 /// BrBB: 2693 /// store i32 %add, i32* %arrayidx2 2694 /// ... // 2695 /// %cmp = icmp ult %x, %y 2696 /// %add.add5 = select i1 %cmp, i32 %add, %add5 2697 /// store i32 %add.add5, i32* %arrayidx2 2698 /// ... 2699 /// 2700 /// \return The pointer to the value of the previous store if the store can be 2701 /// hoisted into the predecessor block. 0 otherwise. 2702 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, 2703 BasicBlock *StoreBB, BasicBlock *EndBB) { 2704 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); 2705 if (!StoreToHoist) 2706 return nullptr; 2707 2708 // Volatile or atomic. 2709 if (!StoreToHoist->isSimple()) 2710 return nullptr; 2711 2712 Value *StorePtr = StoreToHoist->getPointerOperand(); 2713 Type *StoreTy = StoreToHoist->getValueOperand()->getType(); 2714 2715 // Look for a store to the same pointer in BrBB. 2716 unsigned MaxNumInstToLookAt = 9; 2717 // Skip pseudo probe intrinsic calls which are not really killing any memory 2718 // accesses. 2719 for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) { 2720 if (!MaxNumInstToLookAt) 2721 break; 2722 --MaxNumInstToLookAt; 2723 2724 // Could be calling an instruction that affects memory like free(). 2725 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI)) 2726 return nullptr; 2727 2728 if (auto *SI = dyn_cast<StoreInst>(&CurI)) { 2729 // Found the previous store to same location and type. Make sure it is 2730 // simple, to avoid introducing a spurious non-atomic write after an 2731 // atomic write. 2732 if (SI->getPointerOperand() == StorePtr && 2733 SI->getValueOperand()->getType() == StoreTy && SI->isSimple()) 2734 // Found the previous store, return its value operand. 2735 return SI->getValueOperand(); 2736 return nullptr; // Unknown store. 2737 } 2738 2739 if (auto *LI = dyn_cast<LoadInst>(&CurI)) { 2740 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy && 2741 LI->isSimple()) { 2742 // Local objects (created by an `alloca` instruction) are always 2743 // writable, so once we are past a read from a location it is valid to 2744 // also write to that same location. 2745 // If the address of the local object never escapes the function, that 2746 // means it's never concurrently read or written, hence moving the store 2747 // from under the condition will not introduce a data race. 2748 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(StorePtr)); 2749 if (AI && !PointerMayBeCaptured(AI, false, true)) 2750 // Found a previous load, return it. 2751 return LI; 2752 } 2753 // The load didn't work out, but we may still find a store. 2754 } 2755 } 2756 2757 return nullptr; 2758 } 2759 2760 /// Estimate the cost of the insertion(s) and check that the PHI nodes can be 2761 /// converted to selects. 2762 static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB, 2763 BasicBlock *EndBB, 2764 unsigned &SpeculatedInstructions, 2765 InstructionCost &Cost, 2766 const TargetTransformInfo &TTI) { 2767 TargetTransformInfo::TargetCostKind CostKind = 2768 BB->getParent()->hasMinSize() 2769 ? TargetTransformInfo::TCK_CodeSize 2770 : TargetTransformInfo::TCK_SizeAndLatency; 2771 2772 bool HaveRewritablePHIs = false; 2773 for (PHINode &PN : EndBB->phis()) { 2774 Value *OrigV = PN.getIncomingValueForBlock(BB); 2775 Value *ThenV = PN.getIncomingValueForBlock(ThenBB); 2776 2777 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. 2778 // Skip PHIs which are trivial. 2779 if (ThenV == OrigV) 2780 continue; 2781 2782 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(), nullptr, 2783 CmpInst::BAD_ICMP_PREDICATE, CostKind); 2784 2785 // Don't convert to selects if we could remove undefined behavior instead. 2786 if (passingValueIsAlwaysUndefined(OrigV, &PN) || 2787 passingValueIsAlwaysUndefined(ThenV, &PN)) 2788 return false; 2789 2790 HaveRewritablePHIs = true; 2791 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); 2792 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); 2793 if (!OrigCE && !ThenCE) 2794 continue; // Known cheap (FIXME: Maybe not true for aggregates). 2795 2796 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0; 2797 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0; 2798 InstructionCost MaxCost = 2799 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 2800 if (OrigCost + ThenCost > MaxCost) 2801 return false; 2802 2803 // Account for the cost of an unfolded ConstantExpr which could end up 2804 // getting expanded into Instructions. 2805 // FIXME: This doesn't account for how many operations are combined in the 2806 // constant expression. 2807 ++SpeculatedInstructions; 2808 if (SpeculatedInstructions > 1) 2809 return false; 2810 } 2811 2812 return HaveRewritablePHIs; 2813 } 2814 2815 /// Speculate a conditional basic block flattening the CFG. 2816 /// 2817 /// Note that this is a very risky transform currently. Speculating 2818 /// instructions like this is most often not desirable. Instead, there is an MI 2819 /// pass which can do it with full awareness of the resource constraints. 2820 /// However, some cases are "obvious" and we should do directly. An example of 2821 /// this is speculating a single, reasonably cheap instruction. 2822 /// 2823 /// There is only one distinct advantage to flattening the CFG at the IR level: 2824 /// it makes very common but simplistic optimizations such as are common in 2825 /// instcombine and the DAG combiner more powerful by removing CFG edges and 2826 /// modeling their effects with easier to reason about SSA value graphs. 2827 /// 2828 /// 2829 /// An illustration of this transform is turning this IR: 2830 /// \code 2831 /// BB: 2832 /// %cmp = icmp ult %x, %y 2833 /// br i1 %cmp, label %EndBB, label %ThenBB 2834 /// ThenBB: 2835 /// %sub = sub %x, %y 2836 /// br label BB2 2837 /// EndBB: 2838 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] 2839 /// ... 2840 /// \endcode 2841 /// 2842 /// Into this IR: 2843 /// \code 2844 /// BB: 2845 /// %cmp = icmp ult %x, %y 2846 /// %sub = sub %x, %y 2847 /// %cond = select i1 %cmp, 0, %sub 2848 /// ... 2849 /// \endcode 2850 /// 2851 /// \returns true if the conditional block is removed. 2852 bool SimplifyCFGOpt::SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, 2853 const TargetTransformInfo &TTI) { 2854 // Be conservative for now. FP select instruction can often be expensive. 2855 Value *BrCond = BI->getCondition(); 2856 if (isa<FCmpInst>(BrCond)) 2857 return false; 2858 2859 BasicBlock *BB = BI->getParent(); 2860 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); 2861 InstructionCost Budget = 2862 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 2863 2864 // If ThenBB is actually on the false edge of the conditional branch, remember 2865 // to swap the select operands later. 2866 bool Invert = false; 2867 if (ThenBB != BI->getSuccessor(0)) { 2868 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); 2869 Invert = true; 2870 } 2871 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); 2872 2873 // If the branch is non-unpredictable, and is predicted to *not* branch to 2874 // the `then` block, then avoid speculating it. 2875 if (!BI->getMetadata(LLVMContext::MD_unpredictable)) { 2876 uint64_t TWeight, FWeight; 2877 if (extractBranchWeights(*BI, TWeight, FWeight) && 2878 (TWeight + FWeight) != 0) { 2879 uint64_t EndWeight = Invert ? TWeight : FWeight; 2880 BranchProbability BIEndProb = 2881 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight); 2882 BranchProbability Likely = TTI.getPredictableBranchThreshold(); 2883 if (BIEndProb >= Likely) 2884 return false; 2885 } 2886 } 2887 2888 // Keep a count of how many times instructions are used within ThenBB when 2889 // they are candidates for sinking into ThenBB. Specifically: 2890 // - They are defined in BB, and 2891 // - They have no side effects, and 2892 // - All of their uses are in ThenBB. 2893 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; 2894 2895 SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics; 2896 2897 unsigned SpeculatedInstructions = 0; 2898 Value *SpeculatedStoreValue = nullptr; 2899 StoreInst *SpeculatedStore = nullptr; 2900 EphemeralValueTracker EphTracker; 2901 for (Instruction &I : reverse(drop_end(*ThenBB))) { 2902 // Skip debug info. 2903 if (isa<DbgInfoIntrinsic>(I)) { 2904 SpeculatedDbgIntrinsics.push_back(&I); 2905 continue; 2906 } 2907 2908 // Skip pseudo probes. The consequence is we lose track of the branch 2909 // probability for ThenBB, which is fine since the optimization here takes 2910 // place regardless of the branch probability. 2911 if (isa<PseudoProbeInst>(I)) { 2912 // The probe should be deleted so that it will not be over-counted when 2913 // the samples collected on the non-conditional path are counted towards 2914 // the conditional path. We leave it for the counts inference algorithm to 2915 // figure out a proper count for an unknown probe. 2916 SpeculatedDbgIntrinsics.push_back(&I); 2917 continue; 2918 } 2919 2920 // Ignore ephemeral values, they will be dropped by the transform. 2921 if (EphTracker.track(&I)) 2922 continue; 2923 2924 // Only speculatively execute a single instruction (not counting the 2925 // terminator) for now. 2926 ++SpeculatedInstructions; 2927 if (SpeculatedInstructions > 1) 2928 return false; 2929 2930 // Don't hoist the instruction if it's unsafe or expensive. 2931 if (!isSafeToSpeculativelyExecute(&I) && 2932 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore( 2933 &I, BB, ThenBB, EndBB)))) 2934 return false; 2935 if (!SpeculatedStoreValue && 2936 computeSpeculationCost(&I, TTI) > 2937 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic) 2938 return false; 2939 2940 // Store the store speculation candidate. 2941 if (SpeculatedStoreValue) 2942 SpeculatedStore = cast<StoreInst>(&I); 2943 2944 // Do not hoist the instruction if any of its operands are defined but not 2945 // used in BB. The transformation will prevent the operand from 2946 // being sunk into the use block. 2947 for (Use &Op : I.operands()) { 2948 Instruction *OpI = dyn_cast<Instruction>(Op); 2949 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects()) 2950 continue; // Not a candidate for sinking. 2951 2952 ++SinkCandidateUseCounts[OpI]; 2953 } 2954 } 2955 2956 // Consider any sink candidates which are only used in ThenBB as costs for 2957 // speculation. Note, while we iterate over a DenseMap here, we are summing 2958 // and so iteration order isn't significant. 2959 for (const auto &[Inst, Count] : SinkCandidateUseCounts) 2960 if (Inst->hasNUses(Count)) { 2961 ++SpeculatedInstructions; 2962 if (SpeculatedInstructions > 1) 2963 return false; 2964 } 2965 2966 // Check that we can insert the selects and that it's not too expensive to do 2967 // so. 2968 bool Convert = SpeculatedStore != nullptr; 2969 InstructionCost Cost = 0; 2970 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB, 2971 SpeculatedInstructions, 2972 Cost, TTI); 2973 if (!Convert || Cost > Budget) 2974 return false; 2975 2976 // If we get here, we can hoist the instruction and if-convert. 2977 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); 2978 2979 // Insert a select of the value of the speculated store. 2980 if (SpeculatedStoreValue) { 2981 IRBuilder<NoFolder> Builder(BI); 2982 Value *OrigV = SpeculatedStore->getValueOperand(); 2983 Value *TrueV = SpeculatedStore->getValueOperand(); 2984 Value *FalseV = SpeculatedStoreValue; 2985 if (Invert) 2986 std::swap(TrueV, FalseV); 2987 Value *S = Builder.CreateSelect( 2988 BrCond, TrueV, FalseV, "spec.store.select", BI); 2989 SpeculatedStore->setOperand(0, S); 2990 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(), 2991 SpeculatedStore->getDebugLoc()); 2992 // The value stored is still conditional, but the store itself is now 2993 // unconditonally executed, so we must be sure that any linked dbg.assign 2994 // intrinsics are tracking the new stored value (the result of the 2995 // select). If we don't, and the store were to be removed by another pass 2996 // (e.g. DSE), then we'd eventually end up emitting a location describing 2997 // the conditional value, unconditionally. 2998 // 2999 // === Before this transformation === 3000 // pred: 3001 // store %one, %x.dest, !DIAssignID !1 3002 // dbg.assign %one, "x", ..., !1, ... 3003 // br %cond if.then 3004 // 3005 // if.then: 3006 // store %two, %x.dest, !DIAssignID !2 3007 // dbg.assign %two, "x", ..., !2, ... 3008 // 3009 // === After this transformation === 3010 // pred: 3011 // store %one, %x.dest, !DIAssignID !1 3012 // dbg.assign %one, "x", ..., !1 3013 /// ... 3014 // %merge = select %cond, %two, %one 3015 // store %merge, %x.dest, !DIAssignID !2 3016 // dbg.assign %merge, "x", ..., !2 3017 for (auto *DAI : at::getAssignmentMarkers(SpeculatedStore)) { 3018 if (any_of(DAI->location_ops(), [&](Value *V) { return V == OrigV; })) 3019 DAI->replaceVariableLocationOp(OrigV, S); 3020 } 3021 } 3022 3023 // Metadata can be dependent on the condition we are hoisting above. 3024 // Conservatively strip all metadata on the instruction. Drop the debug loc 3025 // to avoid making it appear as if the condition is a constant, which would 3026 // be misleading while debugging. 3027 // Similarly strip attributes that maybe dependent on condition we are 3028 // hoisting above. 3029 for (auto &I : make_early_inc_range(*ThenBB)) { 3030 if (!SpeculatedStoreValue || &I != SpeculatedStore) { 3031 // Don't update the DILocation of dbg.assign intrinsics. 3032 if (!isa<DbgAssignIntrinsic>(&I)) 3033 I.setDebugLoc(DebugLoc()); 3034 } 3035 I.dropUndefImplyingAttrsAndUnknownMetadata(); 3036 3037 // Drop ephemeral values. 3038 if (EphTracker.contains(&I)) { 3039 I.replaceAllUsesWith(PoisonValue::get(I.getType())); 3040 I.eraseFromParent(); 3041 } 3042 } 3043 3044 // Hoist the instructions. 3045 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(), 3046 std::prev(ThenBB->end())); 3047 3048 // Insert selects and rewrite the PHI operands. 3049 IRBuilder<NoFolder> Builder(BI); 3050 for (PHINode &PN : EndBB->phis()) { 3051 unsigned OrigI = PN.getBasicBlockIndex(BB); 3052 unsigned ThenI = PN.getBasicBlockIndex(ThenBB); 3053 Value *OrigV = PN.getIncomingValue(OrigI); 3054 Value *ThenV = PN.getIncomingValue(ThenI); 3055 3056 // Skip PHIs which are trivial. 3057 if (OrigV == ThenV) 3058 continue; 3059 3060 // Create a select whose true value is the speculatively executed value and 3061 // false value is the pre-existing value. Swap them if the branch 3062 // destinations were inverted. 3063 Value *TrueV = ThenV, *FalseV = OrigV; 3064 if (Invert) 3065 std::swap(TrueV, FalseV); 3066 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI); 3067 PN.setIncomingValue(OrigI, V); 3068 PN.setIncomingValue(ThenI, V); 3069 } 3070 3071 // Remove speculated dbg intrinsics. 3072 // FIXME: Is it possible to do this in a more elegant way? Moving/merging the 3073 // dbg value for the different flows and inserting it after the select. 3074 for (Instruction *I : SpeculatedDbgIntrinsics) { 3075 // We still want to know that an assignment took place so don't remove 3076 // dbg.assign intrinsics. 3077 if (!isa<DbgAssignIntrinsic>(I)) 3078 I->eraseFromParent(); 3079 } 3080 3081 ++NumSpeculations; 3082 return true; 3083 } 3084 3085 /// Return true if we can thread a branch across this block. 3086 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { 3087 int Size = 0; 3088 EphemeralValueTracker EphTracker; 3089 3090 // Walk the loop in reverse so that we can identify ephemeral values properly 3091 // (values only feeding assumes). 3092 for (Instruction &I : reverse(BB->instructionsWithoutDebug(false))) { 3093 // Can't fold blocks that contain noduplicate or convergent calls. 3094 if (CallInst *CI = dyn_cast<CallInst>(&I)) 3095 if (CI->cannotDuplicate() || CI->isConvergent()) 3096 return false; 3097 3098 // Ignore ephemeral values which are deleted during codegen. 3099 // We will delete Phis while threading, so Phis should not be accounted in 3100 // block's size. 3101 if (!EphTracker.track(&I) && !isa<PHINode>(I)) { 3102 if (Size++ > MaxSmallBlockSize) 3103 return false; // Don't clone large BB's. 3104 } 3105 3106 // We can only support instructions that do not define values that are 3107 // live outside of the current basic block. 3108 for (User *U : I.users()) { 3109 Instruction *UI = cast<Instruction>(U); 3110 if (UI->getParent() != BB || isa<PHINode>(UI)) 3111 return false; 3112 } 3113 3114 // Looks ok, continue checking. 3115 } 3116 3117 return true; 3118 } 3119 3120 static ConstantInt *getKnownValueOnEdge(Value *V, BasicBlock *From, 3121 BasicBlock *To) { 3122 // Don't look past the block defining the value, we might get the value from 3123 // a previous loop iteration. 3124 auto *I = dyn_cast<Instruction>(V); 3125 if (I && I->getParent() == To) 3126 return nullptr; 3127 3128 // We know the value if the From block branches on it. 3129 auto *BI = dyn_cast<BranchInst>(From->getTerminator()); 3130 if (BI && BI->isConditional() && BI->getCondition() == V && 3131 BI->getSuccessor(0) != BI->getSuccessor(1)) 3132 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext()) 3133 : ConstantInt::getFalse(BI->getContext()); 3134 3135 return nullptr; 3136 } 3137 3138 /// If we have a conditional branch on something for which we know the constant 3139 /// value in predecessors (e.g. a phi node in the current block), thread edges 3140 /// from the predecessor to their ultimate destination. 3141 static std::optional<bool> 3142 FoldCondBranchOnValueKnownInPredecessorImpl(BranchInst *BI, DomTreeUpdater *DTU, 3143 const DataLayout &DL, 3144 AssumptionCache *AC) { 3145 SmallMapVector<ConstantInt *, SmallSetVector<BasicBlock *, 2>, 2> KnownValues; 3146 BasicBlock *BB = BI->getParent(); 3147 Value *Cond = BI->getCondition(); 3148 PHINode *PN = dyn_cast<PHINode>(Cond); 3149 if (PN && PN->getParent() == BB) { 3150 // Degenerate case of a single entry PHI. 3151 if (PN->getNumIncomingValues() == 1) { 3152 FoldSingleEntryPHINodes(PN->getParent()); 3153 return true; 3154 } 3155 3156 for (Use &U : PN->incoming_values()) 3157 if (auto *CB = dyn_cast<ConstantInt>(U)) 3158 KnownValues[CB].insert(PN->getIncomingBlock(U)); 3159 } else { 3160 for (BasicBlock *Pred : predecessors(BB)) { 3161 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB)) 3162 KnownValues[CB].insert(Pred); 3163 } 3164 } 3165 3166 if (KnownValues.empty()) 3167 return false; 3168 3169 // Now we know that this block has multiple preds and two succs. 3170 // Check that the block is small enough and values defined in the block are 3171 // not used outside of it. 3172 if (!BlockIsSimpleEnoughToThreadThrough(BB)) 3173 return false; 3174 3175 for (const auto &Pair : KnownValues) { 3176 // Okay, we now know that all edges from PredBB should be revectored to 3177 // branch to RealDest. 3178 ConstantInt *CB = Pair.first; 3179 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef(); 3180 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); 3181 3182 if (RealDest == BB) 3183 continue; // Skip self loops. 3184 3185 // Skip if the predecessor's terminator is an indirect branch. 3186 if (any_of(PredBBs, [](BasicBlock *PredBB) { 3187 return isa<IndirectBrInst>(PredBB->getTerminator()); 3188 })) 3189 continue; 3190 3191 LLVM_DEBUG({ 3192 dbgs() << "Condition " << *Cond << " in " << BB->getName() 3193 << " has value " << *Pair.first << " in predecessors:\n"; 3194 for (const BasicBlock *PredBB : Pair.second) 3195 dbgs() << " " << PredBB->getName() << "\n"; 3196 dbgs() << "Threading to destination " << RealDest->getName() << ".\n"; 3197 }); 3198 3199 // Split the predecessors we are threading into a new edge block. We'll 3200 // clone the instructions into this block, and then redirect it to RealDest. 3201 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU); 3202 3203 // TODO: These just exist to reduce test diff, we can drop them if we like. 3204 EdgeBB->setName(RealDest->getName() + ".critedge"); 3205 EdgeBB->moveBefore(RealDest); 3206 3207 // Update PHI nodes. 3208 AddPredecessorToBlock(RealDest, EdgeBB, BB); 3209 3210 // BB may have instructions that are being threaded over. Clone these 3211 // instructions into EdgeBB. We know that there will be no uses of the 3212 // cloned instructions outside of EdgeBB. 3213 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt(); 3214 DenseMap<Value *, Value *> TranslateMap; // Track translated values. 3215 TranslateMap[Cond] = CB; 3216 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 3217 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 3218 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB); 3219 continue; 3220 } 3221 // Clone the instruction. 3222 Instruction *N = BBI->clone(); 3223 if (BBI->hasName()) 3224 N->setName(BBI->getName() + ".c"); 3225 3226 // Update operands due to translation. 3227 for (Use &Op : N->operands()) { 3228 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op); 3229 if (PI != TranslateMap.end()) 3230 Op = PI->second; 3231 } 3232 3233 // Check for trivial simplification. 3234 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) { 3235 if (!BBI->use_empty()) 3236 TranslateMap[&*BBI] = V; 3237 if (!N->mayHaveSideEffects()) { 3238 N->deleteValue(); // Instruction folded away, don't need actual inst 3239 N = nullptr; 3240 } 3241 } else { 3242 if (!BBI->use_empty()) 3243 TranslateMap[&*BBI] = N; 3244 } 3245 if (N) { 3246 // Insert the new instruction into its new home. 3247 N->insertInto(EdgeBB, InsertPt); 3248 3249 // Register the new instruction with the assumption cache if necessary. 3250 if (auto *Assume = dyn_cast<AssumeInst>(N)) 3251 if (AC) 3252 AC->registerAssumption(Assume); 3253 } 3254 } 3255 3256 BB->removePredecessor(EdgeBB); 3257 BranchInst *EdgeBI = cast<BranchInst>(EdgeBB->getTerminator()); 3258 EdgeBI->setSuccessor(0, RealDest); 3259 EdgeBI->setDebugLoc(BI->getDebugLoc()); 3260 3261 if (DTU) { 3262 SmallVector<DominatorTree::UpdateType, 2> Updates; 3263 Updates.push_back({DominatorTree::Delete, EdgeBB, BB}); 3264 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest}); 3265 DTU->applyUpdates(Updates); 3266 } 3267 3268 // For simplicity, we created a separate basic block for the edge. Merge 3269 // it back into the predecessor if possible. This not only avoids 3270 // unnecessary SimplifyCFG iterations, but also makes sure that we don't 3271 // bypass the check for trivial cycles above. 3272 MergeBlockIntoPredecessor(EdgeBB, DTU); 3273 3274 // Signal repeat, simplifying any other constants. 3275 return std::nullopt; 3276 } 3277 3278 return false; 3279 } 3280 3281 static bool FoldCondBranchOnValueKnownInPredecessor(BranchInst *BI, 3282 DomTreeUpdater *DTU, 3283 const DataLayout &DL, 3284 AssumptionCache *AC) { 3285 std::optional<bool> Result; 3286 bool EverChanged = false; 3287 do { 3288 // Note that None means "we changed things, but recurse further." 3289 Result = FoldCondBranchOnValueKnownInPredecessorImpl(BI, DTU, DL, AC); 3290 EverChanged |= Result == std::nullopt || *Result; 3291 } while (Result == std::nullopt); 3292 return EverChanged; 3293 } 3294 3295 /// Given a BB that starts with the specified two-entry PHI node, 3296 /// see if we can eliminate it. 3297 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, 3298 DomTreeUpdater *DTU, const DataLayout &DL) { 3299 // Ok, this is a two entry PHI node. Check to see if this is a simple "if 3300 // statement", which has a very simple dominance structure. Basically, we 3301 // are trying to find the condition that is being branched on, which 3302 // subsequently causes this merge to happen. We really want control 3303 // dependence information for this check, but simplifycfg can't keep it up 3304 // to date, and this catches most of the cases we care about anyway. 3305 BasicBlock *BB = PN->getParent(); 3306 3307 BasicBlock *IfTrue, *IfFalse; 3308 BranchInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse); 3309 if (!DomBI) 3310 return false; 3311 Value *IfCond = DomBI->getCondition(); 3312 // Don't bother if the branch will be constant folded trivially. 3313 if (isa<ConstantInt>(IfCond)) 3314 return false; 3315 3316 BasicBlock *DomBlock = DomBI->getParent(); 3317 SmallVector<BasicBlock *, 2> IfBlocks; 3318 llvm::copy_if( 3319 PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) { 3320 return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional(); 3321 }); 3322 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) && 3323 "Will have either one or two blocks to speculate."); 3324 3325 // If the branch is non-unpredictable, see if we either predictably jump to 3326 // the merge bb (if we have only a single 'then' block), or if we predictably 3327 // jump to one specific 'then' block (if we have two of them). 3328 // It isn't beneficial to speculatively execute the code 3329 // from the block that we know is predictably not entered. 3330 if (!DomBI->getMetadata(LLVMContext::MD_unpredictable)) { 3331 uint64_t TWeight, FWeight; 3332 if (extractBranchWeights(*DomBI, TWeight, FWeight) && 3333 (TWeight + FWeight) != 0) { 3334 BranchProbability BITrueProb = 3335 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight); 3336 BranchProbability Likely = TTI.getPredictableBranchThreshold(); 3337 BranchProbability BIFalseProb = BITrueProb.getCompl(); 3338 if (IfBlocks.size() == 1) { 3339 BranchProbability BIBBProb = 3340 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb; 3341 if (BIBBProb >= Likely) 3342 return false; 3343 } else { 3344 if (BITrueProb >= Likely || BIFalseProb >= Likely) 3345 return false; 3346 } 3347 } 3348 } 3349 3350 // Don't try to fold an unreachable block. For example, the phi node itself 3351 // can't be the candidate if-condition for a select that we want to form. 3352 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond)) 3353 if (IfCondPhiInst->getParent() == BB) 3354 return false; 3355 3356 // Okay, we found that we can merge this two-entry phi node into a select. 3357 // Doing so would require us to fold *all* two entry phi nodes in this block. 3358 // At some point this becomes non-profitable (particularly if the target 3359 // doesn't support cmov's). Only do this transformation if there are two or 3360 // fewer PHI nodes in this block. 3361 unsigned NumPhis = 0; 3362 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) 3363 if (NumPhis > 2) 3364 return false; 3365 3366 // Loop over the PHI's seeing if we can promote them all to select 3367 // instructions. While we are at it, keep track of the instructions 3368 // that need to be moved to the dominating block. 3369 SmallPtrSet<Instruction *, 4> AggressiveInsts; 3370 InstructionCost Cost = 0; 3371 InstructionCost Budget = 3372 TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 3373 3374 bool Changed = false; 3375 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { 3376 PHINode *PN = cast<PHINode>(II++); 3377 if (Value *V = simplifyInstruction(PN, {DL, PN})) { 3378 PN->replaceAllUsesWith(V); 3379 PN->eraseFromParent(); 3380 Changed = true; 3381 continue; 3382 } 3383 3384 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts, 3385 Cost, Budget, TTI) || 3386 !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts, 3387 Cost, Budget, TTI)) 3388 return Changed; 3389 } 3390 3391 // If we folded the first phi, PN dangles at this point. Refresh it. If 3392 // we ran out of PHIs then we simplified them all. 3393 PN = dyn_cast<PHINode>(BB->begin()); 3394 if (!PN) 3395 return true; 3396 3397 // Return true if at least one of these is a 'not', and another is either 3398 // a 'not' too, or a constant. 3399 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) { 3400 if (!match(V0, m_Not(m_Value()))) 3401 std::swap(V0, V1); 3402 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant()); 3403 return match(V0, m_Not(m_Value())) && match(V1, Invertible); 3404 }; 3405 3406 // Don't fold i1 branches on PHIs which contain binary operators or 3407 // (possibly inverted) select form of or/ands, unless one of 3408 // the incoming values is an 'not' and another one is freely invertible. 3409 // These can often be turned into switches and other things. 3410 auto IsBinOpOrAnd = [](Value *V) { 3411 return match( 3412 V, m_CombineOr( 3413 m_BinOp(), 3414 m_CombineOr(m_Select(m_Value(), m_ImmConstant(), m_Value()), 3415 m_Select(m_Value(), m_Value(), m_ImmConstant())))); 3416 }; 3417 if (PN->getType()->isIntegerTy(1) && 3418 (IsBinOpOrAnd(PN->getIncomingValue(0)) || 3419 IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) && 3420 !CanHoistNotFromBothValues(PN->getIncomingValue(0), 3421 PN->getIncomingValue(1))) 3422 return Changed; 3423 3424 // If all PHI nodes are promotable, check to make sure that all instructions 3425 // in the predecessor blocks can be promoted as well. If not, we won't be able 3426 // to get rid of the control flow, so it's not worth promoting to select 3427 // instructions. 3428 for (BasicBlock *IfBlock : IfBlocks) 3429 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I) 3430 if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) { 3431 // This is not an aggressive instruction that we can promote. 3432 // Because of this, we won't be able to get rid of the control flow, so 3433 // the xform is not worth it. 3434 return Changed; 3435 } 3436 3437 // If either of the blocks has it's address taken, we can't do this fold. 3438 if (any_of(IfBlocks, 3439 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); })) 3440 return Changed; 3441 3442 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond 3443 << " T: " << IfTrue->getName() 3444 << " F: " << IfFalse->getName() << "\n"); 3445 3446 // If we can still promote the PHI nodes after this gauntlet of tests, 3447 // do all of the PHI's now. 3448 3449 // Move all 'aggressive' instructions, which are defined in the 3450 // conditional parts of the if's up to the dominating block. 3451 for (BasicBlock *IfBlock : IfBlocks) 3452 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock); 3453 3454 IRBuilder<NoFolder> Builder(DomBI); 3455 // Propagate fast-math-flags from phi nodes to replacement selects. 3456 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 3457 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 3458 if (isa<FPMathOperator>(PN)) 3459 Builder.setFastMathFlags(PN->getFastMathFlags()); 3460 3461 // Change the PHI node into a select instruction. 3462 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue); 3463 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse); 3464 3465 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI); 3466 PN->replaceAllUsesWith(Sel); 3467 Sel->takeName(PN); 3468 PN->eraseFromParent(); 3469 } 3470 3471 // At this point, all IfBlocks are empty, so our if statement 3472 // has been flattened. Change DomBlock to jump directly to our new block to 3473 // avoid other simplifycfg's kicking in on the diamond. 3474 Builder.CreateBr(BB); 3475 3476 SmallVector<DominatorTree::UpdateType, 3> Updates; 3477 if (DTU) { 3478 Updates.push_back({DominatorTree::Insert, DomBlock, BB}); 3479 for (auto *Successor : successors(DomBlock)) 3480 Updates.push_back({DominatorTree::Delete, DomBlock, Successor}); 3481 } 3482 3483 DomBI->eraseFromParent(); 3484 if (DTU) 3485 DTU->applyUpdates(Updates); 3486 3487 return true; 3488 } 3489 3490 static Value *createLogicalOp(IRBuilderBase &Builder, 3491 Instruction::BinaryOps Opc, Value *LHS, 3492 Value *RHS, const Twine &Name = "") { 3493 // Try to relax logical op to binary op. 3494 if (impliesPoison(RHS, LHS)) 3495 return Builder.CreateBinOp(Opc, LHS, RHS, Name); 3496 if (Opc == Instruction::And) 3497 return Builder.CreateLogicalAnd(LHS, RHS, Name); 3498 if (Opc == Instruction::Or) 3499 return Builder.CreateLogicalOr(LHS, RHS, Name); 3500 llvm_unreachable("Invalid logical opcode"); 3501 } 3502 3503 /// Return true if either PBI or BI has branch weight available, and store 3504 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does 3505 /// not have branch weight, use 1:1 as its weight. 3506 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, 3507 uint64_t &PredTrueWeight, 3508 uint64_t &PredFalseWeight, 3509 uint64_t &SuccTrueWeight, 3510 uint64_t &SuccFalseWeight) { 3511 bool PredHasWeights = 3512 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight); 3513 bool SuccHasWeights = 3514 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight); 3515 if (PredHasWeights || SuccHasWeights) { 3516 if (!PredHasWeights) 3517 PredTrueWeight = PredFalseWeight = 1; 3518 if (!SuccHasWeights) 3519 SuccTrueWeight = SuccFalseWeight = 1; 3520 return true; 3521 } else { 3522 return false; 3523 } 3524 } 3525 3526 /// Determine if the two branches share a common destination and deduce a glue 3527 /// that joins the branches' conditions to arrive at the common destination if 3528 /// that would be profitable. 3529 static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>> 3530 shouldFoldCondBranchesToCommonDestination(BranchInst *BI, BranchInst *PBI, 3531 const TargetTransformInfo *TTI) { 3532 assert(BI && PBI && BI->isConditional() && PBI->isConditional() && 3533 "Both blocks must end with a conditional branches."); 3534 assert(is_contained(predecessors(BI->getParent()), PBI->getParent()) && 3535 "PredBB must be a predecessor of BB."); 3536 3537 // We have the potential to fold the conditions together, but if the 3538 // predecessor branch is predictable, we may not want to merge them. 3539 uint64_t PTWeight, PFWeight; 3540 BranchProbability PBITrueProb, Likely; 3541 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) && 3542 extractBranchWeights(*PBI, PTWeight, PFWeight) && 3543 (PTWeight + PFWeight) != 0) { 3544 PBITrueProb = 3545 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight); 3546 Likely = TTI->getPredictableBranchThreshold(); 3547 } 3548 3549 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3550 // Speculate the 2nd condition unless the 1st is probably true. 3551 if (PBITrueProb.isUnknown() || PBITrueProb < Likely) 3552 return {{BI->getSuccessor(0), Instruction::Or, false}}; 3553 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3554 // Speculate the 2nd condition unless the 1st is probably false. 3555 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely) 3556 return {{BI->getSuccessor(1), Instruction::And, false}}; 3557 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3558 // Speculate the 2nd condition unless the 1st is probably true. 3559 if (PBITrueProb.isUnknown() || PBITrueProb < Likely) 3560 return {{BI->getSuccessor(1), Instruction::And, true}}; 3561 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3562 // Speculate the 2nd condition unless the 1st is probably false. 3563 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely) 3564 return {{BI->getSuccessor(0), Instruction::Or, true}}; 3565 } 3566 return std::nullopt; 3567 } 3568 3569 static bool performBranchToCommonDestFolding(BranchInst *BI, BranchInst *PBI, 3570 DomTreeUpdater *DTU, 3571 MemorySSAUpdater *MSSAU, 3572 const TargetTransformInfo *TTI) { 3573 BasicBlock *BB = BI->getParent(); 3574 BasicBlock *PredBlock = PBI->getParent(); 3575 3576 // Determine if the two branches share a common destination. 3577 BasicBlock *CommonSucc; 3578 Instruction::BinaryOps Opc; 3579 bool InvertPredCond; 3580 std::tie(CommonSucc, Opc, InvertPredCond) = 3581 *shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI); 3582 3583 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); 3584 3585 IRBuilder<> Builder(PBI); 3586 // The builder is used to create instructions to eliminate the branch in BB. 3587 // If BB's terminator has !annotation metadata, add it to the new 3588 // instructions. 3589 Builder.CollectMetadataToCopy(BB->getTerminator(), 3590 {LLVMContext::MD_annotation}); 3591 3592 // If we need to invert the condition in the pred block to match, do so now. 3593 if (InvertPredCond) { 3594 Value *NewCond = PBI->getCondition(); 3595 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { 3596 CmpInst *CI = cast<CmpInst>(NewCond); 3597 CI->setPredicate(CI->getInversePredicate()); 3598 } else { 3599 NewCond = 3600 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not"); 3601 } 3602 3603 PBI->setCondition(NewCond); 3604 PBI->swapSuccessors(); 3605 } 3606 3607 BasicBlock *UniqueSucc = 3608 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1); 3609 3610 // Before cloning instructions, notify the successor basic block that it 3611 // is about to have a new predecessor. This will update PHI nodes, 3612 // which will allow us to update live-out uses of bonus instructions. 3613 AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU); 3614 3615 // Try to update branch weights. 3616 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3617 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3618 SuccTrueWeight, SuccFalseWeight)) { 3619 SmallVector<uint64_t, 8> NewWeights; 3620 3621 if (PBI->getSuccessor(0) == BB) { 3622 // PBI: br i1 %x, BB, FalseDest 3623 // BI: br i1 %y, UniqueSucc, FalseDest 3624 // TrueWeight is TrueWeight for PBI * TrueWeight for BI. 3625 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 3626 // FalseWeight is FalseWeight for PBI * TotalWeight for BI + 3627 // TrueWeight for PBI * FalseWeight for BI. 3628 // We assume that total weights of a BranchInst can fit into 32 bits. 3629 // Therefore, we will not have overflow using 64-bit arithmetic. 3630 NewWeights.push_back(PredFalseWeight * 3631 (SuccFalseWeight + SuccTrueWeight) + 3632 PredTrueWeight * SuccFalseWeight); 3633 } else { 3634 // PBI: br i1 %x, TrueDest, BB 3635 // BI: br i1 %y, TrueDest, UniqueSucc 3636 // TrueWeight is TrueWeight for PBI * TotalWeight for BI + 3637 // FalseWeight for PBI * TrueWeight for BI. 3638 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) + 3639 PredFalseWeight * SuccTrueWeight); 3640 // FalseWeight is FalseWeight for PBI * FalseWeight for BI. 3641 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 3642 } 3643 3644 // Halve the weights if any of them cannot fit in an uint32_t 3645 FitWeights(NewWeights); 3646 3647 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end()); 3648 setBranchWeights(PBI, MDWeights[0], MDWeights[1]); 3649 3650 // TODO: If BB is reachable from all paths through PredBlock, then we 3651 // could replace PBI's branch probabilities with BI's. 3652 } else 3653 PBI->setMetadata(LLVMContext::MD_prof, nullptr); 3654 3655 // Now, update the CFG. 3656 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc); 3657 3658 if (DTU) 3659 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc}, 3660 {DominatorTree::Delete, PredBlock, BB}}); 3661 3662 // If BI was a loop latch, it may have had associated loop metadata. 3663 // We need to copy it to the new latch, that is, PBI. 3664 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop)) 3665 PBI->setMetadata(LLVMContext::MD_loop, LoopMD); 3666 3667 ValueToValueMapTy VMap; // maps original values to cloned values 3668 CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BB, PredBlock, VMap); 3669 3670 // Now that the Cond was cloned into the predecessor basic block, 3671 // or/and the two conditions together. 3672 Value *BICond = VMap[BI->getCondition()]; 3673 PBI->setCondition( 3674 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond")); 3675 3676 // Copy any debug value intrinsics into the end of PredBlock. 3677 for (Instruction &I : *BB) { 3678 if (isa<DbgInfoIntrinsic>(I)) { 3679 Instruction *NewI = I.clone(); 3680 RemapInstruction(NewI, VMap, 3681 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 3682 NewI->insertBefore(PBI); 3683 } 3684 } 3685 3686 ++NumFoldBranchToCommonDest; 3687 return true; 3688 } 3689 3690 /// Return if an instruction's type or any of its operands' types are a vector 3691 /// type. 3692 static bool isVectorOp(Instruction &I) { 3693 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) { 3694 return U->getType()->isVectorTy(); 3695 }); 3696 } 3697 3698 /// If this basic block is simple enough, and if a predecessor branches to us 3699 /// and one of our successors, fold the block into the predecessor and use 3700 /// logical operations to pick the right destination. 3701 bool llvm::FoldBranchToCommonDest(BranchInst *BI, DomTreeUpdater *DTU, 3702 MemorySSAUpdater *MSSAU, 3703 const TargetTransformInfo *TTI, 3704 unsigned BonusInstThreshold) { 3705 // If this block ends with an unconditional branch, 3706 // let SpeculativelyExecuteBB() deal with it. 3707 if (!BI->isConditional()) 3708 return false; 3709 3710 BasicBlock *BB = BI->getParent(); 3711 TargetTransformInfo::TargetCostKind CostKind = 3712 BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize 3713 : TargetTransformInfo::TCK_SizeAndLatency; 3714 3715 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 3716 3717 if (!Cond || 3718 (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond) && 3719 !isa<SelectInst>(Cond)) || 3720 Cond->getParent() != BB || !Cond->hasOneUse()) 3721 return false; 3722 3723 // Finally, don't infinitely unroll conditional loops. 3724 if (is_contained(successors(BB), BB)) 3725 return false; 3726 3727 // With which predecessors will we want to deal with? 3728 SmallVector<BasicBlock *, 8> Preds; 3729 for (BasicBlock *PredBlock : predecessors(BB)) { 3730 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); 3731 3732 // Check that we have two conditional branches. If there is a PHI node in 3733 // the common successor, verify that the same value flows in from both 3734 // blocks. 3735 if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI)) 3736 continue; 3737 3738 // Determine if the two branches share a common destination. 3739 BasicBlock *CommonSucc; 3740 Instruction::BinaryOps Opc; 3741 bool InvertPredCond; 3742 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI)) 3743 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe; 3744 else 3745 continue; 3746 3747 // Check the cost of inserting the necessary logic before performing the 3748 // transformation. 3749 if (TTI) { 3750 Type *Ty = BI->getCondition()->getType(); 3751 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind); 3752 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() || 3753 !isa<CmpInst>(PBI->getCondition()))) 3754 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind); 3755 3756 if (Cost > BranchFoldThreshold) 3757 continue; 3758 } 3759 3760 // Ok, we do want to deal with this predecessor. Record it. 3761 Preds.emplace_back(PredBlock); 3762 } 3763 3764 // If there aren't any predecessors into which we can fold, 3765 // don't bother checking the cost. 3766 if (Preds.empty()) 3767 return false; 3768 3769 // Only allow this transformation if computing the condition doesn't involve 3770 // too many instructions and these involved instructions can be executed 3771 // unconditionally. We denote all involved instructions except the condition 3772 // as "bonus instructions", and only allow this transformation when the 3773 // number of the bonus instructions we'll need to create when cloning into 3774 // each predecessor does not exceed a certain threshold. 3775 unsigned NumBonusInsts = 0; 3776 bool SawVectorOp = false; 3777 const unsigned PredCount = Preds.size(); 3778 for (Instruction &I : *BB) { 3779 // Don't check the branch condition comparison itself. 3780 if (&I == Cond) 3781 continue; 3782 // Ignore dbg intrinsics, and the terminator. 3783 if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I)) 3784 continue; 3785 // I must be safe to execute unconditionally. 3786 if (!isSafeToSpeculativelyExecute(&I)) 3787 return false; 3788 SawVectorOp |= isVectorOp(I); 3789 3790 // Account for the cost of duplicating this instruction into each 3791 // predecessor. Ignore free instructions. 3792 if (!TTI || TTI->getInstructionCost(&I, CostKind) != 3793 TargetTransformInfo::TCC_Free) { 3794 NumBonusInsts += PredCount; 3795 3796 // Early exits once we reach the limit. 3797 if (NumBonusInsts > 3798 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier) 3799 return false; 3800 } 3801 3802 auto IsBCSSAUse = [BB, &I](Use &U) { 3803 auto *UI = cast<Instruction>(U.getUser()); 3804 if (auto *PN = dyn_cast<PHINode>(UI)) 3805 return PN->getIncomingBlock(U) == BB; 3806 return UI->getParent() == BB && I.comesBefore(UI); 3807 }; 3808 3809 // Does this instruction require rewriting of uses? 3810 if (!all_of(I.uses(), IsBCSSAUse)) 3811 return false; 3812 } 3813 if (NumBonusInsts > 3814 BonusInstThreshold * 3815 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1)) 3816 return false; 3817 3818 // Ok, we have the budget. Perform the transformation. 3819 for (BasicBlock *PredBlock : Preds) { 3820 auto *PBI = cast<BranchInst>(PredBlock->getTerminator()); 3821 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI); 3822 } 3823 return false; 3824 } 3825 3826 // If there is only one store in BB1 and BB2, return it, otherwise return 3827 // nullptr. 3828 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { 3829 StoreInst *S = nullptr; 3830 for (auto *BB : {BB1, BB2}) { 3831 if (!BB) 3832 continue; 3833 for (auto &I : *BB) 3834 if (auto *SI = dyn_cast<StoreInst>(&I)) { 3835 if (S) 3836 // Multiple stores seen. 3837 return nullptr; 3838 else 3839 S = SI; 3840 } 3841 } 3842 return S; 3843 } 3844 3845 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, 3846 Value *AlternativeV = nullptr) { 3847 // PHI is going to be a PHI node that allows the value V that is defined in 3848 // BB to be referenced in BB's only successor. 3849 // 3850 // If AlternativeV is nullptr, the only value we care about in PHI is V. It 3851 // doesn't matter to us what the other operand is (it'll never get used). We 3852 // could just create a new PHI with an undef incoming value, but that could 3853 // increase register pressure if EarlyCSE/InstCombine can't fold it with some 3854 // other PHI. So here we directly look for some PHI in BB's successor with V 3855 // as an incoming operand. If we find one, we use it, else we create a new 3856 // one. 3857 // 3858 // If AlternativeV is not nullptr, we care about both incoming values in PHI. 3859 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] 3860 // where OtherBB is the single other predecessor of BB's only successor. 3861 PHINode *PHI = nullptr; 3862 BasicBlock *Succ = BB->getSingleSuccessor(); 3863 3864 for (auto I = Succ->begin(); isa<PHINode>(I); ++I) 3865 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { 3866 PHI = cast<PHINode>(I); 3867 if (!AlternativeV) 3868 break; 3869 3870 assert(Succ->hasNPredecessors(2)); 3871 auto PredI = pred_begin(Succ); 3872 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; 3873 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) 3874 break; 3875 PHI = nullptr; 3876 } 3877 if (PHI) 3878 return PHI; 3879 3880 // If V is not an instruction defined in BB, just return it. 3881 if (!AlternativeV && 3882 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB)) 3883 return V; 3884 3885 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front()); 3886 PHI->addIncoming(V, BB); 3887 for (BasicBlock *PredBB : predecessors(Succ)) 3888 if (PredBB != BB) 3889 PHI->addIncoming( 3890 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB); 3891 return PHI; 3892 } 3893 3894 static bool mergeConditionalStoreToAddress( 3895 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, 3896 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond, 3897 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) { 3898 // For every pointer, there must be exactly two stores, one coming from 3899 // PTB or PFB, and the other from QTB or QFB. We don't support more than one 3900 // store (to any address) in PTB,PFB or QTB,QFB. 3901 // FIXME: We could relax this restriction with a bit more work and performance 3902 // testing. 3903 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); 3904 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); 3905 if (!PStore || !QStore) 3906 return false; 3907 3908 // Now check the stores are compatible. 3909 if (!QStore->isUnordered() || !PStore->isUnordered() || 3910 PStore->getValueOperand()->getType() != 3911 QStore->getValueOperand()->getType()) 3912 return false; 3913 3914 // Check that sinking the store won't cause program behavior changes. Sinking 3915 // the store out of the Q blocks won't change any behavior as we're sinking 3916 // from a block to its unconditional successor. But we're moving a store from 3917 // the P blocks down through the middle block (QBI) and past both QFB and QTB. 3918 // So we need to check that there are no aliasing loads or stores in 3919 // QBI, QTB and QFB. We also need to check there are no conflicting memory 3920 // operations between PStore and the end of its parent block. 3921 // 3922 // The ideal way to do this is to query AliasAnalysis, but we don't 3923 // preserve AA currently so that is dangerous. Be super safe and just 3924 // check there are no other memory operations at all. 3925 for (auto &I : *QFB->getSinglePredecessor()) 3926 if (I.mayReadOrWriteMemory()) 3927 return false; 3928 for (auto &I : *QFB) 3929 if (&I != QStore && I.mayReadOrWriteMemory()) 3930 return false; 3931 if (QTB) 3932 for (auto &I : *QTB) 3933 if (&I != QStore && I.mayReadOrWriteMemory()) 3934 return false; 3935 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); 3936 I != E; ++I) 3937 if (&*I != PStore && I->mayReadOrWriteMemory()) 3938 return false; 3939 3940 // If we're not in aggressive mode, we only optimize if we have some 3941 // confidence that by optimizing we'll allow P and/or Q to be if-converted. 3942 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) { 3943 if (!BB) 3944 return true; 3945 // Heuristic: if the block can be if-converted/phi-folded and the 3946 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to 3947 // thread this store. 3948 InstructionCost Cost = 0; 3949 InstructionCost Budget = 3950 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 3951 for (auto &I : BB->instructionsWithoutDebug(false)) { 3952 // Consider terminator instruction to be free. 3953 if (I.isTerminator()) 3954 continue; 3955 // If this is one the stores that we want to speculate out of this BB, 3956 // then don't count it's cost, consider it to be free. 3957 if (auto *S = dyn_cast<StoreInst>(&I)) 3958 if (llvm::find(FreeStores, S)) 3959 continue; 3960 // Else, we have a white-list of instructions that we are ak speculating. 3961 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I)) 3962 return false; // Not in white-list - not worthwhile folding. 3963 // And finally, if this is a non-free instruction that we are okay 3964 // speculating, ensure that we consider the speculation budget. 3965 Cost += 3966 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 3967 if (Cost > Budget) 3968 return false; // Eagerly refuse to fold as soon as we're out of budget. 3969 } 3970 assert(Cost <= Budget && 3971 "When we run out of budget we will eagerly return from within the " 3972 "per-instruction loop."); 3973 return true; 3974 }; 3975 3976 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore}; 3977 if (!MergeCondStoresAggressively && 3978 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) || 3979 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores))) 3980 return false; 3981 3982 // If PostBB has more than two predecessors, we need to split it so we can 3983 // sink the store. 3984 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) { 3985 // We know that QFB's only successor is PostBB. And QFB has a single 3986 // predecessor. If QTB exists, then its only successor is also PostBB. 3987 // If QTB does not exist, then QFB's only predecessor has a conditional 3988 // branch to QFB and PostBB. 3989 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor(); 3990 BasicBlock *NewBB = 3991 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU); 3992 if (!NewBB) 3993 return false; 3994 PostBB = NewBB; 3995 } 3996 3997 // OK, we're going to sink the stores to PostBB. The store has to be 3998 // conditional though, so first create the predicate. 3999 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) 4000 ->getCondition(); 4001 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) 4002 ->getCondition(); 4003 4004 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), 4005 PStore->getParent()); 4006 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), 4007 QStore->getParent(), PPHI); 4008 4009 IRBuilder<> QB(&*PostBB->getFirstInsertionPt()); 4010 4011 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); 4012 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); 4013 4014 if (InvertPCond) 4015 PPred = QB.CreateNot(PPred); 4016 if (InvertQCond) 4017 QPred = QB.CreateNot(QPred); 4018 Value *CombinedPred = QB.CreateOr(PPred, QPred); 4019 4020 auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), 4021 /*Unreachable=*/false, 4022 /*BranchWeights=*/nullptr, DTU); 4023 QB.SetInsertPoint(T); 4024 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); 4025 SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata())); 4026 // Choose the minimum alignment. If we could prove both stores execute, we 4027 // could use biggest one. In this case, though, we only know that one of the 4028 // stores executes. And we don't know it's safe to take the alignment from a 4029 // store that doesn't execute. 4030 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign())); 4031 4032 QStore->eraseFromParent(); 4033 PStore->eraseFromParent(); 4034 4035 return true; 4036 } 4037 4038 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI, 4039 DomTreeUpdater *DTU, const DataLayout &DL, 4040 const TargetTransformInfo &TTI) { 4041 // The intention here is to find diamonds or triangles (see below) where each 4042 // conditional block contains a store to the same address. Both of these 4043 // stores are conditional, so they can't be unconditionally sunk. But it may 4044 // be profitable to speculatively sink the stores into one merged store at the 4045 // end, and predicate the merged store on the union of the two conditions of 4046 // PBI and QBI. 4047 // 4048 // This can reduce the number of stores executed if both of the conditions are 4049 // true, and can allow the blocks to become small enough to be if-converted. 4050 // This optimization will also chain, so that ladders of test-and-set 4051 // sequences can be if-converted away. 4052 // 4053 // We only deal with simple diamonds or triangles: 4054 // 4055 // PBI or PBI or a combination of the two 4056 // / \ | \ 4057 // PTB PFB | PFB 4058 // \ / | / 4059 // QBI QBI 4060 // / \ | \ 4061 // QTB QFB | QFB 4062 // \ / | / 4063 // PostBB PostBB 4064 // 4065 // We model triangles as a type of diamond with a nullptr "true" block. 4066 // Triangles are canonicalized so that the fallthrough edge is represented by 4067 // a true condition, as in the diagram above. 4068 BasicBlock *PTB = PBI->getSuccessor(0); 4069 BasicBlock *PFB = PBI->getSuccessor(1); 4070 BasicBlock *QTB = QBI->getSuccessor(0); 4071 BasicBlock *QFB = QBI->getSuccessor(1); 4072 BasicBlock *PostBB = QFB->getSingleSuccessor(); 4073 4074 // Make sure we have a good guess for PostBB. If QTB's only successor is 4075 // QFB, then QFB is a better PostBB. 4076 if (QTB->getSingleSuccessor() == QFB) 4077 PostBB = QFB; 4078 4079 // If we couldn't find a good PostBB, stop. 4080 if (!PostBB) 4081 return false; 4082 4083 bool InvertPCond = false, InvertQCond = false; 4084 // Canonicalize fallthroughs to the true branches. 4085 if (PFB == QBI->getParent()) { 4086 std::swap(PFB, PTB); 4087 InvertPCond = true; 4088 } 4089 if (QFB == PostBB) { 4090 std::swap(QFB, QTB); 4091 InvertQCond = true; 4092 } 4093 4094 // From this point on we can assume PTB or QTB may be fallthroughs but PFB 4095 // and QFB may not. Model fallthroughs as a nullptr block. 4096 if (PTB == QBI->getParent()) 4097 PTB = nullptr; 4098 if (QTB == PostBB) 4099 QTB = nullptr; 4100 4101 // Legality bailouts. We must have at least the non-fallthrough blocks and 4102 // the post-dominating block, and the non-fallthroughs must only have one 4103 // predecessor. 4104 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { 4105 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S; 4106 }; 4107 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || 4108 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) 4109 return false; 4110 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || 4111 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) 4112 return false; 4113 if (!QBI->getParent()->hasNUses(2)) 4114 return false; 4115 4116 // OK, this is a sequence of two diamonds or triangles. 4117 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. 4118 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses; 4119 for (auto *BB : {PTB, PFB}) { 4120 if (!BB) 4121 continue; 4122 for (auto &I : *BB) 4123 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 4124 PStoreAddresses.insert(SI->getPointerOperand()); 4125 } 4126 for (auto *BB : {QTB, QFB}) { 4127 if (!BB) 4128 continue; 4129 for (auto &I : *BB) 4130 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 4131 QStoreAddresses.insert(SI->getPointerOperand()); 4132 } 4133 4134 set_intersect(PStoreAddresses, QStoreAddresses); 4135 // set_intersect mutates PStoreAddresses in place. Rename it here to make it 4136 // clear what it contains. 4137 auto &CommonAddresses = PStoreAddresses; 4138 4139 bool Changed = false; 4140 for (auto *Address : CommonAddresses) 4141 Changed |= 4142 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address, 4143 InvertPCond, InvertQCond, DTU, DL, TTI); 4144 return Changed; 4145 } 4146 4147 /// If the previous block ended with a widenable branch, determine if reusing 4148 /// the target block is profitable and legal. This will have the effect of 4149 /// "widening" PBI, but doesn't require us to reason about hosting safety. 4150 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 4151 DomTreeUpdater *DTU) { 4152 // TODO: This can be generalized in two important ways: 4153 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input 4154 // values from the PBI edge. 4155 // 2) We can sink side effecting instructions into BI's fallthrough 4156 // successor provided they doesn't contribute to computation of 4157 // BI's condition. 4158 Value *CondWB, *WC; 4159 BasicBlock *IfTrueBB, *IfFalseBB; 4160 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) || 4161 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor()) 4162 return false; 4163 if (!IfFalseBB->phis().empty()) 4164 return false; // TODO 4165 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which 4166 // may undo the transform done here. 4167 // TODO: There might be a more fine-grained solution to this. 4168 if (!llvm::succ_empty(IfFalseBB)) 4169 return false; 4170 // Use lambda to lazily compute expensive condition after cheap ones. 4171 auto NoSideEffects = [](BasicBlock &BB) { 4172 return llvm::none_of(BB, [](const Instruction &I) { 4173 return I.mayWriteToMemory() || I.mayHaveSideEffects(); 4174 }); 4175 }; 4176 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping 4177 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability 4178 NoSideEffects(*BI->getParent())) { 4179 auto *OldSuccessor = BI->getSuccessor(1); 4180 OldSuccessor->removePredecessor(BI->getParent()); 4181 BI->setSuccessor(1, IfFalseBB); 4182 if (DTU) 4183 DTU->applyUpdates( 4184 {{DominatorTree::Insert, BI->getParent(), IfFalseBB}, 4185 {DominatorTree::Delete, BI->getParent(), OldSuccessor}}); 4186 return true; 4187 } 4188 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping 4189 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability 4190 NoSideEffects(*BI->getParent())) { 4191 auto *OldSuccessor = BI->getSuccessor(0); 4192 OldSuccessor->removePredecessor(BI->getParent()); 4193 BI->setSuccessor(0, IfFalseBB); 4194 if (DTU) 4195 DTU->applyUpdates( 4196 {{DominatorTree::Insert, BI->getParent(), IfFalseBB}, 4197 {DominatorTree::Delete, BI->getParent(), OldSuccessor}}); 4198 return true; 4199 } 4200 return false; 4201 } 4202 4203 /// If we have a conditional branch as a predecessor of another block, 4204 /// this function tries to simplify it. We know 4205 /// that PBI and BI are both conditional branches, and BI is in one of the 4206 /// successor blocks of PBI - PBI branches to BI. 4207 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 4208 DomTreeUpdater *DTU, 4209 const DataLayout &DL, 4210 const TargetTransformInfo &TTI) { 4211 assert(PBI->isConditional() && BI->isConditional()); 4212 BasicBlock *BB = BI->getParent(); 4213 4214 // If this block ends with a branch instruction, and if there is a 4215 // predecessor that ends on a branch of the same condition, make 4216 // this conditional branch redundant. 4217 if (PBI->getCondition() == BI->getCondition() && 4218 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 4219 // Okay, the outcome of this conditional branch is statically 4220 // knowable. If this block had a single pred, handle specially, otherwise 4221 // FoldCondBranchOnValueKnownInPredecessor() will handle it. 4222 if (BB->getSinglePredecessor()) { 4223 // Turn this into a branch on constant. 4224 bool CondIsTrue = PBI->getSuccessor(0) == BB; 4225 BI->setCondition( 4226 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue)); 4227 return true; // Nuke the branch on constant. 4228 } 4229 } 4230 4231 // If the previous block ended with a widenable branch, determine if reusing 4232 // the target block is profitable and legal. This will have the effect of 4233 // "widening" PBI, but doesn't require us to reason about hosting safety. 4234 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU)) 4235 return true; 4236 4237 // If both branches are conditional and both contain stores to the same 4238 // address, remove the stores from the conditionals and create a conditional 4239 // merged store at the end. 4240 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI)) 4241 return true; 4242 4243 // If this is a conditional branch in an empty block, and if any 4244 // predecessors are a conditional branch to one of our destinations, 4245 // fold the conditions into logical ops and one cond br. 4246 4247 // Ignore dbg intrinsics. 4248 if (&*BB->instructionsWithoutDebug(false).begin() != BI) 4249 return false; 4250 4251 int PBIOp, BIOp; 4252 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 4253 PBIOp = 0; 4254 BIOp = 0; 4255 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 4256 PBIOp = 0; 4257 BIOp = 1; 4258 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 4259 PBIOp = 1; 4260 BIOp = 0; 4261 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 4262 PBIOp = 1; 4263 BIOp = 1; 4264 } else { 4265 return false; 4266 } 4267 4268 // Check to make sure that the other destination of this branch 4269 // isn't BB itself. If so, this is an infinite loop that will 4270 // keep getting unwound. 4271 if (PBI->getSuccessor(PBIOp) == BB) 4272 return false; 4273 4274 // Do not perform this transformation if it would require 4275 // insertion of a large number of select instructions. For targets 4276 // without predication/cmovs, this is a big pessimization. 4277 4278 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 4279 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1); 4280 unsigned NumPhis = 0; 4281 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II); 4282 ++II, ++NumPhis) { 4283 if (NumPhis > 2) // Disable this xform. 4284 return false; 4285 } 4286 4287 // Finally, if everything is ok, fold the branches to logical ops. 4288 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 4289 4290 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 4291 << "AND: " << *BI->getParent()); 4292 4293 SmallVector<DominatorTree::UpdateType, 5> Updates; 4294 4295 // If OtherDest *is* BB, then BB is a basic block with a single conditional 4296 // branch in it, where one edge (OtherDest) goes back to itself but the other 4297 // exits. We don't *know* that the program avoids the infinite loop 4298 // (even though that seems likely). If we do this xform naively, we'll end up 4299 // recursively unpeeling the loop. Since we know that (after the xform is 4300 // done) that the block *is* infinite if reached, we just make it an obviously 4301 // infinite loop with no cond branch. 4302 if (OtherDest == BB) { 4303 // Insert it at the end of the function, because it's either code, 4304 // or it won't matter if it's hot. :) 4305 BasicBlock *InfLoopBlock = 4306 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent()); 4307 BranchInst::Create(InfLoopBlock, InfLoopBlock); 4308 if (DTU) 4309 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock}); 4310 OtherDest = InfLoopBlock; 4311 } 4312 4313 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 4314 4315 // BI may have other predecessors. Because of this, we leave 4316 // it alone, but modify PBI. 4317 4318 // Make sure we get to CommonDest on True&True directions. 4319 Value *PBICond = PBI->getCondition(); 4320 IRBuilder<NoFolder> Builder(PBI); 4321 if (PBIOp) 4322 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not"); 4323 4324 Value *BICond = BI->getCondition(); 4325 if (BIOp) 4326 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not"); 4327 4328 // Merge the conditions. 4329 Value *Cond = 4330 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge"); 4331 4332 // Modify PBI to branch on the new condition to the new dests. 4333 PBI->setCondition(Cond); 4334 PBI->setSuccessor(0, CommonDest); 4335 PBI->setSuccessor(1, OtherDest); 4336 4337 if (DTU) { 4338 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest}); 4339 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest}); 4340 4341 DTU->applyUpdates(Updates); 4342 } 4343 4344 // Update branch weight for PBI. 4345 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 4346 uint64_t PredCommon, PredOther, SuccCommon, SuccOther; 4347 bool HasWeights = 4348 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 4349 SuccTrueWeight, SuccFalseWeight); 4350 if (HasWeights) { 4351 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 4352 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 4353 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 4354 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 4355 // The weight to CommonDest should be PredCommon * SuccTotal + 4356 // PredOther * SuccCommon. 4357 // The weight to OtherDest should be PredOther * SuccOther. 4358 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + 4359 PredOther * SuccCommon, 4360 PredOther * SuccOther}; 4361 // Halve the weights if any of them cannot fit in an uint32_t 4362 FitWeights(NewWeights); 4363 4364 setBranchWeights(PBI, NewWeights[0], NewWeights[1]); 4365 } 4366 4367 // OtherDest may have phi nodes. If so, add an entry from PBI's 4368 // block that are identical to the entries for BI's block. 4369 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 4370 4371 // We know that the CommonDest already had an edge from PBI to 4372 // it. If it has PHIs though, the PHIs may have different 4373 // entries for BB and PBI's BB. If so, insert a select to make 4374 // them agree. 4375 for (PHINode &PN : CommonDest->phis()) { 4376 Value *BIV = PN.getIncomingValueForBlock(BB); 4377 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent()); 4378 Value *PBIV = PN.getIncomingValue(PBBIdx); 4379 if (BIV != PBIV) { 4380 // Insert a select in PBI to pick the right value. 4381 SelectInst *NV = cast<SelectInst>( 4382 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux")); 4383 PN.setIncomingValue(PBBIdx, NV); 4384 // Although the select has the same condition as PBI, the original branch 4385 // weights for PBI do not apply to the new select because the select's 4386 // 'logical' edges are incoming edges of the phi that is eliminated, not 4387 // the outgoing edges of PBI. 4388 if (HasWeights) { 4389 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 4390 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 4391 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 4392 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 4393 // The weight to PredCommonDest should be PredCommon * SuccTotal. 4394 // The weight to PredOtherDest should be PredOther * SuccCommon. 4395 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther), 4396 PredOther * SuccCommon}; 4397 4398 FitWeights(NewWeights); 4399 4400 setBranchWeights(NV, NewWeights[0], NewWeights[1]); 4401 } 4402 } 4403 } 4404 4405 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 4406 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 4407 4408 // This basic block is probably dead. We know it has at least 4409 // one fewer predecessor. 4410 return true; 4411 } 4412 4413 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is 4414 // true or to FalseBB if Cond is false. 4415 // Takes care of updating the successors and removing the old terminator. 4416 // Also makes sure not to introduce new successors by assuming that edges to 4417 // non-successor TrueBBs and FalseBBs aren't reachable. 4418 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm, 4419 Value *Cond, BasicBlock *TrueBB, 4420 BasicBlock *FalseBB, 4421 uint32_t TrueWeight, 4422 uint32_t FalseWeight) { 4423 auto *BB = OldTerm->getParent(); 4424 // Remove any superfluous successor edges from the CFG. 4425 // First, figure out which successors to preserve. 4426 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 4427 // successor. 4428 BasicBlock *KeepEdge1 = TrueBB; 4429 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; 4430 4431 SmallSetVector<BasicBlock *, 2> RemovedSuccessors; 4432 4433 // Then remove the rest. 4434 for (BasicBlock *Succ : successors(OldTerm)) { 4435 // Make sure only to keep exactly one copy of each edge. 4436 if (Succ == KeepEdge1) 4437 KeepEdge1 = nullptr; 4438 else if (Succ == KeepEdge2) 4439 KeepEdge2 = nullptr; 4440 else { 4441 Succ->removePredecessor(BB, 4442 /*KeepOneInputPHIs=*/true); 4443 4444 if (Succ != TrueBB && Succ != FalseBB) 4445 RemovedSuccessors.insert(Succ); 4446 } 4447 } 4448 4449 IRBuilder<> Builder(OldTerm); 4450 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 4451 4452 // Insert an appropriate new terminator. 4453 if (!KeepEdge1 && !KeepEdge2) { 4454 if (TrueBB == FalseBB) { 4455 // We were only looking for one successor, and it was present. 4456 // Create an unconditional branch to it. 4457 Builder.CreateBr(TrueBB); 4458 } else { 4459 // We found both of the successors we were looking for. 4460 // Create a conditional branch sharing the condition of the select. 4461 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 4462 if (TrueWeight != FalseWeight) 4463 setBranchWeights(NewBI, TrueWeight, FalseWeight); 4464 } 4465 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 4466 // Neither of the selected blocks were successors, so this 4467 // terminator must be unreachable. 4468 new UnreachableInst(OldTerm->getContext(), OldTerm); 4469 } else { 4470 // One of the selected values was a successor, but the other wasn't. 4471 // Insert an unconditional branch to the one that was found; 4472 // the edge to the one that wasn't must be unreachable. 4473 if (!KeepEdge1) { 4474 // Only TrueBB was found. 4475 Builder.CreateBr(TrueBB); 4476 } else { 4477 // Only FalseBB was found. 4478 Builder.CreateBr(FalseBB); 4479 } 4480 } 4481 4482 EraseTerminatorAndDCECond(OldTerm); 4483 4484 if (DTU) { 4485 SmallVector<DominatorTree::UpdateType, 2> Updates; 4486 Updates.reserve(RemovedSuccessors.size()); 4487 for (auto *RemovedSuccessor : RemovedSuccessors) 4488 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor}); 4489 DTU->applyUpdates(Updates); 4490 } 4491 4492 return true; 4493 } 4494 4495 // Replaces 4496 // (switch (select cond, X, Y)) on constant X, Y 4497 // with a branch - conditional if X and Y lead to distinct BBs, 4498 // unconditional otherwise. 4499 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI, 4500 SelectInst *Select) { 4501 // Check for constant integer values in the select. 4502 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 4503 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 4504 if (!TrueVal || !FalseVal) 4505 return false; 4506 4507 // Find the relevant condition and destinations. 4508 Value *Condition = Select->getCondition(); 4509 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor(); 4510 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor(); 4511 4512 // Get weight for TrueBB and FalseBB. 4513 uint32_t TrueWeight = 0, FalseWeight = 0; 4514 SmallVector<uint64_t, 8> Weights; 4515 bool HasWeights = hasBranchWeightMD(*SI); 4516 if (HasWeights) { 4517 GetBranchWeights(SI, Weights); 4518 if (Weights.size() == 1 + SI->getNumCases()) { 4519 TrueWeight = 4520 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()]; 4521 FalseWeight = 4522 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()]; 4523 } 4524 } 4525 4526 // Perform the actual simplification. 4527 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight, 4528 FalseWeight); 4529 } 4530 4531 // Replaces 4532 // (indirectbr (select cond, blockaddress(@fn, BlockA), 4533 // blockaddress(@fn, BlockB))) 4534 // with 4535 // (br cond, BlockA, BlockB). 4536 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, 4537 SelectInst *SI) { 4538 // Check that both operands of the select are block addresses. 4539 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 4540 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 4541 if (!TBA || !FBA) 4542 return false; 4543 4544 // Extract the actual blocks. 4545 BasicBlock *TrueBB = TBA->getBasicBlock(); 4546 BasicBlock *FalseBB = FBA->getBasicBlock(); 4547 4548 // Perform the actual simplification. 4549 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0, 4550 0); 4551 } 4552 4553 /// This is called when we find an icmp instruction 4554 /// (a seteq/setne with a constant) as the only instruction in a 4555 /// block that ends with an uncond branch. We are looking for a very specific 4556 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 4557 /// this case, we merge the first two "or's of icmp" into a switch, but then the 4558 /// default value goes to an uncond block with a seteq in it, we get something 4559 /// like: 4560 /// 4561 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 4562 /// DEFAULT: 4563 /// %tmp = icmp eq i8 %A, 92 4564 /// br label %end 4565 /// end: 4566 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 4567 /// 4568 /// We prefer to split the edge to 'end' so that there is a true/false entry to 4569 /// the PHI, merging the third icmp into the switch. 4570 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( 4571 ICmpInst *ICI, IRBuilder<> &Builder) { 4572 BasicBlock *BB = ICI->getParent(); 4573 4574 // If the block has any PHIs in it or the icmp has multiple uses, it is too 4575 // complex. 4576 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) 4577 return false; 4578 4579 Value *V = ICI->getOperand(0); 4580 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 4581 4582 // The pattern we're looking for is where our only predecessor is a switch on 4583 // 'V' and this block is the default case for the switch. In this case we can 4584 // fold the compared value into the switch to simplify things. 4585 BasicBlock *Pred = BB->getSinglePredecessor(); 4586 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) 4587 return false; 4588 4589 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 4590 if (SI->getCondition() != V) 4591 return false; 4592 4593 // If BB is reachable on a non-default case, then we simply know the value of 4594 // V in this block. Substitute it and constant fold the icmp instruction 4595 // away. 4596 if (SI->getDefaultDest() != BB) { 4597 ConstantInt *VVal = SI->findCaseDest(BB); 4598 assert(VVal && "Should have a unique destination value"); 4599 ICI->setOperand(0, VVal); 4600 4601 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) { 4602 ICI->replaceAllUsesWith(V); 4603 ICI->eraseFromParent(); 4604 } 4605 // BB is now empty, so it is likely to simplify away. 4606 return requestResimplify(); 4607 } 4608 4609 // Ok, the block is reachable from the default dest. If the constant we're 4610 // comparing exists in one of the other edges, then we can constant fold ICI 4611 // and zap it. 4612 if (SI->findCaseValue(Cst) != SI->case_default()) { 4613 Value *V; 4614 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 4615 V = ConstantInt::getFalse(BB->getContext()); 4616 else 4617 V = ConstantInt::getTrue(BB->getContext()); 4618 4619 ICI->replaceAllUsesWith(V); 4620 ICI->eraseFromParent(); 4621 // BB is now empty, so it is likely to simplify away. 4622 return requestResimplify(); 4623 } 4624 4625 // The use of the icmp has to be in the 'end' block, by the only PHI node in 4626 // the block. 4627 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 4628 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); 4629 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || 4630 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 4631 return false; 4632 4633 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 4634 // true in the PHI. 4635 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 4636 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 4637 4638 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 4639 std::swap(DefaultCst, NewCst); 4640 4641 // Replace ICI (which is used by the PHI for the default value) with true or 4642 // false depending on if it is EQ or NE. 4643 ICI->replaceAllUsesWith(DefaultCst); 4644 ICI->eraseFromParent(); 4645 4646 SmallVector<DominatorTree::UpdateType, 2> Updates; 4647 4648 // Okay, the switch goes to this block on a default value. Add an edge from 4649 // the switch to the merge point on the compared value. 4650 BasicBlock *NewBB = 4651 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB); 4652 { 4653 SwitchInstProfUpdateWrapper SIW(*SI); 4654 auto W0 = SIW.getSuccessorWeight(0); 4655 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW; 4656 if (W0) { 4657 NewW = ((uint64_t(*W0) + 1) >> 1); 4658 SIW.setSuccessorWeight(0, *NewW); 4659 } 4660 SIW.addCase(Cst, NewBB, NewW); 4661 if (DTU) 4662 Updates.push_back({DominatorTree::Insert, Pred, NewBB}); 4663 } 4664 4665 // NewBB branches to the phi block, add the uncond branch and the phi entry. 4666 Builder.SetInsertPoint(NewBB); 4667 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 4668 Builder.CreateBr(SuccBlock); 4669 PHIUse->addIncoming(NewCst, NewBB); 4670 if (DTU) { 4671 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock}); 4672 DTU->applyUpdates(Updates); 4673 } 4674 return true; 4675 } 4676 4677 /// The specified branch is a conditional branch. 4678 /// Check to see if it is branching on an or/and chain of icmp instructions, and 4679 /// fold it into a switch instruction if so. 4680 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI, 4681 IRBuilder<> &Builder, 4682 const DataLayout &DL) { 4683 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 4684 if (!Cond) 4685 return false; 4686 4687 // Change br (X == 0 | X == 1), T, F into a switch instruction. 4688 // If this is a bunch of seteq's or'd together, or if it's a bunch of 4689 // 'setne's and'ed together, collect them. 4690 4691 // Try to gather values from a chain of and/or to be turned into a switch 4692 ConstantComparesGatherer ConstantCompare(Cond, DL); 4693 // Unpack the result 4694 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals; 4695 Value *CompVal = ConstantCompare.CompValue; 4696 unsigned UsedICmps = ConstantCompare.UsedICmps; 4697 Value *ExtraCase = ConstantCompare.Extra; 4698 4699 // If we didn't have a multiply compared value, fail. 4700 if (!CompVal) 4701 return false; 4702 4703 // Avoid turning single icmps into a switch. 4704 if (UsedICmps <= 1) 4705 return false; 4706 4707 bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value())); 4708 4709 // There might be duplicate constants in the list, which the switch 4710 // instruction can't handle, remove them now. 4711 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 4712 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 4713 4714 // If Extra was used, we require at least two switch values to do the 4715 // transformation. A switch with one value is just a conditional branch. 4716 if (ExtraCase && Values.size() < 2) 4717 return false; 4718 4719 // TODO: Preserve branch weight metadata, similarly to how 4720 // FoldValueComparisonIntoPredecessors preserves it. 4721 4722 // Figure out which block is which destination. 4723 BasicBlock *DefaultBB = BI->getSuccessor(1); 4724 BasicBlock *EdgeBB = BI->getSuccessor(0); 4725 if (!TrueWhenEqual) 4726 std::swap(DefaultBB, EdgeBB); 4727 4728 BasicBlock *BB = BI->getParent(); 4729 4730 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 4731 << " cases into SWITCH. BB is:\n" 4732 << *BB); 4733 4734 SmallVector<DominatorTree::UpdateType, 2> Updates; 4735 4736 // If there are any extra values that couldn't be folded into the switch 4737 // then we evaluate them with an explicit branch first. Split the block 4738 // right before the condbr to handle it. 4739 if (ExtraCase) { 4740 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr, 4741 /*MSSAU=*/nullptr, "switch.early.test"); 4742 4743 // Remove the uncond branch added to the old block. 4744 Instruction *OldTI = BB->getTerminator(); 4745 Builder.SetInsertPoint(OldTI); 4746 4747 // There can be an unintended UB if extra values are Poison. Before the 4748 // transformation, extra values may not be evaluated according to the 4749 // condition, and it will not raise UB. But after transformation, we are 4750 // evaluating extra values before checking the condition, and it will raise 4751 // UB. It can be solved by adding freeze instruction to extra values. 4752 AssumptionCache *AC = Options.AC; 4753 4754 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr)) 4755 ExtraCase = Builder.CreateFreeze(ExtraCase); 4756 4757 if (TrueWhenEqual) 4758 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 4759 else 4760 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 4761 4762 OldTI->eraseFromParent(); 4763 4764 if (DTU) 4765 Updates.push_back({DominatorTree::Insert, BB, EdgeBB}); 4766 4767 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 4768 // for the edge we just added. 4769 AddPredecessorToBlock(EdgeBB, BB, NewBB); 4770 4771 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 4772 << "\nEXTRABB = " << *BB); 4773 BB = NewBB; 4774 } 4775 4776 Builder.SetInsertPoint(BI); 4777 // Convert pointer to int before we switch. 4778 if (CompVal->getType()->isPointerTy()) { 4779 CompVal = Builder.CreatePtrToInt( 4780 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); 4781 } 4782 4783 // Create the new switch instruction now. 4784 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 4785 4786 // Add all of the 'cases' to the switch instruction. 4787 for (unsigned i = 0, e = Values.size(); i != e; ++i) 4788 New->addCase(Values[i], EdgeBB); 4789 4790 // We added edges from PI to the EdgeBB. As such, if there were any 4791 // PHI nodes in EdgeBB, they need entries to be added corresponding to 4792 // the number of edges added. 4793 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) { 4794 PHINode *PN = cast<PHINode>(BBI); 4795 Value *InVal = PN->getIncomingValueForBlock(BB); 4796 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i) 4797 PN->addIncoming(InVal, BB); 4798 } 4799 4800 // Erase the old branch instruction. 4801 EraseTerminatorAndDCECond(BI); 4802 if (DTU) 4803 DTU->applyUpdates(Updates); 4804 4805 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 4806 return true; 4807 } 4808 4809 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 4810 if (isa<PHINode>(RI->getValue())) 4811 return simplifyCommonResume(RI); 4812 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) && 4813 RI->getValue() == RI->getParent()->getFirstNonPHI()) 4814 // The resume must unwind the exception that caused control to branch here. 4815 return simplifySingleResume(RI); 4816 4817 return false; 4818 } 4819 4820 // Check if cleanup block is empty 4821 static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) { 4822 for (Instruction &I : R) { 4823 auto *II = dyn_cast<IntrinsicInst>(&I); 4824 if (!II) 4825 return false; 4826 4827 Intrinsic::ID IntrinsicID = II->getIntrinsicID(); 4828 switch (IntrinsicID) { 4829 case Intrinsic::dbg_declare: 4830 case Intrinsic::dbg_value: 4831 case Intrinsic::dbg_label: 4832 case Intrinsic::lifetime_end: 4833 break; 4834 default: 4835 return false; 4836 } 4837 } 4838 return true; 4839 } 4840 4841 // Simplify resume that is shared by several landing pads (phi of landing pad). 4842 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) { 4843 BasicBlock *BB = RI->getParent(); 4844 4845 // Check that there are no other instructions except for debug and lifetime 4846 // intrinsics between the phi's and resume instruction. 4847 if (!isCleanupBlockEmpty( 4848 make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator()))) 4849 return false; 4850 4851 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks; 4852 auto *PhiLPInst = cast<PHINode>(RI->getValue()); 4853 4854 // Check incoming blocks to see if any of them are trivial. 4855 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End; 4856 Idx++) { 4857 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx); 4858 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx); 4859 4860 // If the block has other successors, we can not delete it because 4861 // it has other dependents. 4862 if (IncomingBB->getUniqueSuccessor() != BB) 4863 continue; 4864 4865 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI()); 4866 // Not the landing pad that caused the control to branch here. 4867 if (IncomingValue != LandingPad) 4868 continue; 4869 4870 if (isCleanupBlockEmpty( 4871 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator()))) 4872 TrivialUnwindBlocks.insert(IncomingBB); 4873 } 4874 4875 // If no trivial unwind blocks, don't do any simplifications. 4876 if (TrivialUnwindBlocks.empty()) 4877 return false; 4878 4879 // Turn all invokes that unwind here into calls. 4880 for (auto *TrivialBB : TrivialUnwindBlocks) { 4881 // Blocks that will be simplified should be removed from the phi node. 4882 // Note there could be multiple edges to the resume block, and we need 4883 // to remove them all. 4884 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1) 4885 BB->removePredecessor(TrivialBB, true); 4886 4887 for (BasicBlock *Pred : 4888 llvm::make_early_inc_range(predecessors(TrivialBB))) { 4889 removeUnwindEdge(Pred, DTU); 4890 ++NumInvokes; 4891 } 4892 4893 // In each SimplifyCFG run, only the current processed block can be erased. 4894 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead 4895 // of erasing TrivialBB, we only remove the branch to the common resume 4896 // block so that we can later erase the resume block since it has no 4897 // predecessors. 4898 TrivialBB->getTerminator()->eraseFromParent(); 4899 new UnreachableInst(RI->getContext(), TrivialBB); 4900 if (DTU) 4901 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}}); 4902 } 4903 4904 // Delete the resume block if all its predecessors have been removed. 4905 if (pred_empty(BB)) 4906 DeleteDeadBlock(BB, DTU); 4907 4908 return !TrivialUnwindBlocks.empty(); 4909 } 4910 4911 // Simplify resume that is only used by a single (non-phi) landing pad. 4912 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) { 4913 BasicBlock *BB = RI->getParent(); 4914 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI()); 4915 assert(RI->getValue() == LPInst && 4916 "Resume must unwind the exception that caused control to here"); 4917 4918 // Check that there are no other instructions except for debug intrinsics. 4919 if (!isCleanupBlockEmpty( 4920 make_range<Instruction *>(LPInst->getNextNode(), RI))) 4921 return false; 4922 4923 // Turn all invokes that unwind here into calls and delete the basic block. 4924 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) { 4925 removeUnwindEdge(Pred, DTU); 4926 ++NumInvokes; 4927 } 4928 4929 // The landingpad is now unreachable. Zap it. 4930 DeleteDeadBlock(BB, DTU); 4931 return true; 4932 } 4933 4934 static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) { 4935 // If this is a trivial cleanup pad that executes no instructions, it can be 4936 // eliminated. If the cleanup pad continues to the caller, any predecessor 4937 // that is an EH pad will be updated to continue to the caller and any 4938 // predecessor that terminates with an invoke instruction will have its invoke 4939 // instruction converted to a call instruction. If the cleanup pad being 4940 // simplified does not continue to the caller, each predecessor will be 4941 // updated to continue to the unwind destination of the cleanup pad being 4942 // simplified. 4943 BasicBlock *BB = RI->getParent(); 4944 CleanupPadInst *CPInst = RI->getCleanupPad(); 4945 if (CPInst->getParent() != BB) 4946 // This isn't an empty cleanup. 4947 return false; 4948 4949 // We cannot kill the pad if it has multiple uses. This typically arises 4950 // from unreachable basic blocks. 4951 if (!CPInst->hasOneUse()) 4952 return false; 4953 4954 // Check that there are no other instructions except for benign intrinsics. 4955 if (!isCleanupBlockEmpty( 4956 make_range<Instruction *>(CPInst->getNextNode(), RI))) 4957 return false; 4958 4959 // If the cleanup return we are simplifying unwinds to the caller, this will 4960 // set UnwindDest to nullptr. 4961 BasicBlock *UnwindDest = RI->getUnwindDest(); 4962 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr; 4963 4964 // We're about to remove BB from the control flow. Before we do, sink any 4965 // PHINodes into the unwind destination. Doing this before changing the 4966 // control flow avoids some potentially slow checks, since we can currently 4967 // be certain that UnwindDest and BB have no common predecessors (since they 4968 // are both EH pads). 4969 if (UnwindDest) { 4970 // First, go through the PHI nodes in UnwindDest and update any nodes that 4971 // reference the block we are removing 4972 for (PHINode &DestPN : UnwindDest->phis()) { 4973 int Idx = DestPN.getBasicBlockIndex(BB); 4974 // Since BB unwinds to UnwindDest, it has to be in the PHI node. 4975 assert(Idx != -1); 4976 // This PHI node has an incoming value that corresponds to a control 4977 // path through the cleanup pad we are removing. If the incoming 4978 // value is in the cleanup pad, it must be a PHINode (because we 4979 // verified above that the block is otherwise empty). Otherwise, the 4980 // value is either a constant or a value that dominates the cleanup 4981 // pad being removed. 4982 // 4983 // Because BB and UnwindDest are both EH pads, all of their 4984 // predecessors must unwind to these blocks, and since no instruction 4985 // can have multiple unwind destinations, there will be no overlap in 4986 // incoming blocks between SrcPN and DestPN. 4987 Value *SrcVal = DestPN.getIncomingValue(Idx); 4988 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); 4989 4990 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB; 4991 for (auto *Pred : predecessors(BB)) { 4992 Value *Incoming = 4993 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal; 4994 DestPN.addIncoming(Incoming, Pred); 4995 } 4996 } 4997 4998 // Sink any remaining PHI nodes directly into UnwindDest. 4999 Instruction *InsertPt = DestEHPad; 5000 for (PHINode &PN : make_early_inc_range(BB->phis())) { 5001 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB)) 5002 // If the PHI node has no uses or all of its uses are in this basic 5003 // block (meaning they are debug or lifetime intrinsics), just leave 5004 // it. It will be erased when we erase BB below. 5005 continue; 5006 5007 // Otherwise, sink this PHI node into UnwindDest. 5008 // Any predecessors to UnwindDest which are not already represented 5009 // must be back edges which inherit the value from the path through 5010 // BB. In this case, the PHI value must reference itself. 5011 for (auto *pred : predecessors(UnwindDest)) 5012 if (pred != BB) 5013 PN.addIncoming(&PN, pred); 5014 PN.moveBefore(InsertPt); 5015 // Also, add a dummy incoming value for the original BB itself, 5016 // so that the PHI is well-formed until we drop said predecessor. 5017 PN.addIncoming(PoisonValue::get(PN.getType()), BB); 5018 } 5019 } 5020 5021 std::vector<DominatorTree::UpdateType> Updates; 5022 5023 // We use make_early_inc_range here because we will remove all predecessors. 5024 for (BasicBlock *PredBB : llvm::make_early_inc_range(predecessors(BB))) { 5025 if (UnwindDest == nullptr) { 5026 if (DTU) { 5027 DTU->applyUpdates(Updates); 5028 Updates.clear(); 5029 } 5030 removeUnwindEdge(PredBB, DTU); 5031 ++NumInvokes; 5032 } else { 5033 BB->removePredecessor(PredBB); 5034 Instruction *TI = PredBB->getTerminator(); 5035 TI->replaceUsesOfWith(BB, UnwindDest); 5036 if (DTU) { 5037 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest}); 5038 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 5039 } 5040 } 5041 } 5042 5043 if (DTU) 5044 DTU->applyUpdates(Updates); 5045 5046 DeleteDeadBlock(BB, DTU); 5047 5048 return true; 5049 } 5050 5051 // Try to merge two cleanuppads together. 5052 static bool mergeCleanupPad(CleanupReturnInst *RI) { 5053 // Skip any cleanuprets which unwind to caller, there is nothing to merge 5054 // with. 5055 BasicBlock *UnwindDest = RI->getUnwindDest(); 5056 if (!UnwindDest) 5057 return false; 5058 5059 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't 5060 // be safe to merge without code duplication. 5061 if (UnwindDest->getSinglePredecessor() != RI->getParent()) 5062 return false; 5063 5064 // Verify that our cleanuppad's unwind destination is another cleanuppad. 5065 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front()); 5066 if (!SuccessorCleanupPad) 5067 return false; 5068 5069 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad(); 5070 // Replace any uses of the successor cleanupad with the predecessor pad 5071 // The only cleanuppad uses should be this cleanupret, it's cleanupret and 5072 // funclet bundle operands. 5073 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad); 5074 // Remove the old cleanuppad. 5075 SuccessorCleanupPad->eraseFromParent(); 5076 // Now, we simply replace the cleanupret with a branch to the unwind 5077 // destination. 5078 BranchInst::Create(UnwindDest, RI->getParent()); 5079 RI->eraseFromParent(); 5080 5081 return true; 5082 } 5083 5084 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) { 5085 // It is possible to transiantly have an undef cleanuppad operand because we 5086 // have deleted some, but not all, dead blocks. 5087 // Eventually, this block will be deleted. 5088 if (isa<UndefValue>(RI->getOperand(0))) 5089 return false; 5090 5091 if (mergeCleanupPad(RI)) 5092 return true; 5093 5094 if (removeEmptyCleanup(RI, DTU)) 5095 return true; 5096 5097 return false; 5098 } 5099 5100 // WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()! 5101 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) { 5102 BasicBlock *BB = UI->getParent(); 5103 5104 bool Changed = false; 5105 5106 // If there are any instructions immediately before the unreachable that can 5107 // be removed, do so. 5108 while (UI->getIterator() != BB->begin()) { 5109 BasicBlock::iterator BBI = UI->getIterator(); 5110 --BBI; 5111 5112 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI)) 5113 break; // Can not drop any more instructions. We're done here. 5114 // Otherwise, this instruction can be freely erased, 5115 // even if it is not side-effect free. 5116 5117 // Note that deleting EH's here is in fact okay, although it involves a bit 5118 // of subtle reasoning. If this inst is an EH, all the predecessors of this 5119 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn, 5120 // and we can therefore guarantee this block will be erased. 5121 5122 // Delete this instruction (any uses are guaranteed to be dead) 5123 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType())); 5124 BBI->eraseFromParent(); 5125 Changed = true; 5126 } 5127 5128 // If the unreachable instruction is the first in the block, take a gander 5129 // at all of the predecessors of this instruction, and simplify them. 5130 if (&BB->front() != UI) 5131 return Changed; 5132 5133 std::vector<DominatorTree::UpdateType> Updates; 5134 5135 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB)); 5136 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 5137 auto *Predecessor = Preds[i]; 5138 Instruction *TI = Predecessor->getTerminator(); 5139 IRBuilder<> Builder(TI); 5140 if (auto *BI = dyn_cast<BranchInst>(TI)) { 5141 // We could either have a proper unconditional branch, 5142 // or a degenerate conditional branch with matching destinations. 5143 if (all_of(BI->successors(), 5144 [BB](auto *Successor) { return Successor == BB; })) { 5145 new UnreachableInst(TI->getContext(), TI); 5146 TI->eraseFromParent(); 5147 Changed = true; 5148 } else { 5149 assert(BI->isConditional() && "Can't get here with an uncond branch."); 5150 Value* Cond = BI->getCondition(); 5151 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 5152 "The destinations are guaranteed to be different here."); 5153 if (BI->getSuccessor(0) == BB) { 5154 Builder.CreateAssumption(Builder.CreateNot(Cond)); 5155 Builder.CreateBr(BI->getSuccessor(1)); 5156 } else { 5157 assert(BI->getSuccessor(1) == BB && "Incorrect CFG"); 5158 Builder.CreateAssumption(Cond); 5159 Builder.CreateBr(BI->getSuccessor(0)); 5160 } 5161 EraseTerminatorAndDCECond(BI); 5162 Changed = true; 5163 } 5164 if (DTU) 5165 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 5166 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { 5167 SwitchInstProfUpdateWrapper SU(*SI); 5168 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) { 5169 if (i->getCaseSuccessor() != BB) { 5170 ++i; 5171 continue; 5172 } 5173 BB->removePredecessor(SU->getParent()); 5174 i = SU.removeCase(i); 5175 e = SU->case_end(); 5176 Changed = true; 5177 } 5178 // Note that the default destination can't be removed! 5179 if (DTU && SI->getDefaultDest() != BB) 5180 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 5181 } else if (auto *II = dyn_cast<InvokeInst>(TI)) { 5182 if (II->getUnwindDest() == BB) { 5183 if (DTU) { 5184 DTU->applyUpdates(Updates); 5185 Updates.clear(); 5186 } 5187 auto *CI = cast<CallInst>(removeUnwindEdge(TI->getParent(), DTU)); 5188 if (!CI->doesNotThrow()) 5189 CI->setDoesNotThrow(); 5190 Changed = true; 5191 } 5192 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 5193 if (CSI->getUnwindDest() == BB) { 5194 if (DTU) { 5195 DTU->applyUpdates(Updates); 5196 Updates.clear(); 5197 } 5198 removeUnwindEdge(TI->getParent(), DTU); 5199 Changed = true; 5200 continue; 5201 } 5202 5203 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(), 5204 E = CSI->handler_end(); 5205 I != E; ++I) { 5206 if (*I == BB) { 5207 CSI->removeHandler(I); 5208 --I; 5209 --E; 5210 Changed = true; 5211 } 5212 } 5213 if (DTU) 5214 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 5215 if (CSI->getNumHandlers() == 0) { 5216 if (CSI->hasUnwindDest()) { 5217 // Redirect all predecessors of the block containing CatchSwitchInst 5218 // to instead branch to the CatchSwitchInst's unwind destination. 5219 if (DTU) { 5220 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) { 5221 Updates.push_back({DominatorTree::Insert, 5222 PredecessorOfPredecessor, 5223 CSI->getUnwindDest()}); 5224 Updates.push_back({DominatorTree::Delete, 5225 PredecessorOfPredecessor, Predecessor}); 5226 } 5227 } 5228 Predecessor->replaceAllUsesWith(CSI->getUnwindDest()); 5229 } else { 5230 // Rewrite all preds to unwind to caller (or from invoke to call). 5231 if (DTU) { 5232 DTU->applyUpdates(Updates); 5233 Updates.clear(); 5234 } 5235 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor)); 5236 for (BasicBlock *EHPred : EHPreds) 5237 removeUnwindEdge(EHPred, DTU); 5238 } 5239 // The catchswitch is no longer reachable. 5240 new UnreachableInst(CSI->getContext(), CSI); 5241 CSI->eraseFromParent(); 5242 Changed = true; 5243 } 5244 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 5245 (void)CRI; 5246 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB && 5247 "Expected to always have an unwind to BB."); 5248 if (DTU) 5249 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 5250 new UnreachableInst(TI->getContext(), TI); 5251 TI->eraseFromParent(); 5252 Changed = true; 5253 } 5254 } 5255 5256 if (DTU) 5257 DTU->applyUpdates(Updates); 5258 5259 // If this block is now dead, remove it. 5260 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) { 5261 DeleteDeadBlock(BB, DTU); 5262 return true; 5263 } 5264 5265 return Changed; 5266 } 5267 5268 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { 5269 assert(Cases.size() >= 1); 5270 5271 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 5272 for (size_t I = 1, E = Cases.size(); I != E; ++I) { 5273 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) 5274 return false; 5275 } 5276 return true; 5277 } 5278 5279 static void createUnreachableSwitchDefault(SwitchInst *Switch, 5280 DomTreeUpdater *DTU) { 5281 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); 5282 auto *BB = Switch->getParent(); 5283 auto *OrigDefaultBlock = Switch->getDefaultDest(); 5284 OrigDefaultBlock->removePredecessor(BB); 5285 BasicBlock *NewDefaultBlock = BasicBlock::Create( 5286 BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(), 5287 OrigDefaultBlock); 5288 new UnreachableInst(Switch->getContext(), NewDefaultBlock); 5289 Switch->setDefaultDest(&*NewDefaultBlock); 5290 if (DTU) { 5291 SmallVector<DominatorTree::UpdateType, 2> Updates; 5292 Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock}); 5293 if (!is_contained(successors(BB), OrigDefaultBlock)) 5294 Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock}); 5295 DTU->applyUpdates(Updates); 5296 } 5297 } 5298 5299 /// Turn a switch into an integer range comparison and branch. 5300 /// Switches with more than 2 destinations are ignored. 5301 /// Switches with 1 destination are also ignored. 5302 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI, 5303 IRBuilder<> &Builder) { 5304 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 5305 5306 bool HasDefault = 5307 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 5308 5309 auto *BB = SI->getParent(); 5310 5311 // Partition the cases into two sets with different destinations. 5312 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; 5313 BasicBlock *DestB = nullptr; 5314 SmallVector<ConstantInt *, 16> CasesA; 5315 SmallVector<ConstantInt *, 16> CasesB; 5316 5317 for (auto Case : SI->cases()) { 5318 BasicBlock *Dest = Case.getCaseSuccessor(); 5319 if (!DestA) 5320 DestA = Dest; 5321 if (Dest == DestA) { 5322 CasesA.push_back(Case.getCaseValue()); 5323 continue; 5324 } 5325 if (!DestB) 5326 DestB = Dest; 5327 if (Dest == DestB) { 5328 CasesB.push_back(Case.getCaseValue()); 5329 continue; 5330 } 5331 return false; // More than two destinations. 5332 } 5333 if (!DestB) 5334 return false; // All destinations are the same and the default is unreachable 5335 5336 assert(DestA && DestB && 5337 "Single-destination switch should have been folded."); 5338 assert(DestA != DestB); 5339 assert(DestB != SI->getDefaultDest()); 5340 assert(!CasesB.empty() && "There must be non-default cases."); 5341 assert(!CasesA.empty() || HasDefault); 5342 5343 // Figure out if one of the sets of cases form a contiguous range. 5344 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; 5345 BasicBlock *ContiguousDest = nullptr; 5346 BasicBlock *OtherDest = nullptr; 5347 if (!CasesA.empty() && CasesAreContiguous(CasesA)) { 5348 ContiguousCases = &CasesA; 5349 ContiguousDest = DestA; 5350 OtherDest = DestB; 5351 } else if (CasesAreContiguous(CasesB)) { 5352 ContiguousCases = &CasesB; 5353 ContiguousDest = DestB; 5354 OtherDest = DestA; 5355 } else 5356 return false; 5357 5358 // Start building the compare and branch. 5359 5360 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); 5361 Constant *NumCases = 5362 ConstantInt::get(Offset->getType(), ContiguousCases->size()); 5363 5364 Value *Sub = SI->getCondition(); 5365 if (!Offset->isNullValue()) 5366 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); 5367 5368 Value *Cmp; 5369 // If NumCases overflowed, then all possible values jump to the successor. 5370 if (NumCases->isNullValue() && !ContiguousCases->empty()) 5371 Cmp = ConstantInt::getTrue(SI->getContext()); 5372 else 5373 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 5374 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); 5375 5376 // Update weight for the newly-created conditional branch. 5377 if (hasBranchWeightMD(*SI)) { 5378 SmallVector<uint64_t, 8> Weights; 5379 GetBranchWeights(SI, Weights); 5380 if (Weights.size() == 1 + SI->getNumCases()) { 5381 uint64_t TrueWeight = 0; 5382 uint64_t FalseWeight = 0; 5383 for (size_t I = 0, E = Weights.size(); I != E; ++I) { 5384 if (SI->getSuccessor(I) == ContiguousDest) 5385 TrueWeight += Weights[I]; 5386 else 5387 FalseWeight += Weights[I]; 5388 } 5389 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { 5390 TrueWeight /= 2; 5391 FalseWeight /= 2; 5392 } 5393 setBranchWeights(NewBI, TrueWeight, FalseWeight); 5394 } 5395 } 5396 5397 // Prune obsolete incoming values off the successors' PHI nodes. 5398 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { 5399 unsigned PreviousEdges = ContiguousCases->size(); 5400 if (ContiguousDest == SI->getDefaultDest()) 5401 ++PreviousEdges; 5402 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 5403 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 5404 } 5405 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { 5406 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); 5407 if (OtherDest == SI->getDefaultDest()) 5408 ++PreviousEdges; 5409 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 5410 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 5411 } 5412 5413 // Clean up the default block - it may have phis or other instructions before 5414 // the unreachable terminator. 5415 if (!HasDefault) 5416 createUnreachableSwitchDefault(SI, DTU); 5417 5418 auto *UnreachableDefault = SI->getDefaultDest(); 5419 5420 // Drop the switch. 5421 SI->eraseFromParent(); 5422 5423 if (!HasDefault && DTU) 5424 DTU->applyUpdates({{DominatorTree::Delete, BB, UnreachableDefault}}); 5425 5426 return true; 5427 } 5428 5429 /// Compute masked bits for the condition of a switch 5430 /// and use it to remove dead cases. 5431 static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU, 5432 AssumptionCache *AC, 5433 const DataLayout &DL) { 5434 Value *Cond = SI->getCondition(); 5435 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI); 5436 5437 // We can also eliminate cases by determining that their values are outside of 5438 // the limited range of the condition based on how many significant (non-sign) 5439 // bits are in the condition value. 5440 unsigned MaxSignificantBitsInCond = 5441 ComputeMaxSignificantBits(Cond, DL, 0, AC, SI); 5442 5443 // Gather dead cases. 5444 SmallVector<ConstantInt *, 8> DeadCases; 5445 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases; 5446 SmallVector<BasicBlock *, 8> UniqueSuccessors; 5447 for (const auto &Case : SI->cases()) { 5448 auto *Successor = Case.getCaseSuccessor(); 5449 if (DTU) { 5450 if (!NumPerSuccessorCases.count(Successor)) 5451 UniqueSuccessors.push_back(Successor); 5452 ++NumPerSuccessorCases[Successor]; 5453 } 5454 const APInt &CaseVal = Case.getCaseValue()->getValue(); 5455 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) || 5456 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) { 5457 DeadCases.push_back(Case.getCaseValue()); 5458 if (DTU) 5459 --NumPerSuccessorCases[Successor]; 5460 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal 5461 << " is dead.\n"); 5462 } 5463 } 5464 5465 // If we can prove that the cases must cover all possible values, the 5466 // default destination becomes dead and we can remove it. If we know some 5467 // of the bits in the value, we can use that to more precisely compute the 5468 // number of possible unique case values. 5469 bool HasDefault = 5470 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 5471 const unsigned NumUnknownBits = 5472 Known.getBitWidth() - (Known.Zero | Known.One).countPopulation(); 5473 assert(NumUnknownBits <= Known.getBitWidth()); 5474 if (HasDefault && DeadCases.empty() && 5475 NumUnknownBits < 64 /* avoid overflow */ && 5476 SI->getNumCases() == (1ULL << NumUnknownBits)) { 5477 createUnreachableSwitchDefault(SI, DTU); 5478 return true; 5479 } 5480 5481 if (DeadCases.empty()) 5482 return false; 5483 5484 SwitchInstProfUpdateWrapper SIW(*SI); 5485 for (ConstantInt *DeadCase : DeadCases) { 5486 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase); 5487 assert(CaseI != SI->case_default() && 5488 "Case was not found. Probably mistake in DeadCases forming."); 5489 // Prune unused values from PHI nodes. 5490 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent()); 5491 SIW.removeCase(CaseI); 5492 } 5493 5494 if (DTU) { 5495 std::vector<DominatorTree::UpdateType> Updates; 5496 for (auto *Successor : UniqueSuccessors) 5497 if (NumPerSuccessorCases[Successor] == 0) 5498 Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor}); 5499 DTU->applyUpdates(Updates); 5500 } 5501 5502 return true; 5503 } 5504 5505 /// If BB would be eligible for simplification by 5506 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 5507 /// by an unconditional branch), look at the phi node for BB in the successor 5508 /// block and see if the incoming value is equal to CaseValue. If so, return 5509 /// the phi node, and set PhiIndex to BB's index in the phi node. 5510 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 5511 BasicBlock *BB, int *PhiIndex) { 5512 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 5513 return nullptr; // BB must be empty to be a candidate for simplification. 5514 if (!BB->getSinglePredecessor()) 5515 return nullptr; // BB must be dominated by the switch. 5516 5517 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 5518 if (!Branch || !Branch->isUnconditional()) 5519 return nullptr; // Terminator must be unconditional branch. 5520 5521 BasicBlock *Succ = Branch->getSuccessor(0); 5522 5523 for (PHINode &PHI : Succ->phis()) { 5524 int Idx = PHI.getBasicBlockIndex(BB); 5525 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 5526 5527 Value *InValue = PHI.getIncomingValue(Idx); 5528 if (InValue != CaseValue) 5529 continue; 5530 5531 *PhiIndex = Idx; 5532 return &PHI; 5533 } 5534 5535 return nullptr; 5536 } 5537 5538 /// Try to forward the condition of a switch instruction to a phi node 5539 /// dominated by the switch, if that would mean that some of the destination 5540 /// blocks of the switch can be folded away. Return true if a change is made. 5541 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 5542 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>; 5543 5544 ForwardingNodesMap ForwardingNodes; 5545 BasicBlock *SwitchBlock = SI->getParent(); 5546 bool Changed = false; 5547 for (const auto &Case : SI->cases()) { 5548 ConstantInt *CaseValue = Case.getCaseValue(); 5549 BasicBlock *CaseDest = Case.getCaseSuccessor(); 5550 5551 // Replace phi operands in successor blocks that are using the constant case 5552 // value rather than the switch condition variable: 5553 // switchbb: 5554 // switch i32 %x, label %default [ 5555 // i32 17, label %succ 5556 // ... 5557 // succ: 5558 // %r = phi i32 ... [ 17, %switchbb ] ... 5559 // --> 5560 // %r = phi i32 ... [ %x, %switchbb ] ... 5561 5562 for (PHINode &Phi : CaseDest->phis()) { 5563 // This only works if there is exactly 1 incoming edge from the switch to 5564 // a phi. If there is >1, that means multiple cases of the switch map to 1 5565 // value in the phi, and that phi value is not the switch condition. Thus, 5566 // this transform would not make sense (the phi would be invalid because 5567 // a phi can't have different incoming values from the same block). 5568 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock); 5569 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue && 5570 count(Phi.blocks(), SwitchBlock) == 1) { 5571 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition()); 5572 Changed = true; 5573 } 5574 } 5575 5576 // Collect phi nodes that are indirectly using this switch's case constants. 5577 int PhiIdx; 5578 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx)) 5579 ForwardingNodes[Phi].push_back(PhiIdx); 5580 } 5581 5582 for (auto &ForwardingNode : ForwardingNodes) { 5583 PHINode *Phi = ForwardingNode.first; 5584 SmallVectorImpl<int> &Indexes = ForwardingNode.second; 5585 if (Indexes.size() < 2) 5586 continue; 5587 5588 for (int Index : Indexes) 5589 Phi->setIncomingValue(Index, SI->getCondition()); 5590 Changed = true; 5591 } 5592 5593 return Changed; 5594 } 5595 5596 /// Return true if the backend will be able to handle 5597 /// initializing an array of constants like C. 5598 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) { 5599 if (C->isThreadDependent()) 5600 return false; 5601 if (C->isDLLImportDependent()) 5602 return false; 5603 5604 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) && 5605 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) && 5606 !isa<UndefValue>(C) && !isa<ConstantExpr>(C)) 5607 return false; 5608 5609 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 5610 // Pointer casts and in-bounds GEPs will not prohibit the backend from 5611 // materializing the array of constants. 5612 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets()); 5613 if (StrippedC == C || !ValidLookupTableConstant(StrippedC, TTI)) 5614 return false; 5615 } 5616 5617 if (!TTI.shouldBuildLookupTablesForConstant(C)) 5618 return false; 5619 5620 return true; 5621 } 5622 5623 /// If V is a Constant, return it. Otherwise, try to look up 5624 /// its constant value in ConstantPool, returning 0 if it's not there. 5625 static Constant * 5626 LookupConstant(Value *V, 5627 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 5628 if (Constant *C = dyn_cast<Constant>(V)) 5629 return C; 5630 return ConstantPool.lookup(V); 5631 } 5632 5633 /// Try to fold instruction I into a constant. This works for 5634 /// simple instructions such as binary operations where both operands are 5635 /// constant or can be replaced by constants from the ConstantPool. Returns the 5636 /// resulting constant on success, 0 otherwise. 5637 static Constant * 5638 ConstantFold(Instruction *I, const DataLayout &DL, 5639 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 5640 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 5641 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 5642 if (!A) 5643 return nullptr; 5644 if (A->isAllOnesValue()) 5645 return LookupConstant(Select->getTrueValue(), ConstantPool); 5646 if (A->isNullValue()) 5647 return LookupConstant(Select->getFalseValue(), ConstantPool); 5648 return nullptr; 5649 } 5650 5651 SmallVector<Constant *, 4> COps; 5652 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { 5653 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) 5654 COps.push_back(A); 5655 else 5656 return nullptr; 5657 } 5658 5659 return ConstantFoldInstOperands(I, COps, DL); 5660 } 5661 5662 /// Try to determine the resulting constant values in phi nodes 5663 /// at the common destination basic block, *CommonDest, for one of the case 5664 /// destionations CaseDest corresponding to value CaseVal (0 for the default 5665 /// case), of a switch instruction SI. 5666 static bool 5667 getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, 5668 BasicBlock **CommonDest, 5669 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, 5670 const DataLayout &DL, const TargetTransformInfo &TTI) { 5671 // The block from which we enter the common destination. 5672 BasicBlock *Pred = SI->getParent(); 5673 5674 // If CaseDest is empty except for some side-effect free instructions through 5675 // which we can constant-propagate the CaseVal, continue to its successor. 5676 SmallDenseMap<Value *, Constant *> ConstantPool; 5677 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 5678 for (Instruction &I : CaseDest->instructionsWithoutDebug(false)) { 5679 if (I.isTerminator()) { 5680 // If the terminator is a simple branch, continue to the next block. 5681 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator()) 5682 return false; 5683 Pred = CaseDest; 5684 CaseDest = I.getSuccessor(0); 5685 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) { 5686 // Instruction is side-effect free and constant. 5687 5688 // If the instruction has uses outside this block or a phi node slot for 5689 // the block, it is not safe to bypass the instruction since it would then 5690 // no longer dominate all its uses. 5691 for (auto &Use : I.uses()) { 5692 User *User = Use.getUser(); 5693 if (Instruction *I = dyn_cast<Instruction>(User)) 5694 if (I->getParent() == CaseDest) 5695 continue; 5696 if (PHINode *Phi = dyn_cast<PHINode>(User)) 5697 if (Phi->getIncomingBlock(Use) == CaseDest) 5698 continue; 5699 return false; 5700 } 5701 5702 ConstantPool.insert(std::make_pair(&I, C)); 5703 } else { 5704 break; 5705 } 5706 } 5707 5708 // If we did not have a CommonDest before, use the current one. 5709 if (!*CommonDest) 5710 *CommonDest = CaseDest; 5711 // If the destination isn't the common one, abort. 5712 if (CaseDest != *CommonDest) 5713 return false; 5714 5715 // Get the values for this case from phi nodes in the destination block. 5716 for (PHINode &PHI : (*CommonDest)->phis()) { 5717 int Idx = PHI.getBasicBlockIndex(Pred); 5718 if (Idx == -1) 5719 continue; 5720 5721 Constant *ConstVal = 5722 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool); 5723 if (!ConstVal) 5724 return false; 5725 5726 // Be conservative about which kinds of constants we support. 5727 if (!ValidLookupTableConstant(ConstVal, TTI)) 5728 return false; 5729 5730 Res.push_back(std::make_pair(&PHI, ConstVal)); 5731 } 5732 5733 return Res.size() > 0; 5734 } 5735 5736 // Helper function used to add CaseVal to the list of cases that generate 5737 // Result. Returns the updated number of cases that generate this result. 5738 static size_t mapCaseToResult(ConstantInt *CaseVal, 5739 SwitchCaseResultVectorTy &UniqueResults, 5740 Constant *Result) { 5741 for (auto &I : UniqueResults) { 5742 if (I.first == Result) { 5743 I.second.push_back(CaseVal); 5744 return I.second.size(); 5745 } 5746 } 5747 UniqueResults.push_back( 5748 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal))); 5749 return 1; 5750 } 5751 5752 // Helper function that initializes a map containing 5753 // results for the PHI node of the common destination block for a switch 5754 // instruction. Returns false if multiple PHI nodes have been found or if 5755 // there is not a common destination block for the switch. 5756 static bool initializeUniqueCases(SwitchInst *SI, PHINode *&PHI, 5757 BasicBlock *&CommonDest, 5758 SwitchCaseResultVectorTy &UniqueResults, 5759 Constant *&DefaultResult, 5760 const DataLayout &DL, 5761 const TargetTransformInfo &TTI, 5762 uintptr_t MaxUniqueResults) { 5763 for (const auto &I : SI->cases()) { 5764 ConstantInt *CaseVal = I.getCaseValue(); 5765 5766 // Resulting value at phi nodes for this case value. 5767 SwitchCaseResultsTy Results; 5768 if (!getCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, 5769 DL, TTI)) 5770 return false; 5771 5772 // Only one value per case is permitted. 5773 if (Results.size() > 1) 5774 return false; 5775 5776 // Add the case->result mapping to UniqueResults. 5777 const size_t NumCasesForResult = 5778 mapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); 5779 5780 // Early out if there are too many cases for this result. 5781 if (NumCasesForResult > MaxSwitchCasesPerResult) 5782 return false; 5783 5784 // Early out if there are too many unique results. 5785 if (UniqueResults.size() > MaxUniqueResults) 5786 return false; 5787 5788 // Check the PHI consistency. 5789 if (!PHI) 5790 PHI = Results[0].first; 5791 else if (PHI != Results[0].first) 5792 return false; 5793 } 5794 // Find the default result value. 5795 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; 5796 BasicBlock *DefaultDest = SI->getDefaultDest(); 5797 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, 5798 DL, TTI); 5799 // If the default value is not found abort unless the default destination 5800 // is unreachable. 5801 DefaultResult = 5802 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; 5803 if ((!DefaultResult && 5804 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) 5805 return false; 5806 5807 return true; 5808 } 5809 5810 // Helper function that checks if it is possible to transform a switch with only 5811 // two cases (or two cases + default) that produces a result into a select. 5812 // TODO: Handle switches with more than 2 cases that map to the same result. 5813 static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector, 5814 Constant *DefaultResult, Value *Condition, 5815 IRBuilder<> &Builder) { 5816 // If we are selecting between only two cases transform into a simple 5817 // select or a two-way select if default is possible. 5818 // Example: 5819 // switch (a) { %0 = icmp eq i32 %a, 10 5820 // case 10: return 42; %1 = select i1 %0, i32 42, i32 4 5821 // case 20: return 2; ----> %2 = icmp eq i32 %a, 20 5822 // default: return 4; %3 = select i1 %2, i32 2, i32 %1 5823 // } 5824 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 && 5825 ResultVector[1].second.size() == 1) { 5826 ConstantInt *FirstCase = ResultVector[0].second[0]; 5827 ConstantInt *SecondCase = ResultVector[1].second[0]; 5828 Value *SelectValue = ResultVector[1].first; 5829 if (DefaultResult) { 5830 Value *ValueCompare = 5831 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); 5832 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, 5833 DefaultResult, "switch.select"); 5834 } 5835 Value *ValueCompare = 5836 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); 5837 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, 5838 SelectValue, "switch.select"); 5839 } 5840 5841 // Handle the degenerate case where two cases have the same result value. 5842 if (ResultVector.size() == 1 && DefaultResult) { 5843 ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second; 5844 unsigned CaseCount = CaseValues.size(); 5845 // n bits group cases map to the same result: 5846 // case 0,4 -> Cond & 0b1..1011 == 0 ? result : default 5847 // case 0,2,4,6 -> Cond & 0b1..1001 == 0 ? result : default 5848 // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default 5849 if (isPowerOf2_32(CaseCount)) { 5850 ConstantInt *MinCaseVal = CaseValues[0]; 5851 // Find mininal value. 5852 for (auto *Case : CaseValues) 5853 if (Case->getValue().slt(MinCaseVal->getValue())) 5854 MinCaseVal = Case; 5855 5856 // Mark the bits case number touched. 5857 APInt BitMask = APInt::getZero(MinCaseVal->getBitWidth()); 5858 for (auto *Case : CaseValues) 5859 BitMask |= (Case->getValue() - MinCaseVal->getValue()); 5860 5861 // Check if cases with the same result can cover all number 5862 // in touched bits. 5863 if (BitMask.countPopulation() == Log2_32(CaseCount)) { 5864 if (!MinCaseVal->isNullValue()) 5865 Condition = Builder.CreateSub(Condition, MinCaseVal); 5866 Value *And = Builder.CreateAnd(Condition, ~BitMask, "switch.and"); 5867 Value *Cmp = Builder.CreateICmpEQ( 5868 And, Constant::getNullValue(And->getType()), "switch.selectcmp"); 5869 return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult); 5870 } 5871 } 5872 5873 // Handle the degenerate case where two cases have the same value. 5874 if (CaseValues.size() == 2) { 5875 Value *Cmp1 = Builder.CreateICmpEQ(Condition, CaseValues[0], 5876 "switch.selectcmp.case1"); 5877 Value *Cmp2 = Builder.CreateICmpEQ(Condition, CaseValues[1], 5878 "switch.selectcmp.case2"); 5879 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp"); 5880 return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult); 5881 } 5882 } 5883 5884 return nullptr; 5885 } 5886 5887 // Helper function to cleanup a switch instruction that has been converted into 5888 // a select, fixing up PHI nodes and basic blocks. 5889 static void removeSwitchAfterSelectFold(SwitchInst *SI, PHINode *PHI, 5890 Value *SelectValue, 5891 IRBuilder<> &Builder, 5892 DomTreeUpdater *DTU) { 5893 std::vector<DominatorTree::UpdateType> Updates; 5894 5895 BasicBlock *SelectBB = SI->getParent(); 5896 BasicBlock *DestBB = PHI->getParent(); 5897 5898 if (DTU && !is_contained(predecessors(DestBB), SelectBB)) 5899 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB}); 5900 Builder.CreateBr(DestBB); 5901 5902 // Remove the switch. 5903 5904 while (PHI->getBasicBlockIndex(SelectBB) >= 0) 5905 PHI->removeIncomingValue(SelectBB); 5906 PHI->addIncoming(SelectValue, SelectBB); 5907 5908 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors; 5909 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5910 BasicBlock *Succ = SI->getSuccessor(i); 5911 5912 if (Succ == DestBB) 5913 continue; 5914 Succ->removePredecessor(SelectBB); 5915 if (DTU && RemovedSuccessors.insert(Succ).second) 5916 Updates.push_back({DominatorTree::Delete, SelectBB, Succ}); 5917 } 5918 SI->eraseFromParent(); 5919 if (DTU) 5920 DTU->applyUpdates(Updates); 5921 } 5922 5923 /// If a switch is only used to initialize one or more phi nodes in a common 5924 /// successor block with only two different constant values, try to replace the 5925 /// switch with a select. Returns true if the fold was made. 5926 static bool trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, 5927 DomTreeUpdater *DTU, const DataLayout &DL, 5928 const TargetTransformInfo &TTI) { 5929 Value *const Cond = SI->getCondition(); 5930 PHINode *PHI = nullptr; 5931 BasicBlock *CommonDest = nullptr; 5932 Constant *DefaultResult; 5933 SwitchCaseResultVectorTy UniqueResults; 5934 // Collect all the cases that will deliver the same value from the switch. 5935 if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, 5936 DL, TTI, /*MaxUniqueResults*/ 2)) 5937 return false; 5938 5939 assert(PHI != nullptr && "PHI for value select not found"); 5940 Builder.SetInsertPoint(SI); 5941 Value *SelectValue = 5942 foldSwitchToSelect(UniqueResults, DefaultResult, Cond, Builder); 5943 if (!SelectValue) 5944 return false; 5945 5946 removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU); 5947 return true; 5948 } 5949 5950 namespace { 5951 5952 /// This class represents a lookup table that can be used to replace a switch. 5953 class SwitchLookupTable { 5954 public: 5955 /// Create a lookup table to use as a switch replacement with the contents 5956 /// of Values, using DefaultValue to fill any holes in the table. 5957 SwitchLookupTable( 5958 Module &M, uint64_t TableSize, ConstantInt *Offset, 5959 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5960 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName); 5961 5962 /// Build instructions with Builder to retrieve the value at 5963 /// the position given by Index in the lookup table. 5964 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 5965 5966 /// Return true if a table with TableSize elements of 5967 /// type ElementType would fit in a target-legal register. 5968 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, 5969 Type *ElementType); 5970 5971 private: 5972 // Depending on the contents of the table, it can be represented in 5973 // different ways. 5974 enum { 5975 // For tables where each element contains the same value, we just have to 5976 // store that single value and return it for each lookup. 5977 SingleValueKind, 5978 5979 // For tables where there is a linear relationship between table index 5980 // and values. We calculate the result with a simple multiplication 5981 // and addition instead of a table lookup. 5982 LinearMapKind, 5983 5984 // For small tables with integer elements, we can pack them into a bitmap 5985 // that fits into a target-legal register. Values are retrieved by 5986 // shift and mask operations. 5987 BitMapKind, 5988 5989 // The table is stored as an array of values. Values are retrieved by load 5990 // instructions from the table. 5991 ArrayKind 5992 } Kind; 5993 5994 // For SingleValueKind, this is the single value. 5995 Constant *SingleValue = nullptr; 5996 5997 // For BitMapKind, this is the bitmap. 5998 ConstantInt *BitMap = nullptr; 5999 IntegerType *BitMapElementTy = nullptr; 6000 6001 // For LinearMapKind, these are the constants used to derive the value. 6002 ConstantInt *LinearOffset = nullptr; 6003 ConstantInt *LinearMultiplier = nullptr; 6004 6005 // For ArrayKind, this is the array. 6006 GlobalVariable *Array = nullptr; 6007 }; 6008 6009 } // end anonymous namespace 6010 6011 SwitchLookupTable::SwitchLookupTable( 6012 Module &M, uint64_t TableSize, ConstantInt *Offset, 6013 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 6014 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) { 6015 assert(Values.size() && "Can't build lookup table without values!"); 6016 assert(TableSize >= Values.size() && "Can't fit values in table!"); 6017 6018 // If all values in the table are equal, this is that value. 6019 SingleValue = Values.begin()->second; 6020 6021 Type *ValueType = Values.begin()->second->getType(); 6022 6023 // Build up the table contents. 6024 SmallVector<Constant *, 64> TableContents(TableSize); 6025 for (size_t I = 0, E = Values.size(); I != E; ++I) { 6026 ConstantInt *CaseVal = Values[I].first; 6027 Constant *CaseRes = Values[I].second; 6028 assert(CaseRes->getType() == ValueType); 6029 6030 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue(); 6031 TableContents[Idx] = CaseRes; 6032 6033 if (CaseRes != SingleValue) 6034 SingleValue = nullptr; 6035 } 6036 6037 // Fill in any holes in the table with the default result. 6038 if (Values.size() < TableSize) { 6039 assert(DefaultValue && 6040 "Need a default value to fill the lookup table holes."); 6041 assert(DefaultValue->getType() == ValueType); 6042 for (uint64_t I = 0; I < TableSize; ++I) { 6043 if (!TableContents[I]) 6044 TableContents[I] = DefaultValue; 6045 } 6046 6047 if (DefaultValue != SingleValue) 6048 SingleValue = nullptr; 6049 } 6050 6051 // If each element in the table contains the same value, we only need to store 6052 // that single value. 6053 if (SingleValue) { 6054 Kind = SingleValueKind; 6055 return; 6056 } 6057 6058 // Check if we can derive the value with a linear transformation from the 6059 // table index. 6060 if (isa<IntegerType>(ValueType)) { 6061 bool LinearMappingPossible = true; 6062 APInt PrevVal; 6063 APInt DistToPrev; 6064 assert(TableSize >= 2 && "Should be a SingleValue table."); 6065 // Check if there is the same distance between two consecutive values. 6066 for (uint64_t I = 0; I < TableSize; ++I) { 6067 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); 6068 if (!ConstVal) { 6069 // This is an undef. We could deal with it, but undefs in lookup tables 6070 // are very seldom. It's probably not worth the additional complexity. 6071 LinearMappingPossible = false; 6072 break; 6073 } 6074 const APInt &Val = ConstVal->getValue(); 6075 if (I != 0) { 6076 APInt Dist = Val - PrevVal; 6077 if (I == 1) { 6078 DistToPrev = Dist; 6079 } else if (Dist != DistToPrev) { 6080 LinearMappingPossible = false; 6081 break; 6082 } 6083 } 6084 PrevVal = Val; 6085 } 6086 if (LinearMappingPossible) { 6087 LinearOffset = cast<ConstantInt>(TableContents[0]); 6088 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); 6089 Kind = LinearMapKind; 6090 ++NumLinearMaps; 6091 return; 6092 } 6093 } 6094 6095 // If the type is integer and the table fits in a register, build a bitmap. 6096 if (WouldFitInRegister(DL, TableSize, ValueType)) { 6097 IntegerType *IT = cast<IntegerType>(ValueType); 6098 APInt TableInt(TableSize * IT->getBitWidth(), 0); 6099 for (uint64_t I = TableSize; I > 0; --I) { 6100 TableInt <<= IT->getBitWidth(); 6101 // Insert values into the bitmap. Undef values are set to zero. 6102 if (!isa<UndefValue>(TableContents[I - 1])) { 6103 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 6104 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 6105 } 6106 } 6107 BitMap = ConstantInt::get(M.getContext(), TableInt); 6108 BitMapElementTy = IT; 6109 Kind = BitMapKind; 6110 ++NumBitMaps; 6111 return; 6112 } 6113 6114 // Store the table in an array. 6115 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); 6116 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 6117 6118 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true, 6119 GlobalVariable::PrivateLinkage, Initializer, 6120 "switch.table." + FuncName); 6121 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 6122 // Set the alignment to that of an array items. We will be only loading one 6123 // value out of it. 6124 Array->setAlignment(DL.getPrefTypeAlign(ValueType)); 6125 Kind = ArrayKind; 6126 } 6127 6128 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 6129 switch (Kind) { 6130 case SingleValueKind: 6131 return SingleValue; 6132 case LinearMapKind: { 6133 // Derive the result value from the input value. 6134 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), 6135 false, "switch.idx.cast"); 6136 if (!LinearMultiplier->isOne()) 6137 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); 6138 if (!LinearOffset->isZero()) 6139 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); 6140 return Result; 6141 } 6142 case BitMapKind: { 6143 // Type of the bitmap (e.g. i59). 6144 IntegerType *MapTy = BitMap->getType(); 6145 6146 // Cast Index to the same type as the bitmap. 6147 // Note: The Index is <= the number of elements in the table, so 6148 // truncating it to the width of the bitmask is safe. 6149 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 6150 6151 // Multiply the shift amount by the element width. 6152 ShiftAmt = Builder.CreateMul( 6153 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 6154 "switch.shiftamt"); 6155 6156 // Shift down. 6157 Value *DownShifted = 6158 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift"); 6159 // Mask off. 6160 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked"); 6161 } 6162 case ArrayKind: { 6163 // Make sure the table index will not overflow when treated as signed. 6164 IntegerType *IT = cast<IntegerType>(Index->getType()); 6165 uint64_t TableSize = 6166 Array->getInitializer()->getType()->getArrayNumElements(); 6167 if (TableSize > (1ULL << std::min(IT->getBitWidth() - 1, 63u))) 6168 Index = Builder.CreateZExt( 6169 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1), 6170 "switch.tableidx.zext"); 6171 6172 Value *GEPIndices[] = {Builder.getInt32(0), Index}; 6173 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, 6174 GEPIndices, "switch.gep"); 6175 return Builder.CreateLoad( 6176 cast<ArrayType>(Array->getValueType())->getElementType(), GEP, 6177 "switch.load"); 6178 } 6179 } 6180 llvm_unreachable("Unknown lookup table kind!"); 6181 } 6182 6183 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, 6184 uint64_t TableSize, 6185 Type *ElementType) { 6186 auto *IT = dyn_cast<IntegerType>(ElementType); 6187 if (!IT) 6188 return false; 6189 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 6190 // are <= 15, we could try to narrow the type. 6191 6192 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 6193 if (TableSize >= UINT_MAX / IT->getBitWidth()) 6194 return false; 6195 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); 6196 } 6197 6198 static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI, 6199 const DataLayout &DL) { 6200 // Allow any legal type. 6201 if (TTI.isTypeLegal(Ty)) 6202 return true; 6203 6204 auto *IT = dyn_cast<IntegerType>(Ty); 6205 if (!IT) 6206 return false; 6207 6208 // Also allow power of 2 integer types that have at least 8 bits and fit in 6209 // a register. These types are common in frontend languages and targets 6210 // usually support loads of these types. 6211 // TODO: We could relax this to any integer that fits in a register and rely 6212 // on ABI alignment and padding in the table to allow the load to be widened. 6213 // Or we could widen the constants and truncate the load. 6214 unsigned BitWidth = IT->getBitWidth(); 6215 return BitWidth >= 8 && isPowerOf2_32(BitWidth) && 6216 DL.fitsInLegalInteger(IT->getBitWidth()); 6217 } 6218 6219 static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange) { 6220 // 40% is the default density for building a jump table in optsize/minsize 6221 // mode. See also TargetLoweringBase::isSuitableForJumpTable(), which this 6222 // function was based on. 6223 const uint64_t MinDensity = 40; 6224 6225 if (CaseRange >= UINT64_MAX / 100) 6226 return false; // Avoid multiplication overflows below. 6227 6228 return NumCases * 100 >= CaseRange * MinDensity; 6229 } 6230 6231 static bool isSwitchDense(ArrayRef<int64_t> Values) { 6232 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front(); 6233 uint64_t Range = Diff + 1; 6234 if (Range < Diff) 6235 return false; // Overflow. 6236 6237 return isSwitchDense(Values.size(), Range); 6238 } 6239 6240 /// Determine whether a lookup table should be built for this switch, based on 6241 /// the number of cases, size of the table, and the types of the results. 6242 // TODO: We could support larger than legal types by limiting based on the 6243 // number of loads required and/or table size. If the constants are small we 6244 // could use smaller table entries and extend after the load. 6245 static bool 6246 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, 6247 const TargetTransformInfo &TTI, const DataLayout &DL, 6248 const SmallDenseMap<PHINode *, Type *> &ResultTypes) { 6249 if (SI->getNumCases() > TableSize) 6250 return false; // TableSize overflowed. 6251 6252 bool AllTablesFitInRegister = true; 6253 bool HasIllegalType = false; 6254 for (const auto &I : ResultTypes) { 6255 Type *Ty = I.second; 6256 6257 // Saturate this flag to true. 6258 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL); 6259 6260 // Saturate this flag to false. 6261 AllTablesFitInRegister = 6262 AllTablesFitInRegister && 6263 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); 6264 6265 // If both flags saturate, we're done. NOTE: This *only* works with 6266 // saturating flags, and all flags have to saturate first due to the 6267 // non-deterministic behavior of iterating over a dense map. 6268 if (HasIllegalType && !AllTablesFitInRegister) 6269 break; 6270 } 6271 6272 // If each table would fit in a register, we should build it anyway. 6273 if (AllTablesFitInRegister) 6274 return true; 6275 6276 // Don't build a table that doesn't fit in-register if it has illegal types. 6277 if (HasIllegalType) 6278 return false; 6279 6280 return isSwitchDense(SI->getNumCases(), TableSize); 6281 } 6282 6283 static bool ShouldUseSwitchConditionAsTableIndex( 6284 ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal, 6285 bool HasDefaultResults, const SmallDenseMap<PHINode *, Type *> &ResultTypes, 6286 const DataLayout &DL, const TargetTransformInfo &TTI) { 6287 if (MinCaseVal.isNullValue()) 6288 return true; 6289 if (MinCaseVal.isNegative() || 6290 MaxCaseVal.getLimitedValue() == std::numeric_limits<uint64_t>::max() || 6291 !HasDefaultResults) 6292 return false; 6293 return all_of(ResultTypes, [&](const auto &KV) { 6294 return SwitchLookupTable::WouldFitInRegister( 6295 DL, MaxCaseVal.getLimitedValue() + 1 /* TableSize */, 6296 KV.second /* ResultType */); 6297 }); 6298 } 6299 6300 /// Try to reuse the switch table index compare. Following pattern: 6301 /// \code 6302 /// if (idx < tablesize) 6303 /// r = table[idx]; // table does not contain default_value 6304 /// else 6305 /// r = default_value; 6306 /// if (r != default_value) 6307 /// ... 6308 /// \endcode 6309 /// Is optimized to: 6310 /// \code 6311 /// cond = idx < tablesize; 6312 /// if (cond) 6313 /// r = table[idx]; 6314 /// else 6315 /// r = default_value; 6316 /// if (cond) 6317 /// ... 6318 /// \endcode 6319 /// Jump threading will then eliminate the second if(cond). 6320 static void reuseTableCompare( 6321 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, 6322 Constant *DefaultValue, 6323 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) { 6324 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); 6325 if (!CmpInst) 6326 return; 6327 6328 // We require that the compare is in the same block as the phi so that jump 6329 // threading can do its work afterwards. 6330 if (CmpInst->getParent() != PhiBlock) 6331 return; 6332 6333 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); 6334 if (!CmpOp1) 6335 return; 6336 6337 Value *RangeCmp = RangeCheckBranch->getCondition(); 6338 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); 6339 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); 6340 6341 // Check if the compare with the default value is constant true or false. 6342 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 6343 DefaultValue, CmpOp1, true); 6344 if (DefaultConst != TrueConst && DefaultConst != FalseConst) 6345 return; 6346 6347 // Check if the compare with the case values is distinct from the default 6348 // compare result. 6349 for (auto ValuePair : Values) { 6350 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 6351 ValuePair.second, CmpOp1, true); 6352 if (!CaseConst || CaseConst == DefaultConst || 6353 (CaseConst != TrueConst && CaseConst != FalseConst)) 6354 return; 6355 } 6356 6357 // Check if the branch instruction dominates the phi node. It's a simple 6358 // dominance check, but sufficient for our needs. 6359 // Although this check is invariant in the calling loops, it's better to do it 6360 // at this late stage. Practically we do it at most once for a switch. 6361 BasicBlock *BranchBlock = RangeCheckBranch->getParent(); 6362 for (BasicBlock *Pred : predecessors(PhiBlock)) { 6363 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) 6364 return; 6365 } 6366 6367 if (DefaultConst == FalseConst) { 6368 // The compare yields the same result. We can replace it. 6369 CmpInst->replaceAllUsesWith(RangeCmp); 6370 ++NumTableCmpReuses; 6371 } else { 6372 // The compare yields the same result, just inverted. We can replace it. 6373 Value *InvertedTableCmp = BinaryOperator::CreateXor( 6374 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", 6375 RangeCheckBranch); 6376 CmpInst->replaceAllUsesWith(InvertedTableCmp); 6377 ++NumTableCmpReuses; 6378 } 6379 } 6380 6381 /// If the switch is only used to initialize one or more phi nodes in a common 6382 /// successor block with different constant values, replace the switch with 6383 /// lookup tables. 6384 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, 6385 DomTreeUpdater *DTU, const DataLayout &DL, 6386 const TargetTransformInfo &TTI) { 6387 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 6388 6389 BasicBlock *BB = SI->getParent(); 6390 Function *Fn = BB->getParent(); 6391 // Only build lookup table when we have a target that supports it or the 6392 // attribute is not set. 6393 if (!TTI.shouldBuildLookupTables() || 6394 (Fn->getFnAttribute("no-jump-tables").getValueAsBool())) 6395 return false; 6396 6397 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 6398 // split off a dense part and build a lookup table for that. 6399 6400 // FIXME: This creates arrays of GEPs to constant strings, which means each 6401 // GEP needs a runtime relocation in PIC code. We should just build one big 6402 // string and lookup indices into that. 6403 6404 // Ignore switches with less than three cases. Lookup tables will not make 6405 // them faster, so we don't analyze them. 6406 if (SI->getNumCases() < 3) 6407 return false; 6408 6409 // Figure out the corresponding result for each case value and phi node in the 6410 // common destination, as well as the min and max case values. 6411 assert(!SI->cases().empty()); 6412 SwitchInst::CaseIt CI = SI->case_begin(); 6413 ConstantInt *MinCaseVal = CI->getCaseValue(); 6414 ConstantInt *MaxCaseVal = CI->getCaseValue(); 6415 6416 BasicBlock *CommonDest = nullptr; 6417 6418 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>; 6419 SmallDenseMap<PHINode *, ResultListTy> ResultLists; 6420 6421 SmallDenseMap<PHINode *, Constant *> DefaultResults; 6422 SmallDenseMap<PHINode *, Type *> ResultTypes; 6423 SmallVector<PHINode *, 4> PHIs; 6424 6425 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 6426 ConstantInt *CaseVal = CI->getCaseValue(); 6427 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 6428 MinCaseVal = CaseVal; 6429 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 6430 MaxCaseVal = CaseVal; 6431 6432 // Resulting value at phi nodes for this case value. 6433 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; 6434 ResultsTy Results; 6435 if (!getCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest, 6436 Results, DL, TTI)) 6437 return false; 6438 6439 // Append the result from this case to the list for each phi. 6440 for (const auto &I : Results) { 6441 PHINode *PHI = I.first; 6442 Constant *Value = I.second; 6443 if (!ResultLists.count(PHI)) 6444 PHIs.push_back(PHI); 6445 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); 6446 } 6447 } 6448 6449 // Keep track of the result types. 6450 for (PHINode *PHI : PHIs) { 6451 ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); 6452 } 6453 6454 uint64_t NumResults = ResultLists[PHIs[0]].size(); 6455 6456 // If the table has holes, we need a constant result for the default case 6457 // or a bitmask that fits in a register. 6458 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList; 6459 bool HasDefaultResults = 6460 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, 6461 DefaultResultsList, DL, TTI); 6462 6463 for (const auto &I : DefaultResultsList) { 6464 PHINode *PHI = I.first; 6465 Constant *Result = I.second; 6466 DefaultResults[PHI] = Result; 6467 } 6468 6469 bool UseSwitchConditionAsTableIndex = ShouldUseSwitchConditionAsTableIndex( 6470 *MinCaseVal, *MaxCaseVal, HasDefaultResults, ResultTypes, DL, TTI); 6471 uint64_t TableSize; 6472 if (UseSwitchConditionAsTableIndex) 6473 TableSize = MaxCaseVal->getLimitedValue() + 1; 6474 else 6475 TableSize = 6476 (MaxCaseVal->getValue() - MinCaseVal->getValue()).getLimitedValue() + 1; 6477 6478 bool TableHasHoles = (NumResults < TableSize); 6479 bool NeedMask = (TableHasHoles && !HasDefaultResults); 6480 if (NeedMask) { 6481 // As an extra penalty for the validity test we require more cases. 6482 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). 6483 return false; 6484 if (!DL.fitsInLegalInteger(TableSize)) 6485 return false; 6486 } 6487 6488 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) 6489 return false; 6490 6491 std::vector<DominatorTree::UpdateType> Updates; 6492 6493 // Create the BB that does the lookups. 6494 Module &Mod = *CommonDest->getParent()->getParent(); 6495 BasicBlock *LookupBB = BasicBlock::Create( 6496 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest); 6497 6498 // Compute the table index value. 6499 Builder.SetInsertPoint(SI); 6500 Value *TableIndex; 6501 ConstantInt *TableIndexOffset; 6502 if (UseSwitchConditionAsTableIndex) { 6503 TableIndexOffset = ConstantInt::get(MaxCaseVal->getType(), 0); 6504 TableIndex = SI->getCondition(); 6505 } else { 6506 TableIndexOffset = MinCaseVal; 6507 TableIndex = 6508 Builder.CreateSub(SI->getCondition(), TableIndexOffset, "switch.tableidx"); 6509 } 6510 6511 // Compute the maximum table size representable by the integer type we are 6512 // switching upon. 6513 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); 6514 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; 6515 assert(MaxTableSize >= TableSize && 6516 "It is impossible for a switch to have more entries than the max " 6517 "representable value of its input integer type's size."); 6518 6519 // If the default destination is unreachable, or if the lookup table covers 6520 // all values of the conditional variable, branch directly to the lookup table 6521 // BB. Otherwise, check that the condition is within the case range. 6522 const bool DefaultIsReachable = 6523 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 6524 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); 6525 BranchInst *RangeCheckBranch = nullptr; 6526 6527 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 6528 Builder.CreateBr(LookupBB); 6529 if (DTU) 6530 Updates.push_back({DominatorTree::Insert, BB, LookupBB}); 6531 // Note: We call removeProdecessor later since we need to be able to get the 6532 // PHI value for the default case in case we're using a bit mask. 6533 } else { 6534 Value *Cmp = Builder.CreateICmpULT( 6535 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize)); 6536 RangeCheckBranch = 6537 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 6538 if (DTU) 6539 Updates.push_back({DominatorTree::Insert, BB, LookupBB}); 6540 } 6541 6542 // Populate the BB that does the lookups. 6543 Builder.SetInsertPoint(LookupBB); 6544 6545 if (NeedMask) { 6546 // Before doing the lookup, we do the hole check. The LookupBB is therefore 6547 // re-purposed to do the hole check, and we create a new LookupBB. 6548 BasicBlock *MaskBB = LookupBB; 6549 MaskBB->setName("switch.hole_check"); 6550 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup", 6551 CommonDest->getParent(), CommonDest); 6552 6553 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid 6554 // unnecessary illegal types. 6555 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); 6556 APInt MaskInt(TableSizePowOf2, 0); 6557 APInt One(TableSizePowOf2, 1); 6558 // Build bitmask; fill in a 1 bit for every case. 6559 const ResultListTy &ResultList = ResultLists[PHIs[0]]; 6560 for (size_t I = 0, E = ResultList.size(); I != E; ++I) { 6561 uint64_t Idx = (ResultList[I].first->getValue() - TableIndexOffset->getValue()) 6562 .getLimitedValue(); 6563 MaskInt |= One << Idx; 6564 } 6565 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); 6566 6567 // Get the TableIndex'th bit of the bitmask. 6568 // If this bit is 0 (meaning hole) jump to the default destination, 6569 // else continue with table lookup. 6570 IntegerType *MapTy = TableMask->getType(); 6571 Value *MaskIndex = 6572 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex"); 6573 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted"); 6574 Value *LoBit = Builder.CreateTrunc( 6575 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit"); 6576 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); 6577 if (DTU) { 6578 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB}); 6579 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()}); 6580 } 6581 Builder.SetInsertPoint(LookupBB); 6582 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB); 6583 } 6584 6585 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 6586 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later, 6587 // do not delete PHINodes here. 6588 SI->getDefaultDest()->removePredecessor(BB, 6589 /*KeepOneInputPHIs=*/true); 6590 if (DTU) 6591 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()}); 6592 } 6593 6594 for (PHINode *PHI : PHIs) { 6595 const ResultListTy &ResultList = ResultLists[PHI]; 6596 6597 // If using a bitmask, use any value to fill the lookup table holes. 6598 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; 6599 StringRef FuncName = Fn->getName(); 6600 SwitchLookupTable Table(Mod, TableSize, TableIndexOffset, ResultList, DV, 6601 DL, FuncName); 6602 6603 Value *Result = Table.BuildLookup(TableIndex, Builder); 6604 6605 // Do a small peephole optimization: re-use the switch table compare if 6606 // possible. 6607 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { 6608 BasicBlock *PhiBlock = PHI->getParent(); 6609 // Search for compare instructions which use the phi. 6610 for (auto *User : PHI->users()) { 6611 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); 6612 } 6613 } 6614 6615 PHI->addIncoming(Result, LookupBB); 6616 } 6617 6618 Builder.CreateBr(CommonDest); 6619 if (DTU) 6620 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest}); 6621 6622 // Remove the switch. 6623 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors; 6624 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 6625 BasicBlock *Succ = SI->getSuccessor(i); 6626 6627 if (Succ == SI->getDefaultDest()) 6628 continue; 6629 Succ->removePredecessor(BB); 6630 if (DTU && RemovedSuccessors.insert(Succ).second) 6631 Updates.push_back({DominatorTree::Delete, BB, Succ}); 6632 } 6633 SI->eraseFromParent(); 6634 6635 if (DTU) 6636 DTU->applyUpdates(Updates); 6637 6638 ++NumLookupTables; 6639 if (NeedMask) 6640 ++NumLookupTablesHoles; 6641 return true; 6642 } 6643 6644 /// Try to transform a switch that has "holes" in it to a contiguous sequence 6645 /// of cases. 6646 /// 6647 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be 6648 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}. 6649 /// 6650 /// This converts a sparse switch into a dense switch which allows better 6651 /// lowering and could also allow transforming into a lookup table. 6652 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, 6653 const DataLayout &DL, 6654 const TargetTransformInfo &TTI) { 6655 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType()); 6656 if (CondTy->getIntegerBitWidth() > 64 || 6657 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth())) 6658 return false; 6659 // Only bother with this optimization if there are more than 3 switch cases; 6660 // SDAG will only bother creating jump tables for 4 or more cases. 6661 if (SI->getNumCases() < 4) 6662 return false; 6663 6664 // This transform is agnostic to the signedness of the input or case values. We 6665 // can treat the case values as signed or unsigned. We can optimize more common 6666 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values 6667 // as signed. 6668 SmallVector<int64_t,4> Values; 6669 for (const auto &C : SI->cases()) 6670 Values.push_back(C.getCaseValue()->getValue().getSExtValue()); 6671 llvm::sort(Values); 6672 6673 // If the switch is already dense, there's nothing useful to do here. 6674 if (isSwitchDense(Values)) 6675 return false; 6676 6677 // First, transform the values such that they start at zero and ascend. 6678 int64_t Base = Values[0]; 6679 for (auto &V : Values) 6680 V -= (uint64_t)(Base); 6681 6682 // Now we have signed numbers that have been shifted so that, given enough 6683 // precision, there are no negative values. Since the rest of the transform 6684 // is bitwise only, we switch now to an unsigned representation. 6685 6686 // This transform can be done speculatively because it is so cheap - it 6687 // results in a single rotate operation being inserted. 6688 // FIXME: It's possible that optimizing a switch on powers of two might also 6689 // be beneficial - flag values are often powers of two and we could use a CLZ 6690 // as the key function. 6691 6692 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than 6693 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be 6694 // less than 64. 6695 unsigned Shift = 64; 6696 for (auto &V : Values) 6697 Shift = std::min(Shift, countTrailingZeros((uint64_t)V)); 6698 assert(Shift < 64); 6699 if (Shift > 0) 6700 for (auto &V : Values) 6701 V = (int64_t)((uint64_t)V >> Shift); 6702 6703 if (!isSwitchDense(Values)) 6704 // Transform didn't create a dense switch. 6705 return false; 6706 6707 // The obvious transform is to shift the switch condition right and emit a 6708 // check that the condition actually cleanly divided by GCD, i.e. 6709 // C & (1 << Shift - 1) == 0 6710 // inserting a new CFG edge to handle the case where it didn't divide cleanly. 6711 // 6712 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the 6713 // shift and puts the shifted-off bits in the uppermost bits. If any of these 6714 // are nonzero then the switch condition will be very large and will hit the 6715 // default case. 6716 6717 auto *Ty = cast<IntegerType>(SI->getCondition()->getType()); 6718 Builder.SetInsertPoint(SI); 6719 auto *ShiftC = ConstantInt::get(Ty, Shift); 6720 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base)); 6721 auto *LShr = Builder.CreateLShr(Sub, ShiftC); 6722 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift); 6723 auto *Rot = Builder.CreateOr(LShr, Shl); 6724 SI->replaceUsesOfWith(SI->getCondition(), Rot); 6725 6726 for (auto Case : SI->cases()) { 6727 auto *Orig = Case.getCaseValue(); 6728 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base); 6729 Case.setValue( 6730 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue())))); 6731 } 6732 return true; 6733 } 6734 6735 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 6736 BasicBlock *BB = SI->getParent(); 6737 6738 if (isValueEqualityComparison(SI)) { 6739 // If we only have one predecessor, and if it is a branch on this value, 6740 // see if that predecessor totally determines the outcome of this switch. 6741 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 6742 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 6743 return requestResimplify(); 6744 6745 Value *Cond = SI->getCondition(); 6746 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 6747 if (SimplifySwitchOnSelect(SI, Select)) 6748 return requestResimplify(); 6749 6750 // If the block only contains the switch, see if we can fold the block 6751 // away into any preds. 6752 if (SI == &*BB->instructionsWithoutDebug(false).begin()) 6753 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 6754 return requestResimplify(); 6755 } 6756 6757 // Try to transform the switch into an icmp and a branch. 6758 // The conversion from switch to comparison may lose information on 6759 // impossible switch values, so disable it early in the pipeline. 6760 if (Options.ConvertSwitchRangeToICmp && TurnSwitchRangeIntoICmp(SI, Builder)) 6761 return requestResimplify(); 6762 6763 // Remove unreachable cases. 6764 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL)) 6765 return requestResimplify(); 6766 6767 if (trySwitchToSelect(SI, Builder, DTU, DL, TTI)) 6768 return requestResimplify(); 6769 6770 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI)) 6771 return requestResimplify(); 6772 6773 // The conversion from switch to lookup tables results in difficult-to-analyze 6774 // code and makes pruning branches much harder. This is a problem if the 6775 // switch expression itself can still be restricted as a result of inlining or 6776 // CVP. Therefore, only apply this transformation during late stages of the 6777 // optimisation pipeline. 6778 if (Options.ConvertSwitchToLookupTable && 6779 SwitchToLookupTable(SI, Builder, DTU, DL, TTI)) 6780 return requestResimplify(); 6781 6782 if (ReduceSwitchRange(SI, Builder, DL, TTI)) 6783 return requestResimplify(); 6784 6785 return false; 6786 } 6787 6788 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) { 6789 BasicBlock *BB = IBI->getParent(); 6790 bool Changed = false; 6791 6792 // Eliminate redundant destinations. 6793 SmallPtrSet<Value *, 8> Succs; 6794 SmallSetVector<BasicBlock *, 8> RemovedSuccs; 6795 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 6796 BasicBlock *Dest = IBI->getDestination(i); 6797 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { 6798 if (!Dest->hasAddressTaken()) 6799 RemovedSuccs.insert(Dest); 6800 Dest->removePredecessor(BB); 6801 IBI->removeDestination(i); 6802 --i; 6803 --e; 6804 Changed = true; 6805 } 6806 } 6807 6808 if (DTU) { 6809 std::vector<DominatorTree::UpdateType> Updates; 6810 Updates.reserve(RemovedSuccs.size()); 6811 for (auto *RemovedSucc : RemovedSuccs) 6812 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc}); 6813 DTU->applyUpdates(Updates); 6814 } 6815 6816 if (IBI->getNumDestinations() == 0) { 6817 // If the indirectbr has no successors, change it to unreachable. 6818 new UnreachableInst(IBI->getContext(), IBI); 6819 EraseTerminatorAndDCECond(IBI); 6820 return true; 6821 } 6822 6823 if (IBI->getNumDestinations() == 1) { 6824 // If the indirectbr has one successor, change it to a direct branch. 6825 BranchInst::Create(IBI->getDestination(0), IBI); 6826 EraseTerminatorAndDCECond(IBI); 6827 return true; 6828 } 6829 6830 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 6831 if (SimplifyIndirectBrOnSelect(IBI, SI)) 6832 return requestResimplify(); 6833 } 6834 return Changed; 6835 } 6836 6837 /// Given an block with only a single landing pad and a unconditional branch 6838 /// try to find another basic block which this one can be merged with. This 6839 /// handles cases where we have multiple invokes with unique landing pads, but 6840 /// a shared handler. 6841 /// 6842 /// We specifically choose to not worry about merging non-empty blocks 6843 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In 6844 /// practice, the optimizer produces empty landing pad blocks quite frequently 6845 /// when dealing with exception dense code. (see: instcombine, gvn, if-else 6846 /// sinking in this file) 6847 /// 6848 /// This is primarily a code size optimization. We need to avoid performing 6849 /// any transform which might inhibit optimization (such as our ability to 6850 /// specialize a particular handler via tail commoning). We do this by not 6851 /// merging any blocks which require us to introduce a phi. Since the same 6852 /// values are flowing through both blocks, we don't lose any ability to 6853 /// specialize. If anything, we make such specialization more likely. 6854 /// 6855 /// TODO - This transformation could remove entries from a phi in the target 6856 /// block when the inputs in the phi are the same for the two blocks being 6857 /// merged. In some cases, this could result in removal of the PHI entirely. 6858 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, 6859 BasicBlock *BB, DomTreeUpdater *DTU) { 6860 auto Succ = BB->getUniqueSuccessor(); 6861 assert(Succ); 6862 // If there's a phi in the successor block, we'd likely have to introduce 6863 // a phi into the merged landing pad block. 6864 if (isa<PHINode>(*Succ->begin())) 6865 return false; 6866 6867 for (BasicBlock *OtherPred : predecessors(Succ)) { 6868 if (BB == OtherPred) 6869 continue; 6870 BasicBlock::iterator I = OtherPred->begin(); 6871 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); 6872 if (!LPad2 || !LPad2->isIdenticalTo(LPad)) 6873 continue; 6874 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6875 ; 6876 BranchInst *BI2 = dyn_cast<BranchInst>(I); 6877 if (!BI2 || !BI2->isIdenticalTo(BI)) 6878 continue; 6879 6880 std::vector<DominatorTree::UpdateType> Updates; 6881 6882 // We've found an identical block. Update our predecessors to take that 6883 // path instead and make ourselves dead. 6884 SmallSetVector<BasicBlock *, 16> UniquePreds(pred_begin(BB), pred_end(BB)); 6885 for (BasicBlock *Pred : UniquePreds) { 6886 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); 6887 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB && 6888 "unexpected successor"); 6889 II->setUnwindDest(OtherPred); 6890 if (DTU) { 6891 Updates.push_back({DominatorTree::Insert, Pred, OtherPred}); 6892 Updates.push_back({DominatorTree::Delete, Pred, BB}); 6893 } 6894 } 6895 6896 // The debug info in OtherPred doesn't cover the merged control flow that 6897 // used to go through BB. We need to delete it or update it. 6898 for (Instruction &Inst : llvm::make_early_inc_range(*OtherPred)) 6899 if (isa<DbgInfoIntrinsic>(Inst)) 6900 Inst.eraseFromParent(); 6901 6902 SmallSetVector<BasicBlock *, 16> UniqueSuccs(succ_begin(BB), succ_end(BB)); 6903 for (BasicBlock *Succ : UniqueSuccs) { 6904 Succ->removePredecessor(BB); 6905 if (DTU) 6906 Updates.push_back({DominatorTree::Delete, BB, Succ}); 6907 } 6908 6909 IRBuilder<> Builder(BI); 6910 Builder.CreateUnreachable(); 6911 BI->eraseFromParent(); 6912 if (DTU) 6913 DTU->applyUpdates(Updates); 6914 return true; 6915 } 6916 return false; 6917 } 6918 6919 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) { 6920 return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder) 6921 : simplifyCondBranch(Branch, Builder); 6922 } 6923 6924 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI, 6925 IRBuilder<> &Builder) { 6926 BasicBlock *BB = BI->getParent(); 6927 BasicBlock *Succ = BI->getSuccessor(0); 6928 6929 // If the Terminator is the only non-phi instruction, simplify the block. 6930 // If LoopHeader is provided, check if the block or its successor is a loop 6931 // header. (This is for early invocations before loop simplify and 6932 // vectorization to keep canonical loop forms for nested loops. These blocks 6933 // can be eliminated when the pass is invoked later in the back-end.) 6934 // Note that if BB has only one predecessor then we do not introduce new 6935 // backedge, so we can eliminate BB. 6936 bool NeedCanonicalLoop = 6937 Options.NeedCanonicalLoop && 6938 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) && 6939 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ))); 6940 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(true)->getIterator(); 6941 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 6942 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU)) 6943 return true; 6944 6945 // If the only instruction in the block is a seteq/setne comparison against a 6946 // constant, try to simplify the block. 6947 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 6948 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 6949 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6950 ; 6951 if (I->isTerminator() && 6952 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder)) 6953 return true; 6954 } 6955 6956 // See if we can merge an empty landing pad block with another which is 6957 // equivalent. 6958 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { 6959 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6960 ; 6961 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB, DTU)) 6962 return true; 6963 } 6964 6965 // If this basic block is ONLY a compare and a branch, and if a predecessor 6966 // branches to us and our successor, fold the comparison into the 6967 // predecessor and use logical operations to update the incoming value 6968 // for PHI nodes in common successor. 6969 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, 6970 Options.BonusInstThreshold)) 6971 return requestResimplify(); 6972 return false; 6973 } 6974 6975 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { 6976 BasicBlock *PredPred = nullptr; 6977 for (auto *P : predecessors(BB)) { 6978 BasicBlock *PPred = P->getSinglePredecessor(); 6979 if (!PPred || (PredPred && PredPred != PPred)) 6980 return nullptr; 6981 PredPred = PPred; 6982 } 6983 return PredPred; 6984 } 6985 6986 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 6987 assert( 6988 !isa<ConstantInt>(BI->getCondition()) && 6989 BI->getSuccessor(0) != BI->getSuccessor(1) && 6990 "Tautological conditional branch should have been eliminated already."); 6991 6992 BasicBlock *BB = BI->getParent(); 6993 if (!Options.SimplifyCondBranch) 6994 return false; 6995 6996 // Conditional branch 6997 if (isValueEqualityComparison(BI)) { 6998 // If we only have one predecessor, and if it is a branch on this value, 6999 // see if that predecessor totally determines the outcome of this 7000 // switch. 7001 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 7002 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 7003 return requestResimplify(); 7004 7005 // This block must be empty, except for the setcond inst, if it exists. 7006 // Ignore dbg and pseudo intrinsics. 7007 auto I = BB->instructionsWithoutDebug(true).begin(); 7008 if (&*I == BI) { 7009 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 7010 return requestResimplify(); 7011 } else if (&*I == cast<Instruction>(BI->getCondition())) { 7012 ++I; 7013 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 7014 return requestResimplify(); 7015 } 7016 } 7017 7018 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 7019 if (SimplifyBranchOnICmpChain(BI, Builder, DL)) 7020 return true; 7021 7022 // If this basic block has dominating predecessor blocks and the dominating 7023 // blocks' conditions imply BI's condition, we know the direction of BI. 7024 std::optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL); 7025 if (Imp) { 7026 // Turn this into a branch on constant. 7027 auto *OldCond = BI->getCondition(); 7028 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext()) 7029 : ConstantInt::getFalse(BB->getContext()); 7030 BI->setCondition(TorF); 7031 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 7032 return requestResimplify(); 7033 } 7034 7035 // If this basic block is ONLY a compare and a branch, and if a predecessor 7036 // branches to us and one of our successors, fold the comparison into the 7037 // predecessor and use logical operations to pick the right destination. 7038 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, 7039 Options.BonusInstThreshold)) 7040 return requestResimplify(); 7041 7042 // We have a conditional branch to two blocks that are only reachable 7043 // from BI. We know that the condbr dominates the two blocks, so see if 7044 // there is any identical code in the "then" and "else" blocks. If so, we 7045 // can hoist it up to the branching block. 7046 if (BI->getSuccessor(0)->getSinglePredecessor()) { 7047 if (BI->getSuccessor(1)->getSinglePredecessor()) { 7048 if (HoistCommon && 7049 HoistThenElseCodeToIf(BI, TTI, !Options.HoistCommonInsts)) 7050 return requestResimplify(); 7051 } else { 7052 // If Successor #1 has multiple preds, we may be able to conditionally 7053 // execute Successor #0 if it branches to Successor #1. 7054 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator(); 7055 if (Succ0TI->getNumSuccessors() == 1 && 7056 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 7057 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) 7058 return requestResimplify(); 7059 } 7060 } else if (BI->getSuccessor(1)->getSinglePredecessor()) { 7061 // If Successor #0 has multiple preds, we may be able to conditionally 7062 // execute Successor #1 if it branches to Successor #0. 7063 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator(); 7064 if (Succ1TI->getNumSuccessors() == 1 && 7065 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 7066 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) 7067 return requestResimplify(); 7068 } 7069 7070 // If this is a branch on something for which we know the constant value in 7071 // predecessors (e.g. a phi node in the current block), thread control 7072 // through this block. 7073 if (FoldCondBranchOnValueKnownInPredecessor(BI, DTU, DL, Options.AC)) 7074 return requestResimplify(); 7075 7076 // Scan predecessor blocks for conditional branches. 7077 for (BasicBlock *Pred : predecessors(BB)) 7078 if (BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator())) 7079 if (PBI != BI && PBI->isConditional()) 7080 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI)) 7081 return requestResimplify(); 7082 7083 // Look for diamond patterns. 7084 if (MergeCondStores) 7085 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) 7086 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) 7087 if (PBI != BI && PBI->isConditional()) 7088 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI)) 7089 return requestResimplify(); 7090 7091 return false; 7092 } 7093 7094 /// Check if passing a value to an instruction will cause undefined behavior. 7095 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) { 7096 Constant *C = dyn_cast<Constant>(V); 7097 if (!C) 7098 return false; 7099 7100 if (I->use_empty()) 7101 return false; 7102 7103 if (C->isNullValue() || isa<UndefValue>(C)) { 7104 // Only look at the first use, avoid hurting compile time with long uselists 7105 auto *Use = cast<Instruction>(*I->user_begin()); 7106 // Bail out if Use is not in the same BB as I or Use == I or Use comes 7107 // before I in the block. The latter two can be the case if Use is a PHI 7108 // node. 7109 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I)) 7110 return false; 7111 7112 // Now make sure that there are no instructions in between that can alter 7113 // control flow (eg. calls) 7114 auto InstrRange = 7115 make_range(std::next(I->getIterator()), Use->getIterator()); 7116 if (any_of(InstrRange, [](Instruction &I) { 7117 return !isGuaranteedToTransferExecutionToSuccessor(&I); 7118 })) 7119 return false; 7120 7121 // Look through GEPs. A load from a GEP derived from NULL is still undefined 7122 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 7123 if (GEP->getPointerOperand() == I) { 7124 if (!GEP->isInBounds() || !GEP->hasAllZeroIndices()) 7125 PtrValueMayBeModified = true; 7126 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified); 7127 } 7128 7129 // Look through bitcasts. 7130 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 7131 return passingValueIsAlwaysUndefined(V, BC, PtrValueMayBeModified); 7132 7133 // Load from null is undefined. 7134 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 7135 if (!LI->isVolatile()) 7136 return !NullPointerIsDefined(LI->getFunction(), 7137 LI->getPointerAddressSpace()); 7138 7139 // Store to null is undefined. 7140 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 7141 if (!SI->isVolatile()) 7142 return (!NullPointerIsDefined(SI->getFunction(), 7143 SI->getPointerAddressSpace())) && 7144 SI->getPointerOperand() == I; 7145 7146 if (auto *CB = dyn_cast<CallBase>(Use)) { 7147 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction())) 7148 return false; 7149 // A call to null is undefined. 7150 if (CB->getCalledOperand() == I) 7151 return true; 7152 7153 if (C->isNullValue()) { 7154 for (const llvm::Use &Arg : CB->args()) 7155 if (Arg == I) { 7156 unsigned ArgIdx = CB->getArgOperandNo(&Arg); 7157 if (CB->isPassingUndefUB(ArgIdx) && 7158 CB->paramHasAttr(ArgIdx, Attribute::NonNull)) { 7159 // Passing null to a nonnnull+noundef argument is undefined. 7160 return !PtrValueMayBeModified; 7161 } 7162 } 7163 } else if (isa<UndefValue>(C)) { 7164 // Passing undef to a noundef argument is undefined. 7165 for (const llvm::Use &Arg : CB->args()) 7166 if (Arg == I) { 7167 unsigned ArgIdx = CB->getArgOperandNo(&Arg); 7168 if (CB->isPassingUndefUB(ArgIdx)) { 7169 // Passing undef to a noundef argument is undefined. 7170 return true; 7171 } 7172 } 7173 } 7174 } 7175 } 7176 return false; 7177 } 7178 7179 /// If BB has an incoming value that will always trigger undefined behavior 7180 /// (eg. null pointer dereference), remove the branch leading here. 7181 static bool removeUndefIntroducingPredecessor(BasicBlock *BB, 7182 DomTreeUpdater *DTU) { 7183 for (PHINode &PHI : BB->phis()) 7184 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) 7185 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) { 7186 BasicBlock *Predecessor = PHI.getIncomingBlock(i); 7187 Instruction *T = Predecessor->getTerminator(); 7188 IRBuilder<> Builder(T); 7189 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 7190 BB->removePredecessor(Predecessor); 7191 // Turn unconditional branches into unreachables and remove the dead 7192 // destination from conditional branches. 7193 if (BI->isUnconditional()) 7194 Builder.CreateUnreachable(); 7195 else { 7196 // Preserve guarding condition in assume, because it might not be 7197 // inferrable from any dominating condition. 7198 Value *Cond = BI->getCondition(); 7199 if (BI->getSuccessor(0) == BB) 7200 Builder.CreateAssumption(Builder.CreateNot(Cond)); 7201 else 7202 Builder.CreateAssumption(Cond); 7203 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) 7204 : BI->getSuccessor(0)); 7205 } 7206 BI->eraseFromParent(); 7207 if (DTU) 7208 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}}); 7209 return true; 7210 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { 7211 // Redirect all branches leading to UB into 7212 // a newly created unreachable block. 7213 BasicBlock *Unreachable = BasicBlock::Create( 7214 Predecessor->getContext(), "unreachable", BB->getParent(), BB); 7215 Builder.SetInsertPoint(Unreachable); 7216 // The new block contains only one instruction: Unreachable 7217 Builder.CreateUnreachable(); 7218 for (const auto &Case : SI->cases()) 7219 if (Case.getCaseSuccessor() == BB) { 7220 BB->removePredecessor(Predecessor); 7221 Case.setSuccessor(Unreachable); 7222 } 7223 if (SI->getDefaultDest() == BB) { 7224 BB->removePredecessor(Predecessor); 7225 SI->setDefaultDest(Unreachable); 7226 } 7227 7228 if (DTU) 7229 DTU->applyUpdates( 7230 { { DominatorTree::Insert, Predecessor, Unreachable }, 7231 { DominatorTree::Delete, Predecessor, BB } }); 7232 return true; 7233 } 7234 } 7235 7236 return false; 7237 } 7238 7239 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) { 7240 bool Changed = false; 7241 7242 assert(BB && BB->getParent() && "Block not embedded in function!"); 7243 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 7244 7245 // Remove basic blocks that have no predecessors (except the entry block)... 7246 // or that just have themself as a predecessor. These are unreachable. 7247 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) || 7248 BB->getSinglePredecessor() == BB) { 7249 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB); 7250 DeleteDeadBlock(BB, DTU); 7251 return true; 7252 } 7253 7254 // Check to see if we can constant propagate this terminator instruction 7255 // away... 7256 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true, 7257 /*TLI=*/nullptr, DTU); 7258 7259 // Check for and eliminate duplicate PHI nodes in this block. 7260 Changed |= EliminateDuplicatePHINodes(BB); 7261 7262 // Check for and remove branches that will always cause undefined behavior. 7263 if (removeUndefIntroducingPredecessor(BB, DTU)) 7264 return requestResimplify(); 7265 7266 // Merge basic blocks into their predecessor if there is only one distinct 7267 // pred, and if there is only one distinct successor of the predecessor, and 7268 // if there are no PHI nodes. 7269 if (MergeBlockIntoPredecessor(BB, DTU)) 7270 return true; 7271 7272 if (SinkCommon && Options.SinkCommonInsts) 7273 if (SinkCommonCodeFromPredecessors(BB, DTU) || 7274 MergeCompatibleInvokes(BB, DTU)) { 7275 // SinkCommonCodeFromPredecessors() does not automatically CSE PHI's, 7276 // so we may now how duplicate PHI's. 7277 // Let's rerun EliminateDuplicatePHINodes() first, 7278 // before FoldTwoEntryPHINode() potentially converts them into select's, 7279 // after which we'd need a whole EarlyCSE pass run to cleanup them. 7280 return true; 7281 } 7282 7283 IRBuilder<> Builder(BB); 7284 7285 if (Options.FoldTwoEntryPHINode) { 7286 // If there is a trivial two-entry PHI node in this basic block, and we can 7287 // eliminate it, do so now. 7288 if (auto *PN = dyn_cast<PHINode>(BB->begin())) 7289 if (PN->getNumIncomingValues() == 2) 7290 if (FoldTwoEntryPHINode(PN, TTI, DTU, DL)) 7291 return true; 7292 } 7293 7294 Instruction *Terminator = BB->getTerminator(); 7295 Builder.SetInsertPoint(Terminator); 7296 switch (Terminator->getOpcode()) { 7297 case Instruction::Br: 7298 Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder); 7299 break; 7300 case Instruction::Resume: 7301 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder); 7302 break; 7303 case Instruction::CleanupRet: 7304 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator)); 7305 break; 7306 case Instruction::Switch: 7307 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder); 7308 break; 7309 case Instruction::Unreachable: 7310 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator)); 7311 break; 7312 case Instruction::IndirectBr: 7313 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator)); 7314 break; 7315 } 7316 7317 return Changed; 7318 } 7319 7320 bool SimplifyCFGOpt::run(BasicBlock *BB) { 7321 bool Changed = false; 7322 7323 // Repeated simplify BB as long as resimplification is requested. 7324 do { 7325 Resimplify = false; 7326 7327 // Perform one round of simplifcation. Resimplify flag will be set if 7328 // another iteration is requested. 7329 Changed |= simplifyOnce(BB); 7330 } while (Resimplify); 7331 7332 return Changed; 7333 } 7334 7335 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 7336 DomTreeUpdater *DTU, const SimplifyCFGOptions &Options, 7337 ArrayRef<WeakVH> LoopHeaders) { 7338 return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders, 7339 Options) 7340 .run(BB); 7341 } 7342