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