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