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