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