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