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