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