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