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