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(false))) { 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) && !I->isDebugOrPseudoInst()) { 2895 // This is not an aggressive instruction that we can promote. 2896 // Because of this, we won't be able to get rid of the control flow, so 2897 // the xform is not worth it. 2898 return Changed; 2899 } 2900 2901 // If either of the blocks has it's address taken, we can't do this fold. 2902 if (any_of(IfBlocks, 2903 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); })) 2904 return Changed; 2905 2906 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond 2907 << " T: " << IfTrue->getName() 2908 << " F: " << IfFalse->getName() << "\n"); 2909 2910 // If we can still promote the PHI nodes after this gauntlet of tests, 2911 // do all of the PHI's now. 2912 2913 // Move all 'aggressive' instructions, which are defined in the 2914 // conditional parts of the if's up to the dominating block. 2915 for (BasicBlock *IfBlock : IfBlocks) 2916 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock); 2917 2918 IRBuilder<NoFolder> Builder(DomBI); 2919 // Propagate fast-math-flags from phi nodes to replacement selects. 2920 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 2921 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 2922 if (isa<FPMathOperator>(PN)) 2923 Builder.setFastMathFlags(PN->getFastMathFlags()); 2924 2925 // Change the PHI node into a select instruction. 2926 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue); 2927 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse); 2928 2929 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI); 2930 PN->replaceAllUsesWith(Sel); 2931 Sel->takeName(PN); 2932 PN->eraseFromParent(); 2933 } 2934 2935 // At this point, all IfBlocks are empty, so our if statement 2936 // has been flattened. Change DomBlock to jump directly to our new block to 2937 // avoid other simplifycfg's kicking in on the diamond. 2938 Builder.CreateBr(BB); 2939 2940 SmallVector<DominatorTree::UpdateType, 3> Updates; 2941 if (DTU) { 2942 Updates.push_back({DominatorTree::Insert, DomBlock, BB}); 2943 for (auto *Successor : successors(DomBlock)) 2944 Updates.push_back({DominatorTree::Delete, DomBlock, Successor}); 2945 } 2946 2947 DomBI->eraseFromParent(); 2948 if (DTU) 2949 DTU->applyUpdates(Updates); 2950 2951 return true; 2952 } 2953 2954 static Value *createLogicalOp(IRBuilderBase &Builder, 2955 Instruction::BinaryOps Opc, Value *LHS, 2956 Value *RHS, const Twine &Name = "") { 2957 // Try to relax logical op to binary op. 2958 if (impliesPoison(RHS, LHS)) 2959 return Builder.CreateBinOp(Opc, LHS, RHS, Name); 2960 if (Opc == Instruction::And) 2961 return Builder.CreateLogicalAnd(LHS, RHS, Name); 2962 if (Opc == Instruction::Or) 2963 return Builder.CreateLogicalOr(LHS, RHS, Name); 2964 llvm_unreachable("Invalid logical opcode"); 2965 } 2966 2967 /// Return true if either PBI or BI has branch weight available, and store 2968 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does 2969 /// not have branch weight, use 1:1 as its weight. 2970 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, 2971 uint64_t &PredTrueWeight, 2972 uint64_t &PredFalseWeight, 2973 uint64_t &SuccTrueWeight, 2974 uint64_t &SuccFalseWeight) { 2975 bool PredHasWeights = 2976 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight); 2977 bool SuccHasWeights = 2978 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight); 2979 if (PredHasWeights || SuccHasWeights) { 2980 if (!PredHasWeights) 2981 PredTrueWeight = PredFalseWeight = 1; 2982 if (!SuccHasWeights) 2983 SuccTrueWeight = SuccFalseWeight = 1; 2984 return true; 2985 } else { 2986 return false; 2987 } 2988 } 2989 2990 /// Determine if the two branches share a common destination and deduce a glue 2991 /// that joins the branches' conditions to arrive at the common destination if 2992 /// that would be profitable. 2993 static Optional<std::pair<Instruction::BinaryOps, bool>> 2994 shouldFoldCondBranchesToCommonDestination(BranchInst *BI, BranchInst *PBI, 2995 const TargetTransformInfo *TTI) { 2996 assert(BI && PBI && BI->isConditional() && PBI->isConditional() && 2997 "Both blocks must end with a conditional branches."); 2998 assert(is_contained(predecessors(BI->getParent()), PBI->getParent()) && 2999 "PredBB must be a predecessor of BB."); 3000 3001 // We have the potential to fold the conditions together, but if the 3002 // predecessor branch is predictable, we may not want to merge them. 3003 uint64_t PTWeight, PFWeight; 3004 BranchProbability PBITrueProb, Likely; 3005 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) && 3006 PBI->extractProfMetadata(PTWeight, PFWeight) && 3007 (PTWeight + PFWeight) != 0) { 3008 PBITrueProb = 3009 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight); 3010 Likely = TTI->getPredictableBranchThreshold(); 3011 } 3012 3013 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3014 // Speculate the 2nd condition unless the 1st is probably true. 3015 if (PBITrueProb.isUnknown() || PBITrueProb < Likely) 3016 return {{Instruction::Or, false}}; 3017 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3018 // Speculate the 2nd condition unless the 1st is probably false. 3019 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely) 3020 return {{Instruction::And, false}}; 3021 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3022 // Speculate the 2nd condition unless the 1st is probably true. 3023 if (PBITrueProb.isUnknown() || PBITrueProb < Likely) 3024 return {{Instruction::And, true}}; 3025 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3026 // Speculate the 2nd condition unless the 1st is probably false. 3027 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely) 3028 return {{Instruction::Or, true}}; 3029 } 3030 return None; 3031 } 3032 3033 static bool performBranchToCommonDestFolding(BranchInst *BI, BranchInst *PBI, 3034 DomTreeUpdater *DTU, 3035 MemorySSAUpdater *MSSAU, 3036 const TargetTransformInfo *TTI) { 3037 BasicBlock *BB = BI->getParent(); 3038 BasicBlock *PredBlock = PBI->getParent(); 3039 3040 // Determine if the two branches share a common destination. 3041 Instruction::BinaryOps Opc; 3042 bool InvertPredCond; 3043 std::tie(Opc, InvertPredCond) = 3044 *shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI); 3045 3046 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); 3047 3048 IRBuilder<> Builder(PBI); 3049 // The builder is used to create instructions to eliminate the branch in BB. 3050 // If BB's terminator has !annotation metadata, add it to the new 3051 // instructions. 3052 Builder.CollectMetadataToCopy(BB->getTerminator(), 3053 {LLVMContext::MD_annotation}); 3054 3055 // If we need to invert the condition in the pred block to match, do so now. 3056 if (InvertPredCond) { 3057 Value *NewCond = PBI->getCondition(); 3058 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { 3059 CmpInst *CI = cast<CmpInst>(NewCond); 3060 CI->setPredicate(CI->getInversePredicate()); 3061 } else { 3062 NewCond = 3063 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not"); 3064 } 3065 3066 PBI->setCondition(NewCond); 3067 PBI->swapSuccessors(); 3068 } 3069 3070 BasicBlock *UniqueSucc = 3071 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1); 3072 3073 // Before cloning instructions, notify the successor basic block that it 3074 // is about to have a new predecessor. This will update PHI nodes, 3075 // which will allow us to update live-out uses of bonus instructions. 3076 AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU); 3077 3078 // Try to update branch weights. 3079 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3080 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3081 SuccTrueWeight, SuccFalseWeight)) { 3082 SmallVector<uint64_t, 8> NewWeights; 3083 3084 if (PBI->getSuccessor(0) == BB) { 3085 // PBI: br i1 %x, BB, FalseDest 3086 // BI: br i1 %y, UniqueSucc, FalseDest 3087 // TrueWeight is TrueWeight for PBI * TrueWeight for BI. 3088 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 3089 // FalseWeight is FalseWeight for PBI * TotalWeight for BI + 3090 // TrueWeight for PBI * FalseWeight for BI. 3091 // We assume that total weights of a BranchInst can fit into 32 bits. 3092 // Therefore, we will not have overflow using 64-bit arithmetic. 3093 NewWeights.push_back(PredFalseWeight * 3094 (SuccFalseWeight + SuccTrueWeight) + 3095 PredTrueWeight * SuccFalseWeight); 3096 } else { 3097 // PBI: br i1 %x, TrueDest, BB 3098 // BI: br i1 %y, TrueDest, UniqueSucc 3099 // TrueWeight is TrueWeight for PBI * TotalWeight for BI + 3100 // FalseWeight for PBI * TrueWeight for BI. 3101 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) + 3102 PredFalseWeight * SuccTrueWeight); 3103 // FalseWeight is FalseWeight for PBI * FalseWeight for BI. 3104 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 3105 } 3106 3107 // Halve the weights if any of them cannot fit in an uint32_t 3108 FitWeights(NewWeights); 3109 3110 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end()); 3111 setBranchWeights(PBI, MDWeights[0], MDWeights[1]); 3112 3113 // TODO: If BB is reachable from all paths through PredBlock, then we 3114 // could replace PBI's branch probabilities with BI's. 3115 } else 3116 PBI->setMetadata(LLVMContext::MD_prof, nullptr); 3117 3118 // Now, update the CFG. 3119 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc); 3120 3121 if (DTU) 3122 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc}, 3123 {DominatorTree::Delete, PredBlock, BB}}); 3124 3125 // If BI was a loop latch, it may have had associated loop metadata. 3126 // We need to copy it to the new latch, that is, PBI. 3127 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop)) 3128 PBI->setMetadata(LLVMContext::MD_loop, LoopMD); 3129 3130 ValueToValueMapTy VMap; // maps original values to cloned values 3131 CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BB, PredBlock, VMap); 3132 3133 // Now that the Cond was cloned into the predecessor basic block, 3134 // or/and the two conditions together. 3135 Value *BICond = VMap[BI->getCondition()]; 3136 PBI->setCondition( 3137 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond")); 3138 3139 // Copy any debug value intrinsics into the end of PredBlock. 3140 for (Instruction &I : *BB) { 3141 if (isa<DbgInfoIntrinsic>(I)) { 3142 Instruction *NewI = I.clone(); 3143 RemapInstruction(NewI, VMap, 3144 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 3145 NewI->insertBefore(PBI); 3146 } 3147 } 3148 3149 ++NumFoldBranchToCommonDest; 3150 return true; 3151 } 3152 3153 /// Return if an instruction's type or any of its operands' types are a vector 3154 /// type. 3155 static bool isVectorOp(Instruction &I) { 3156 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) { 3157 return U->getType()->isVectorTy(); 3158 }); 3159 } 3160 3161 /// If this basic block is simple enough, and if a predecessor branches to us 3162 /// and one of our successors, fold the block into the predecessor and use 3163 /// logical operations to pick the right destination. 3164 bool llvm::FoldBranchToCommonDest(BranchInst *BI, DomTreeUpdater *DTU, 3165 MemorySSAUpdater *MSSAU, 3166 const TargetTransformInfo *TTI, 3167 unsigned BonusInstThreshold) { 3168 // If this block ends with an unconditional branch, 3169 // let SpeculativelyExecuteBB() deal with it. 3170 if (!BI->isConditional()) 3171 return false; 3172 3173 BasicBlock *BB = BI->getParent(); 3174 TargetTransformInfo::TargetCostKind CostKind = 3175 BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize 3176 : TargetTransformInfo::TCK_SizeAndLatency; 3177 3178 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 3179 3180 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || 3181 Cond->getParent() != BB || !Cond->hasOneUse()) 3182 return false; 3183 3184 // Cond is known to be a compare or binary operator. Check to make sure that 3185 // neither operand is a potentially-trapping constant expression. 3186 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) 3187 if (CE->canTrap()) 3188 return false; 3189 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) 3190 if (CE->canTrap()) 3191 return false; 3192 3193 // Finally, don't infinitely unroll conditional loops. 3194 if (is_contained(successors(BB), BB)) 3195 return false; 3196 3197 // With which predecessors will we want to deal with? 3198 SmallVector<BasicBlock *, 8> Preds; 3199 for (BasicBlock *PredBlock : predecessors(BB)) { 3200 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); 3201 3202 // Check that we have two conditional branches. If there is a PHI node in 3203 // the common successor, verify that the same value flows in from both 3204 // blocks. 3205 if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI)) 3206 continue; 3207 3208 // Determine if the two branches share a common destination. 3209 Instruction::BinaryOps Opc; 3210 bool InvertPredCond; 3211 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI)) 3212 std::tie(Opc, InvertPredCond) = *Recipe; 3213 else 3214 continue; 3215 3216 // Check the cost of inserting the necessary logic before performing the 3217 // transformation. 3218 if (TTI) { 3219 Type *Ty = BI->getCondition()->getType(); 3220 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind); 3221 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() || 3222 !isa<CmpInst>(PBI->getCondition()))) 3223 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind); 3224 3225 if (Cost > BranchFoldThreshold) 3226 continue; 3227 } 3228 3229 // Ok, we do want to deal with this predecessor. Record it. 3230 Preds.emplace_back(PredBlock); 3231 } 3232 3233 // If there aren't any predecessors into which we can fold, 3234 // don't bother checking the cost. 3235 if (Preds.empty()) 3236 return false; 3237 3238 // Only allow this transformation if computing the condition doesn't involve 3239 // too many instructions and these involved instructions can be executed 3240 // unconditionally. We denote all involved instructions except the condition 3241 // as "bonus instructions", and only allow this transformation when the 3242 // number of the bonus instructions we'll need to create when cloning into 3243 // each predecessor does not exceed a certain threshold. 3244 unsigned NumBonusInsts = 0; 3245 bool SawVectorOp = false; 3246 const unsigned PredCount = Preds.size(); 3247 for (Instruction &I : *BB) { 3248 // Don't check the branch condition comparison itself. 3249 if (&I == Cond) 3250 continue; 3251 // Ignore dbg intrinsics, and the terminator. 3252 if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I)) 3253 continue; 3254 // I must be safe to execute unconditionally. 3255 if (!isSafeToSpeculativelyExecute(&I)) 3256 return false; 3257 SawVectorOp |= isVectorOp(I); 3258 3259 // Account for the cost of duplicating this instruction into each 3260 // predecessor. Ignore free instructions. 3261 if (!TTI || 3262 TTI->getUserCost(&I, CostKind) != TargetTransformInfo::TCC_Free) { 3263 NumBonusInsts += PredCount; 3264 3265 // Early exits once we reach the limit. 3266 if (NumBonusInsts > 3267 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier) 3268 return false; 3269 } 3270 3271 auto IsBCSSAUse = [BB, &I](Use &U) { 3272 auto *UI = cast<Instruction>(U.getUser()); 3273 if (auto *PN = dyn_cast<PHINode>(UI)) 3274 return PN->getIncomingBlock(U) == BB; 3275 return UI->getParent() == BB && I.comesBefore(UI); 3276 }; 3277 3278 // Does this instruction require rewriting of uses? 3279 if (!all_of(I.uses(), IsBCSSAUse)) 3280 return false; 3281 } 3282 if (NumBonusInsts > 3283 BonusInstThreshold * 3284 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1)) 3285 return false; 3286 3287 // Ok, we have the budget. Perform the transformation. 3288 for (BasicBlock *PredBlock : Preds) { 3289 auto *PBI = cast<BranchInst>(PredBlock->getTerminator()); 3290 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI); 3291 } 3292 return false; 3293 } 3294 3295 // If there is only one store in BB1 and BB2, return it, otherwise return 3296 // nullptr. 3297 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { 3298 StoreInst *S = nullptr; 3299 for (auto *BB : {BB1, BB2}) { 3300 if (!BB) 3301 continue; 3302 for (auto &I : *BB) 3303 if (auto *SI = dyn_cast<StoreInst>(&I)) { 3304 if (S) 3305 // Multiple stores seen. 3306 return nullptr; 3307 else 3308 S = SI; 3309 } 3310 } 3311 return S; 3312 } 3313 3314 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, 3315 Value *AlternativeV = nullptr) { 3316 // PHI is going to be a PHI node that allows the value V that is defined in 3317 // BB to be referenced in BB's only successor. 3318 // 3319 // If AlternativeV is nullptr, the only value we care about in PHI is V. It 3320 // doesn't matter to us what the other operand is (it'll never get used). We 3321 // could just create a new PHI with an undef incoming value, but that could 3322 // increase register pressure if EarlyCSE/InstCombine can't fold it with some 3323 // other PHI. So here we directly look for some PHI in BB's successor with V 3324 // as an incoming operand. If we find one, we use it, else we create a new 3325 // one. 3326 // 3327 // If AlternativeV is not nullptr, we care about both incoming values in PHI. 3328 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] 3329 // where OtherBB is the single other predecessor of BB's only successor. 3330 PHINode *PHI = nullptr; 3331 BasicBlock *Succ = BB->getSingleSuccessor(); 3332 3333 for (auto I = Succ->begin(); isa<PHINode>(I); ++I) 3334 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { 3335 PHI = cast<PHINode>(I); 3336 if (!AlternativeV) 3337 break; 3338 3339 assert(Succ->hasNPredecessors(2)); 3340 auto PredI = pred_begin(Succ); 3341 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; 3342 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) 3343 break; 3344 PHI = nullptr; 3345 } 3346 if (PHI) 3347 return PHI; 3348 3349 // If V is not an instruction defined in BB, just return it. 3350 if (!AlternativeV && 3351 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB)) 3352 return V; 3353 3354 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front()); 3355 PHI->addIncoming(V, BB); 3356 for (BasicBlock *PredBB : predecessors(Succ)) 3357 if (PredBB != BB) 3358 PHI->addIncoming( 3359 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB); 3360 return PHI; 3361 } 3362 3363 static bool mergeConditionalStoreToAddress( 3364 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, 3365 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond, 3366 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) { 3367 // For every pointer, there must be exactly two stores, one coming from 3368 // PTB or PFB, and the other from QTB or QFB. We don't support more than one 3369 // store (to any address) in PTB,PFB or QTB,QFB. 3370 // FIXME: We could relax this restriction with a bit more work and performance 3371 // testing. 3372 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); 3373 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); 3374 if (!PStore || !QStore) 3375 return false; 3376 3377 // Now check the stores are compatible. 3378 if (!QStore->isUnordered() || !PStore->isUnordered()) 3379 return false; 3380 3381 // Check that sinking the store won't cause program behavior changes. Sinking 3382 // the store out of the Q blocks won't change any behavior as we're sinking 3383 // from a block to its unconditional successor. But we're moving a store from 3384 // the P blocks down through the middle block (QBI) and past both QFB and QTB. 3385 // So we need to check that there are no aliasing loads or stores in 3386 // QBI, QTB and QFB. We also need to check there are no conflicting memory 3387 // operations between PStore and the end of its parent block. 3388 // 3389 // The ideal way to do this is to query AliasAnalysis, but we don't 3390 // preserve AA currently so that is dangerous. Be super safe and just 3391 // check there are no other memory operations at all. 3392 for (auto &I : *QFB->getSinglePredecessor()) 3393 if (I.mayReadOrWriteMemory()) 3394 return false; 3395 for (auto &I : *QFB) 3396 if (&I != QStore && I.mayReadOrWriteMemory()) 3397 return false; 3398 if (QTB) 3399 for (auto &I : *QTB) 3400 if (&I != QStore && I.mayReadOrWriteMemory()) 3401 return false; 3402 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); 3403 I != E; ++I) 3404 if (&*I != PStore && I->mayReadOrWriteMemory()) 3405 return false; 3406 3407 // If we're not in aggressive mode, we only optimize if we have some 3408 // confidence that by optimizing we'll allow P and/or Q to be if-converted. 3409 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) { 3410 if (!BB) 3411 return true; 3412 // Heuristic: if the block can be if-converted/phi-folded and the 3413 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to 3414 // thread this store. 3415 InstructionCost Cost = 0; 3416 InstructionCost Budget = 3417 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 3418 for (auto &I : BB->instructionsWithoutDebug(false)) { 3419 // Consider terminator instruction to be free. 3420 if (I.isTerminator()) 3421 continue; 3422 // If this is one the stores that we want to speculate out of this BB, 3423 // then don't count it's cost, consider it to be free. 3424 if (auto *S = dyn_cast<StoreInst>(&I)) 3425 if (llvm::find(FreeStores, S)) 3426 continue; 3427 // Else, we have a white-list of instructions that we are ak speculating. 3428 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I)) 3429 return false; // Not in white-list - not worthwhile folding. 3430 // And finally, if this is a non-free instruction that we are okay 3431 // speculating, ensure that we consider the speculation budget. 3432 Cost += TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 3433 if (Cost > Budget) 3434 return false; // Eagerly refuse to fold as soon as we're out of budget. 3435 } 3436 assert(Cost <= Budget && 3437 "When we run out of budget we will eagerly return from within the " 3438 "per-instruction loop."); 3439 return true; 3440 }; 3441 3442 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore}; 3443 if (!MergeCondStoresAggressively && 3444 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) || 3445 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores))) 3446 return false; 3447 3448 // If PostBB has more than two predecessors, we need to split it so we can 3449 // sink the store. 3450 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) { 3451 // We know that QFB's only successor is PostBB. And QFB has a single 3452 // predecessor. If QTB exists, then its only successor is also PostBB. 3453 // If QTB does not exist, then QFB's only predecessor has a conditional 3454 // branch to QFB and PostBB. 3455 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor(); 3456 BasicBlock *NewBB = 3457 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU); 3458 if (!NewBB) 3459 return false; 3460 PostBB = NewBB; 3461 } 3462 3463 // OK, we're going to sink the stores to PostBB. The store has to be 3464 // conditional though, so first create the predicate. 3465 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) 3466 ->getCondition(); 3467 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) 3468 ->getCondition(); 3469 3470 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), 3471 PStore->getParent()); 3472 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), 3473 QStore->getParent(), PPHI); 3474 3475 IRBuilder<> QB(&*PostBB->getFirstInsertionPt()); 3476 3477 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); 3478 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); 3479 3480 if (InvertPCond) 3481 PPred = QB.CreateNot(PPred); 3482 if (InvertQCond) 3483 QPred = QB.CreateNot(QPred); 3484 Value *CombinedPred = QB.CreateOr(PPred, QPred); 3485 3486 auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), 3487 /*Unreachable=*/false, 3488 /*BranchWeights=*/nullptr, DTU); 3489 QB.SetInsertPoint(T); 3490 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); 3491 SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata())); 3492 // Choose the minimum alignment. If we could prove both stores execute, we 3493 // could use biggest one. In this case, though, we only know that one of the 3494 // stores executes. And we don't know it's safe to take the alignment from a 3495 // store that doesn't execute. 3496 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign())); 3497 3498 QStore->eraseFromParent(); 3499 PStore->eraseFromParent(); 3500 3501 return true; 3502 } 3503 3504 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI, 3505 DomTreeUpdater *DTU, const DataLayout &DL, 3506 const TargetTransformInfo &TTI) { 3507 // The intention here is to find diamonds or triangles (see below) where each 3508 // conditional block contains a store to the same address. Both of these 3509 // stores are conditional, so they can't be unconditionally sunk. But it may 3510 // be profitable to speculatively sink the stores into one merged store at the 3511 // end, and predicate the merged store on the union of the two conditions of 3512 // PBI and QBI. 3513 // 3514 // This can reduce the number of stores executed if both of the conditions are 3515 // true, and can allow the blocks to become small enough to be if-converted. 3516 // This optimization will also chain, so that ladders of test-and-set 3517 // sequences can be if-converted away. 3518 // 3519 // We only deal with simple diamonds or triangles: 3520 // 3521 // PBI or PBI or a combination of the two 3522 // / \ | \ 3523 // PTB PFB | PFB 3524 // \ / | / 3525 // QBI QBI 3526 // / \ | \ 3527 // QTB QFB | QFB 3528 // \ / | / 3529 // PostBB PostBB 3530 // 3531 // We model triangles as a type of diamond with a nullptr "true" block. 3532 // Triangles are canonicalized so that the fallthrough edge is represented by 3533 // a true condition, as in the diagram above. 3534 BasicBlock *PTB = PBI->getSuccessor(0); 3535 BasicBlock *PFB = PBI->getSuccessor(1); 3536 BasicBlock *QTB = QBI->getSuccessor(0); 3537 BasicBlock *QFB = QBI->getSuccessor(1); 3538 BasicBlock *PostBB = QFB->getSingleSuccessor(); 3539 3540 // Make sure we have a good guess for PostBB. If QTB's only successor is 3541 // QFB, then QFB is a better PostBB. 3542 if (QTB->getSingleSuccessor() == QFB) 3543 PostBB = QFB; 3544 3545 // If we couldn't find a good PostBB, stop. 3546 if (!PostBB) 3547 return false; 3548 3549 bool InvertPCond = false, InvertQCond = false; 3550 // Canonicalize fallthroughs to the true branches. 3551 if (PFB == QBI->getParent()) { 3552 std::swap(PFB, PTB); 3553 InvertPCond = true; 3554 } 3555 if (QFB == PostBB) { 3556 std::swap(QFB, QTB); 3557 InvertQCond = true; 3558 } 3559 3560 // From this point on we can assume PTB or QTB may be fallthroughs but PFB 3561 // and QFB may not. Model fallthroughs as a nullptr block. 3562 if (PTB == QBI->getParent()) 3563 PTB = nullptr; 3564 if (QTB == PostBB) 3565 QTB = nullptr; 3566 3567 // Legality bailouts. We must have at least the non-fallthrough blocks and 3568 // the post-dominating block, and the non-fallthroughs must only have one 3569 // predecessor. 3570 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { 3571 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S; 3572 }; 3573 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || 3574 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) 3575 return false; 3576 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || 3577 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) 3578 return false; 3579 if (!QBI->getParent()->hasNUses(2)) 3580 return false; 3581 3582 // OK, this is a sequence of two diamonds or triangles. 3583 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. 3584 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses; 3585 for (auto *BB : {PTB, PFB}) { 3586 if (!BB) 3587 continue; 3588 for (auto &I : *BB) 3589 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3590 PStoreAddresses.insert(SI->getPointerOperand()); 3591 } 3592 for (auto *BB : {QTB, QFB}) { 3593 if (!BB) 3594 continue; 3595 for (auto &I : *BB) 3596 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3597 QStoreAddresses.insert(SI->getPointerOperand()); 3598 } 3599 3600 set_intersect(PStoreAddresses, QStoreAddresses); 3601 // set_intersect mutates PStoreAddresses in place. Rename it here to make it 3602 // clear what it contains. 3603 auto &CommonAddresses = PStoreAddresses; 3604 3605 bool Changed = false; 3606 for (auto *Address : CommonAddresses) 3607 Changed |= 3608 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address, 3609 InvertPCond, InvertQCond, DTU, DL, TTI); 3610 return Changed; 3611 } 3612 3613 /// If the previous block ended with a widenable branch, determine if reusing 3614 /// the target block is profitable and legal. This will have the effect of 3615 /// "widening" PBI, but doesn't require us to reason about hosting safety. 3616 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 3617 DomTreeUpdater *DTU) { 3618 // TODO: This can be generalized in two important ways: 3619 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input 3620 // values from the PBI edge. 3621 // 2) We can sink side effecting instructions into BI's fallthrough 3622 // successor provided they doesn't contribute to computation of 3623 // BI's condition. 3624 Value *CondWB, *WC; 3625 BasicBlock *IfTrueBB, *IfFalseBB; 3626 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) || 3627 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor()) 3628 return false; 3629 if (!IfFalseBB->phis().empty()) 3630 return false; // TODO 3631 // Use lambda to lazily compute expensive condition after cheap ones. 3632 auto NoSideEffects = [](BasicBlock &BB) { 3633 return !llvm::any_of(BB, [](const Instruction &I) { 3634 return I.mayWriteToMemory() || I.mayHaveSideEffects(); 3635 }); 3636 }; 3637 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping 3638 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability 3639 NoSideEffects(*BI->getParent())) { 3640 auto *OldSuccessor = BI->getSuccessor(1); 3641 OldSuccessor->removePredecessor(BI->getParent()); 3642 BI->setSuccessor(1, IfFalseBB); 3643 if (DTU) 3644 DTU->applyUpdates( 3645 {{DominatorTree::Insert, BI->getParent(), IfFalseBB}, 3646 {DominatorTree::Delete, BI->getParent(), OldSuccessor}}); 3647 return true; 3648 } 3649 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping 3650 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability 3651 NoSideEffects(*BI->getParent())) { 3652 auto *OldSuccessor = BI->getSuccessor(0); 3653 OldSuccessor->removePredecessor(BI->getParent()); 3654 BI->setSuccessor(0, IfFalseBB); 3655 if (DTU) 3656 DTU->applyUpdates( 3657 {{DominatorTree::Insert, BI->getParent(), IfFalseBB}, 3658 {DominatorTree::Delete, BI->getParent(), OldSuccessor}}); 3659 return true; 3660 } 3661 return false; 3662 } 3663 3664 /// If we have a conditional branch as a predecessor of another block, 3665 /// this function tries to simplify it. We know 3666 /// that PBI and BI are both conditional branches, and BI is in one of the 3667 /// successor blocks of PBI - PBI branches to BI. 3668 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 3669 DomTreeUpdater *DTU, 3670 const DataLayout &DL, 3671 const TargetTransformInfo &TTI) { 3672 assert(PBI->isConditional() && BI->isConditional()); 3673 BasicBlock *BB = BI->getParent(); 3674 3675 // If this block ends with a branch instruction, and if there is a 3676 // predecessor that ends on a branch of the same condition, make 3677 // this conditional branch redundant. 3678 if (PBI->getCondition() == BI->getCondition() && 3679 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3680 // Okay, the outcome of this conditional branch is statically 3681 // knowable. If this block had a single pred, handle specially. 3682 if (BB->getSinglePredecessor()) { 3683 // Turn this into a branch on constant. 3684 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3685 BI->setCondition( 3686 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue)); 3687 return true; // Nuke the branch on constant. 3688 } 3689 3690 // Otherwise, if there are multiple predecessors, insert a PHI that merges 3691 // in the constant and simplify the block result. Subsequent passes of 3692 // simplifycfg will thread the block. 3693 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 3694 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 3695 PHINode *NewPN = PHINode::Create( 3696 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE), 3697 BI->getCondition()->getName() + ".pr", &BB->front()); 3698 // Okay, we're going to insert the PHI node. Since PBI is not the only 3699 // predecessor, compute the PHI'd conditional value for all of the preds. 3700 // Any predecessor where the condition is not computable we keep symbolic. 3701 for (pred_iterator PI = PB; PI != PE; ++PI) { 3702 BasicBlock *P = *PI; 3703 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI && 3704 PBI->isConditional() && PBI->getCondition() == BI->getCondition() && 3705 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3706 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3707 NewPN->addIncoming( 3708 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue), 3709 P); 3710 } else { 3711 NewPN->addIncoming(BI->getCondition(), P); 3712 } 3713 } 3714 3715 BI->setCondition(NewPN); 3716 return true; 3717 } 3718 } 3719 3720 // If the previous block ended with a widenable branch, determine if reusing 3721 // the target block is profitable and legal. This will have the effect of 3722 // "widening" PBI, but doesn't require us to reason about hosting safety. 3723 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU)) 3724 return true; 3725 3726 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition())) 3727 if (CE->canTrap()) 3728 return false; 3729 3730 // If both branches are conditional and both contain stores to the same 3731 // address, remove the stores from the conditionals and create a conditional 3732 // merged store at the end. 3733 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI)) 3734 return true; 3735 3736 // If this is a conditional branch in an empty block, and if any 3737 // predecessors are a conditional branch to one of our destinations, 3738 // fold the conditions into logical ops and one cond br. 3739 3740 // Ignore dbg intrinsics. 3741 if (&*BB->instructionsWithoutDebug(false).begin() != BI) 3742 return false; 3743 3744 int PBIOp, BIOp; 3745 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3746 PBIOp = 0; 3747 BIOp = 0; 3748 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3749 PBIOp = 0; 3750 BIOp = 1; 3751 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3752 PBIOp = 1; 3753 BIOp = 0; 3754 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3755 PBIOp = 1; 3756 BIOp = 1; 3757 } else { 3758 return false; 3759 } 3760 3761 // Check to make sure that the other destination of this branch 3762 // isn't BB itself. If so, this is an infinite loop that will 3763 // keep getting unwound. 3764 if (PBI->getSuccessor(PBIOp) == BB) 3765 return false; 3766 3767 // Do not perform this transformation if it would require 3768 // insertion of a large number of select instructions. For targets 3769 // without predication/cmovs, this is a big pessimization. 3770 3771 // Also do not perform this transformation if any phi node in the common 3772 // destination block can trap when reached by BB or PBB (PR17073). In that 3773 // case, it would be unsafe to hoist the operation into a select instruction. 3774 3775 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 3776 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1); 3777 unsigned NumPhis = 0; 3778 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II); 3779 ++II, ++NumPhis) { 3780 if (NumPhis > 2) // Disable this xform. 3781 return false; 3782 3783 PHINode *PN = cast<PHINode>(II); 3784 Value *BIV = PN->getIncomingValueForBlock(BB); 3785 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) 3786 if (CE->canTrap()) 3787 return false; 3788 3789 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 3790 Value *PBIV = PN->getIncomingValue(PBBIdx); 3791 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) 3792 if (CE->canTrap()) 3793 return false; 3794 } 3795 3796 // Finally, if everything is ok, fold the branches to logical ops. 3797 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 3798 3799 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 3800 << "AND: " << *BI->getParent()); 3801 3802 SmallVector<DominatorTree::UpdateType, 5> Updates; 3803 3804 // If OtherDest *is* BB, then BB is a basic block with a single conditional 3805 // branch in it, where one edge (OtherDest) goes back to itself but the other 3806 // exits. We don't *know* that the program avoids the infinite loop 3807 // (even though that seems likely). If we do this xform naively, we'll end up 3808 // recursively unpeeling the loop. Since we know that (after the xform is 3809 // done) that the block *is* infinite if reached, we just make it an obviously 3810 // infinite loop with no cond branch. 3811 if (OtherDest == BB) { 3812 // Insert it at the end of the function, because it's either code, 3813 // or it won't matter if it's hot. :) 3814 BasicBlock *InfLoopBlock = 3815 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent()); 3816 BranchInst::Create(InfLoopBlock, InfLoopBlock); 3817 if (DTU) 3818 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock}); 3819 OtherDest = InfLoopBlock; 3820 } 3821 3822 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3823 3824 // BI may have other predecessors. Because of this, we leave 3825 // it alone, but modify PBI. 3826 3827 // Make sure we get to CommonDest on True&True directions. 3828 Value *PBICond = PBI->getCondition(); 3829 IRBuilder<NoFolder> Builder(PBI); 3830 if (PBIOp) 3831 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not"); 3832 3833 Value *BICond = BI->getCondition(); 3834 if (BIOp) 3835 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not"); 3836 3837 // Merge the conditions. 3838 Value *Cond = 3839 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge"); 3840 3841 // Modify PBI to branch on the new condition to the new dests. 3842 PBI->setCondition(Cond); 3843 PBI->setSuccessor(0, CommonDest); 3844 PBI->setSuccessor(1, OtherDest); 3845 3846 if (DTU) { 3847 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest}); 3848 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest}); 3849 3850 DTU->applyUpdates(Updates); 3851 } 3852 3853 // Update branch weight for PBI. 3854 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3855 uint64_t PredCommon, PredOther, SuccCommon, SuccOther; 3856 bool HasWeights = 3857 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3858 SuccTrueWeight, SuccFalseWeight); 3859 if (HasWeights) { 3860 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3861 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3862 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3863 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3864 // The weight to CommonDest should be PredCommon * SuccTotal + 3865 // PredOther * SuccCommon. 3866 // The weight to OtherDest should be PredOther * SuccOther. 3867 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + 3868 PredOther * SuccCommon, 3869 PredOther * SuccOther}; 3870 // Halve the weights if any of them cannot fit in an uint32_t 3871 FitWeights(NewWeights); 3872 3873 setBranchWeights(PBI, NewWeights[0], NewWeights[1]); 3874 } 3875 3876 // OtherDest may have phi nodes. If so, add an entry from PBI's 3877 // block that are identical to the entries for BI's block. 3878 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 3879 3880 // We know that the CommonDest already had an edge from PBI to 3881 // it. If it has PHIs though, the PHIs may have different 3882 // entries for BB and PBI's BB. If so, insert a select to make 3883 // them agree. 3884 for (PHINode &PN : CommonDest->phis()) { 3885 Value *BIV = PN.getIncomingValueForBlock(BB); 3886 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent()); 3887 Value *PBIV = PN.getIncomingValue(PBBIdx); 3888 if (BIV != PBIV) { 3889 // Insert a select in PBI to pick the right value. 3890 SelectInst *NV = cast<SelectInst>( 3891 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux")); 3892 PN.setIncomingValue(PBBIdx, NV); 3893 // Although the select has the same condition as PBI, the original branch 3894 // weights for PBI do not apply to the new select because the select's 3895 // 'logical' edges are incoming edges of the phi that is eliminated, not 3896 // the outgoing edges of PBI. 3897 if (HasWeights) { 3898 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3899 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3900 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3901 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3902 // The weight to PredCommonDest should be PredCommon * SuccTotal. 3903 // The weight to PredOtherDest should be PredOther * SuccCommon. 3904 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther), 3905 PredOther * SuccCommon}; 3906 3907 FitWeights(NewWeights); 3908 3909 setBranchWeights(NV, NewWeights[0], NewWeights[1]); 3910 } 3911 } 3912 } 3913 3914 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 3915 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3916 3917 // This basic block is probably dead. We know it has at least 3918 // one fewer predecessor. 3919 return true; 3920 } 3921 3922 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is 3923 // true or to FalseBB if Cond is false. 3924 // Takes care of updating the successors and removing the old terminator. 3925 // Also makes sure not to introduce new successors by assuming that edges to 3926 // non-successor TrueBBs and FalseBBs aren't reachable. 3927 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm, 3928 Value *Cond, BasicBlock *TrueBB, 3929 BasicBlock *FalseBB, 3930 uint32_t TrueWeight, 3931 uint32_t FalseWeight) { 3932 auto *BB = OldTerm->getParent(); 3933 // Remove any superfluous successor edges from the CFG. 3934 // First, figure out which successors to preserve. 3935 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 3936 // successor. 3937 BasicBlock *KeepEdge1 = TrueBB; 3938 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; 3939 3940 SmallPtrSet<BasicBlock *, 2> RemovedSuccessors; 3941 3942 // Then remove the rest. 3943 for (BasicBlock *Succ : successors(OldTerm)) { 3944 // Make sure only to keep exactly one copy of each edge. 3945 if (Succ == KeepEdge1) 3946 KeepEdge1 = nullptr; 3947 else if (Succ == KeepEdge2) 3948 KeepEdge2 = nullptr; 3949 else { 3950 Succ->removePredecessor(BB, 3951 /*KeepOneInputPHIs=*/true); 3952 3953 if (Succ != TrueBB && Succ != FalseBB) 3954 RemovedSuccessors.insert(Succ); 3955 } 3956 } 3957 3958 IRBuilder<> Builder(OldTerm); 3959 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 3960 3961 // Insert an appropriate new terminator. 3962 if (!KeepEdge1 && !KeepEdge2) { 3963 if (TrueBB == FalseBB) { 3964 // We were only looking for one successor, and it was present. 3965 // Create an unconditional branch to it. 3966 Builder.CreateBr(TrueBB); 3967 } else { 3968 // We found both of the successors we were looking for. 3969 // Create a conditional branch sharing the condition of the select. 3970 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 3971 if (TrueWeight != FalseWeight) 3972 setBranchWeights(NewBI, TrueWeight, FalseWeight); 3973 } 3974 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 3975 // Neither of the selected blocks were successors, so this 3976 // terminator must be unreachable. 3977 new UnreachableInst(OldTerm->getContext(), OldTerm); 3978 } else { 3979 // One of the selected values was a successor, but the other wasn't. 3980 // Insert an unconditional branch to the one that was found; 3981 // the edge to the one that wasn't must be unreachable. 3982 if (!KeepEdge1) { 3983 // Only TrueBB was found. 3984 Builder.CreateBr(TrueBB); 3985 } else { 3986 // Only FalseBB was found. 3987 Builder.CreateBr(FalseBB); 3988 } 3989 } 3990 3991 EraseTerminatorAndDCECond(OldTerm); 3992 3993 if (DTU) { 3994 SmallVector<DominatorTree::UpdateType, 2> Updates; 3995 Updates.reserve(RemovedSuccessors.size()); 3996 for (auto *RemovedSuccessor : RemovedSuccessors) 3997 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor}); 3998 DTU->applyUpdates(Updates); 3999 } 4000 4001 return true; 4002 } 4003 4004 // Replaces 4005 // (switch (select cond, X, Y)) on constant X, Y 4006 // with a branch - conditional if X and Y lead to distinct BBs, 4007 // unconditional otherwise. 4008 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI, 4009 SelectInst *Select) { 4010 // Check for constant integer values in the select. 4011 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 4012 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 4013 if (!TrueVal || !FalseVal) 4014 return false; 4015 4016 // Find the relevant condition and destinations. 4017 Value *Condition = Select->getCondition(); 4018 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor(); 4019 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor(); 4020 4021 // Get weight for TrueBB and FalseBB. 4022 uint32_t TrueWeight = 0, FalseWeight = 0; 4023 SmallVector<uint64_t, 8> Weights; 4024 bool HasWeights = HasBranchWeights(SI); 4025 if (HasWeights) { 4026 GetBranchWeights(SI, Weights); 4027 if (Weights.size() == 1 + SI->getNumCases()) { 4028 TrueWeight = 4029 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()]; 4030 FalseWeight = 4031 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()]; 4032 } 4033 } 4034 4035 // Perform the actual simplification. 4036 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight, 4037 FalseWeight); 4038 } 4039 4040 // Replaces 4041 // (indirectbr (select cond, blockaddress(@fn, BlockA), 4042 // blockaddress(@fn, BlockB))) 4043 // with 4044 // (br cond, BlockA, BlockB). 4045 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, 4046 SelectInst *SI) { 4047 // Check that both operands of the select are block addresses. 4048 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 4049 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 4050 if (!TBA || !FBA) 4051 return false; 4052 4053 // Extract the actual blocks. 4054 BasicBlock *TrueBB = TBA->getBasicBlock(); 4055 BasicBlock *FalseBB = FBA->getBasicBlock(); 4056 4057 // Perform the actual simplification. 4058 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0, 4059 0); 4060 } 4061 4062 /// This is called when we find an icmp instruction 4063 /// (a seteq/setne with a constant) as the only instruction in a 4064 /// block that ends with an uncond branch. We are looking for a very specific 4065 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 4066 /// this case, we merge the first two "or's of icmp" into a switch, but then the 4067 /// default value goes to an uncond block with a seteq in it, we get something 4068 /// like: 4069 /// 4070 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 4071 /// DEFAULT: 4072 /// %tmp = icmp eq i8 %A, 92 4073 /// br label %end 4074 /// end: 4075 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 4076 /// 4077 /// We prefer to split the edge to 'end' so that there is a true/false entry to 4078 /// the PHI, merging the third icmp into the switch. 4079 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( 4080 ICmpInst *ICI, IRBuilder<> &Builder) { 4081 BasicBlock *BB = ICI->getParent(); 4082 4083 // If the block has any PHIs in it or the icmp has multiple uses, it is too 4084 // complex. 4085 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) 4086 return false; 4087 4088 Value *V = ICI->getOperand(0); 4089 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 4090 4091 // The pattern we're looking for is where our only predecessor is a switch on 4092 // 'V' and this block is the default case for the switch. In this case we can 4093 // fold the compared value into the switch to simplify things. 4094 BasicBlock *Pred = BB->getSinglePredecessor(); 4095 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) 4096 return false; 4097 4098 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 4099 if (SI->getCondition() != V) 4100 return false; 4101 4102 // If BB is reachable on a non-default case, then we simply know the value of 4103 // V in this block. Substitute it and constant fold the icmp instruction 4104 // away. 4105 if (SI->getDefaultDest() != BB) { 4106 ConstantInt *VVal = SI->findCaseDest(BB); 4107 assert(VVal && "Should have a unique destination value"); 4108 ICI->setOperand(0, VVal); 4109 4110 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) { 4111 ICI->replaceAllUsesWith(V); 4112 ICI->eraseFromParent(); 4113 } 4114 // BB is now empty, so it is likely to simplify away. 4115 return requestResimplify(); 4116 } 4117 4118 // Ok, the block is reachable from the default dest. If the constant we're 4119 // comparing exists in one of the other edges, then we can constant fold ICI 4120 // and zap it. 4121 if (SI->findCaseValue(Cst) != SI->case_default()) { 4122 Value *V; 4123 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 4124 V = ConstantInt::getFalse(BB->getContext()); 4125 else 4126 V = ConstantInt::getTrue(BB->getContext()); 4127 4128 ICI->replaceAllUsesWith(V); 4129 ICI->eraseFromParent(); 4130 // BB is now empty, so it is likely to simplify away. 4131 return requestResimplify(); 4132 } 4133 4134 // The use of the icmp has to be in the 'end' block, by the only PHI node in 4135 // the block. 4136 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 4137 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); 4138 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || 4139 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 4140 return false; 4141 4142 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 4143 // true in the PHI. 4144 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 4145 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 4146 4147 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 4148 std::swap(DefaultCst, NewCst); 4149 4150 // Replace ICI (which is used by the PHI for the default value) with true or 4151 // false depending on if it is EQ or NE. 4152 ICI->replaceAllUsesWith(DefaultCst); 4153 ICI->eraseFromParent(); 4154 4155 SmallVector<DominatorTree::UpdateType, 2> Updates; 4156 4157 // Okay, the switch goes to this block on a default value. Add an edge from 4158 // the switch to the merge point on the compared value. 4159 BasicBlock *NewBB = 4160 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB); 4161 { 4162 SwitchInstProfUpdateWrapper SIW(*SI); 4163 auto W0 = SIW.getSuccessorWeight(0); 4164 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW; 4165 if (W0) { 4166 NewW = ((uint64_t(*W0) + 1) >> 1); 4167 SIW.setSuccessorWeight(0, *NewW); 4168 } 4169 SIW.addCase(Cst, NewBB, NewW); 4170 if (DTU) 4171 Updates.push_back({DominatorTree::Insert, Pred, NewBB}); 4172 } 4173 4174 // NewBB branches to the phi block, add the uncond branch and the phi entry. 4175 Builder.SetInsertPoint(NewBB); 4176 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 4177 Builder.CreateBr(SuccBlock); 4178 PHIUse->addIncoming(NewCst, NewBB); 4179 if (DTU) { 4180 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock}); 4181 DTU->applyUpdates(Updates); 4182 } 4183 return true; 4184 } 4185 4186 /// The specified branch is a conditional branch. 4187 /// Check to see if it is branching on an or/and chain of icmp instructions, and 4188 /// fold it into a switch instruction if so. 4189 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI, 4190 IRBuilder<> &Builder, 4191 const DataLayout &DL) { 4192 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 4193 if (!Cond) 4194 return false; 4195 4196 // Change br (X == 0 | X == 1), T, F into a switch instruction. 4197 // If this is a bunch of seteq's or'd together, or if it's a bunch of 4198 // 'setne's and'ed together, collect them. 4199 4200 // Try to gather values from a chain of and/or to be turned into a switch 4201 ConstantComparesGatherer ConstantCompare(Cond, DL); 4202 // Unpack the result 4203 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals; 4204 Value *CompVal = ConstantCompare.CompValue; 4205 unsigned UsedICmps = ConstantCompare.UsedICmps; 4206 Value *ExtraCase = ConstantCompare.Extra; 4207 4208 // If we didn't have a multiply compared value, fail. 4209 if (!CompVal) 4210 return false; 4211 4212 // Avoid turning single icmps into a switch. 4213 if (UsedICmps <= 1) 4214 return false; 4215 4216 bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value())); 4217 4218 // There might be duplicate constants in the list, which the switch 4219 // instruction can't handle, remove them now. 4220 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 4221 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 4222 4223 // If Extra was used, we require at least two switch values to do the 4224 // transformation. A switch with one value is just a conditional branch. 4225 if (ExtraCase && Values.size() < 2) 4226 return false; 4227 4228 // TODO: Preserve branch weight metadata, similarly to how 4229 // FoldValueComparisonIntoPredecessors preserves it. 4230 4231 // Figure out which block is which destination. 4232 BasicBlock *DefaultBB = BI->getSuccessor(1); 4233 BasicBlock *EdgeBB = BI->getSuccessor(0); 4234 if (!TrueWhenEqual) 4235 std::swap(DefaultBB, EdgeBB); 4236 4237 BasicBlock *BB = BI->getParent(); 4238 4239 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 4240 << " cases into SWITCH. BB is:\n" 4241 << *BB); 4242 4243 SmallVector<DominatorTree::UpdateType, 2> Updates; 4244 4245 // If there are any extra values that couldn't be folded into the switch 4246 // then we evaluate them with an explicit branch first. Split the block 4247 // right before the condbr to handle it. 4248 if (ExtraCase) { 4249 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr, 4250 /*MSSAU=*/nullptr, "switch.early.test"); 4251 4252 // Remove the uncond branch added to the old block. 4253 Instruction *OldTI = BB->getTerminator(); 4254 Builder.SetInsertPoint(OldTI); 4255 4256 // There can be an unintended UB if extra values are Poison. Before the 4257 // transformation, extra values may not be evaluated according to the 4258 // condition, and it will not raise UB. But after transformation, we are 4259 // evaluating extra values before checking the condition, and it will raise 4260 // UB. It can be solved by adding freeze instruction to extra values. 4261 AssumptionCache *AC = Options.AC; 4262 4263 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr)) 4264 ExtraCase = Builder.CreateFreeze(ExtraCase); 4265 4266 if (TrueWhenEqual) 4267 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 4268 else 4269 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 4270 4271 OldTI->eraseFromParent(); 4272 4273 if (DTU) 4274 Updates.push_back({DominatorTree::Insert, BB, EdgeBB}); 4275 4276 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 4277 // for the edge we just added. 4278 AddPredecessorToBlock(EdgeBB, BB, NewBB); 4279 4280 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 4281 << "\nEXTRABB = " << *BB); 4282 BB = NewBB; 4283 } 4284 4285 Builder.SetInsertPoint(BI); 4286 // Convert pointer to int before we switch. 4287 if (CompVal->getType()->isPointerTy()) { 4288 CompVal = Builder.CreatePtrToInt( 4289 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); 4290 } 4291 4292 // Create the new switch instruction now. 4293 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 4294 4295 // Add all of the 'cases' to the switch instruction. 4296 for (unsigned i = 0, e = Values.size(); i != e; ++i) 4297 New->addCase(Values[i], EdgeBB); 4298 4299 // We added edges from PI to the EdgeBB. As such, if there were any 4300 // PHI nodes in EdgeBB, they need entries to be added corresponding to 4301 // the number of edges added. 4302 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) { 4303 PHINode *PN = cast<PHINode>(BBI); 4304 Value *InVal = PN->getIncomingValueForBlock(BB); 4305 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i) 4306 PN->addIncoming(InVal, BB); 4307 } 4308 4309 // Erase the old branch instruction. 4310 EraseTerminatorAndDCECond(BI); 4311 if (DTU) 4312 DTU->applyUpdates(Updates); 4313 4314 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 4315 return true; 4316 } 4317 4318 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 4319 if (isa<PHINode>(RI->getValue())) 4320 return simplifyCommonResume(RI); 4321 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) && 4322 RI->getValue() == RI->getParent()->getFirstNonPHI()) 4323 // The resume must unwind the exception that caused control to branch here. 4324 return simplifySingleResume(RI); 4325 4326 return false; 4327 } 4328 4329 // Check if cleanup block is empty 4330 static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) { 4331 for (Instruction &I : R) { 4332 auto *II = dyn_cast<IntrinsicInst>(&I); 4333 if (!II) 4334 return false; 4335 4336 Intrinsic::ID IntrinsicID = II->getIntrinsicID(); 4337 switch (IntrinsicID) { 4338 case Intrinsic::dbg_declare: 4339 case Intrinsic::dbg_value: 4340 case Intrinsic::dbg_label: 4341 case Intrinsic::lifetime_end: 4342 break; 4343 default: 4344 return false; 4345 } 4346 } 4347 return true; 4348 } 4349 4350 // Simplify resume that is shared by several landing pads (phi of landing pad). 4351 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) { 4352 BasicBlock *BB = RI->getParent(); 4353 4354 // Check that there are no other instructions except for debug and lifetime 4355 // intrinsics between the phi's and resume instruction. 4356 if (!isCleanupBlockEmpty( 4357 make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator()))) 4358 return false; 4359 4360 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks; 4361 auto *PhiLPInst = cast<PHINode>(RI->getValue()); 4362 4363 // Check incoming blocks to see if any of them are trivial. 4364 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End; 4365 Idx++) { 4366 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx); 4367 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx); 4368 4369 // If the block has other successors, we can not delete it because 4370 // it has other dependents. 4371 if (IncomingBB->getUniqueSuccessor() != BB) 4372 continue; 4373 4374 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI()); 4375 // Not the landing pad that caused the control to branch here. 4376 if (IncomingValue != LandingPad) 4377 continue; 4378 4379 if (isCleanupBlockEmpty( 4380 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator()))) 4381 TrivialUnwindBlocks.insert(IncomingBB); 4382 } 4383 4384 // If no trivial unwind blocks, don't do any simplifications. 4385 if (TrivialUnwindBlocks.empty()) 4386 return false; 4387 4388 // Turn all invokes that unwind here into calls. 4389 for (auto *TrivialBB : TrivialUnwindBlocks) { 4390 // Blocks that will be simplified should be removed from the phi node. 4391 // Note there could be multiple edges to the resume block, and we need 4392 // to remove them all. 4393 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1) 4394 BB->removePredecessor(TrivialBB, true); 4395 4396 for (BasicBlock *Pred : 4397 llvm::make_early_inc_range(predecessors(TrivialBB))) { 4398 removeUnwindEdge(Pred, DTU); 4399 ++NumInvokes; 4400 } 4401 4402 // In each SimplifyCFG run, only the current processed block can be erased. 4403 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead 4404 // of erasing TrivialBB, we only remove the branch to the common resume 4405 // block so that we can later erase the resume block since it has no 4406 // predecessors. 4407 TrivialBB->getTerminator()->eraseFromParent(); 4408 new UnreachableInst(RI->getContext(), TrivialBB); 4409 if (DTU) 4410 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}}); 4411 } 4412 4413 // Delete the resume block if all its predecessors have been removed. 4414 if (pred_empty(BB)) 4415 DeleteDeadBlock(BB, DTU); 4416 4417 return !TrivialUnwindBlocks.empty(); 4418 } 4419 4420 // Simplify resume that is only used by a single (non-phi) landing pad. 4421 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) { 4422 BasicBlock *BB = RI->getParent(); 4423 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI()); 4424 assert(RI->getValue() == LPInst && 4425 "Resume must unwind the exception that caused control to here"); 4426 4427 // Check that there are no other instructions except for debug intrinsics. 4428 if (!isCleanupBlockEmpty( 4429 make_range<Instruction *>(LPInst->getNextNode(), RI))) 4430 return false; 4431 4432 // Turn all invokes that unwind here into calls and delete the basic block. 4433 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) { 4434 removeUnwindEdge(Pred, DTU); 4435 ++NumInvokes; 4436 } 4437 4438 // The landingpad is now unreachable. Zap it. 4439 DeleteDeadBlock(BB, DTU); 4440 return true; 4441 } 4442 4443 static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) { 4444 // If this is a trivial cleanup pad that executes no instructions, it can be 4445 // eliminated. If the cleanup pad continues to the caller, any predecessor 4446 // that is an EH pad will be updated to continue to the caller and any 4447 // predecessor that terminates with an invoke instruction will have its invoke 4448 // instruction converted to a call instruction. If the cleanup pad being 4449 // simplified does not continue to the caller, each predecessor will be 4450 // updated to continue to the unwind destination of the cleanup pad being 4451 // simplified. 4452 BasicBlock *BB = RI->getParent(); 4453 CleanupPadInst *CPInst = RI->getCleanupPad(); 4454 if (CPInst->getParent() != BB) 4455 // This isn't an empty cleanup. 4456 return false; 4457 4458 // We cannot kill the pad if it has multiple uses. This typically arises 4459 // from unreachable basic blocks. 4460 if (!CPInst->hasOneUse()) 4461 return false; 4462 4463 // Check that there are no other instructions except for benign intrinsics. 4464 if (!isCleanupBlockEmpty( 4465 make_range<Instruction *>(CPInst->getNextNode(), RI))) 4466 return false; 4467 4468 // If the cleanup return we are simplifying unwinds to the caller, this will 4469 // set UnwindDest to nullptr. 4470 BasicBlock *UnwindDest = RI->getUnwindDest(); 4471 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr; 4472 4473 // We're about to remove BB from the control flow. Before we do, sink any 4474 // PHINodes into the unwind destination. Doing this before changing the 4475 // control flow avoids some potentially slow checks, since we can currently 4476 // be certain that UnwindDest and BB have no common predecessors (since they 4477 // are both EH pads). 4478 if (UnwindDest) { 4479 // First, go through the PHI nodes in UnwindDest and update any nodes that 4480 // reference the block we are removing 4481 for (PHINode &DestPN : UnwindDest->phis()) { 4482 int Idx = DestPN.getBasicBlockIndex(BB); 4483 // Since BB unwinds to UnwindDest, it has to be in the PHI node. 4484 assert(Idx != -1); 4485 // This PHI node has an incoming value that corresponds to a control 4486 // path through the cleanup pad we are removing. If the incoming 4487 // value is in the cleanup pad, it must be a PHINode (because we 4488 // verified above that the block is otherwise empty). Otherwise, the 4489 // value is either a constant or a value that dominates the cleanup 4490 // pad being removed. 4491 // 4492 // Because BB and UnwindDest are both EH pads, all of their 4493 // predecessors must unwind to these blocks, and since no instruction 4494 // can have multiple unwind destinations, there will be no overlap in 4495 // incoming blocks between SrcPN and DestPN. 4496 Value *SrcVal = DestPN.getIncomingValue(Idx); 4497 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); 4498 4499 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB; 4500 for (auto *Pred : predecessors(BB)) { 4501 Value *Incoming = 4502 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal; 4503 DestPN.addIncoming(Incoming, Pred); 4504 } 4505 } 4506 4507 // Sink any remaining PHI nodes directly into UnwindDest. 4508 Instruction *InsertPt = DestEHPad; 4509 for (PHINode &PN : make_early_inc_range(BB->phis())) { 4510 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB)) 4511 // If the PHI node has no uses or all of its uses are in this basic 4512 // block (meaning they are debug or lifetime intrinsics), just leave 4513 // it. It will be erased when we erase BB below. 4514 continue; 4515 4516 // Otherwise, sink this PHI node into UnwindDest. 4517 // Any predecessors to UnwindDest which are not already represented 4518 // must be back edges which inherit the value from the path through 4519 // BB. In this case, the PHI value must reference itself. 4520 for (auto *pred : predecessors(UnwindDest)) 4521 if (pred != BB) 4522 PN.addIncoming(&PN, pred); 4523 PN.moveBefore(InsertPt); 4524 // Also, add a dummy incoming value for the original BB itself, 4525 // so that the PHI is well-formed until we drop said predecessor. 4526 PN.addIncoming(UndefValue::get(PN.getType()), BB); 4527 } 4528 } 4529 4530 std::vector<DominatorTree::UpdateType> Updates; 4531 4532 // We use make_early_inc_range here because we will remove all predecessors. 4533 for (BasicBlock *PredBB : llvm::make_early_inc_range(predecessors(BB))) { 4534 if (UnwindDest == nullptr) { 4535 if (DTU) { 4536 DTU->applyUpdates(Updates); 4537 Updates.clear(); 4538 } 4539 removeUnwindEdge(PredBB, DTU); 4540 ++NumInvokes; 4541 } else { 4542 BB->removePredecessor(PredBB); 4543 Instruction *TI = PredBB->getTerminator(); 4544 TI->replaceUsesOfWith(BB, UnwindDest); 4545 if (DTU) { 4546 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest}); 4547 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 4548 } 4549 } 4550 } 4551 4552 if (DTU) 4553 DTU->applyUpdates(Updates); 4554 4555 DeleteDeadBlock(BB, DTU); 4556 4557 return true; 4558 } 4559 4560 // Try to merge two cleanuppads together. 4561 static bool mergeCleanupPad(CleanupReturnInst *RI) { 4562 // Skip any cleanuprets which unwind to caller, there is nothing to merge 4563 // with. 4564 BasicBlock *UnwindDest = RI->getUnwindDest(); 4565 if (!UnwindDest) 4566 return false; 4567 4568 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't 4569 // be safe to merge without code duplication. 4570 if (UnwindDest->getSinglePredecessor() != RI->getParent()) 4571 return false; 4572 4573 // Verify that our cleanuppad's unwind destination is another cleanuppad. 4574 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front()); 4575 if (!SuccessorCleanupPad) 4576 return false; 4577 4578 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad(); 4579 // Replace any uses of the successor cleanupad with the predecessor pad 4580 // The only cleanuppad uses should be this cleanupret, it's cleanupret and 4581 // funclet bundle operands. 4582 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad); 4583 // Remove the old cleanuppad. 4584 SuccessorCleanupPad->eraseFromParent(); 4585 // Now, we simply replace the cleanupret with a branch to the unwind 4586 // destination. 4587 BranchInst::Create(UnwindDest, RI->getParent()); 4588 RI->eraseFromParent(); 4589 4590 return true; 4591 } 4592 4593 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) { 4594 // It is possible to transiantly have an undef cleanuppad operand because we 4595 // have deleted some, but not all, dead blocks. 4596 // Eventually, this block will be deleted. 4597 if (isa<UndefValue>(RI->getOperand(0))) 4598 return false; 4599 4600 if (mergeCleanupPad(RI)) 4601 return true; 4602 4603 if (removeEmptyCleanup(RI, DTU)) 4604 return true; 4605 4606 return false; 4607 } 4608 4609 // WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()! 4610 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) { 4611 BasicBlock *BB = UI->getParent(); 4612 4613 bool Changed = false; 4614 4615 // If there are any instructions immediately before the unreachable that can 4616 // be removed, do so. 4617 while (UI->getIterator() != BB->begin()) { 4618 BasicBlock::iterator BBI = UI->getIterator(); 4619 --BBI; 4620 4621 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI)) 4622 break; // Can not drop any more instructions. We're done here. 4623 // Otherwise, this instruction can be freely erased, 4624 // even if it is not side-effect free. 4625 4626 // Note that deleting EH's here is in fact okay, although it involves a bit 4627 // of subtle reasoning. If this inst is an EH, all the predecessors of this 4628 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn, 4629 // and we can therefore guarantee this block will be erased. 4630 4631 // Delete this instruction (any uses are guaranteed to be dead) 4632 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType())); 4633 BBI->eraseFromParent(); 4634 Changed = true; 4635 } 4636 4637 // If the unreachable instruction is the first in the block, take a gander 4638 // at all of the predecessors of this instruction, and simplify them. 4639 if (&BB->front() != UI) 4640 return Changed; 4641 4642 std::vector<DominatorTree::UpdateType> Updates; 4643 4644 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB)); 4645 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 4646 auto *Predecessor = Preds[i]; 4647 Instruction *TI = Predecessor->getTerminator(); 4648 IRBuilder<> Builder(TI); 4649 if (auto *BI = dyn_cast<BranchInst>(TI)) { 4650 // We could either have a proper unconditional branch, 4651 // or a degenerate conditional branch with matching destinations. 4652 if (all_of(BI->successors(), 4653 [BB](auto *Successor) { return Successor == BB; })) { 4654 new UnreachableInst(TI->getContext(), TI); 4655 TI->eraseFromParent(); 4656 Changed = true; 4657 } else { 4658 assert(BI->isConditional() && "Can't get here with an uncond branch."); 4659 Value* Cond = BI->getCondition(); 4660 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4661 "The destinations are guaranteed to be different here."); 4662 if (BI->getSuccessor(0) == BB) { 4663 Builder.CreateAssumption(Builder.CreateNot(Cond)); 4664 Builder.CreateBr(BI->getSuccessor(1)); 4665 } else { 4666 assert(BI->getSuccessor(1) == BB && "Incorrect CFG"); 4667 Builder.CreateAssumption(Cond); 4668 Builder.CreateBr(BI->getSuccessor(0)); 4669 } 4670 EraseTerminatorAndDCECond(BI); 4671 Changed = true; 4672 } 4673 if (DTU) 4674 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4675 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { 4676 SwitchInstProfUpdateWrapper SU(*SI); 4677 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) { 4678 if (i->getCaseSuccessor() != BB) { 4679 ++i; 4680 continue; 4681 } 4682 BB->removePredecessor(SU->getParent()); 4683 i = SU.removeCase(i); 4684 e = SU->case_end(); 4685 Changed = true; 4686 } 4687 // Note that the default destination can't be removed! 4688 if (DTU && SI->getDefaultDest() != BB) 4689 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4690 } else if (auto *II = dyn_cast<InvokeInst>(TI)) { 4691 if (II->getUnwindDest() == BB) { 4692 if (DTU) { 4693 DTU->applyUpdates(Updates); 4694 Updates.clear(); 4695 } 4696 removeUnwindEdge(TI->getParent(), DTU); 4697 Changed = true; 4698 } 4699 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 4700 if (CSI->getUnwindDest() == BB) { 4701 if (DTU) { 4702 DTU->applyUpdates(Updates); 4703 Updates.clear(); 4704 } 4705 removeUnwindEdge(TI->getParent(), DTU); 4706 Changed = true; 4707 continue; 4708 } 4709 4710 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(), 4711 E = CSI->handler_end(); 4712 I != E; ++I) { 4713 if (*I == BB) { 4714 CSI->removeHandler(I); 4715 --I; 4716 --E; 4717 Changed = true; 4718 } 4719 } 4720 if (DTU) 4721 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4722 if (CSI->getNumHandlers() == 0) { 4723 if (CSI->hasUnwindDest()) { 4724 // Redirect all predecessors of the block containing CatchSwitchInst 4725 // to instead branch to the CatchSwitchInst's unwind destination. 4726 if (DTU) { 4727 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) { 4728 Updates.push_back({DominatorTree::Insert, 4729 PredecessorOfPredecessor, 4730 CSI->getUnwindDest()}); 4731 Updates.push_back({DominatorTree::Delete, 4732 PredecessorOfPredecessor, Predecessor}); 4733 } 4734 } 4735 Predecessor->replaceAllUsesWith(CSI->getUnwindDest()); 4736 } else { 4737 // Rewrite all preds to unwind to caller (or from invoke to call). 4738 if (DTU) { 4739 DTU->applyUpdates(Updates); 4740 Updates.clear(); 4741 } 4742 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor)); 4743 for (BasicBlock *EHPred : EHPreds) 4744 removeUnwindEdge(EHPred, DTU); 4745 } 4746 // The catchswitch is no longer reachable. 4747 new UnreachableInst(CSI->getContext(), CSI); 4748 CSI->eraseFromParent(); 4749 Changed = true; 4750 } 4751 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 4752 (void)CRI; 4753 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB && 4754 "Expected to always have an unwind to BB."); 4755 if (DTU) 4756 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4757 new UnreachableInst(TI->getContext(), TI); 4758 TI->eraseFromParent(); 4759 Changed = true; 4760 } 4761 } 4762 4763 if (DTU) 4764 DTU->applyUpdates(Updates); 4765 4766 // If this block is now dead, remove it. 4767 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) { 4768 DeleteDeadBlock(BB, DTU); 4769 return true; 4770 } 4771 4772 return Changed; 4773 } 4774 4775 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { 4776 assert(Cases.size() >= 1); 4777 4778 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 4779 for (size_t I = 1, E = Cases.size(); I != E; ++I) { 4780 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) 4781 return false; 4782 } 4783 return true; 4784 } 4785 4786 static void createUnreachableSwitchDefault(SwitchInst *Switch, 4787 DomTreeUpdater *DTU) { 4788 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); 4789 auto *BB = Switch->getParent(); 4790 auto *OrigDefaultBlock = Switch->getDefaultDest(); 4791 OrigDefaultBlock->removePredecessor(BB); 4792 BasicBlock *NewDefaultBlock = BasicBlock::Create( 4793 BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(), 4794 OrigDefaultBlock); 4795 new UnreachableInst(Switch->getContext(), NewDefaultBlock); 4796 Switch->setDefaultDest(&*NewDefaultBlock); 4797 if (DTU) { 4798 SmallVector<DominatorTree::UpdateType, 2> Updates; 4799 Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock}); 4800 if (!is_contained(successors(BB), OrigDefaultBlock)) 4801 Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock}); 4802 DTU->applyUpdates(Updates); 4803 } 4804 } 4805 4806 /// Turn a switch with two reachable destinations into an integer range 4807 /// comparison and branch. 4808 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI, 4809 IRBuilder<> &Builder) { 4810 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 4811 4812 bool HasDefault = 4813 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4814 4815 auto *BB = SI->getParent(); 4816 4817 // Partition the cases into two sets with different destinations. 4818 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; 4819 BasicBlock *DestB = nullptr; 4820 SmallVector<ConstantInt *, 16> CasesA; 4821 SmallVector<ConstantInt *, 16> CasesB; 4822 4823 for (auto Case : SI->cases()) { 4824 BasicBlock *Dest = Case.getCaseSuccessor(); 4825 if (!DestA) 4826 DestA = Dest; 4827 if (Dest == DestA) { 4828 CasesA.push_back(Case.getCaseValue()); 4829 continue; 4830 } 4831 if (!DestB) 4832 DestB = Dest; 4833 if (Dest == DestB) { 4834 CasesB.push_back(Case.getCaseValue()); 4835 continue; 4836 } 4837 return false; // More than two destinations. 4838 } 4839 4840 assert(DestA && DestB && 4841 "Single-destination switch should have been folded."); 4842 assert(DestA != DestB); 4843 assert(DestB != SI->getDefaultDest()); 4844 assert(!CasesB.empty() && "There must be non-default cases."); 4845 assert(!CasesA.empty() || HasDefault); 4846 4847 // Figure out if one of the sets of cases form a contiguous range. 4848 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; 4849 BasicBlock *ContiguousDest = nullptr; 4850 BasicBlock *OtherDest = nullptr; 4851 if (!CasesA.empty() && CasesAreContiguous(CasesA)) { 4852 ContiguousCases = &CasesA; 4853 ContiguousDest = DestA; 4854 OtherDest = DestB; 4855 } else if (CasesAreContiguous(CasesB)) { 4856 ContiguousCases = &CasesB; 4857 ContiguousDest = DestB; 4858 OtherDest = DestA; 4859 } else 4860 return false; 4861 4862 // Start building the compare and branch. 4863 4864 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); 4865 Constant *NumCases = 4866 ConstantInt::get(Offset->getType(), ContiguousCases->size()); 4867 4868 Value *Sub = SI->getCondition(); 4869 if (!Offset->isNullValue()) 4870 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); 4871 4872 Value *Cmp; 4873 // If NumCases overflowed, then all possible values jump to the successor. 4874 if (NumCases->isNullValue() && !ContiguousCases->empty()) 4875 Cmp = ConstantInt::getTrue(SI->getContext()); 4876 else 4877 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 4878 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); 4879 4880 // Update weight for the newly-created conditional branch. 4881 if (HasBranchWeights(SI)) { 4882 SmallVector<uint64_t, 8> Weights; 4883 GetBranchWeights(SI, Weights); 4884 if (Weights.size() == 1 + SI->getNumCases()) { 4885 uint64_t TrueWeight = 0; 4886 uint64_t FalseWeight = 0; 4887 for (size_t I = 0, E = Weights.size(); I != E; ++I) { 4888 if (SI->getSuccessor(I) == ContiguousDest) 4889 TrueWeight += Weights[I]; 4890 else 4891 FalseWeight += Weights[I]; 4892 } 4893 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { 4894 TrueWeight /= 2; 4895 FalseWeight /= 2; 4896 } 4897 setBranchWeights(NewBI, TrueWeight, FalseWeight); 4898 } 4899 } 4900 4901 // Prune obsolete incoming values off the successors' PHI nodes. 4902 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { 4903 unsigned PreviousEdges = ContiguousCases->size(); 4904 if (ContiguousDest == SI->getDefaultDest()) 4905 ++PreviousEdges; 4906 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4907 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4908 } 4909 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { 4910 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); 4911 if (OtherDest == SI->getDefaultDest()) 4912 ++PreviousEdges; 4913 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4914 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4915 } 4916 4917 // Clean up the default block - it may have phis or other instructions before 4918 // the unreachable terminator. 4919 if (!HasDefault) 4920 createUnreachableSwitchDefault(SI, DTU); 4921 4922 auto *UnreachableDefault = SI->getDefaultDest(); 4923 4924 // Drop the switch. 4925 SI->eraseFromParent(); 4926 4927 if (!HasDefault && DTU) 4928 DTU->applyUpdates({{DominatorTree::Delete, BB, UnreachableDefault}}); 4929 4930 return true; 4931 } 4932 4933 /// Compute masked bits for the condition of a switch 4934 /// and use it to remove dead cases. 4935 static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU, 4936 AssumptionCache *AC, 4937 const DataLayout &DL) { 4938 Value *Cond = SI->getCondition(); 4939 unsigned Bits = Cond->getType()->getIntegerBitWidth(); 4940 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI); 4941 4942 // We can also eliminate cases by determining that their values are outside of 4943 // the limited range of the condition based on how many significant (non-sign) 4944 // bits are in the condition value. 4945 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1; 4946 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits; 4947 4948 // Gather dead cases. 4949 SmallVector<ConstantInt *, 8> DeadCases; 4950 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases; 4951 for (auto &Case : SI->cases()) { 4952 auto *Successor = Case.getCaseSuccessor(); 4953 if (DTU) 4954 ++NumPerSuccessorCases[Successor]; 4955 const APInt &CaseVal = Case.getCaseValue()->getValue(); 4956 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) || 4957 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) { 4958 DeadCases.push_back(Case.getCaseValue()); 4959 if (DTU) 4960 --NumPerSuccessorCases[Successor]; 4961 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal 4962 << " is dead.\n"); 4963 } 4964 } 4965 4966 // If we can prove that the cases must cover all possible values, the 4967 // default destination becomes dead and we can remove it. If we know some 4968 // of the bits in the value, we can use that to more precisely compute the 4969 // number of possible unique case values. 4970 bool HasDefault = 4971 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4972 const unsigned NumUnknownBits = 4973 Bits - (Known.Zero | Known.One).countPopulation(); 4974 assert(NumUnknownBits <= Bits); 4975 if (HasDefault && DeadCases.empty() && 4976 NumUnknownBits < 64 /* avoid overflow */ && 4977 SI->getNumCases() == (1ULL << NumUnknownBits)) { 4978 createUnreachableSwitchDefault(SI, DTU); 4979 return true; 4980 } 4981 4982 if (DeadCases.empty()) 4983 return false; 4984 4985 SwitchInstProfUpdateWrapper SIW(*SI); 4986 for (ConstantInt *DeadCase : DeadCases) { 4987 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase); 4988 assert(CaseI != SI->case_default() && 4989 "Case was not found. Probably mistake in DeadCases forming."); 4990 // Prune unused values from PHI nodes. 4991 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent()); 4992 SIW.removeCase(CaseI); 4993 } 4994 4995 if (DTU) { 4996 std::vector<DominatorTree::UpdateType> Updates; 4997 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases) 4998 if (I.second == 0) 4999 Updates.push_back({DominatorTree::Delete, SI->getParent(), I.first}); 5000 DTU->applyUpdates(Updates); 5001 } 5002 5003 return true; 5004 } 5005 5006 /// If BB would be eligible for simplification by 5007 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 5008 /// by an unconditional branch), look at the phi node for BB in the successor 5009 /// block and see if the incoming value is equal to CaseValue. If so, return 5010 /// the phi node, and set PhiIndex to BB's index in the phi node. 5011 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 5012 BasicBlock *BB, int *PhiIndex) { 5013 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 5014 return nullptr; // BB must be empty to be a candidate for simplification. 5015 if (!BB->getSinglePredecessor()) 5016 return nullptr; // BB must be dominated by the switch. 5017 5018 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 5019 if (!Branch || !Branch->isUnconditional()) 5020 return nullptr; // Terminator must be unconditional branch. 5021 5022 BasicBlock *Succ = Branch->getSuccessor(0); 5023 5024 for (PHINode &PHI : Succ->phis()) { 5025 int Idx = PHI.getBasicBlockIndex(BB); 5026 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 5027 5028 Value *InValue = PHI.getIncomingValue(Idx); 5029 if (InValue != CaseValue) 5030 continue; 5031 5032 *PhiIndex = Idx; 5033 return &PHI; 5034 } 5035 5036 return nullptr; 5037 } 5038 5039 /// Try to forward the condition of a switch instruction to a phi node 5040 /// dominated by the switch, if that would mean that some of the destination 5041 /// blocks of the switch can be folded away. Return true if a change is made. 5042 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 5043 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>; 5044 5045 ForwardingNodesMap ForwardingNodes; 5046 BasicBlock *SwitchBlock = SI->getParent(); 5047 bool Changed = false; 5048 for (auto &Case : SI->cases()) { 5049 ConstantInt *CaseValue = Case.getCaseValue(); 5050 BasicBlock *CaseDest = Case.getCaseSuccessor(); 5051 5052 // Replace phi operands in successor blocks that are using the constant case 5053 // value rather than the switch condition variable: 5054 // switchbb: 5055 // switch i32 %x, label %default [ 5056 // i32 17, label %succ 5057 // ... 5058 // succ: 5059 // %r = phi i32 ... [ 17, %switchbb ] ... 5060 // --> 5061 // %r = phi i32 ... [ %x, %switchbb ] ... 5062 5063 for (PHINode &Phi : CaseDest->phis()) { 5064 // This only works if there is exactly 1 incoming edge from the switch to 5065 // a phi. If there is >1, that means multiple cases of the switch map to 1 5066 // value in the phi, and that phi value is not the switch condition. Thus, 5067 // this transform would not make sense (the phi would be invalid because 5068 // a phi can't have different incoming values from the same block). 5069 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock); 5070 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue && 5071 count(Phi.blocks(), SwitchBlock) == 1) { 5072 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition()); 5073 Changed = true; 5074 } 5075 } 5076 5077 // Collect phi nodes that are indirectly using this switch's case constants. 5078 int PhiIdx; 5079 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx)) 5080 ForwardingNodes[Phi].push_back(PhiIdx); 5081 } 5082 5083 for (auto &ForwardingNode : ForwardingNodes) { 5084 PHINode *Phi = ForwardingNode.first; 5085 SmallVectorImpl<int> &Indexes = ForwardingNode.second; 5086 if (Indexes.size() < 2) 5087 continue; 5088 5089 for (int Index : Indexes) 5090 Phi->setIncomingValue(Index, SI->getCondition()); 5091 Changed = true; 5092 } 5093 5094 return Changed; 5095 } 5096 5097 /// Return true if the backend will be able to handle 5098 /// initializing an array of constants like C. 5099 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) { 5100 if (C->isThreadDependent()) 5101 return false; 5102 if (C->isDLLImportDependent()) 5103 return false; 5104 5105 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) && 5106 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) && 5107 !isa<UndefValue>(C) && !isa<ConstantExpr>(C)) 5108 return false; 5109 5110 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 5111 // Pointer casts and in-bounds GEPs will not prohibit the backend from 5112 // materializing the array of constants. 5113 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets()); 5114 if (StrippedC == C || !ValidLookupTableConstant(StrippedC, TTI)) 5115 return false; 5116 } 5117 5118 if (!TTI.shouldBuildLookupTablesForConstant(C)) 5119 return false; 5120 5121 return true; 5122 } 5123 5124 /// If V is a Constant, return it. Otherwise, try to look up 5125 /// its constant value in ConstantPool, returning 0 if it's not there. 5126 static Constant * 5127 LookupConstant(Value *V, 5128 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 5129 if (Constant *C = dyn_cast<Constant>(V)) 5130 return C; 5131 return ConstantPool.lookup(V); 5132 } 5133 5134 /// Try to fold instruction I into a constant. This works for 5135 /// simple instructions such as binary operations where both operands are 5136 /// constant or can be replaced by constants from the ConstantPool. Returns the 5137 /// resulting constant on success, 0 otherwise. 5138 static Constant * 5139 ConstantFold(Instruction *I, const DataLayout &DL, 5140 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 5141 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 5142 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 5143 if (!A) 5144 return nullptr; 5145 if (A->isAllOnesValue()) 5146 return LookupConstant(Select->getTrueValue(), ConstantPool); 5147 if (A->isNullValue()) 5148 return LookupConstant(Select->getFalseValue(), ConstantPool); 5149 return nullptr; 5150 } 5151 5152 SmallVector<Constant *, 4> COps; 5153 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { 5154 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) 5155 COps.push_back(A); 5156 else 5157 return nullptr; 5158 } 5159 5160 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 5161 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], 5162 COps[1], DL); 5163 } 5164 5165 return ConstantFoldInstOperands(I, COps, DL); 5166 } 5167 5168 /// Try to determine the resulting constant values in phi nodes 5169 /// at the common destination basic block, *CommonDest, for one of the case 5170 /// destionations CaseDest corresponding to value CaseVal (0 for the default 5171 /// case), of a switch instruction SI. 5172 static bool 5173 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, 5174 BasicBlock **CommonDest, 5175 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, 5176 const DataLayout &DL, const TargetTransformInfo &TTI) { 5177 // The block from which we enter the common destination. 5178 BasicBlock *Pred = SI->getParent(); 5179 5180 // If CaseDest is empty except for some side-effect free instructions through 5181 // which we can constant-propagate the CaseVal, continue to its successor. 5182 SmallDenseMap<Value *, Constant *> ConstantPool; 5183 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 5184 for (Instruction &I : CaseDest->instructionsWithoutDebug(false)) { 5185 if (I.isTerminator()) { 5186 // If the terminator is a simple branch, continue to the next block. 5187 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator()) 5188 return false; 5189 Pred = CaseDest; 5190 CaseDest = I.getSuccessor(0); 5191 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) { 5192 // Instruction is side-effect free and constant. 5193 5194 // If the instruction has uses outside this block or a phi node slot for 5195 // the block, it is not safe to bypass the instruction since it would then 5196 // no longer dominate all its uses. 5197 for (auto &Use : I.uses()) { 5198 User *User = Use.getUser(); 5199 if (Instruction *I = dyn_cast<Instruction>(User)) 5200 if (I->getParent() == CaseDest) 5201 continue; 5202 if (PHINode *Phi = dyn_cast<PHINode>(User)) 5203 if (Phi->getIncomingBlock(Use) == CaseDest) 5204 continue; 5205 return false; 5206 } 5207 5208 ConstantPool.insert(std::make_pair(&I, C)); 5209 } else { 5210 break; 5211 } 5212 } 5213 5214 // If we did not have a CommonDest before, use the current one. 5215 if (!*CommonDest) 5216 *CommonDest = CaseDest; 5217 // If the destination isn't the common one, abort. 5218 if (CaseDest != *CommonDest) 5219 return false; 5220 5221 // Get the values for this case from phi nodes in the destination block. 5222 for (PHINode &PHI : (*CommonDest)->phis()) { 5223 int Idx = PHI.getBasicBlockIndex(Pred); 5224 if (Idx == -1) 5225 continue; 5226 5227 Constant *ConstVal = 5228 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool); 5229 if (!ConstVal) 5230 return false; 5231 5232 // Be conservative about which kinds of constants we support. 5233 if (!ValidLookupTableConstant(ConstVal, TTI)) 5234 return false; 5235 5236 Res.push_back(std::make_pair(&PHI, ConstVal)); 5237 } 5238 5239 return Res.size() > 0; 5240 } 5241 5242 // Helper function used to add CaseVal to the list of cases that generate 5243 // Result. Returns the updated number of cases that generate this result. 5244 static uintptr_t MapCaseToResult(ConstantInt *CaseVal, 5245 SwitchCaseResultVectorTy &UniqueResults, 5246 Constant *Result) { 5247 for (auto &I : UniqueResults) { 5248 if (I.first == Result) { 5249 I.second.push_back(CaseVal); 5250 return I.second.size(); 5251 } 5252 } 5253 UniqueResults.push_back( 5254 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal))); 5255 return 1; 5256 } 5257 5258 // Helper function that initializes a map containing 5259 // results for the PHI node of the common destination block for a switch 5260 // instruction. Returns false if multiple PHI nodes have been found or if 5261 // there is not a common destination block for the switch. 5262 static bool 5263 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, 5264 SwitchCaseResultVectorTy &UniqueResults, 5265 Constant *&DefaultResult, const DataLayout &DL, 5266 const TargetTransformInfo &TTI, 5267 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) { 5268 for (auto &I : SI->cases()) { 5269 ConstantInt *CaseVal = I.getCaseValue(); 5270 5271 // Resulting value at phi nodes for this case value. 5272 SwitchCaseResultsTy Results; 5273 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, 5274 DL, TTI)) 5275 return false; 5276 5277 // Only one value per case is permitted. 5278 if (Results.size() > 1) 5279 return false; 5280 5281 // Add the case->result mapping to UniqueResults. 5282 const uintptr_t NumCasesForResult = 5283 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); 5284 5285 // Early out if there are too many cases for this result. 5286 if (NumCasesForResult > MaxCasesPerResult) 5287 return false; 5288 5289 // Early out if there are too many unique results. 5290 if (UniqueResults.size() > MaxUniqueResults) 5291 return false; 5292 5293 // Check the PHI consistency. 5294 if (!PHI) 5295 PHI = Results[0].first; 5296 else if (PHI != Results[0].first) 5297 return false; 5298 } 5299 // Find the default result value. 5300 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; 5301 BasicBlock *DefaultDest = SI->getDefaultDest(); 5302 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, 5303 DL, TTI); 5304 // If the default value is not found abort unless the default destination 5305 // is unreachable. 5306 DefaultResult = 5307 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; 5308 if ((!DefaultResult && 5309 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) 5310 return false; 5311 5312 return true; 5313 } 5314 5315 // Helper function that checks if it is possible to transform a switch with only 5316 // two cases (or two cases + default) that produces a result into a select. 5317 // Example: 5318 // switch (a) { 5319 // case 10: %0 = icmp eq i32 %a, 10 5320 // return 10; %1 = select i1 %0, i32 10, i32 4 5321 // case 20: ----> %2 = icmp eq i32 %a, 20 5322 // return 2; %3 = select i1 %2, i32 2, i32 %1 5323 // default: 5324 // return 4; 5325 // } 5326 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, 5327 Constant *DefaultResult, Value *Condition, 5328 IRBuilder<> &Builder) { 5329 // If we are selecting between only two cases transform into a simple 5330 // select or a two-way select if default is possible. 5331 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 && 5332 ResultVector[1].second.size() == 1) { 5333 ConstantInt *const FirstCase = ResultVector[0].second[0]; 5334 ConstantInt *const SecondCase = ResultVector[1].second[0]; 5335 5336 bool DefaultCanTrigger = DefaultResult; 5337 Value *SelectValue = ResultVector[1].first; 5338 if (DefaultCanTrigger) { 5339 Value *const ValueCompare = 5340 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); 5341 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, 5342 DefaultResult, "switch.select"); 5343 } 5344 Value *const ValueCompare = 5345 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); 5346 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, 5347 SelectValue, "switch.select"); 5348 } 5349 5350 // Handle the degenerate case where two cases have the same value. 5351 if (ResultVector.size() == 1 && ResultVector[0].second.size() == 2 && 5352 DefaultResult) { 5353 Value *Cmp1 = Builder.CreateICmpEQ( 5354 Condition, ResultVector[0].second[0], "switch.selectcmp.case1"); 5355 Value *Cmp2 = Builder.CreateICmpEQ( 5356 Condition, ResultVector[0].second[1], "switch.selectcmp.case2"); 5357 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp"); 5358 return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult); 5359 } 5360 5361 return nullptr; 5362 } 5363 5364 // Helper function to cleanup a switch instruction that has been converted into 5365 // a select, fixing up PHI nodes and basic blocks. 5366 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, 5367 Value *SelectValue, 5368 IRBuilder<> &Builder, 5369 DomTreeUpdater *DTU) { 5370 std::vector<DominatorTree::UpdateType> Updates; 5371 5372 BasicBlock *SelectBB = SI->getParent(); 5373 BasicBlock *DestBB = PHI->getParent(); 5374 5375 if (DTU && !is_contained(predecessors(DestBB), SelectBB)) 5376 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB}); 5377 Builder.CreateBr(DestBB); 5378 5379 // Remove the switch. 5380 5381 while (PHI->getBasicBlockIndex(SelectBB) >= 0) 5382 PHI->removeIncomingValue(SelectBB); 5383 PHI->addIncoming(SelectValue, SelectBB); 5384 5385 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors; 5386 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5387 BasicBlock *Succ = SI->getSuccessor(i); 5388 5389 if (Succ == DestBB) 5390 continue; 5391 Succ->removePredecessor(SelectBB); 5392 if (DTU && RemovedSuccessors.insert(Succ).second) 5393 Updates.push_back({DominatorTree::Delete, SelectBB, Succ}); 5394 } 5395 SI->eraseFromParent(); 5396 if (DTU) 5397 DTU->applyUpdates(Updates); 5398 } 5399 5400 /// If the switch is only used to initialize one or more 5401 /// phi nodes in a common successor block with only two different 5402 /// constant values, replace the switch with select. 5403 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder, 5404 DomTreeUpdater *DTU, const DataLayout &DL, 5405 const TargetTransformInfo &TTI) { 5406 Value *const Cond = SI->getCondition(); 5407 PHINode *PHI = nullptr; 5408 BasicBlock *CommonDest = nullptr; 5409 Constant *DefaultResult; 5410 SwitchCaseResultVectorTy UniqueResults; 5411 // Collect all the cases that will deliver the same value from the switch. 5412 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, 5413 DL, TTI, /*MaxUniqueResults*/2, 5414 /*MaxCasesPerResult*/2)) 5415 return false; 5416 assert(PHI != nullptr && "PHI for value select not found"); 5417 5418 Builder.SetInsertPoint(SI); 5419 Value *SelectValue = 5420 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder); 5421 if (SelectValue) { 5422 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder, DTU); 5423 return true; 5424 } 5425 // The switch couldn't be converted into a select. 5426 return false; 5427 } 5428 5429 namespace { 5430 5431 /// This class represents a lookup table that can be used to replace a switch. 5432 class SwitchLookupTable { 5433 public: 5434 /// Create a lookup table to use as a switch replacement with the contents 5435 /// of Values, using DefaultValue to fill any holes in the table. 5436 SwitchLookupTable( 5437 Module &M, uint64_t TableSize, ConstantInt *Offset, 5438 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5439 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName); 5440 5441 /// Build instructions with Builder to retrieve the value at 5442 /// the position given by Index in the lookup table. 5443 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 5444 5445 /// Return true if a table with TableSize elements of 5446 /// type ElementType would fit in a target-legal register. 5447 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, 5448 Type *ElementType); 5449 5450 private: 5451 // Depending on the contents of the table, it can be represented in 5452 // different ways. 5453 enum { 5454 // For tables where each element contains the same value, we just have to 5455 // store that single value and return it for each lookup. 5456 SingleValueKind, 5457 5458 // For tables where there is a linear relationship between table index 5459 // and values. We calculate the result with a simple multiplication 5460 // and addition instead of a table lookup. 5461 LinearMapKind, 5462 5463 // For small tables with integer elements, we can pack them into a bitmap 5464 // that fits into a target-legal register. Values are retrieved by 5465 // shift and mask operations. 5466 BitMapKind, 5467 5468 // The table is stored as an array of values. Values are retrieved by load 5469 // instructions from the table. 5470 ArrayKind 5471 } Kind; 5472 5473 // For SingleValueKind, this is the single value. 5474 Constant *SingleValue = nullptr; 5475 5476 // For BitMapKind, this is the bitmap. 5477 ConstantInt *BitMap = nullptr; 5478 IntegerType *BitMapElementTy = nullptr; 5479 5480 // For LinearMapKind, these are the constants used to derive the value. 5481 ConstantInt *LinearOffset = nullptr; 5482 ConstantInt *LinearMultiplier = nullptr; 5483 5484 // For ArrayKind, this is the array. 5485 GlobalVariable *Array = nullptr; 5486 }; 5487 5488 } // end anonymous namespace 5489 5490 SwitchLookupTable::SwitchLookupTable( 5491 Module &M, uint64_t TableSize, ConstantInt *Offset, 5492 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5493 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) { 5494 assert(Values.size() && "Can't build lookup table without values!"); 5495 assert(TableSize >= Values.size() && "Can't fit values in table!"); 5496 5497 // If all values in the table are equal, this is that value. 5498 SingleValue = Values.begin()->second; 5499 5500 Type *ValueType = Values.begin()->second->getType(); 5501 5502 // Build up the table contents. 5503 SmallVector<Constant *, 64> TableContents(TableSize); 5504 for (size_t I = 0, E = Values.size(); I != E; ++I) { 5505 ConstantInt *CaseVal = Values[I].first; 5506 Constant *CaseRes = Values[I].second; 5507 assert(CaseRes->getType() == ValueType); 5508 5509 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue(); 5510 TableContents[Idx] = CaseRes; 5511 5512 if (CaseRes != SingleValue) 5513 SingleValue = nullptr; 5514 } 5515 5516 // Fill in any holes in the table with the default result. 5517 if (Values.size() < TableSize) { 5518 assert(DefaultValue && 5519 "Need a default value to fill the lookup table holes."); 5520 assert(DefaultValue->getType() == ValueType); 5521 for (uint64_t I = 0; I < TableSize; ++I) { 5522 if (!TableContents[I]) 5523 TableContents[I] = DefaultValue; 5524 } 5525 5526 if (DefaultValue != SingleValue) 5527 SingleValue = nullptr; 5528 } 5529 5530 // If each element in the table contains the same value, we only need to store 5531 // that single value. 5532 if (SingleValue) { 5533 Kind = SingleValueKind; 5534 return; 5535 } 5536 5537 // Check if we can derive the value with a linear transformation from the 5538 // table index. 5539 if (isa<IntegerType>(ValueType)) { 5540 bool LinearMappingPossible = true; 5541 APInt PrevVal; 5542 APInt DistToPrev; 5543 assert(TableSize >= 2 && "Should be a SingleValue table."); 5544 // Check if there is the same distance between two consecutive values. 5545 for (uint64_t I = 0; I < TableSize; ++I) { 5546 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); 5547 if (!ConstVal) { 5548 // This is an undef. We could deal with it, but undefs in lookup tables 5549 // are very seldom. It's probably not worth the additional complexity. 5550 LinearMappingPossible = false; 5551 break; 5552 } 5553 const APInt &Val = ConstVal->getValue(); 5554 if (I != 0) { 5555 APInt Dist = Val - PrevVal; 5556 if (I == 1) { 5557 DistToPrev = Dist; 5558 } else if (Dist != DistToPrev) { 5559 LinearMappingPossible = false; 5560 break; 5561 } 5562 } 5563 PrevVal = Val; 5564 } 5565 if (LinearMappingPossible) { 5566 LinearOffset = cast<ConstantInt>(TableContents[0]); 5567 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); 5568 Kind = LinearMapKind; 5569 ++NumLinearMaps; 5570 return; 5571 } 5572 } 5573 5574 // If the type is integer and the table fits in a register, build a bitmap. 5575 if (WouldFitInRegister(DL, TableSize, ValueType)) { 5576 IntegerType *IT = cast<IntegerType>(ValueType); 5577 APInt TableInt(TableSize * IT->getBitWidth(), 0); 5578 for (uint64_t I = TableSize; I > 0; --I) { 5579 TableInt <<= IT->getBitWidth(); 5580 // Insert values into the bitmap. Undef values are set to zero. 5581 if (!isa<UndefValue>(TableContents[I - 1])) { 5582 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 5583 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 5584 } 5585 } 5586 BitMap = ConstantInt::get(M.getContext(), TableInt); 5587 BitMapElementTy = IT; 5588 Kind = BitMapKind; 5589 ++NumBitMaps; 5590 return; 5591 } 5592 5593 // Store the table in an array. 5594 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); 5595 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 5596 5597 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true, 5598 GlobalVariable::PrivateLinkage, Initializer, 5599 "switch.table." + FuncName); 5600 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 5601 // Set the alignment to that of an array items. We will be only loading one 5602 // value out of it. 5603 Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType))); 5604 Kind = ArrayKind; 5605 } 5606 5607 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 5608 switch (Kind) { 5609 case SingleValueKind: 5610 return SingleValue; 5611 case LinearMapKind: { 5612 // Derive the result value from the input value. 5613 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), 5614 false, "switch.idx.cast"); 5615 if (!LinearMultiplier->isOne()) 5616 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); 5617 if (!LinearOffset->isZero()) 5618 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); 5619 return Result; 5620 } 5621 case BitMapKind: { 5622 // Type of the bitmap (e.g. i59). 5623 IntegerType *MapTy = BitMap->getType(); 5624 5625 // Cast Index to the same type as the bitmap. 5626 // Note: The Index is <= the number of elements in the table, so 5627 // truncating it to the width of the bitmask is safe. 5628 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 5629 5630 // Multiply the shift amount by the element width. 5631 ShiftAmt = Builder.CreateMul( 5632 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 5633 "switch.shiftamt"); 5634 5635 // Shift down. 5636 Value *DownShifted = 5637 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift"); 5638 // Mask off. 5639 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked"); 5640 } 5641 case ArrayKind: { 5642 // Make sure the table index will not overflow when treated as signed. 5643 IntegerType *IT = cast<IntegerType>(Index->getType()); 5644 uint64_t TableSize = 5645 Array->getInitializer()->getType()->getArrayNumElements(); 5646 if (TableSize > (1ULL << (IT->getBitWidth() - 1))) 5647 Index = Builder.CreateZExt( 5648 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1), 5649 "switch.tableidx.zext"); 5650 5651 Value *GEPIndices[] = {Builder.getInt32(0), Index}; 5652 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, 5653 GEPIndices, "switch.gep"); 5654 return Builder.CreateLoad( 5655 cast<ArrayType>(Array->getValueType())->getElementType(), GEP, 5656 "switch.load"); 5657 } 5658 } 5659 llvm_unreachable("Unknown lookup table kind!"); 5660 } 5661 5662 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, 5663 uint64_t TableSize, 5664 Type *ElementType) { 5665 auto *IT = dyn_cast<IntegerType>(ElementType); 5666 if (!IT) 5667 return false; 5668 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 5669 // are <= 15, we could try to narrow the type. 5670 5671 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 5672 if (TableSize >= UINT_MAX / IT->getBitWidth()) 5673 return false; 5674 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); 5675 } 5676 5677 static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI, 5678 const DataLayout &DL) { 5679 // Allow any legal type. 5680 if (TTI.isTypeLegal(Ty)) 5681 return true; 5682 5683 auto *IT = dyn_cast<IntegerType>(Ty); 5684 if (!IT) 5685 return false; 5686 5687 // Also allow power of 2 integer types that have at least 8 bits and fit in 5688 // a register. These types are common in frontend languages and targets 5689 // usually support loads of these types. 5690 // TODO: We could relax this to any integer that fits in a register and rely 5691 // on ABI alignment and padding in the table to allow the load to be widened. 5692 // Or we could widen the constants and truncate the load. 5693 unsigned BitWidth = IT->getBitWidth(); 5694 return BitWidth >= 8 && isPowerOf2_32(BitWidth) && 5695 DL.fitsInLegalInteger(IT->getBitWidth()); 5696 } 5697 5698 /// Determine whether a lookup table should be built for this switch, based on 5699 /// the number of cases, size of the table, and the types of the results. 5700 // TODO: We could support larger than legal types by limiting based on the 5701 // number of loads required and/or table size. If the constants are small we 5702 // could use smaller table entries and extend after the load. 5703 static bool 5704 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, 5705 const TargetTransformInfo &TTI, const DataLayout &DL, 5706 const SmallDenseMap<PHINode *, Type *> &ResultTypes) { 5707 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) 5708 return false; // TableSize overflowed, or mul below might overflow. 5709 5710 bool AllTablesFitInRegister = true; 5711 bool HasIllegalType = false; 5712 for (const auto &I : ResultTypes) { 5713 Type *Ty = I.second; 5714 5715 // Saturate this flag to true. 5716 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL); 5717 5718 // Saturate this flag to false. 5719 AllTablesFitInRegister = 5720 AllTablesFitInRegister && 5721 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); 5722 5723 // If both flags saturate, we're done. NOTE: This *only* works with 5724 // saturating flags, and all flags have to saturate first due to the 5725 // non-deterministic behavior of iterating over a dense map. 5726 if (HasIllegalType && !AllTablesFitInRegister) 5727 break; 5728 } 5729 5730 // If each table would fit in a register, we should build it anyway. 5731 if (AllTablesFitInRegister) 5732 return true; 5733 5734 // Don't build a table that doesn't fit in-register if it has illegal types. 5735 if (HasIllegalType) 5736 return false; 5737 5738 // The table density should be at least 40%. This is the same criterion as for 5739 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. 5740 // FIXME: Find the best cut-off. 5741 return SI->getNumCases() * 10 >= TableSize * 4; 5742 } 5743 5744 /// Try to reuse the switch table index compare. Following pattern: 5745 /// \code 5746 /// if (idx < tablesize) 5747 /// r = table[idx]; // table does not contain default_value 5748 /// else 5749 /// r = default_value; 5750 /// if (r != default_value) 5751 /// ... 5752 /// \endcode 5753 /// Is optimized to: 5754 /// \code 5755 /// cond = idx < tablesize; 5756 /// if (cond) 5757 /// r = table[idx]; 5758 /// else 5759 /// r = default_value; 5760 /// if (cond) 5761 /// ... 5762 /// \endcode 5763 /// Jump threading will then eliminate the second if(cond). 5764 static void reuseTableCompare( 5765 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, 5766 Constant *DefaultValue, 5767 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) { 5768 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); 5769 if (!CmpInst) 5770 return; 5771 5772 // We require that the compare is in the same block as the phi so that jump 5773 // threading can do its work afterwards. 5774 if (CmpInst->getParent() != PhiBlock) 5775 return; 5776 5777 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); 5778 if (!CmpOp1) 5779 return; 5780 5781 Value *RangeCmp = RangeCheckBranch->getCondition(); 5782 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); 5783 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); 5784 5785 // Check if the compare with the default value is constant true or false. 5786 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5787 DefaultValue, CmpOp1, true); 5788 if (DefaultConst != TrueConst && DefaultConst != FalseConst) 5789 return; 5790 5791 // Check if the compare with the case values is distinct from the default 5792 // compare result. 5793 for (auto ValuePair : Values) { 5794 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5795 ValuePair.second, CmpOp1, true); 5796 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst)) 5797 return; 5798 assert((CaseConst == TrueConst || CaseConst == FalseConst) && 5799 "Expect true or false as compare result."); 5800 } 5801 5802 // Check if the branch instruction dominates the phi node. It's a simple 5803 // dominance check, but sufficient for our needs. 5804 // Although this check is invariant in the calling loops, it's better to do it 5805 // at this late stage. Practically we do it at most once for a switch. 5806 BasicBlock *BranchBlock = RangeCheckBranch->getParent(); 5807 for (BasicBlock *Pred : predecessors(PhiBlock)) { 5808 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) 5809 return; 5810 } 5811 5812 if (DefaultConst == FalseConst) { 5813 // The compare yields the same result. We can replace it. 5814 CmpInst->replaceAllUsesWith(RangeCmp); 5815 ++NumTableCmpReuses; 5816 } else { 5817 // The compare yields the same result, just inverted. We can replace it. 5818 Value *InvertedTableCmp = BinaryOperator::CreateXor( 5819 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", 5820 RangeCheckBranch); 5821 CmpInst->replaceAllUsesWith(InvertedTableCmp); 5822 ++NumTableCmpReuses; 5823 } 5824 } 5825 5826 /// If the switch is only used to initialize one or more phi nodes in a common 5827 /// successor block with different constant values, replace the switch with 5828 /// lookup tables. 5829 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, 5830 DomTreeUpdater *DTU, const DataLayout &DL, 5831 const TargetTransformInfo &TTI) { 5832 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 5833 5834 BasicBlock *BB = SI->getParent(); 5835 Function *Fn = BB->getParent(); 5836 // Only build lookup table when we have a target that supports it or the 5837 // attribute is not set. 5838 if (!TTI.shouldBuildLookupTables() || 5839 (Fn->getFnAttribute("no-jump-tables").getValueAsBool())) 5840 return false; 5841 5842 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 5843 // split off a dense part and build a lookup table for that. 5844 5845 // FIXME: This creates arrays of GEPs to constant strings, which means each 5846 // GEP needs a runtime relocation in PIC code. We should just build one big 5847 // string and lookup indices into that. 5848 5849 // Ignore switches with less than three cases. Lookup tables will not make 5850 // them faster, so we don't analyze them. 5851 if (SI->getNumCases() < 3) 5852 return false; 5853 5854 // Figure out the corresponding result for each case value and phi node in the 5855 // common destination, as well as the min and max case values. 5856 assert(!SI->cases().empty()); 5857 SwitchInst::CaseIt CI = SI->case_begin(); 5858 ConstantInt *MinCaseVal = CI->getCaseValue(); 5859 ConstantInt *MaxCaseVal = CI->getCaseValue(); 5860 5861 BasicBlock *CommonDest = nullptr; 5862 5863 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>; 5864 SmallDenseMap<PHINode *, ResultListTy> ResultLists; 5865 5866 SmallDenseMap<PHINode *, Constant *> DefaultResults; 5867 SmallDenseMap<PHINode *, Type *> ResultTypes; 5868 SmallVector<PHINode *, 4> PHIs; 5869 5870 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 5871 ConstantInt *CaseVal = CI->getCaseValue(); 5872 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 5873 MinCaseVal = CaseVal; 5874 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 5875 MaxCaseVal = CaseVal; 5876 5877 // Resulting value at phi nodes for this case value. 5878 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; 5879 ResultsTy Results; 5880 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest, 5881 Results, DL, TTI)) 5882 return false; 5883 5884 // Append the result from this case to the list for each phi. 5885 for (const auto &I : Results) { 5886 PHINode *PHI = I.first; 5887 Constant *Value = I.second; 5888 if (!ResultLists.count(PHI)) 5889 PHIs.push_back(PHI); 5890 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); 5891 } 5892 } 5893 5894 // Keep track of the result types. 5895 for (PHINode *PHI : PHIs) { 5896 ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); 5897 } 5898 5899 uint64_t NumResults = ResultLists[PHIs[0]].size(); 5900 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); 5901 uint64_t TableSize = RangeSpread.getLimitedValue() + 1; 5902 bool TableHasHoles = (NumResults < TableSize); 5903 5904 // If the table has holes, we need a constant result for the default case 5905 // or a bitmask that fits in a register. 5906 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList; 5907 bool HasDefaultResults = 5908 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, 5909 DefaultResultsList, DL, TTI); 5910 5911 bool NeedMask = (TableHasHoles && !HasDefaultResults); 5912 if (NeedMask) { 5913 // As an extra penalty for the validity test we require more cases. 5914 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). 5915 return false; 5916 if (!DL.fitsInLegalInteger(TableSize)) 5917 return false; 5918 } 5919 5920 for (const auto &I : DefaultResultsList) { 5921 PHINode *PHI = I.first; 5922 Constant *Result = I.second; 5923 DefaultResults[PHI] = Result; 5924 } 5925 5926 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) 5927 return false; 5928 5929 std::vector<DominatorTree::UpdateType> Updates; 5930 5931 // Create the BB that does the lookups. 5932 Module &Mod = *CommonDest->getParent()->getParent(); 5933 BasicBlock *LookupBB = BasicBlock::Create( 5934 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest); 5935 5936 // Compute the table index value. 5937 Builder.SetInsertPoint(SI); 5938 Value *TableIndex; 5939 if (MinCaseVal->isNullValue()) 5940 TableIndex = SI->getCondition(); 5941 else 5942 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, 5943 "switch.tableidx"); 5944 5945 // Compute the maximum table size representable by the integer type we are 5946 // switching upon. 5947 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); 5948 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; 5949 assert(MaxTableSize >= TableSize && 5950 "It is impossible for a switch to have more entries than the max " 5951 "representable value of its input integer type's size."); 5952 5953 // If the default destination is unreachable, or if the lookup table covers 5954 // all values of the conditional variable, branch directly to the lookup table 5955 // BB. Otherwise, check that the condition is within the case range. 5956 const bool DefaultIsReachable = 5957 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 5958 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); 5959 BranchInst *RangeCheckBranch = nullptr; 5960 5961 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5962 Builder.CreateBr(LookupBB); 5963 if (DTU) 5964 Updates.push_back({DominatorTree::Insert, BB, LookupBB}); 5965 // Note: We call removeProdecessor later since we need to be able to get the 5966 // PHI value for the default case in case we're using a bit mask. 5967 } else { 5968 Value *Cmp = Builder.CreateICmpULT( 5969 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize)); 5970 RangeCheckBranch = 5971 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 5972 if (DTU) 5973 Updates.push_back({DominatorTree::Insert, BB, LookupBB}); 5974 } 5975 5976 // Populate the BB that does the lookups. 5977 Builder.SetInsertPoint(LookupBB); 5978 5979 if (NeedMask) { 5980 // Before doing the lookup, we do the hole check. The LookupBB is therefore 5981 // re-purposed to do the hole check, and we create a new LookupBB. 5982 BasicBlock *MaskBB = LookupBB; 5983 MaskBB->setName("switch.hole_check"); 5984 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup", 5985 CommonDest->getParent(), CommonDest); 5986 5987 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid 5988 // unnecessary illegal types. 5989 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); 5990 APInt MaskInt(TableSizePowOf2, 0); 5991 APInt One(TableSizePowOf2, 1); 5992 // Build bitmask; fill in a 1 bit for every case. 5993 const ResultListTy &ResultList = ResultLists[PHIs[0]]; 5994 for (size_t I = 0, E = ResultList.size(); I != E; ++I) { 5995 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue()) 5996 .getLimitedValue(); 5997 MaskInt |= One << Idx; 5998 } 5999 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); 6000 6001 // Get the TableIndex'th bit of the bitmask. 6002 // If this bit is 0 (meaning hole) jump to the default destination, 6003 // else continue with table lookup. 6004 IntegerType *MapTy = TableMask->getType(); 6005 Value *MaskIndex = 6006 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex"); 6007 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted"); 6008 Value *LoBit = Builder.CreateTrunc( 6009 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit"); 6010 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); 6011 if (DTU) { 6012 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB}); 6013 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()}); 6014 } 6015 Builder.SetInsertPoint(LookupBB); 6016 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB); 6017 } 6018 6019 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 6020 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later, 6021 // do not delete PHINodes here. 6022 SI->getDefaultDest()->removePredecessor(BB, 6023 /*KeepOneInputPHIs=*/true); 6024 if (DTU) 6025 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()}); 6026 } 6027 6028 for (PHINode *PHI : PHIs) { 6029 const ResultListTy &ResultList = ResultLists[PHI]; 6030 6031 // If using a bitmask, use any value to fill the lookup table holes. 6032 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; 6033 StringRef FuncName = Fn->getName(); 6034 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL, 6035 FuncName); 6036 6037 Value *Result = Table.BuildLookup(TableIndex, Builder); 6038 6039 // Do a small peephole optimization: re-use the switch table compare if 6040 // possible. 6041 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { 6042 BasicBlock *PhiBlock = PHI->getParent(); 6043 // Search for compare instructions which use the phi. 6044 for (auto *User : PHI->users()) { 6045 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); 6046 } 6047 } 6048 6049 PHI->addIncoming(Result, LookupBB); 6050 } 6051 6052 Builder.CreateBr(CommonDest); 6053 if (DTU) 6054 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest}); 6055 6056 // Remove the switch. 6057 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors; 6058 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 6059 BasicBlock *Succ = SI->getSuccessor(i); 6060 6061 if (Succ == SI->getDefaultDest()) 6062 continue; 6063 Succ->removePredecessor(BB); 6064 RemovedSuccessors.insert(Succ); 6065 } 6066 SI->eraseFromParent(); 6067 6068 if (DTU) { 6069 for (BasicBlock *RemovedSuccessor : RemovedSuccessors) 6070 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor}); 6071 DTU->applyUpdates(Updates); 6072 } 6073 6074 ++NumLookupTables; 6075 if (NeedMask) 6076 ++NumLookupTablesHoles; 6077 return true; 6078 } 6079 6080 static bool isSwitchDense(ArrayRef<int64_t> Values) { 6081 // See also SelectionDAGBuilder::isDense(), which this function was based on. 6082 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front(); 6083 uint64_t Range = Diff + 1; 6084 uint64_t NumCases = Values.size(); 6085 // 40% is the default density for building a jump table in optsize/minsize mode. 6086 uint64_t MinDensity = 40; 6087 6088 return NumCases * 100 >= Range * MinDensity; 6089 } 6090 6091 /// Try to transform a switch that has "holes" in it to a contiguous sequence 6092 /// of cases. 6093 /// 6094 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be 6095 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}. 6096 /// 6097 /// This converts a sparse switch into a dense switch which allows better 6098 /// lowering and could also allow transforming into a lookup table. 6099 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, 6100 const DataLayout &DL, 6101 const TargetTransformInfo &TTI) { 6102 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType()); 6103 if (CondTy->getIntegerBitWidth() > 64 || 6104 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth())) 6105 return false; 6106 // Only bother with this optimization if there are more than 3 switch cases; 6107 // SDAG will only bother creating jump tables for 4 or more cases. 6108 if (SI->getNumCases() < 4) 6109 return false; 6110 6111 // This transform is agnostic to the signedness of the input or case values. We 6112 // can treat the case values as signed or unsigned. We can optimize more common 6113 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values 6114 // as signed. 6115 SmallVector<int64_t,4> Values; 6116 for (auto &C : SI->cases()) 6117 Values.push_back(C.getCaseValue()->getValue().getSExtValue()); 6118 llvm::sort(Values); 6119 6120 // If the switch is already dense, there's nothing useful to do here. 6121 if (isSwitchDense(Values)) 6122 return false; 6123 6124 // First, transform the values such that they start at zero and ascend. 6125 int64_t Base = Values[0]; 6126 for (auto &V : Values) 6127 V -= (uint64_t)(Base); 6128 6129 // Now we have signed numbers that have been shifted so that, given enough 6130 // precision, there are no negative values. Since the rest of the transform 6131 // is bitwise only, we switch now to an unsigned representation. 6132 6133 // This transform can be done speculatively because it is so cheap - it 6134 // results in a single rotate operation being inserted. 6135 // FIXME: It's possible that optimizing a switch on powers of two might also 6136 // be beneficial - flag values are often powers of two and we could use a CLZ 6137 // as the key function. 6138 6139 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than 6140 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be 6141 // less than 64. 6142 unsigned Shift = 64; 6143 for (auto &V : Values) 6144 Shift = std::min(Shift, countTrailingZeros((uint64_t)V)); 6145 assert(Shift < 64); 6146 if (Shift > 0) 6147 for (auto &V : Values) 6148 V = (int64_t)((uint64_t)V >> Shift); 6149 6150 if (!isSwitchDense(Values)) 6151 // Transform didn't create a dense switch. 6152 return false; 6153 6154 // The obvious transform is to shift the switch condition right and emit a 6155 // check that the condition actually cleanly divided by GCD, i.e. 6156 // C & (1 << Shift - 1) == 0 6157 // inserting a new CFG edge to handle the case where it didn't divide cleanly. 6158 // 6159 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the 6160 // shift and puts the shifted-off bits in the uppermost bits. If any of these 6161 // are nonzero then the switch condition will be very large and will hit the 6162 // default case. 6163 6164 auto *Ty = cast<IntegerType>(SI->getCondition()->getType()); 6165 Builder.SetInsertPoint(SI); 6166 auto *ShiftC = ConstantInt::get(Ty, Shift); 6167 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base)); 6168 auto *LShr = Builder.CreateLShr(Sub, ShiftC); 6169 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift); 6170 auto *Rot = Builder.CreateOr(LShr, Shl); 6171 SI->replaceUsesOfWith(SI->getCondition(), Rot); 6172 6173 for (auto Case : SI->cases()) { 6174 auto *Orig = Case.getCaseValue(); 6175 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base); 6176 Case.setValue( 6177 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue())))); 6178 } 6179 return true; 6180 } 6181 6182 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 6183 BasicBlock *BB = SI->getParent(); 6184 6185 if (isValueEqualityComparison(SI)) { 6186 // If we only have one predecessor, and if it is a branch on this value, 6187 // see if that predecessor totally determines the outcome of this switch. 6188 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 6189 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 6190 return requestResimplify(); 6191 6192 Value *Cond = SI->getCondition(); 6193 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 6194 if (SimplifySwitchOnSelect(SI, Select)) 6195 return requestResimplify(); 6196 6197 // If the block only contains the switch, see if we can fold the block 6198 // away into any preds. 6199 if (SI == &*BB->instructionsWithoutDebug(false).begin()) 6200 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 6201 return requestResimplify(); 6202 } 6203 6204 // Try to transform the switch into an icmp and a branch. 6205 if (TurnSwitchRangeIntoICmp(SI, Builder)) 6206 return requestResimplify(); 6207 6208 // Remove unreachable cases. 6209 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL)) 6210 return requestResimplify(); 6211 6212 if (switchToSelect(SI, Builder, DTU, DL, TTI)) 6213 return requestResimplify(); 6214 6215 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI)) 6216 return requestResimplify(); 6217 6218 // The conversion from switch to lookup tables results in difficult-to-analyze 6219 // code and makes pruning branches much harder. This is a problem if the 6220 // switch expression itself can still be restricted as a result of inlining or 6221 // CVP. Therefore, only apply this transformation during late stages of the 6222 // optimisation pipeline. 6223 if (Options.ConvertSwitchToLookupTable && 6224 SwitchToLookupTable(SI, Builder, DTU, DL, TTI)) 6225 return requestResimplify(); 6226 6227 if (ReduceSwitchRange(SI, Builder, DL, TTI)) 6228 return requestResimplify(); 6229 6230 return false; 6231 } 6232 6233 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) { 6234 BasicBlock *BB = IBI->getParent(); 6235 bool Changed = false; 6236 6237 // Eliminate redundant destinations. 6238 SmallPtrSet<Value *, 8> Succs; 6239 SmallPtrSet<BasicBlock *, 8> RemovedSuccs; 6240 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 6241 BasicBlock *Dest = IBI->getDestination(i); 6242 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { 6243 if (!Dest->hasAddressTaken()) 6244 RemovedSuccs.insert(Dest); 6245 Dest->removePredecessor(BB); 6246 IBI->removeDestination(i); 6247 --i; 6248 --e; 6249 Changed = true; 6250 } 6251 } 6252 6253 if (DTU) { 6254 std::vector<DominatorTree::UpdateType> Updates; 6255 Updates.reserve(RemovedSuccs.size()); 6256 for (auto *RemovedSucc : RemovedSuccs) 6257 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc}); 6258 DTU->applyUpdates(Updates); 6259 } 6260 6261 if (IBI->getNumDestinations() == 0) { 6262 // If the indirectbr has no successors, change it to unreachable. 6263 new UnreachableInst(IBI->getContext(), IBI); 6264 EraseTerminatorAndDCECond(IBI); 6265 return true; 6266 } 6267 6268 if (IBI->getNumDestinations() == 1) { 6269 // If the indirectbr has one successor, change it to a direct branch. 6270 BranchInst::Create(IBI->getDestination(0), IBI); 6271 EraseTerminatorAndDCECond(IBI); 6272 return true; 6273 } 6274 6275 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 6276 if (SimplifyIndirectBrOnSelect(IBI, SI)) 6277 return requestResimplify(); 6278 } 6279 return Changed; 6280 } 6281 6282 /// Given an block with only a single landing pad and a unconditional branch 6283 /// try to find another basic block which this one can be merged with. This 6284 /// handles cases where we have multiple invokes with unique landing pads, but 6285 /// a shared handler. 6286 /// 6287 /// We specifically choose to not worry about merging non-empty blocks 6288 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In 6289 /// practice, the optimizer produces empty landing pad blocks quite frequently 6290 /// when dealing with exception dense code. (see: instcombine, gvn, if-else 6291 /// sinking in this file) 6292 /// 6293 /// This is primarily a code size optimization. We need to avoid performing 6294 /// any transform which might inhibit optimization (such as our ability to 6295 /// specialize a particular handler via tail commoning). We do this by not 6296 /// merging any blocks which require us to introduce a phi. Since the same 6297 /// values are flowing through both blocks, we don't lose any ability to 6298 /// specialize. If anything, we make such specialization more likely. 6299 /// 6300 /// TODO - This transformation could remove entries from a phi in the target 6301 /// block when the inputs in the phi are the same for the two blocks being 6302 /// merged. In some cases, this could result in removal of the PHI entirely. 6303 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, 6304 BasicBlock *BB, DomTreeUpdater *DTU) { 6305 auto Succ = BB->getUniqueSuccessor(); 6306 assert(Succ); 6307 // If there's a phi in the successor block, we'd likely have to introduce 6308 // a phi into the merged landing pad block. 6309 if (isa<PHINode>(*Succ->begin())) 6310 return false; 6311 6312 for (BasicBlock *OtherPred : predecessors(Succ)) { 6313 if (BB == OtherPred) 6314 continue; 6315 BasicBlock::iterator I = OtherPred->begin(); 6316 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); 6317 if (!LPad2 || !LPad2->isIdenticalTo(LPad)) 6318 continue; 6319 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6320 ; 6321 BranchInst *BI2 = dyn_cast<BranchInst>(I); 6322 if (!BI2 || !BI2->isIdenticalTo(BI)) 6323 continue; 6324 6325 std::vector<DominatorTree::UpdateType> Updates; 6326 6327 // We've found an identical block. Update our predecessors to take that 6328 // path instead and make ourselves dead. 6329 SmallPtrSet<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB)); 6330 for (BasicBlock *Pred : Preds) { 6331 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); 6332 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB && 6333 "unexpected successor"); 6334 II->setUnwindDest(OtherPred); 6335 if (DTU) { 6336 Updates.push_back({DominatorTree::Insert, Pred, OtherPred}); 6337 Updates.push_back({DominatorTree::Delete, Pred, BB}); 6338 } 6339 } 6340 6341 // The debug info in OtherPred doesn't cover the merged control flow that 6342 // used to go through BB. We need to delete it or update it. 6343 for (Instruction &Inst : llvm::make_early_inc_range(*OtherPred)) 6344 if (isa<DbgInfoIntrinsic>(Inst)) 6345 Inst.eraseFromParent(); 6346 6347 SmallPtrSet<BasicBlock *, 16> Succs(succ_begin(BB), succ_end(BB)); 6348 for (BasicBlock *Succ : Succs) { 6349 Succ->removePredecessor(BB); 6350 if (DTU) 6351 Updates.push_back({DominatorTree::Delete, BB, Succ}); 6352 } 6353 6354 IRBuilder<> Builder(BI); 6355 Builder.CreateUnreachable(); 6356 BI->eraseFromParent(); 6357 if (DTU) 6358 DTU->applyUpdates(Updates); 6359 return true; 6360 } 6361 return false; 6362 } 6363 6364 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) { 6365 return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder) 6366 : simplifyCondBranch(Branch, Builder); 6367 } 6368 6369 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI, 6370 IRBuilder<> &Builder) { 6371 BasicBlock *BB = BI->getParent(); 6372 BasicBlock *Succ = BI->getSuccessor(0); 6373 6374 // If the Terminator is the only non-phi instruction, simplify the block. 6375 // If LoopHeader is provided, check if the block or its successor is a loop 6376 // header. (This is for early invocations before loop simplify and 6377 // vectorization to keep canonical loop forms for nested loops. These blocks 6378 // can be eliminated when the pass is invoked later in the back-end.) 6379 // Note that if BB has only one predecessor then we do not introduce new 6380 // backedge, so we can eliminate BB. 6381 bool NeedCanonicalLoop = 6382 Options.NeedCanonicalLoop && 6383 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) && 6384 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ))); 6385 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(true)->getIterator(); 6386 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 6387 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU)) 6388 return true; 6389 6390 // If the only instruction in the block is a seteq/setne comparison against a 6391 // constant, try to simplify the block. 6392 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 6393 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 6394 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6395 ; 6396 if (I->isTerminator() && 6397 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder)) 6398 return true; 6399 } 6400 6401 // See if we can merge an empty landing pad block with another which is 6402 // equivalent. 6403 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { 6404 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6405 ; 6406 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB, DTU)) 6407 return true; 6408 } 6409 6410 // If this basic block is ONLY a compare and a branch, and if a predecessor 6411 // branches to us and our successor, fold the comparison into the 6412 // predecessor and use logical operations to update the incoming value 6413 // for PHI nodes in common successor. 6414 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, 6415 Options.BonusInstThreshold)) 6416 return requestResimplify(); 6417 return false; 6418 } 6419 6420 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { 6421 BasicBlock *PredPred = nullptr; 6422 for (auto *P : predecessors(BB)) { 6423 BasicBlock *PPred = P->getSinglePredecessor(); 6424 if (!PPred || (PredPred && PredPred != PPred)) 6425 return nullptr; 6426 PredPred = PPred; 6427 } 6428 return PredPred; 6429 } 6430 6431 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 6432 assert( 6433 !isa<ConstantInt>(BI->getCondition()) && 6434 BI->getSuccessor(0) != BI->getSuccessor(1) && 6435 "Tautological conditional branch should have been eliminated already."); 6436 6437 BasicBlock *BB = BI->getParent(); 6438 if (!Options.SimplifyCondBranch) 6439 return false; 6440 6441 // Conditional branch 6442 if (isValueEqualityComparison(BI)) { 6443 // If we only have one predecessor, and if it is a branch on this value, 6444 // see if that predecessor totally determines the outcome of this 6445 // switch. 6446 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 6447 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 6448 return requestResimplify(); 6449 6450 // This block must be empty, except for the setcond inst, if it exists. 6451 // Ignore dbg and pseudo intrinsics. 6452 auto I = BB->instructionsWithoutDebug(true).begin(); 6453 if (&*I == BI) { 6454 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 6455 return requestResimplify(); 6456 } else if (&*I == cast<Instruction>(BI->getCondition())) { 6457 ++I; 6458 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 6459 return requestResimplify(); 6460 } 6461 } 6462 6463 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 6464 if (SimplifyBranchOnICmpChain(BI, Builder, DL)) 6465 return true; 6466 6467 // If this basic block has dominating predecessor blocks and the dominating 6468 // blocks' conditions imply BI's condition, we know the direction of BI. 6469 Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL); 6470 if (Imp) { 6471 // Turn this into a branch on constant. 6472 auto *OldCond = BI->getCondition(); 6473 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext()) 6474 : ConstantInt::getFalse(BB->getContext()); 6475 BI->setCondition(TorF); 6476 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 6477 return requestResimplify(); 6478 } 6479 6480 // If this basic block is ONLY a compare and a branch, and if a predecessor 6481 // branches to us and one of our successors, fold the comparison into the 6482 // predecessor and use logical operations to pick the right destination. 6483 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, 6484 Options.BonusInstThreshold)) 6485 return requestResimplify(); 6486 6487 // We have a conditional branch to two blocks that are only reachable 6488 // from BI. We know that the condbr dominates the two blocks, so see if 6489 // there is any identical code in the "then" and "else" blocks. If so, we 6490 // can hoist it up to the branching block. 6491 if (BI->getSuccessor(0)->getSinglePredecessor()) { 6492 if (BI->getSuccessor(1)->getSinglePredecessor()) { 6493 if (HoistCommon && 6494 HoistThenElseCodeToIf(BI, TTI, !Options.HoistCommonInsts)) 6495 return requestResimplify(); 6496 } else { 6497 // If Successor #1 has multiple preds, we may be able to conditionally 6498 // execute Successor #0 if it branches to Successor #1. 6499 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator(); 6500 if (Succ0TI->getNumSuccessors() == 1 && 6501 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 6502 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) 6503 return requestResimplify(); 6504 } 6505 } else if (BI->getSuccessor(1)->getSinglePredecessor()) { 6506 // If Successor #0 has multiple preds, we may be able to conditionally 6507 // execute Successor #1 if it branches to Successor #0. 6508 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator(); 6509 if (Succ1TI->getNumSuccessors() == 1 && 6510 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 6511 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) 6512 return requestResimplify(); 6513 } 6514 6515 // If this is a branch on a phi node in the current block, thread control 6516 // through this block if any PHI node entries are constants. 6517 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 6518 if (PN->getParent() == BI->getParent()) 6519 if (FoldCondBranchOnPHI(BI, DTU, DL, Options.AC)) 6520 return requestResimplify(); 6521 6522 // Scan predecessor blocks for conditional branches. 6523 for (BasicBlock *Pred : predecessors(BB)) 6524 if (BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator())) 6525 if (PBI != BI && PBI->isConditional()) 6526 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI)) 6527 return requestResimplify(); 6528 6529 // Look for diamond patterns. 6530 if (MergeCondStores) 6531 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) 6532 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) 6533 if (PBI != BI && PBI->isConditional()) 6534 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI)) 6535 return requestResimplify(); 6536 6537 return false; 6538 } 6539 6540 /// Check if passing a value to an instruction will cause undefined behavior. 6541 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) { 6542 Constant *C = dyn_cast<Constant>(V); 6543 if (!C) 6544 return false; 6545 6546 if (I->use_empty()) 6547 return false; 6548 6549 if (C->isNullValue() || isa<UndefValue>(C)) { 6550 // Only look at the first use, avoid hurting compile time with long uselists 6551 User *Use = *I->user_begin(); 6552 6553 // Now make sure that there are no instructions in between that can alter 6554 // control flow (eg. calls) 6555 for (BasicBlock::iterator 6556 i = ++BasicBlock::iterator(I), 6557 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use)); 6558 i != UI; ++i) { 6559 if (i == I->getParent()->end()) 6560 return false; 6561 if (!isGuaranteedToTransferExecutionToSuccessor(&*i)) 6562 return false; 6563 } 6564 6565 // Look through GEPs. A load from a GEP derived from NULL is still undefined 6566 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 6567 if (GEP->getPointerOperand() == I) { 6568 if (!GEP->isInBounds() || !GEP->hasAllZeroIndices()) 6569 PtrValueMayBeModified = true; 6570 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified); 6571 } 6572 6573 // Look through bitcasts. 6574 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 6575 return passingValueIsAlwaysUndefined(V, BC, PtrValueMayBeModified); 6576 6577 // Load from null is undefined. 6578 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 6579 if (!LI->isVolatile()) 6580 return !NullPointerIsDefined(LI->getFunction(), 6581 LI->getPointerAddressSpace()); 6582 6583 // Store to null is undefined. 6584 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 6585 if (!SI->isVolatile()) 6586 return (!NullPointerIsDefined(SI->getFunction(), 6587 SI->getPointerAddressSpace())) && 6588 SI->getPointerOperand() == I; 6589 6590 if (auto *CB = dyn_cast<CallBase>(Use)) { 6591 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction())) 6592 return false; 6593 // A call to null is undefined. 6594 if (CB->getCalledOperand() == I) 6595 return true; 6596 6597 if (C->isNullValue()) { 6598 for (const llvm::Use &Arg : CB->args()) 6599 if (Arg == I) { 6600 unsigned ArgIdx = CB->getArgOperandNo(&Arg); 6601 if (CB->isPassingUndefUB(ArgIdx) && 6602 CB->paramHasAttr(ArgIdx, Attribute::NonNull)) { 6603 // Passing null to a nonnnull+noundef argument is undefined. 6604 return !PtrValueMayBeModified; 6605 } 6606 } 6607 } else if (isa<UndefValue>(C)) { 6608 // Passing undef to a noundef argument is undefined. 6609 for (const llvm::Use &Arg : CB->args()) 6610 if (Arg == I) { 6611 unsigned ArgIdx = CB->getArgOperandNo(&Arg); 6612 if (CB->isPassingUndefUB(ArgIdx)) { 6613 // Passing undef to a noundef argument is undefined. 6614 return true; 6615 } 6616 } 6617 } 6618 } 6619 } 6620 return false; 6621 } 6622 6623 /// If BB has an incoming value that will always trigger undefined behavior 6624 /// (eg. null pointer dereference), remove the branch leading here. 6625 static bool removeUndefIntroducingPredecessor(BasicBlock *BB, 6626 DomTreeUpdater *DTU) { 6627 for (PHINode &PHI : BB->phis()) 6628 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) 6629 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) { 6630 BasicBlock *Predecessor = PHI.getIncomingBlock(i); 6631 Instruction *T = Predecessor->getTerminator(); 6632 IRBuilder<> Builder(T); 6633 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 6634 BB->removePredecessor(Predecessor); 6635 // Turn uncoditional branches into unreachables and remove the dead 6636 // destination from conditional branches. 6637 if (BI->isUnconditional()) 6638 Builder.CreateUnreachable(); 6639 else { 6640 // Preserve guarding condition in assume, because it might not be 6641 // inferrable from any dominating condition. 6642 Value *Cond = BI->getCondition(); 6643 if (BI->getSuccessor(0) == BB) 6644 Builder.CreateAssumption(Builder.CreateNot(Cond)); 6645 else 6646 Builder.CreateAssumption(Cond); 6647 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) 6648 : BI->getSuccessor(0)); 6649 } 6650 BI->eraseFromParent(); 6651 if (DTU) 6652 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}}); 6653 return true; 6654 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { 6655 // Redirect all branches leading to UB into 6656 // a newly created unreachable block. 6657 BasicBlock *Unreachable = BasicBlock::Create( 6658 Predecessor->getContext(), "unreachable", BB->getParent(), BB); 6659 Builder.SetInsertPoint(Unreachable); 6660 // The new block contains only one instruction: Unreachable 6661 Builder.CreateUnreachable(); 6662 for (auto &Case : SI->cases()) 6663 if (Case.getCaseSuccessor() == BB) { 6664 BB->removePredecessor(Predecessor); 6665 Case.setSuccessor(Unreachable); 6666 } 6667 if (SI->getDefaultDest() == BB) { 6668 BB->removePredecessor(Predecessor); 6669 SI->setDefaultDest(Unreachable); 6670 } 6671 6672 if (DTU) 6673 DTU->applyUpdates( 6674 { { DominatorTree::Insert, Predecessor, Unreachable }, 6675 { DominatorTree::Delete, Predecessor, BB } }); 6676 return true; 6677 } 6678 } 6679 6680 return false; 6681 } 6682 6683 bool SimplifyCFGOpt::simplifyOnceImpl(BasicBlock *BB) { 6684 bool Changed = false; 6685 6686 assert(BB && BB->getParent() && "Block not embedded in function!"); 6687 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 6688 6689 // Remove basic blocks that have no predecessors (except the entry block)... 6690 // or that just have themself as a predecessor. These are unreachable. 6691 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) || 6692 BB->getSinglePredecessor() == BB) { 6693 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB); 6694 DeleteDeadBlock(BB, DTU); 6695 return true; 6696 } 6697 6698 // Check to see if we can constant propagate this terminator instruction 6699 // away... 6700 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true, 6701 /*TLI=*/nullptr, DTU); 6702 6703 // Check for and eliminate duplicate PHI nodes in this block. 6704 Changed |= EliminateDuplicatePHINodes(BB); 6705 6706 // Check for and remove branches that will always cause undefined behavior. 6707 if (removeUndefIntroducingPredecessor(BB, DTU)) 6708 return requestResimplify(); 6709 6710 // Merge basic blocks into their predecessor if there is only one distinct 6711 // pred, and if there is only one distinct successor of the predecessor, and 6712 // if there are no PHI nodes. 6713 if (MergeBlockIntoPredecessor(BB, DTU)) 6714 return true; 6715 6716 if (SinkCommon && Options.SinkCommonInsts) 6717 if (SinkCommonCodeFromPredecessors(BB, DTU)) { 6718 // SinkCommonCodeFromPredecessors() does not automatically CSE PHI's, 6719 // so we may now how duplicate PHI's. 6720 // Let's rerun EliminateDuplicatePHINodes() first, 6721 // before FoldTwoEntryPHINode() potentially converts them into select's, 6722 // after which we'd need a whole EarlyCSE pass run to cleanup them. 6723 return true; 6724 } 6725 6726 IRBuilder<> Builder(BB); 6727 6728 if (Options.FoldTwoEntryPHINode) { 6729 // If there is a trivial two-entry PHI node in this basic block, and we can 6730 // eliminate it, do so now. 6731 if (auto *PN = dyn_cast<PHINode>(BB->begin())) 6732 if (PN->getNumIncomingValues() == 2) 6733 if (FoldTwoEntryPHINode(PN, TTI, DTU, DL)) 6734 return true; 6735 } 6736 6737 Instruction *Terminator = BB->getTerminator(); 6738 Builder.SetInsertPoint(Terminator); 6739 switch (Terminator->getOpcode()) { 6740 case Instruction::Br: 6741 Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder); 6742 break; 6743 case Instruction::Resume: 6744 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder); 6745 break; 6746 case Instruction::CleanupRet: 6747 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator)); 6748 break; 6749 case Instruction::Switch: 6750 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder); 6751 break; 6752 case Instruction::Unreachable: 6753 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator)); 6754 break; 6755 case Instruction::IndirectBr: 6756 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator)); 6757 break; 6758 } 6759 6760 return Changed; 6761 } 6762 6763 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) { 6764 bool Changed = simplifyOnceImpl(BB); 6765 6766 return Changed; 6767 } 6768 6769 bool SimplifyCFGOpt::run(BasicBlock *BB) { 6770 bool Changed = false; 6771 6772 // Repeated simplify BB as long as resimplification is requested. 6773 do { 6774 Resimplify = false; 6775 6776 // Perform one round of simplifcation. Resimplify flag will be set if 6777 // another iteration is requested. 6778 Changed |= simplifyOnce(BB); 6779 } while (Resimplify); 6780 6781 return Changed; 6782 } 6783 6784 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 6785 DomTreeUpdater *DTU, const SimplifyCFGOptions &Options, 6786 ArrayRef<WeakVH> LoopHeaders) { 6787 return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders, 6788 Options) 6789 .run(BB); 6790 } 6791