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