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