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