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