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