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/InstructionSimplify.h" 28 #include "llvm/Analysis/MemorySSA.h" 29 #include "llvm/Analysis/MemorySSAUpdater.h" 30 #include "llvm/Analysis/TargetTransformInfo.h" 31 #include "llvm/Analysis/ValueTracking.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/BasicBlock.h" 34 #include "llvm/IR/CFG.h" 35 #include "llvm/IR/CallSite.h" 36 #include "llvm/IR/Constant.h" 37 #include "llvm/IR/ConstantRange.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/DataLayout.h" 40 #include "llvm/IR/DerivedTypes.h" 41 #include "llvm/IR/Function.h" 42 #include "llvm/IR/GlobalValue.h" 43 #include "llvm/IR/GlobalVariable.h" 44 #include "llvm/IR/IRBuilder.h" 45 #include "llvm/IR/InstrTypes.h" 46 #include "llvm/IR/Instruction.h" 47 #include "llvm/IR/Instructions.h" 48 #include "llvm/IR/IntrinsicInst.h" 49 #include "llvm/IR/Intrinsics.h" 50 #include "llvm/IR/LLVMContext.h" 51 #include "llvm/IR/MDBuilder.h" 52 #include "llvm/IR/Metadata.h" 53 #include "llvm/IR/Module.h" 54 #include "llvm/IR/NoFolder.h" 55 #include "llvm/IR/Operator.h" 56 #include "llvm/IR/PatternMatch.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/Use.h" 59 #include "llvm/IR/User.h" 60 #include "llvm/IR/Value.h" 61 #include "llvm/Support/Casting.h" 62 #include "llvm/Support/CommandLine.h" 63 #include "llvm/Support/Debug.h" 64 #include "llvm/Support/ErrorHandling.h" 65 #include "llvm/Support/KnownBits.h" 66 #include "llvm/Support/MathExtras.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 69 #include "llvm/Transforms/Utils/Local.h" 70 #include "llvm/Transforms/Utils/ValueMapper.h" 71 #include <algorithm> 72 #include <cassert> 73 #include <climits> 74 #include <cstddef> 75 #include <cstdint> 76 #include <iterator> 77 #include <map> 78 #include <set> 79 #include <tuple> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 using namespace PatternMatch; 85 86 #define DEBUG_TYPE "simplifycfg" 87 88 // Chosen as 2 so as to be cheap, but still to have enough power to fold 89 // a select, so the "clamp" idiom (of a min followed by a max) will be caught. 90 // To catch this, we need to fold a compare and a select, hence '2' being the 91 // minimum reasonable default. 92 static cl::opt<unsigned> PHINodeFoldingThreshold( 93 "phi-node-folding-threshold", cl::Hidden, cl::init(2), 94 cl::desc( 95 "Control the amount of phi node folding to perform (default = 2)")); 96 97 static cl::opt<unsigned> TwoEntryPHINodeFoldingThreshold( 98 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4), 99 cl::desc("Control the maximal total instruction cost that we are willing " 100 "to speculatively execute to fold a 2-entry PHI node into a " 101 "select (default = 4)")); 102 103 static cl::opt<bool> DupRet( 104 "simplifycfg-dup-ret", cl::Hidden, cl::init(false), 105 cl::desc("Duplicate return instructions into unconditional branches")); 106 107 static cl::opt<bool> 108 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), 109 cl::desc("Sink common instructions down to the end block")); 110 111 static cl::opt<bool> HoistCondStores( 112 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), 113 cl::desc("Hoist conditional stores if an unconditional store precedes")); 114 115 static cl::opt<bool> MergeCondStores( 116 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), 117 cl::desc("Hoist conditional stores even if an unconditional store does not " 118 "precede - hoist multiple conditional stores into a single " 119 "predicated store")); 120 121 static cl::opt<bool> MergeCondStoresAggressively( 122 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), 123 cl::desc("When merging conditional stores, do so even if the resultant " 124 "basic blocks are unlikely to be if-converted as a result")); 125 126 static cl::opt<bool> SpeculateOneExpensiveInst( 127 "speculate-one-expensive-inst", cl::Hidden, cl::init(true), 128 cl::desc("Allow exactly one expensive instruction to be speculatively " 129 "executed")); 130 131 static cl::opt<unsigned> MaxSpeculationDepth( 132 "max-speculation-depth", cl::Hidden, cl::init(10), 133 cl::desc("Limit maximum recursion depth when calculating costs of " 134 "speculatively executed instructions")); 135 136 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); 137 STATISTIC(NumLinearMaps, 138 "Number of switch instructions turned into linear mapping"); 139 STATISTIC(NumLookupTables, 140 "Number of switch instructions turned into lookup tables"); 141 STATISTIC( 142 NumLookupTablesHoles, 143 "Number of switch instructions turned into lookup tables (holes checked)"); 144 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares"); 145 STATISTIC(NumSinkCommons, 146 "Number of common instructions sunk down to the end block"); 147 STATISTIC(NumSpeculations, "Number of speculative executed instructions"); 148 149 namespace { 150 151 // The first field contains the value that the switch produces when a certain 152 // case group is selected, and the second field is a vector containing the 153 // cases composing the case group. 154 using SwitchCaseResultVectorTy = 155 SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>; 156 157 // The first field contains the phi node that generates a result of the switch 158 // and the second field contains the value generated for a certain case in the 159 // switch for that PHI. 160 using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; 161 162 /// ValueEqualityComparisonCase - Represents a case of a switch. 163 struct ValueEqualityComparisonCase { 164 ConstantInt *Value; 165 BasicBlock *Dest; 166 167 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) 168 : Value(Value), Dest(Dest) {} 169 170 bool operator<(ValueEqualityComparisonCase RHS) const { 171 // Comparing pointers is ok as we only rely on the order for uniquing. 172 return Value < RHS.Value; 173 } 174 175 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } 176 }; 177 178 class SimplifyCFGOpt { 179 const TargetTransformInfo &TTI; 180 const DataLayout &DL; 181 SmallPtrSetImpl<BasicBlock *> *LoopHeaders; 182 const SimplifyCFGOptions &Options; 183 bool Resimplify; 184 185 Value *isValueEqualityComparison(Instruction *TI); 186 BasicBlock *GetValueEqualityComparisonCases( 187 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases); 188 bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI, 189 BasicBlock *Pred, 190 IRBuilder<> &Builder); 191 bool FoldValueComparisonIntoPredecessors(Instruction *TI, 192 IRBuilder<> &Builder); 193 194 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); 195 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); 196 bool SimplifySingleResume(ResumeInst *RI); 197 bool SimplifyCommonResume(ResumeInst *RI); 198 bool SimplifyCleanupReturn(CleanupReturnInst *RI); 199 bool SimplifyUnreachable(UnreachableInst *UI); 200 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); 201 bool SimplifyIndirectBr(IndirectBrInst *IBI); 202 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder); 203 bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder); 204 205 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI, 206 IRBuilder<> &Builder); 207 208 public: 209 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL, 210 SmallPtrSetImpl<BasicBlock *> *LoopHeaders, 211 const SimplifyCFGOptions &Opts) 212 : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {} 213 214 bool run(BasicBlock *BB); 215 bool simplifyOnce(BasicBlock *BB); 216 217 // Helper to set Resimplify and return change indication. 218 bool requestResimplify() { 219 Resimplify = true; 220 return true; 221 } 222 }; 223 224 } // end anonymous namespace 225 226 /// Return true if it is safe to merge these two 227 /// terminator instructions together. 228 static bool 229 SafeToMergeTerminators(Instruction *SI1, Instruction *SI2, 230 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) { 231 if (SI1 == SI2) 232 return false; // Can't merge with self! 233 234 // It is not safe to merge these two switch instructions if they have a common 235 // successor, and if that successor has a PHI node, and if *that* PHI node has 236 // conflicting incoming values from the two switch blocks. 237 BasicBlock *SI1BB = SI1->getParent(); 238 BasicBlock *SI2BB = SI2->getParent(); 239 240 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 241 bool Fail = false; 242 for (BasicBlock *Succ : successors(SI2BB)) 243 if (SI1Succs.count(Succ)) 244 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { 245 PHINode *PN = cast<PHINode>(BBI); 246 if (PN->getIncomingValueForBlock(SI1BB) != 247 PN->getIncomingValueForBlock(SI2BB)) { 248 if (FailBlocks) 249 FailBlocks->insert(Succ); 250 Fail = true; 251 } 252 } 253 254 return !Fail; 255 } 256 257 /// Return true if it is safe and profitable to merge these two terminator 258 /// instructions together, where SI1 is an unconditional branch. PhiNodes will 259 /// store all PHI nodes in common successors. 260 static bool 261 isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2, 262 Instruction *Cond, 263 SmallVectorImpl<PHINode *> &PhiNodes) { 264 if (SI1 == SI2) 265 return false; // Can't merge with self! 266 assert(SI1->isUnconditional() && SI2->isConditional()); 267 268 // We fold the unconditional branch if we can easily update all PHI nodes in 269 // common successors: 270 // 1> We have a constant incoming value for the conditional branch; 271 // 2> We have "Cond" as the incoming value for the unconditional branch; 272 // 3> SI2->getCondition() and Cond have same operands. 273 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); 274 if (!Ci2) 275 return false; 276 if (!(Cond->getOperand(0) == Ci2->getOperand(0) && 277 Cond->getOperand(1) == Ci2->getOperand(1)) && 278 !(Cond->getOperand(0) == Ci2->getOperand(1) && 279 Cond->getOperand(1) == Ci2->getOperand(0))) 280 return false; 281 282 BasicBlock *SI1BB = SI1->getParent(); 283 BasicBlock *SI2BB = SI2->getParent(); 284 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 285 for (BasicBlock *Succ : successors(SI2BB)) 286 if (SI1Succs.count(Succ)) 287 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { 288 PHINode *PN = cast<PHINode>(BBI); 289 if (PN->getIncomingValueForBlock(SI1BB) != Cond || 290 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) 291 return false; 292 PhiNodes.push_back(PN); 293 } 294 return true; 295 } 296 297 /// Update PHI nodes in Succ to indicate that there will now be entries in it 298 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes 299 /// will be the same as those coming in from ExistPred, an existing predecessor 300 /// of Succ. 301 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, 302 BasicBlock *ExistPred, 303 MemorySSAUpdater *MSSAU = nullptr) { 304 for (PHINode &PN : Succ->phis()) 305 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred); 306 if (MSSAU) 307 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ)) 308 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred); 309 } 310 311 /// Compute an abstract "cost" of speculating the given instruction, 312 /// which is assumed to be safe to speculate. TCC_Free means cheap, 313 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively 314 /// expensive. 315 static unsigned ComputeSpeculationCost(const User *I, 316 const TargetTransformInfo &TTI) { 317 assert(isSafeToSpeculativelyExecute(I) && 318 "Instruction is not safe to speculatively execute!"); 319 return TTI.getUserCost(I); 320 } 321 322 /// If we have a merge point of an "if condition" as accepted above, 323 /// return true if the specified value dominates the block. We 324 /// don't handle the true generality of domination here, just a special case 325 /// which works well enough for us. 326 /// 327 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to 328 /// see if V (which must be an instruction) and its recursive operands 329 /// that do not dominate BB have a combined cost lower than CostRemaining and 330 /// are non-trapping. If both are true, the instruction is inserted into the 331 /// set and true is returned. 332 /// 333 /// The cost for most non-trapping instructions is defined as 1 except for 334 /// Select whose cost is 2. 335 /// 336 /// After this function returns, CostRemaining is decreased by the cost of 337 /// V plus its non-dominating operands. If that cost is greater than 338 /// CostRemaining, false is returned and CostRemaining is undefined. 339 static bool DominatesMergePoint(Value *V, BasicBlock *BB, 340 SmallPtrSetImpl<Instruction *> &AggressiveInsts, 341 int &BudgetRemaining, 342 const TargetTransformInfo &TTI, 343 unsigned Depth = 0) { 344 // It is possible to hit a zero-cost cycle (phi/gep instructions for example), 345 // so limit the recursion depth. 346 // TODO: While this recursion limit does prevent pathological behavior, it 347 // would be better to track visited instructions to avoid cycles. 348 if (Depth == MaxSpeculationDepth) 349 return false; 350 351 Instruction *I = dyn_cast<Instruction>(V); 352 if (!I) { 353 // Non-instructions all dominate instructions, but not all constantexprs 354 // can be executed unconditionally. 355 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) 356 if (C->canTrap()) 357 return false; 358 return true; 359 } 360 BasicBlock *PBB = I->getParent(); 361 362 // We don't want to allow weird loops that might have the "if condition" in 363 // the bottom of this block. 364 if (PBB == BB) 365 return false; 366 367 // If this instruction is defined in a block that contains an unconditional 368 // branch to BB, then it must be in the 'conditional' part of the "if 369 // statement". If not, it definitely dominates the region. 370 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); 371 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB) 372 return true; 373 374 // If we have seen this instruction before, don't count it again. 375 if (AggressiveInsts.count(I)) 376 return true; 377 378 // Okay, it looks like the instruction IS in the "condition". Check to 379 // see if it's a cheap instruction to unconditionally compute, and if it 380 // only uses stuff defined outside of the condition. If so, hoist it out. 381 if (!isSafeToSpeculativelyExecute(I)) 382 return false; 383 384 BudgetRemaining -= ComputeSpeculationCost(I, TTI); 385 386 // Allow exactly one instruction to be speculated regardless of its cost 387 // (as long as it is safe to do so). 388 // This is intended to flatten the CFG even if the instruction is a division 389 // or other expensive operation. The speculation of an expensive instruction 390 // is expected to be undone in CodeGenPrepare if the speculation has not 391 // enabled further IR optimizations. 392 if (BudgetRemaining < 0 && 393 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0)) 394 return false; 395 396 // Okay, we can only really hoist these out if their operands do 397 // not take us over the cost threshold. 398 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) 399 if (!DominatesMergePoint(*i, BB, AggressiveInsts, BudgetRemaining, TTI, 400 Depth + 1)) 401 return false; 402 // Okay, it's safe to do this! Remember this instruction. 403 AggressiveInsts.insert(I); 404 return true; 405 } 406 407 /// Extract ConstantInt from value, looking through IntToPtr 408 /// and PointerNullValue. Return NULL if value is not a constant int. 409 static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) { 410 // Normal constant int. 411 ConstantInt *CI = dyn_cast<ConstantInt>(V); 412 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy()) 413 return CI; 414 415 // This is some kind of pointer constant. Turn it into a pointer-sized 416 // ConstantInt if possible. 417 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType())); 418 419 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). 420 if (isa<ConstantPointerNull>(V)) 421 return ConstantInt::get(PtrTy, 0); 422 423 // IntToPtr const int. 424 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 425 if (CE->getOpcode() == Instruction::IntToPtr) 426 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { 427 // The constant is very likely to have the right type already. 428 if (CI->getType() == PtrTy) 429 return CI; 430 else 431 return cast<ConstantInt>( 432 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); 433 } 434 return nullptr; 435 } 436 437 namespace { 438 439 /// Given a chain of or (||) or and (&&) comparison of a value against a 440 /// constant, this will try to recover the information required for a switch 441 /// structure. 442 /// It will depth-first traverse the chain of comparison, seeking for patterns 443 /// like %a == 12 or %a < 4 and combine them to produce a set of integer 444 /// representing the different cases for the switch. 445 /// Note that if the chain is composed of '||' it will build the set of elements 446 /// that matches the comparisons (i.e. any of this value validate the chain) 447 /// while for a chain of '&&' it will build the set elements that make the test 448 /// fail. 449 struct ConstantComparesGatherer { 450 const DataLayout &DL; 451 452 /// Value found for the switch comparison 453 Value *CompValue = nullptr; 454 455 /// Extra clause to be checked before the switch 456 Value *Extra = nullptr; 457 458 /// Set of integers to match in switch 459 SmallVector<ConstantInt *, 8> Vals; 460 461 /// Number of comparisons matched in the and/or chain 462 unsigned UsedICmps = 0; 463 464 /// Construct and compute the result for the comparison instruction Cond 465 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) { 466 gather(Cond); 467 } 468 469 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete; 470 ConstantComparesGatherer & 471 operator=(const ConstantComparesGatherer &) = delete; 472 473 private: 474 /// Try to set the current value used for the comparison, it succeeds only if 475 /// it wasn't set before or if the new value is the same as the old one 476 bool setValueOnce(Value *NewVal) { 477 if (CompValue && CompValue != NewVal) 478 return false; 479 CompValue = NewVal; 480 return (CompValue != nullptr); 481 } 482 483 /// Try to match Instruction "I" as a comparison against a constant and 484 /// populates the array Vals with the set of values that match (or do not 485 /// match depending on isEQ). 486 /// Return false on failure. On success, the Value the comparison matched 487 /// against is placed in CompValue. 488 /// If CompValue is already set, the function is expected to fail if a match 489 /// is found but the value compared to is different. 490 bool matchInstruction(Instruction *I, bool isEQ) { 491 // If this is an icmp against a constant, handle this as one of the cases. 492 ICmpInst *ICI; 493 ConstantInt *C; 494 if (!((ICI = dyn_cast<ICmpInst>(I)) && 495 (C = GetConstantInt(I->getOperand(1), DL)))) { 496 return false; 497 } 498 499 Value *RHSVal; 500 const APInt *RHSC; 501 502 // Pattern match a special case 503 // (x & ~2^z) == y --> x == y || x == y|2^z 504 // This undoes a transformation done by instcombine to fuse 2 compares. 505 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) { 506 // It's a little bit hard to see why the following transformations are 507 // correct. Here is a CVC3 program to verify them for 64-bit values: 508 509 /* 510 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63); 511 x : BITVECTOR(64); 512 y : BITVECTOR(64); 513 z : BITVECTOR(64); 514 mask : BITVECTOR(64) = BVSHL(ONE, z); 515 QUERY( (y & ~mask = y) => 516 ((x & ~mask = y) <=> (x = y OR x = (y | mask))) 517 ); 518 QUERY( (y | mask = y) => 519 ((x | mask = y) <=> (x = y OR x = (y & ~mask))) 520 ); 521 */ 522 523 // Please note that each pattern must be a dual implication (<--> or 524 // iff). One directional implication can create spurious matches. If the 525 // implication is only one-way, an unsatisfiable condition on the left 526 // side can imply a satisfiable condition on the right side. Dual 527 // implication ensures that satisfiable conditions are transformed to 528 // other satisfiable conditions and unsatisfiable conditions are 529 // transformed to other unsatisfiable conditions. 530 531 // Here is a concrete example of a unsatisfiable condition on the left 532 // implying a satisfiable condition on the right: 533 // 534 // mask = (1 << z) 535 // (x & ~mask) == y --> (x == y || x == (y | mask)) 536 // 537 // Substituting y = 3, z = 0 yields: 538 // (x & -2) == 3 --> (x == 3 || x == 2) 539 540 // Pattern match a special case: 541 /* 542 QUERY( (y & ~mask = y) => 543 ((x & ~mask = y) <=> (x = y OR x = (y | mask))) 544 ); 545 */ 546 if (match(ICI->getOperand(0), 547 m_And(m_Value(RHSVal), m_APInt(RHSC)))) { 548 APInt Mask = ~*RHSC; 549 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) { 550 // If we already have a value for the switch, it has to match! 551 if (!setValueOnce(RHSVal)) 552 return false; 553 554 Vals.push_back(C); 555 Vals.push_back( 556 ConstantInt::get(C->getContext(), 557 C->getValue() | Mask)); 558 UsedICmps++; 559 return true; 560 } 561 } 562 563 // Pattern match a special case: 564 /* 565 QUERY( (y | mask = y) => 566 ((x | mask = y) <=> (x = y OR x = (y & ~mask))) 567 ); 568 */ 569 if (match(ICI->getOperand(0), 570 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) { 571 APInt Mask = *RHSC; 572 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) { 573 // If we already have a value for the switch, it has to match! 574 if (!setValueOnce(RHSVal)) 575 return false; 576 577 Vals.push_back(C); 578 Vals.push_back(ConstantInt::get(C->getContext(), 579 C->getValue() & ~Mask)); 580 UsedICmps++; 581 return true; 582 } 583 } 584 585 // If we already have a value for the switch, it has to match! 586 if (!setValueOnce(ICI->getOperand(0))) 587 return false; 588 589 UsedICmps++; 590 Vals.push_back(C); 591 return ICI->getOperand(0); 592 } 593 594 // If we have "x ult 3", for example, then we can add 0,1,2 to the set. 595 ConstantRange Span = ConstantRange::makeAllowedICmpRegion( 596 ICI->getPredicate(), C->getValue()); 597 598 // Shift the range if the compare is fed by an add. This is the range 599 // compare idiom as emitted by instcombine. 600 Value *CandidateVal = I->getOperand(0); 601 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) { 602 Span = Span.subtract(*RHSC); 603 CandidateVal = RHSVal; 604 } 605 606 // If this is an and/!= check, then we are looking to build the set of 607 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into 608 // x != 0 && x != 1. 609 if (!isEQ) 610 Span = Span.inverse(); 611 612 // If there are a ton of values, we don't want to make a ginormous switch. 613 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) { 614 return false; 615 } 616 617 // If we already have a value for the switch, it has to match! 618 if (!setValueOnce(CandidateVal)) 619 return false; 620 621 // Add all values from the range to the set 622 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) 623 Vals.push_back(ConstantInt::get(I->getContext(), Tmp)); 624 625 UsedICmps++; 626 return true; 627 } 628 629 /// Given a potentially 'or'd or 'and'd together collection of icmp 630 /// eq/ne/lt/gt instructions that compare a value against a constant, extract 631 /// the value being compared, and stick the list constants into the Vals 632 /// vector. 633 /// One "Extra" case is allowed to differ from the other. 634 void gather(Value *V) { 635 Instruction *I = dyn_cast<Instruction>(V); 636 bool isEQ = (I->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 2405 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond 2406 << " T: " << IfTrue->getName() 2407 << " F: " << IfFalse->getName() << "\n"); 2408 2409 // If we can still promote the PHI nodes after this gauntlet of tests, 2410 // do all of the PHI's now. 2411 Instruction *InsertPt = DomBlock->getTerminator(); 2412 IRBuilder<NoFolder> Builder(InsertPt); 2413 2414 // Move all 'aggressive' instructions, which are defined in the 2415 // conditional parts of the if's up to the dominating block. 2416 if (IfBlock1) 2417 hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1); 2418 if (IfBlock2) 2419 hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2); 2420 2421 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 2422 // Change the PHI node into a select instruction. 2423 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); 2424 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); 2425 2426 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt); 2427 PN->replaceAllUsesWith(Sel); 2428 Sel->takeName(PN); 2429 PN->eraseFromParent(); 2430 } 2431 2432 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement 2433 // has been flattened. Change DomBlock to jump directly to our new block to 2434 // avoid other simplifycfg's kicking in on the diamond. 2435 Instruction *OldTI = DomBlock->getTerminator(); 2436 Builder.SetInsertPoint(OldTI); 2437 Builder.CreateBr(BB); 2438 OldTI->eraseFromParent(); 2439 return true; 2440 } 2441 2442 /// If we found a conditional branch that goes to two returning blocks, 2443 /// try to merge them together into one return, 2444 /// introducing a select if the return values disagree. 2445 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, 2446 IRBuilder<> &Builder) { 2447 assert(BI->isConditional() && "Must be a conditional branch"); 2448 BasicBlock *TrueSucc = BI->getSuccessor(0); 2449 BasicBlock *FalseSucc = BI->getSuccessor(1); 2450 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); 2451 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); 2452 2453 // Check to ensure both blocks are empty (just a return) or optionally empty 2454 // with PHI nodes. If there are other instructions, merging would cause extra 2455 // computation on one path or the other. 2456 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) 2457 return false; 2458 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) 2459 return false; 2460 2461 Builder.SetInsertPoint(BI); 2462 // Okay, we found a branch that is going to two return nodes. If 2463 // there is no return value for this function, just change the 2464 // branch into a return. 2465 if (FalseRet->getNumOperands() == 0) { 2466 TrueSucc->removePredecessor(BI->getParent()); 2467 FalseSucc->removePredecessor(BI->getParent()); 2468 Builder.CreateRetVoid(); 2469 EraseTerminatorAndDCECond(BI); 2470 return true; 2471 } 2472 2473 // Otherwise, figure out what the true and false return values are 2474 // so we can insert a new select instruction. 2475 Value *TrueValue = TrueRet->getReturnValue(); 2476 Value *FalseValue = FalseRet->getReturnValue(); 2477 2478 // Unwrap any PHI nodes in the return blocks. 2479 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) 2480 if (TVPN->getParent() == TrueSucc) 2481 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); 2482 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) 2483 if (FVPN->getParent() == FalseSucc) 2484 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); 2485 2486 // In order for this transformation to be safe, we must be able to 2487 // unconditionally execute both operands to the return. This is 2488 // normally the case, but we could have a potentially-trapping 2489 // constant expression that prevents this transformation from being 2490 // safe. 2491 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) 2492 if (TCV->canTrap()) 2493 return false; 2494 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) 2495 if (FCV->canTrap()) 2496 return false; 2497 2498 // Okay, we collected all the mapped values and checked them for sanity, and 2499 // defined to really do this transformation. First, update the CFG. 2500 TrueSucc->removePredecessor(BI->getParent()); 2501 FalseSucc->removePredecessor(BI->getParent()); 2502 2503 // Insert select instructions where needed. 2504 Value *BrCond = BI->getCondition(); 2505 if (TrueValue) { 2506 // Insert a select if the results differ. 2507 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { 2508 } else if (isa<UndefValue>(TrueValue)) { 2509 TrueValue = FalseValue; 2510 } else { 2511 TrueValue = 2512 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI); 2513 } 2514 } 2515 2516 Value *RI = 2517 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); 2518 2519 (void)RI; 2520 2521 LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 2522 << "\n " << *BI << "NewRet = " << *RI << "TRUEBLOCK: " 2523 << *TrueSucc << "FALSEBLOCK: " << *FalseSucc); 2524 2525 EraseTerminatorAndDCECond(BI); 2526 2527 return true; 2528 } 2529 2530 /// Return true if the given instruction is available 2531 /// in its predecessor block. If yes, the instruction will be removed. 2532 static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB) { 2533 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) 2534 return false; 2535 for (Instruction &I : *PB) { 2536 Instruction *PBI = &I; 2537 // Check whether Inst and PBI generate the same value. 2538 if (Inst->isIdenticalTo(PBI)) { 2539 Inst->replaceAllUsesWith(PBI); 2540 Inst->eraseFromParent(); 2541 return true; 2542 } 2543 } 2544 return false; 2545 } 2546 2547 /// Return true if either PBI or BI has branch weight available, and store 2548 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does 2549 /// not have branch weight, use 1:1 as its weight. 2550 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, 2551 uint64_t &PredTrueWeight, 2552 uint64_t &PredFalseWeight, 2553 uint64_t &SuccTrueWeight, 2554 uint64_t &SuccFalseWeight) { 2555 bool PredHasWeights = 2556 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight); 2557 bool SuccHasWeights = 2558 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight); 2559 if (PredHasWeights || SuccHasWeights) { 2560 if (!PredHasWeights) 2561 PredTrueWeight = PredFalseWeight = 1; 2562 if (!SuccHasWeights) 2563 SuccTrueWeight = SuccFalseWeight = 1; 2564 return true; 2565 } else { 2566 return false; 2567 } 2568 } 2569 2570 /// If this basic block is simple enough, and if a predecessor branches to us 2571 /// and one of our successors, fold the block into the predecessor and use 2572 /// logical operations to pick the right destination. 2573 bool llvm::FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU, 2574 unsigned BonusInstThreshold) { 2575 BasicBlock *BB = BI->getParent(); 2576 2577 const unsigned PredCount = pred_size(BB); 2578 2579 Instruction *Cond = nullptr; 2580 if (BI->isConditional()) 2581 Cond = dyn_cast<Instruction>(BI->getCondition()); 2582 else { 2583 // For unconditional branch, check for a simple CFG pattern, where 2584 // BB has a single predecessor and BB's successor is also its predecessor's 2585 // successor. If such pattern exists, check for CSE between BB and its 2586 // predecessor. 2587 if (BasicBlock *PB = BB->getSinglePredecessor()) 2588 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) 2589 if (PBI->isConditional() && 2590 (BI->getSuccessor(0) == PBI->getSuccessor(0) || 2591 BI->getSuccessor(0) == PBI->getSuccessor(1))) { 2592 for (auto I = BB->instructionsWithoutDebug().begin(), 2593 E = BB->instructionsWithoutDebug().end(); 2594 I != E;) { 2595 Instruction *Curr = &*I++; 2596 if (isa<CmpInst>(Curr)) { 2597 Cond = Curr; 2598 break; 2599 } 2600 // Quit if we can't remove this instruction. 2601 if (!tryCSEWithPredecessor(Curr, PB)) 2602 return false; 2603 } 2604 } 2605 2606 if (!Cond) 2607 return false; 2608 } 2609 2610 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || 2611 Cond->getParent() != BB || !Cond->hasOneUse()) 2612 return false; 2613 2614 // Make sure the instruction after the condition is the cond branch. 2615 BasicBlock::iterator CondIt = ++Cond->getIterator(); 2616 2617 // Ignore dbg intrinsics. 2618 while (isa<DbgInfoIntrinsic>(CondIt)) 2619 ++CondIt; 2620 2621 if (&*CondIt != BI) 2622 return false; 2623 2624 // Only allow this transformation if computing the condition doesn't involve 2625 // too many instructions and these involved instructions can be executed 2626 // unconditionally. We denote all involved instructions except the condition 2627 // as "bonus instructions", and only allow this transformation when the 2628 // number of the bonus instructions we'll need to create when cloning into 2629 // each predecessor does not exceed a certain threshold. 2630 unsigned NumBonusInsts = 0; 2631 for (auto I = BB->begin(); Cond != &*I; ++I) { 2632 // Ignore dbg intrinsics. 2633 if (isa<DbgInfoIntrinsic>(I)) 2634 continue; 2635 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I)) 2636 return false; 2637 // I has only one use and can be executed unconditionally. 2638 Instruction *User = dyn_cast<Instruction>(I->user_back()); 2639 if (User == nullptr || User->getParent() != BB) 2640 return false; 2641 // I is used in the same BB. Since BI uses Cond and doesn't have more slots 2642 // to use any other instruction, User must be an instruction between next(I) 2643 // and Cond. 2644 2645 // Account for the cost of duplicating this instruction into each 2646 // predecessor. 2647 NumBonusInsts += PredCount; 2648 // Early exits once we reach the limit. 2649 if (NumBonusInsts > BonusInstThreshold) 2650 return false; 2651 } 2652 2653 // Cond is known to be a compare or binary operator. Check to make sure that 2654 // neither operand is a potentially-trapping constant expression. 2655 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) 2656 if (CE->canTrap()) 2657 return false; 2658 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) 2659 if (CE->canTrap()) 2660 return false; 2661 2662 // Finally, don't infinitely unroll conditional loops. 2663 BasicBlock *TrueDest = BI->getSuccessor(0); 2664 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; 2665 if (TrueDest == BB || FalseDest == BB) 2666 return false; 2667 2668 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 2669 BasicBlock *PredBlock = *PI; 2670 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); 2671 2672 // Check that we have two conditional branches. If there is a PHI node in 2673 // the common successor, verify that the same value flows in from both 2674 // blocks. 2675 SmallVector<PHINode *, 4> PHIs; 2676 if (!PBI || PBI->isUnconditional() || 2677 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) || 2678 (!BI->isConditional() && 2679 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) 2680 continue; 2681 2682 // Determine if the two branches share a common destination. 2683 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; 2684 bool InvertPredCond = false; 2685 2686 if (BI->isConditional()) { 2687 if (PBI->getSuccessor(0) == TrueDest) { 2688 Opc = Instruction::Or; 2689 } else if (PBI->getSuccessor(1) == FalseDest) { 2690 Opc = Instruction::And; 2691 } else if (PBI->getSuccessor(0) == FalseDest) { 2692 Opc = Instruction::And; 2693 InvertPredCond = true; 2694 } else if (PBI->getSuccessor(1) == TrueDest) { 2695 Opc = Instruction::Or; 2696 InvertPredCond = true; 2697 } else { 2698 continue; 2699 } 2700 } else { 2701 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) 2702 continue; 2703 } 2704 2705 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); 2706 IRBuilder<> Builder(PBI); 2707 2708 // If we need to invert the condition in the pred block to match, do so now. 2709 if (InvertPredCond) { 2710 Value *NewCond = PBI->getCondition(); 2711 2712 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { 2713 CmpInst *CI = cast<CmpInst>(NewCond); 2714 CI->setPredicate(CI->getInversePredicate()); 2715 } else { 2716 NewCond = 2717 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not"); 2718 } 2719 2720 PBI->setCondition(NewCond); 2721 PBI->swapSuccessors(); 2722 } 2723 2724 // If we have bonus instructions, clone them into the predecessor block. 2725 // Note that there may be multiple predecessor blocks, so we cannot move 2726 // bonus instructions to a predecessor block. 2727 ValueToValueMapTy VMap; // maps original values to cloned values 2728 // We already make sure Cond is the last instruction before BI. Therefore, 2729 // all instructions before Cond other than DbgInfoIntrinsic are bonus 2730 // instructions. 2731 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) { 2732 if (isa<DbgInfoIntrinsic>(BonusInst)) 2733 continue; 2734 Instruction *NewBonusInst = BonusInst->clone(); 2735 RemapInstruction(NewBonusInst, VMap, 2736 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 2737 VMap[&*BonusInst] = NewBonusInst; 2738 2739 // If we moved a load, we cannot any longer claim any knowledge about 2740 // its potential value. The previous information might have been valid 2741 // only given the branch precondition. 2742 // For an analogous reason, we must also drop all the metadata whose 2743 // semantics we don't understand. 2744 NewBonusInst->dropUnknownNonDebugMetadata(); 2745 2746 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst); 2747 NewBonusInst->takeName(&*BonusInst); 2748 BonusInst->setName(BonusInst->getName() + ".old"); 2749 } 2750 2751 // Clone Cond into the predecessor basic block, and or/and the 2752 // two conditions together. 2753 Instruction *CondInPred = Cond->clone(); 2754 RemapInstruction(CondInPred, VMap, 2755 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 2756 PredBlock->getInstList().insert(PBI->getIterator(), CondInPred); 2757 CondInPred->takeName(Cond); 2758 Cond->setName(CondInPred->getName() + ".old"); 2759 2760 if (BI->isConditional()) { 2761 Instruction *NewCond = cast<Instruction>( 2762 Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond")); 2763 PBI->setCondition(NewCond); 2764 2765 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 2766 bool HasWeights = 2767 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 2768 SuccTrueWeight, SuccFalseWeight); 2769 SmallVector<uint64_t, 8> NewWeights; 2770 2771 if (PBI->getSuccessor(0) == BB) { 2772 if (HasWeights) { 2773 // PBI: br i1 %x, BB, FalseDest 2774 // BI: br i1 %y, TrueDest, FalseDest 2775 // TrueWeight is TrueWeight for PBI * TrueWeight for BI. 2776 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 2777 // FalseWeight is FalseWeight for PBI * TotalWeight for BI + 2778 // TrueWeight for PBI * FalseWeight for BI. 2779 // We assume that total weights of a BranchInst can fit into 32 bits. 2780 // Therefore, we will not have overflow using 64-bit arithmetic. 2781 NewWeights.push_back(PredFalseWeight * 2782 (SuccFalseWeight + SuccTrueWeight) + 2783 PredTrueWeight * SuccFalseWeight); 2784 } 2785 AddPredecessorToBlock(TrueDest, PredBlock, BB, MSSAU); 2786 PBI->setSuccessor(0, TrueDest); 2787 } 2788 if (PBI->getSuccessor(1) == BB) { 2789 if (HasWeights) { 2790 // PBI: br i1 %x, TrueDest, BB 2791 // BI: br i1 %y, TrueDest, FalseDest 2792 // TrueWeight is TrueWeight for PBI * TotalWeight for BI + 2793 // FalseWeight for PBI * TrueWeight for BI. 2794 NewWeights.push_back(PredTrueWeight * 2795 (SuccFalseWeight + SuccTrueWeight) + 2796 PredFalseWeight * SuccTrueWeight); 2797 // FalseWeight is FalseWeight for PBI * FalseWeight for BI. 2798 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 2799 } 2800 AddPredecessorToBlock(FalseDest, PredBlock, BB, MSSAU); 2801 PBI->setSuccessor(1, FalseDest); 2802 } 2803 if (NewWeights.size() == 2) { 2804 // Halve the weights if any of them cannot fit in an uint32_t 2805 FitWeights(NewWeights); 2806 2807 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), 2808 NewWeights.end()); 2809 setBranchWeights(PBI, MDWeights[0], MDWeights[1]); 2810 } else 2811 PBI->setMetadata(LLVMContext::MD_prof, nullptr); 2812 } else { 2813 // Update PHI nodes in the common successors. 2814 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { 2815 ConstantInt *PBI_C = cast<ConstantInt>( 2816 PHIs[i]->getIncomingValueForBlock(PBI->getParent())); 2817 assert(PBI_C->getType()->isIntegerTy(1)); 2818 Instruction *MergedCond = nullptr; 2819 if (PBI->getSuccessor(0) == TrueDest) { 2820 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) 2821 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) 2822 // is false: !PBI_Cond and BI_Value 2823 Instruction *NotCond = cast<Instruction>( 2824 Builder.CreateNot(PBI->getCondition(), "not.cond")); 2825 MergedCond = cast<Instruction>( 2826 Builder.CreateBinOp(Instruction::And, NotCond, CondInPred, 2827 "and.cond")); 2828 if (PBI_C->isOne()) 2829 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2830 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond")); 2831 } else { 2832 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) 2833 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) 2834 // is false: PBI_Cond and BI_Value 2835 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2836 Instruction::And, PBI->getCondition(), CondInPred, "and.cond")); 2837 if (PBI_C->isOne()) { 2838 Instruction *NotCond = cast<Instruction>( 2839 Builder.CreateNot(PBI->getCondition(), "not.cond")); 2840 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2841 Instruction::Or, NotCond, MergedCond, "or.cond")); 2842 } 2843 } 2844 // Update PHI Node. 2845 PHIs[i]->setIncomingValueForBlock(PBI->getParent(), MergedCond); 2846 } 2847 2848 // PBI is changed to branch to TrueDest below. Remove itself from 2849 // potential phis from all other successors. 2850 if (MSSAU) 2851 MSSAU->changeCondBranchToUnconditionalTo(PBI, TrueDest); 2852 2853 // Change PBI from Conditional to Unconditional. 2854 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); 2855 EraseTerminatorAndDCECond(PBI, MSSAU); 2856 PBI = New_PBI; 2857 } 2858 2859 // If BI was a loop latch, it may have had associated loop metadata. 2860 // We need to copy it to the new latch, that is, PBI. 2861 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop)) 2862 PBI->setMetadata(LLVMContext::MD_loop, LoopMD); 2863 2864 // TODO: If BB is reachable from all paths through PredBlock, then we 2865 // could replace PBI's branch probabilities with BI's. 2866 2867 // Copy any debug value intrinsics into the end of PredBlock. 2868 for (Instruction &I : *BB) 2869 if (isa<DbgInfoIntrinsic>(I)) 2870 I.clone()->insertBefore(PBI); 2871 2872 return true; 2873 } 2874 return false; 2875 } 2876 2877 // If there is only one store in BB1 and BB2, return it, otherwise return 2878 // nullptr. 2879 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { 2880 StoreInst *S = nullptr; 2881 for (auto *BB : {BB1, BB2}) { 2882 if (!BB) 2883 continue; 2884 for (auto &I : *BB) 2885 if (auto *SI = dyn_cast<StoreInst>(&I)) { 2886 if (S) 2887 // Multiple stores seen. 2888 return nullptr; 2889 else 2890 S = SI; 2891 } 2892 } 2893 return S; 2894 } 2895 2896 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, 2897 Value *AlternativeV = nullptr) { 2898 // PHI is going to be a PHI node that allows the value V that is defined in 2899 // BB to be referenced in BB's only successor. 2900 // 2901 // If AlternativeV is nullptr, the only value we care about in PHI is V. It 2902 // doesn't matter to us what the other operand is (it'll never get used). We 2903 // could just create a new PHI with an undef incoming value, but that could 2904 // increase register pressure if EarlyCSE/InstCombine can't fold it with some 2905 // other PHI. So here we directly look for some PHI in BB's successor with V 2906 // as an incoming operand. If we find one, we use it, else we create a new 2907 // one. 2908 // 2909 // If AlternativeV is not nullptr, we care about both incoming values in PHI. 2910 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] 2911 // where OtherBB is the single other predecessor of BB's only successor. 2912 PHINode *PHI = nullptr; 2913 BasicBlock *Succ = BB->getSingleSuccessor(); 2914 2915 for (auto I = Succ->begin(); isa<PHINode>(I); ++I) 2916 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { 2917 PHI = cast<PHINode>(I); 2918 if (!AlternativeV) 2919 break; 2920 2921 assert(Succ->hasNPredecessors(2)); 2922 auto PredI = pred_begin(Succ); 2923 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; 2924 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) 2925 break; 2926 PHI = nullptr; 2927 } 2928 if (PHI) 2929 return PHI; 2930 2931 // If V is not an instruction defined in BB, just return it. 2932 if (!AlternativeV && 2933 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB)) 2934 return V; 2935 2936 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front()); 2937 PHI->addIncoming(V, BB); 2938 for (BasicBlock *PredBB : predecessors(Succ)) 2939 if (PredBB != BB) 2940 PHI->addIncoming( 2941 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB); 2942 return PHI; 2943 } 2944 2945 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, 2946 BasicBlock *QTB, BasicBlock *QFB, 2947 BasicBlock *PostBB, Value *Address, 2948 bool InvertPCond, bool InvertQCond, 2949 const DataLayout &DL) { 2950 auto IsaBitcastOfPointerType = [](const Instruction &I) { 2951 return Operator::getOpcode(&I) == Instruction::BitCast && 2952 I.getType()->isPointerTy(); 2953 }; 2954 2955 // If we're not in aggressive mode, we only optimize if we have some 2956 // confidence that by optimizing we'll allow P and/or Q to be if-converted. 2957 auto IsWorthwhile = [&](BasicBlock *BB) { 2958 if (!BB) 2959 return true; 2960 // Heuristic: if the block can be if-converted/phi-folded and the 2961 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to 2962 // thread this store. 2963 unsigned N = 0; 2964 for (auto &I : BB->instructionsWithoutDebug()) { 2965 // Cheap instructions viable for folding. 2966 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) || 2967 isa<StoreInst>(I)) 2968 ++N; 2969 // Free instructions. 2970 else if (I.isTerminator() || IsaBitcastOfPointerType(I)) 2971 continue; 2972 else 2973 return false; 2974 } 2975 // The store we want to merge is counted in N, so add 1 to make sure 2976 // we're counting the instructions that would be left. 2977 return N <= (PHINodeFoldingThreshold + 1); 2978 }; 2979 2980 if (!MergeCondStoresAggressively && 2981 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) || 2982 !IsWorthwhile(QFB))) 2983 return false; 2984 2985 // For every pointer, there must be exactly two stores, one coming from 2986 // PTB or PFB, and the other from QTB or QFB. We don't support more than one 2987 // store (to any address) in PTB,PFB or QTB,QFB. 2988 // FIXME: We could relax this restriction with a bit more work and performance 2989 // testing. 2990 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); 2991 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); 2992 if (!PStore || !QStore) 2993 return false; 2994 2995 // Now check the stores are compatible. 2996 if (!QStore->isUnordered() || !PStore->isUnordered()) 2997 return false; 2998 2999 // Check that sinking the store won't cause program behavior changes. Sinking 3000 // the store out of the Q blocks won't change any behavior as we're sinking 3001 // from a block to its unconditional successor. But we're moving a store from 3002 // the P blocks down through the middle block (QBI) and past both QFB and QTB. 3003 // So we need to check that there are no aliasing loads or stores in 3004 // QBI, QTB and QFB. We also need to check there are no conflicting memory 3005 // operations between PStore and the end of its parent block. 3006 // 3007 // The ideal way to do this is to query AliasAnalysis, but we don't 3008 // preserve AA currently so that is dangerous. Be super safe and just 3009 // check there are no other memory operations at all. 3010 for (auto &I : *QFB->getSinglePredecessor()) 3011 if (I.mayReadOrWriteMemory()) 3012 return false; 3013 for (auto &I : *QFB) 3014 if (&I != QStore && I.mayReadOrWriteMemory()) 3015 return false; 3016 if (QTB) 3017 for (auto &I : *QTB) 3018 if (&I != QStore && I.mayReadOrWriteMemory()) 3019 return false; 3020 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); 3021 I != E; ++I) 3022 if (&*I != PStore && I->mayReadOrWriteMemory()) 3023 return false; 3024 3025 // If PostBB has more than two predecessors, we need to split it so we can 3026 // sink the store. 3027 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) { 3028 // We know that QFB's only successor is PostBB. And QFB has a single 3029 // predecessor. If QTB exists, then its only successor is also PostBB. 3030 // If QTB does not exist, then QFB's only predecessor has a conditional 3031 // branch to QFB and PostBB. 3032 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor(); 3033 BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred}, 3034 "condstore.split"); 3035 if (!NewBB) 3036 return false; 3037 PostBB = NewBB; 3038 } 3039 3040 // OK, we're going to sink the stores to PostBB. The store has to be 3041 // conditional though, so first create the predicate. 3042 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) 3043 ->getCondition(); 3044 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) 3045 ->getCondition(); 3046 3047 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), 3048 PStore->getParent()); 3049 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), 3050 QStore->getParent(), PPHI); 3051 3052 IRBuilder<> QB(&*PostBB->getFirstInsertionPt()); 3053 3054 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); 3055 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); 3056 3057 if (InvertPCond) 3058 PPred = QB.CreateNot(PPred); 3059 if (InvertQCond) 3060 QPred = QB.CreateNot(QPred); 3061 Value *CombinedPred = QB.CreateOr(PPred, QPred); 3062 3063 auto *T = 3064 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false); 3065 QB.SetInsertPoint(T); 3066 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); 3067 AAMDNodes AAMD; 3068 PStore->getAAMetadata(AAMD, /*Merge=*/false); 3069 PStore->getAAMetadata(AAMD, /*Merge=*/true); 3070 SI->setAAMetadata(AAMD); 3071 unsigned PAlignment = PStore->getAlignment(); 3072 unsigned QAlignment = QStore->getAlignment(); 3073 unsigned TypeAlignment = 3074 DL.getABITypeAlignment(SI->getValueOperand()->getType()); 3075 unsigned MinAlignment; 3076 unsigned MaxAlignment; 3077 std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment); 3078 // Choose the minimum alignment. If we could prove both stores execute, we 3079 // could use biggest one. In this case, though, we only know that one of the 3080 // stores executes. And we don't know it's safe to take the alignment from a 3081 // store that doesn't execute. 3082 if (MinAlignment != 0) { 3083 // Choose the minimum of all non-zero alignments. 3084 SI->setAlignment(MinAlignment); 3085 } else if (MaxAlignment != 0) { 3086 // Choose the minimal alignment between the non-zero alignment and the ABI 3087 // default alignment for the type of the stored value. 3088 SI->setAlignment(std::min(MaxAlignment, TypeAlignment)); 3089 } else { 3090 // If both alignments are zero, use ABI default alignment for the type of 3091 // the stored value. 3092 SI->setAlignment(TypeAlignment); 3093 } 3094 3095 QStore->eraseFromParent(); 3096 PStore->eraseFromParent(); 3097 3098 return true; 3099 } 3100 3101 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI, 3102 const DataLayout &DL) { 3103 // The intention here is to find diamonds or triangles (see below) where each 3104 // conditional block contains a store to the same address. Both of these 3105 // stores are conditional, so they can't be unconditionally sunk. But it may 3106 // be profitable to speculatively sink the stores into one merged store at the 3107 // end, and predicate the merged store on the union of the two conditions of 3108 // PBI and QBI. 3109 // 3110 // This can reduce the number of stores executed if both of the conditions are 3111 // true, and can allow the blocks to become small enough to be if-converted. 3112 // This optimization will also chain, so that ladders of test-and-set 3113 // sequences can be if-converted away. 3114 // 3115 // We only deal with simple diamonds or triangles: 3116 // 3117 // PBI or PBI or a combination of the two 3118 // / \ | \ 3119 // PTB PFB | PFB 3120 // \ / | / 3121 // QBI QBI 3122 // / \ | \ 3123 // QTB QFB | QFB 3124 // \ / | / 3125 // PostBB PostBB 3126 // 3127 // We model triangles as a type of diamond with a nullptr "true" block. 3128 // Triangles are canonicalized so that the fallthrough edge is represented by 3129 // a true condition, as in the diagram above. 3130 BasicBlock *PTB = PBI->getSuccessor(0); 3131 BasicBlock *PFB = PBI->getSuccessor(1); 3132 BasicBlock *QTB = QBI->getSuccessor(0); 3133 BasicBlock *QFB = QBI->getSuccessor(1); 3134 BasicBlock *PostBB = QFB->getSingleSuccessor(); 3135 3136 // Make sure we have a good guess for PostBB. If QTB's only successor is 3137 // QFB, then QFB is a better PostBB. 3138 if (QTB->getSingleSuccessor() == QFB) 3139 PostBB = QFB; 3140 3141 // If we couldn't find a good PostBB, stop. 3142 if (!PostBB) 3143 return false; 3144 3145 bool InvertPCond = false, InvertQCond = false; 3146 // Canonicalize fallthroughs to the true branches. 3147 if (PFB == QBI->getParent()) { 3148 std::swap(PFB, PTB); 3149 InvertPCond = true; 3150 } 3151 if (QFB == PostBB) { 3152 std::swap(QFB, QTB); 3153 InvertQCond = true; 3154 } 3155 3156 // From this point on we can assume PTB or QTB may be fallthroughs but PFB 3157 // and QFB may not. Model fallthroughs as a nullptr block. 3158 if (PTB == QBI->getParent()) 3159 PTB = nullptr; 3160 if (QTB == PostBB) 3161 QTB = nullptr; 3162 3163 // Legality bailouts. We must have at least the non-fallthrough blocks and 3164 // the post-dominating block, and the non-fallthroughs must only have one 3165 // predecessor. 3166 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { 3167 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S; 3168 }; 3169 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || 3170 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) 3171 return false; 3172 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || 3173 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) 3174 return false; 3175 if (!QBI->getParent()->hasNUses(2)) 3176 return false; 3177 3178 // OK, this is a sequence of two diamonds or triangles. 3179 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. 3180 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses; 3181 for (auto *BB : {PTB, PFB}) { 3182 if (!BB) 3183 continue; 3184 for (auto &I : *BB) 3185 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3186 PStoreAddresses.insert(SI->getPointerOperand()); 3187 } 3188 for (auto *BB : {QTB, QFB}) { 3189 if (!BB) 3190 continue; 3191 for (auto &I : *BB) 3192 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3193 QStoreAddresses.insert(SI->getPointerOperand()); 3194 } 3195 3196 set_intersect(PStoreAddresses, QStoreAddresses); 3197 // set_intersect mutates PStoreAddresses in place. Rename it here to make it 3198 // clear what it contains. 3199 auto &CommonAddresses = PStoreAddresses; 3200 3201 bool Changed = false; 3202 for (auto *Address : CommonAddresses) 3203 Changed |= mergeConditionalStoreToAddress( 3204 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL); 3205 return Changed; 3206 } 3207 3208 /// If we have a conditional branch as a predecessor of another block, 3209 /// this function tries to simplify it. We know 3210 /// that PBI and BI are both conditional branches, and BI is in one of the 3211 /// successor blocks of PBI - PBI branches to BI. 3212 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 3213 const DataLayout &DL) { 3214 assert(PBI->isConditional() && BI->isConditional()); 3215 BasicBlock *BB = BI->getParent(); 3216 3217 // If this block ends with a branch instruction, and if there is a 3218 // predecessor that ends on a branch of the same condition, make 3219 // this conditional branch redundant. 3220 if (PBI->getCondition() == BI->getCondition() && 3221 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3222 // Okay, the outcome of this conditional branch is statically 3223 // knowable. If this block had a single pred, handle specially. 3224 if (BB->getSinglePredecessor()) { 3225 // Turn this into a branch on constant. 3226 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3227 BI->setCondition( 3228 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue)); 3229 return true; // Nuke the branch on constant. 3230 } 3231 3232 // Otherwise, if there are multiple predecessors, insert a PHI that merges 3233 // in the constant and simplify the block result. Subsequent passes of 3234 // simplifycfg will thread the block. 3235 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 3236 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 3237 PHINode *NewPN = PHINode::Create( 3238 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE), 3239 BI->getCondition()->getName() + ".pr", &BB->front()); 3240 // Okay, we're going to insert the PHI node. Since PBI is not the only 3241 // predecessor, compute the PHI'd conditional value for all of the preds. 3242 // Any predecessor where the condition is not computable we keep symbolic. 3243 for (pred_iterator PI = PB; PI != PE; ++PI) { 3244 BasicBlock *P = *PI; 3245 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI && 3246 PBI->isConditional() && PBI->getCondition() == BI->getCondition() && 3247 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3248 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3249 NewPN->addIncoming( 3250 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue), 3251 P); 3252 } else { 3253 NewPN->addIncoming(BI->getCondition(), P); 3254 } 3255 } 3256 3257 BI->setCondition(NewPN); 3258 return true; 3259 } 3260 } 3261 3262 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition())) 3263 if (CE->canTrap()) 3264 return false; 3265 3266 // If both branches are conditional and both contain stores to the same 3267 // address, remove the stores from the conditionals and create a conditional 3268 // merged store at the end. 3269 if (MergeCondStores && mergeConditionalStores(PBI, BI, DL)) 3270 return true; 3271 3272 // If this is a conditional branch in an empty block, and if any 3273 // predecessors are a conditional branch to one of our destinations, 3274 // fold the conditions into logical ops and one cond br. 3275 3276 // Ignore dbg intrinsics. 3277 if (&*BB->instructionsWithoutDebug().begin() != BI) 3278 return false; 3279 3280 int PBIOp, BIOp; 3281 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3282 PBIOp = 0; 3283 BIOp = 0; 3284 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3285 PBIOp = 0; 3286 BIOp = 1; 3287 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3288 PBIOp = 1; 3289 BIOp = 0; 3290 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3291 PBIOp = 1; 3292 BIOp = 1; 3293 } else { 3294 return false; 3295 } 3296 3297 // Check to make sure that the other destination of this branch 3298 // isn't BB itself. If so, this is an infinite loop that will 3299 // keep getting unwound. 3300 if (PBI->getSuccessor(PBIOp) == BB) 3301 return false; 3302 3303 // Do not perform this transformation if it would require 3304 // insertion of a large number of select instructions. For targets 3305 // without predication/cmovs, this is a big pessimization. 3306 3307 // Also do not perform this transformation if any phi node in the common 3308 // destination block can trap when reached by BB or PBB (PR17073). In that 3309 // case, it would be unsafe to hoist the operation into a select instruction. 3310 3311 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 3312 unsigned NumPhis = 0; 3313 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II); 3314 ++II, ++NumPhis) { 3315 if (NumPhis > 2) // Disable this xform. 3316 return false; 3317 3318 PHINode *PN = cast<PHINode>(II); 3319 Value *BIV = PN->getIncomingValueForBlock(BB); 3320 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) 3321 if (CE->canTrap()) 3322 return false; 3323 3324 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 3325 Value *PBIV = PN->getIncomingValue(PBBIdx); 3326 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) 3327 if (CE->canTrap()) 3328 return false; 3329 } 3330 3331 // Finally, if everything is ok, fold the branches to logical ops. 3332 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 3333 3334 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 3335 << "AND: " << *BI->getParent()); 3336 3337 // If OtherDest *is* BB, then BB is a basic block with a single conditional 3338 // branch in it, where one edge (OtherDest) goes back to itself but the other 3339 // exits. We don't *know* that the program avoids the infinite loop 3340 // (even though that seems likely). If we do this xform naively, we'll end up 3341 // recursively unpeeling the loop. Since we know that (after the xform is 3342 // done) that the block *is* infinite if reached, we just make it an obviously 3343 // infinite loop with no cond branch. 3344 if (OtherDest == BB) { 3345 // Insert it at the end of the function, because it's either code, 3346 // or it won't matter if it's hot. :) 3347 BasicBlock *InfLoopBlock = 3348 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent()); 3349 BranchInst::Create(InfLoopBlock, InfLoopBlock); 3350 OtherDest = InfLoopBlock; 3351 } 3352 3353 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3354 3355 // BI may have other predecessors. Because of this, we leave 3356 // it alone, but modify PBI. 3357 3358 // Make sure we get to CommonDest on True&True directions. 3359 Value *PBICond = PBI->getCondition(); 3360 IRBuilder<NoFolder> Builder(PBI); 3361 if (PBIOp) 3362 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not"); 3363 3364 Value *BICond = BI->getCondition(); 3365 if (BIOp) 3366 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not"); 3367 3368 // Merge the conditions. 3369 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); 3370 3371 // Modify PBI to branch on the new condition to the new dests. 3372 PBI->setCondition(Cond); 3373 PBI->setSuccessor(0, CommonDest); 3374 PBI->setSuccessor(1, OtherDest); 3375 3376 // Update branch weight for PBI. 3377 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3378 uint64_t PredCommon, PredOther, SuccCommon, SuccOther; 3379 bool HasWeights = 3380 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3381 SuccTrueWeight, SuccFalseWeight); 3382 if (HasWeights) { 3383 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3384 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3385 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3386 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3387 // The weight to CommonDest should be PredCommon * SuccTotal + 3388 // PredOther * SuccCommon. 3389 // The weight to OtherDest should be PredOther * SuccOther. 3390 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + 3391 PredOther * SuccCommon, 3392 PredOther * SuccOther}; 3393 // Halve the weights if any of them cannot fit in an uint32_t 3394 FitWeights(NewWeights); 3395 3396 setBranchWeights(PBI, NewWeights[0], NewWeights[1]); 3397 } 3398 3399 // OtherDest may have phi nodes. If so, add an entry from PBI's 3400 // block that are identical to the entries for BI's block. 3401 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 3402 3403 // We know that the CommonDest already had an edge from PBI to 3404 // it. If it has PHIs though, the PHIs may have different 3405 // entries for BB and PBI's BB. If so, insert a select to make 3406 // them agree. 3407 for (PHINode &PN : CommonDest->phis()) { 3408 Value *BIV = PN.getIncomingValueForBlock(BB); 3409 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent()); 3410 Value *PBIV = PN.getIncomingValue(PBBIdx); 3411 if (BIV != PBIV) { 3412 // Insert a select in PBI to pick the right value. 3413 SelectInst *NV = cast<SelectInst>( 3414 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux")); 3415 PN.setIncomingValue(PBBIdx, NV); 3416 // Although the select has the same condition as PBI, the original branch 3417 // weights for PBI do not apply to the new select because the select's 3418 // 'logical' edges are incoming edges of the phi that is eliminated, not 3419 // the outgoing edges of PBI. 3420 if (HasWeights) { 3421 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3422 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3423 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3424 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3425 // The weight to PredCommonDest should be PredCommon * SuccTotal. 3426 // The weight to PredOtherDest should be PredOther * SuccCommon. 3427 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther), 3428 PredOther * SuccCommon}; 3429 3430 FitWeights(NewWeights); 3431 3432 setBranchWeights(NV, NewWeights[0], NewWeights[1]); 3433 } 3434 } 3435 } 3436 3437 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 3438 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3439 3440 // This basic block is probably dead. We know it has at least 3441 // one fewer predecessor. 3442 return true; 3443 } 3444 3445 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is 3446 // true or to FalseBB if Cond is false. 3447 // Takes care of updating the successors and removing the old terminator. 3448 // Also makes sure not to introduce new successors by assuming that edges to 3449 // non-successor TrueBBs and FalseBBs aren't reachable. 3450 static bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond, 3451 BasicBlock *TrueBB, BasicBlock *FalseBB, 3452 uint32_t TrueWeight, 3453 uint32_t FalseWeight) { 3454 // Remove any superfluous successor edges from the CFG. 3455 // First, figure out which successors to preserve. 3456 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 3457 // successor. 3458 BasicBlock *KeepEdge1 = TrueBB; 3459 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; 3460 3461 // Then remove the rest. 3462 for (BasicBlock *Succ : successors(OldTerm)) { 3463 // Make sure only to keep exactly one copy of each edge. 3464 if (Succ == KeepEdge1) 3465 KeepEdge1 = nullptr; 3466 else if (Succ == KeepEdge2) 3467 KeepEdge2 = nullptr; 3468 else 3469 Succ->removePredecessor(OldTerm->getParent(), 3470 /*KeepOneInputPHIs=*/true); 3471 } 3472 3473 IRBuilder<> Builder(OldTerm); 3474 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 3475 3476 // Insert an appropriate new terminator. 3477 if (!KeepEdge1 && !KeepEdge2) { 3478 if (TrueBB == FalseBB) 3479 // We were only looking for one successor, and it was present. 3480 // Create an unconditional branch to it. 3481 Builder.CreateBr(TrueBB); 3482 else { 3483 // We found both of the successors we were looking for. 3484 // Create a conditional branch sharing the condition of the select. 3485 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 3486 if (TrueWeight != FalseWeight) 3487 setBranchWeights(NewBI, TrueWeight, FalseWeight); 3488 } 3489 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 3490 // Neither of the selected blocks were successors, so this 3491 // terminator must be unreachable. 3492 new UnreachableInst(OldTerm->getContext(), OldTerm); 3493 } else { 3494 // One of the selected values was a successor, but the other wasn't. 3495 // Insert an unconditional branch to the one that was found; 3496 // the edge to the one that wasn't must be unreachable. 3497 if (!KeepEdge1) 3498 // Only TrueBB was found. 3499 Builder.CreateBr(TrueBB); 3500 else 3501 // Only FalseBB was found. 3502 Builder.CreateBr(FalseBB); 3503 } 3504 3505 EraseTerminatorAndDCECond(OldTerm); 3506 return true; 3507 } 3508 3509 // Replaces 3510 // (switch (select cond, X, Y)) on constant X, Y 3511 // with a branch - conditional if X and Y lead to distinct BBs, 3512 // unconditional otherwise. 3513 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) { 3514 // Check for constant integer values in the select. 3515 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 3516 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 3517 if (!TrueVal || !FalseVal) 3518 return false; 3519 3520 // Find the relevant condition and destinations. 3521 Value *Condition = Select->getCondition(); 3522 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor(); 3523 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor(); 3524 3525 // Get weight for TrueBB and FalseBB. 3526 uint32_t TrueWeight = 0, FalseWeight = 0; 3527 SmallVector<uint64_t, 8> Weights; 3528 bool HasWeights = HasBranchWeights(SI); 3529 if (HasWeights) { 3530 GetBranchWeights(SI, Weights); 3531 if (Weights.size() == 1 + SI->getNumCases()) { 3532 TrueWeight = 3533 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()]; 3534 FalseWeight = 3535 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()]; 3536 } 3537 } 3538 3539 // Perform the actual simplification. 3540 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight, 3541 FalseWeight); 3542 } 3543 3544 // Replaces 3545 // (indirectbr (select cond, blockaddress(@fn, BlockA), 3546 // blockaddress(@fn, BlockB))) 3547 // with 3548 // (br cond, BlockA, BlockB). 3549 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) { 3550 // Check that both operands of the select are block addresses. 3551 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 3552 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 3553 if (!TBA || !FBA) 3554 return false; 3555 3556 // Extract the actual blocks. 3557 BasicBlock *TrueBB = TBA->getBasicBlock(); 3558 BasicBlock *FalseBB = FBA->getBasicBlock(); 3559 3560 // Perform the actual simplification. 3561 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0, 3562 0); 3563 } 3564 3565 /// This is called when we find an icmp instruction 3566 /// (a seteq/setne with a constant) as the only instruction in a 3567 /// block that ends with an uncond branch. We are looking for a very specific 3568 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 3569 /// this case, we merge the first two "or's of icmp" into a switch, but then the 3570 /// default value goes to an uncond block with a seteq in it, we get something 3571 /// like: 3572 /// 3573 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 3574 /// DEFAULT: 3575 /// %tmp = icmp eq i8 %A, 92 3576 /// br label %end 3577 /// end: 3578 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 3579 /// 3580 /// We prefer to split the edge to 'end' so that there is a true/false entry to 3581 /// the PHI, merging the third icmp into the switch. 3582 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( 3583 ICmpInst *ICI, IRBuilder<> &Builder) { 3584 BasicBlock *BB = ICI->getParent(); 3585 3586 // If the block has any PHIs in it or the icmp has multiple uses, it is too 3587 // complex. 3588 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) 3589 return false; 3590 3591 Value *V = ICI->getOperand(0); 3592 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 3593 3594 // The pattern we're looking for is where our only predecessor is a switch on 3595 // 'V' and this block is the default case for the switch. In this case we can 3596 // fold the compared value into the switch to simplify things. 3597 BasicBlock *Pred = BB->getSinglePredecessor(); 3598 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) 3599 return false; 3600 3601 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 3602 if (SI->getCondition() != V) 3603 return false; 3604 3605 // If BB is reachable on a non-default case, then we simply know the value of 3606 // V in this block. Substitute it and constant fold the icmp instruction 3607 // away. 3608 if (SI->getDefaultDest() != BB) { 3609 ConstantInt *VVal = SI->findCaseDest(BB); 3610 assert(VVal && "Should have a unique destination value"); 3611 ICI->setOperand(0, VVal); 3612 3613 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) { 3614 ICI->replaceAllUsesWith(V); 3615 ICI->eraseFromParent(); 3616 } 3617 // BB is now empty, so it is likely to simplify away. 3618 return requestResimplify(); 3619 } 3620 3621 // Ok, the block is reachable from the default dest. If the constant we're 3622 // comparing exists in one of the other edges, then we can constant fold ICI 3623 // and zap it. 3624 if (SI->findCaseValue(Cst) != SI->case_default()) { 3625 Value *V; 3626 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3627 V = ConstantInt::getFalse(BB->getContext()); 3628 else 3629 V = ConstantInt::getTrue(BB->getContext()); 3630 3631 ICI->replaceAllUsesWith(V); 3632 ICI->eraseFromParent(); 3633 // BB is now empty, so it is likely to simplify away. 3634 return requestResimplify(); 3635 } 3636 3637 // The use of the icmp has to be in the 'end' block, by the only PHI node in 3638 // the block. 3639 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 3640 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); 3641 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || 3642 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 3643 return false; 3644 3645 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 3646 // true in the PHI. 3647 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 3648 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 3649 3650 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3651 std::swap(DefaultCst, NewCst); 3652 3653 // Replace ICI (which is used by the PHI for the default value) with true or 3654 // false depending on if it is EQ or NE. 3655 ICI->replaceAllUsesWith(DefaultCst); 3656 ICI->eraseFromParent(); 3657 3658 // Okay, the switch goes to this block on a default value. Add an edge from 3659 // the switch to the merge point on the compared value. 3660 BasicBlock *NewBB = 3661 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB); 3662 { 3663 SwitchInstProfUpdateWrapper SIW(*SI); 3664 auto W0 = SIW.getSuccessorWeight(0); 3665 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW; 3666 if (W0) { 3667 NewW = ((uint64_t(*W0) + 1) >> 1); 3668 SIW.setSuccessorWeight(0, *NewW); 3669 } 3670 SIW.addCase(Cst, NewBB, NewW); 3671 } 3672 3673 // NewBB branches to the phi block, add the uncond branch and the phi entry. 3674 Builder.SetInsertPoint(NewBB); 3675 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 3676 Builder.CreateBr(SuccBlock); 3677 PHIUse->addIncoming(NewCst, NewBB); 3678 return true; 3679 } 3680 3681 /// The specified branch is a conditional branch. 3682 /// Check to see if it is branching on an or/and chain of icmp instructions, and 3683 /// fold it into a switch instruction if so. 3684 static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder, 3685 const DataLayout &DL) { 3686 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 3687 if (!Cond) 3688 return false; 3689 3690 // Change br (X == 0 | X == 1), T, F into a switch instruction. 3691 // If this is a bunch of seteq's or'd together, or if it's a bunch of 3692 // 'setne's and'ed together, collect them. 3693 3694 // Try to gather values from a chain of and/or to be turned into a switch 3695 ConstantComparesGatherer ConstantCompare(Cond, DL); 3696 // Unpack the result 3697 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals; 3698 Value *CompVal = ConstantCompare.CompValue; 3699 unsigned UsedICmps = ConstantCompare.UsedICmps; 3700 Value *ExtraCase = ConstantCompare.Extra; 3701 3702 // If we didn't have a multiply compared value, fail. 3703 if (!CompVal) 3704 return false; 3705 3706 // Avoid turning single icmps into a switch. 3707 if (UsedICmps <= 1) 3708 return false; 3709 3710 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or); 3711 3712 // There might be duplicate constants in the list, which the switch 3713 // instruction can't handle, remove them now. 3714 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 3715 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 3716 3717 // If Extra was used, we require at least two switch values to do the 3718 // transformation. A switch with one value is just a conditional branch. 3719 if (ExtraCase && Values.size() < 2) 3720 return false; 3721 3722 // TODO: Preserve branch weight metadata, similarly to how 3723 // FoldValueComparisonIntoPredecessors preserves it. 3724 3725 // Figure out which block is which destination. 3726 BasicBlock *DefaultBB = BI->getSuccessor(1); 3727 BasicBlock *EdgeBB = BI->getSuccessor(0); 3728 if (!TrueWhenEqual) 3729 std::swap(DefaultBB, EdgeBB); 3730 3731 BasicBlock *BB = BI->getParent(); 3732 3733 // MSAN does not like undefs as branch condition which can be introduced 3734 // with "explicit branch". 3735 if (ExtraCase && BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory)) 3736 return false; 3737 3738 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 3739 << " cases into SWITCH. BB is:\n" 3740 << *BB); 3741 3742 // If there are any extra values that couldn't be folded into the switch 3743 // then we evaluate them with an explicit branch first. Split the block 3744 // right before the condbr to handle it. 3745 if (ExtraCase) { 3746 BasicBlock *NewBB = 3747 BB->splitBasicBlock(BI->getIterator(), "switch.early.test"); 3748 // Remove the uncond branch added to the old block. 3749 Instruction *OldTI = BB->getTerminator(); 3750 Builder.SetInsertPoint(OldTI); 3751 3752 if (TrueWhenEqual) 3753 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 3754 else 3755 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 3756 3757 OldTI->eraseFromParent(); 3758 3759 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 3760 // for the edge we just added. 3761 AddPredecessorToBlock(EdgeBB, BB, NewBB); 3762 3763 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 3764 << "\nEXTRABB = " << *BB); 3765 BB = NewBB; 3766 } 3767 3768 Builder.SetInsertPoint(BI); 3769 // Convert pointer to int before we switch. 3770 if (CompVal->getType()->isPointerTy()) { 3771 CompVal = Builder.CreatePtrToInt( 3772 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); 3773 } 3774 3775 // Create the new switch instruction now. 3776 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 3777 3778 // Add all of the 'cases' to the switch instruction. 3779 for (unsigned i = 0, e = Values.size(); i != e; ++i) 3780 New->addCase(Values[i], EdgeBB); 3781 3782 // We added edges from PI to the EdgeBB. As such, if there were any 3783 // PHI nodes in EdgeBB, they need entries to be added corresponding to 3784 // the number of edges added. 3785 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) { 3786 PHINode *PN = cast<PHINode>(BBI); 3787 Value *InVal = PN->getIncomingValueForBlock(BB); 3788 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i) 3789 PN->addIncoming(InVal, BB); 3790 } 3791 3792 // Erase the old branch instruction. 3793 EraseTerminatorAndDCECond(BI); 3794 3795 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 3796 return true; 3797 } 3798 3799 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 3800 if (isa<PHINode>(RI->getValue())) 3801 return SimplifyCommonResume(RI); 3802 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) && 3803 RI->getValue() == RI->getParent()->getFirstNonPHI()) 3804 // The resume must unwind the exception that caused control to branch here. 3805 return SimplifySingleResume(RI); 3806 3807 return false; 3808 } 3809 3810 // Simplify resume that is shared by several landing pads (phi of landing pad). 3811 bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) { 3812 BasicBlock *BB = RI->getParent(); 3813 3814 // Check that there are no other instructions except for debug intrinsics 3815 // between the phi of landing pads (RI->getValue()) and resume instruction. 3816 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(), 3817 E = RI->getIterator(); 3818 while (++I != E) 3819 if (!isa<DbgInfoIntrinsic>(I)) 3820 return false; 3821 3822 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks; 3823 auto *PhiLPInst = cast<PHINode>(RI->getValue()); 3824 3825 // Check incoming blocks to see if any of them are trivial. 3826 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End; 3827 Idx++) { 3828 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx); 3829 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx); 3830 3831 // If the block has other successors, we can not delete it because 3832 // it has other dependents. 3833 if (IncomingBB->getUniqueSuccessor() != BB) 3834 continue; 3835 3836 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI()); 3837 // Not the landing pad that caused the control to branch here. 3838 if (IncomingValue != LandingPad) 3839 continue; 3840 3841 bool isTrivial = true; 3842 3843 I = IncomingBB->getFirstNonPHI()->getIterator(); 3844 E = IncomingBB->getTerminator()->getIterator(); 3845 while (++I != E) 3846 if (!isa<DbgInfoIntrinsic>(I)) { 3847 isTrivial = false; 3848 break; 3849 } 3850 3851 if (isTrivial) 3852 TrivialUnwindBlocks.insert(IncomingBB); 3853 } 3854 3855 // If no trivial unwind blocks, don't do any simplifications. 3856 if (TrivialUnwindBlocks.empty()) 3857 return false; 3858 3859 // Turn all invokes that unwind here into calls. 3860 for (auto *TrivialBB : TrivialUnwindBlocks) { 3861 // Blocks that will be simplified should be removed from the phi node. 3862 // Note there could be multiple edges to the resume block, and we need 3863 // to remove them all. 3864 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1) 3865 BB->removePredecessor(TrivialBB, true); 3866 3867 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB); 3868 PI != PE;) { 3869 BasicBlock *Pred = *PI++; 3870 removeUnwindEdge(Pred); 3871 } 3872 3873 // In each SimplifyCFG run, only the current processed block can be erased. 3874 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead 3875 // of erasing TrivialBB, we only remove the branch to the common resume 3876 // block so that we can later erase the resume block since it has no 3877 // predecessors. 3878 TrivialBB->getTerminator()->eraseFromParent(); 3879 new UnreachableInst(RI->getContext(), TrivialBB); 3880 } 3881 3882 // Delete the resume block if all its predecessors have been removed. 3883 if (pred_empty(BB)) 3884 BB->eraseFromParent(); 3885 3886 return !TrivialUnwindBlocks.empty(); 3887 } 3888 3889 // Simplify resume that is only used by a single (non-phi) landing pad. 3890 bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) { 3891 BasicBlock *BB = RI->getParent(); 3892 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()); 3893 assert(RI->getValue() == LPInst && 3894 "Resume must unwind the exception that caused control to here"); 3895 3896 // Check that there are no other instructions except for debug intrinsics. 3897 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator(); 3898 while (++I != E) 3899 if (!isa<DbgInfoIntrinsic>(I)) 3900 return false; 3901 3902 // Turn all invokes that unwind here into calls and delete the basic block. 3903 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 3904 BasicBlock *Pred = *PI++; 3905 removeUnwindEdge(Pred); 3906 } 3907 3908 // The landingpad is now unreachable. Zap it. 3909 if (LoopHeaders) 3910 LoopHeaders->erase(BB); 3911 BB->eraseFromParent(); 3912 return true; 3913 } 3914 3915 static bool removeEmptyCleanup(CleanupReturnInst *RI) { 3916 // If this is a trivial cleanup pad that executes no instructions, it can be 3917 // eliminated. If the cleanup pad continues to the caller, any predecessor 3918 // that is an EH pad will be updated to continue to the caller and any 3919 // predecessor that terminates with an invoke instruction will have its invoke 3920 // instruction converted to a call instruction. If the cleanup pad being 3921 // simplified does not continue to the caller, each predecessor will be 3922 // updated to continue to the unwind destination of the cleanup pad being 3923 // simplified. 3924 BasicBlock *BB = RI->getParent(); 3925 CleanupPadInst *CPInst = RI->getCleanupPad(); 3926 if (CPInst->getParent() != BB) 3927 // This isn't an empty cleanup. 3928 return false; 3929 3930 // We cannot kill the pad if it has multiple uses. This typically arises 3931 // from unreachable basic blocks. 3932 if (!CPInst->hasOneUse()) 3933 return false; 3934 3935 // Check that there are no other instructions except for benign intrinsics. 3936 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator(); 3937 while (++I != E) { 3938 auto *II = dyn_cast<IntrinsicInst>(I); 3939 if (!II) 3940 return false; 3941 3942 Intrinsic::ID IntrinsicID = II->getIntrinsicID(); 3943 switch (IntrinsicID) { 3944 case Intrinsic::dbg_declare: 3945 case Intrinsic::dbg_value: 3946 case Intrinsic::dbg_label: 3947 case Intrinsic::lifetime_end: 3948 break; 3949 default: 3950 return false; 3951 } 3952 } 3953 3954 // If the cleanup return we are simplifying unwinds to the caller, this will 3955 // set UnwindDest to nullptr. 3956 BasicBlock *UnwindDest = RI->getUnwindDest(); 3957 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr; 3958 3959 // We're about to remove BB from the control flow. Before we do, sink any 3960 // PHINodes into the unwind destination. Doing this before changing the 3961 // control flow avoids some potentially slow checks, since we can currently 3962 // be certain that UnwindDest and BB have no common predecessors (since they 3963 // are both EH pads). 3964 if (UnwindDest) { 3965 // First, go through the PHI nodes in UnwindDest and update any nodes that 3966 // reference the block we are removing 3967 for (BasicBlock::iterator I = UnwindDest->begin(), 3968 IE = DestEHPad->getIterator(); 3969 I != IE; ++I) { 3970 PHINode *DestPN = cast<PHINode>(I); 3971 3972 int Idx = DestPN->getBasicBlockIndex(BB); 3973 // Since BB unwinds to UnwindDest, it has to be in the PHI node. 3974 assert(Idx != -1); 3975 // This PHI node has an incoming value that corresponds to a control 3976 // path through the cleanup pad we are removing. If the incoming 3977 // value is in the cleanup pad, it must be a PHINode (because we 3978 // verified above that the block is otherwise empty). Otherwise, the 3979 // value is either a constant or a value that dominates the cleanup 3980 // pad being removed. 3981 // 3982 // Because BB and UnwindDest are both EH pads, all of their 3983 // predecessors must unwind to these blocks, and since no instruction 3984 // can have multiple unwind destinations, there will be no overlap in 3985 // incoming blocks between SrcPN and DestPN. 3986 Value *SrcVal = DestPN->getIncomingValue(Idx); 3987 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); 3988 3989 // Remove the entry for the block we are deleting. 3990 DestPN->removeIncomingValue(Idx, false); 3991 3992 if (SrcPN && SrcPN->getParent() == BB) { 3993 // If the incoming value was a PHI node in the cleanup pad we are 3994 // removing, we need to merge that PHI node's incoming values into 3995 // DestPN. 3996 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues(); 3997 SrcIdx != SrcE; ++SrcIdx) { 3998 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx), 3999 SrcPN->getIncomingBlock(SrcIdx)); 4000 } 4001 } else { 4002 // Otherwise, the incoming value came from above BB and 4003 // so we can just reuse it. We must associate all of BB's 4004 // predecessors with this value. 4005 for (auto *pred : predecessors(BB)) { 4006 DestPN->addIncoming(SrcVal, pred); 4007 } 4008 } 4009 } 4010 4011 // Sink any remaining PHI nodes directly into UnwindDest. 4012 Instruction *InsertPt = DestEHPad; 4013 for (BasicBlock::iterator I = BB->begin(), 4014 IE = BB->getFirstNonPHI()->getIterator(); 4015 I != IE;) { 4016 // The iterator must be incremented here because the instructions are 4017 // being moved to another block. 4018 PHINode *PN = cast<PHINode>(I++); 4019 if (PN->use_empty()) 4020 // If the PHI node has no uses, just leave it. It will be erased 4021 // when we erase BB below. 4022 continue; 4023 4024 // Otherwise, sink this PHI node into UnwindDest. 4025 // Any predecessors to UnwindDest which are not already represented 4026 // must be back edges which inherit the value from the path through 4027 // BB. In this case, the PHI value must reference itself. 4028 for (auto *pred : predecessors(UnwindDest)) 4029 if (pred != BB) 4030 PN->addIncoming(PN, pred); 4031 PN->moveBefore(InsertPt); 4032 } 4033 } 4034 4035 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 4036 // The iterator must be updated here because we are removing this pred. 4037 BasicBlock *PredBB = *PI++; 4038 if (UnwindDest == nullptr) { 4039 removeUnwindEdge(PredBB); 4040 } else { 4041 Instruction *TI = PredBB->getTerminator(); 4042 TI->replaceUsesOfWith(BB, UnwindDest); 4043 } 4044 } 4045 4046 // The cleanup pad is now unreachable. Zap it. 4047 BB->eraseFromParent(); 4048 return true; 4049 } 4050 4051 // Try to merge two cleanuppads together. 4052 static bool mergeCleanupPad(CleanupReturnInst *RI) { 4053 // Skip any cleanuprets which unwind to caller, there is nothing to merge 4054 // with. 4055 BasicBlock *UnwindDest = RI->getUnwindDest(); 4056 if (!UnwindDest) 4057 return false; 4058 4059 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't 4060 // be safe to merge without code duplication. 4061 if (UnwindDest->getSinglePredecessor() != RI->getParent()) 4062 return false; 4063 4064 // Verify that our cleanuppad's unwind destination is another cleanuppad. 4065 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front()); 4066 if (!SuccessorCleanupPad) 4067 return false; 4068 4069 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad(); 4070 // Replace any uses of the successor cleanupad with the predecessor pad 4071 // The only cleanuppad uses should be this cleanupret, it's cleanupret and 4072 // funclet bundle operands. 4073 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad); 4074 // Remove the old cleanuppad. 4075 SuccessorCleanupPad->eraseFromParent(); 4076 // Now, we simply replace the cleanupret with a branch to the unwind 4077 // destination. 4078 BranchInst::Create(UnwindDest, RI->getParent()); 4079 RI->eraseFromParent(); 4080 4081 return true; 4082 } 4083 4084 bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) { 4085 // It is possible to transiantly have an undef cleanuppad operand because we 4086 // have deleted some, but not all, dead blocks. 4087 // Eventually, this block will be deleted. 4088 if (isa<UndefValue>(RI->getOperand(0))) 4089 return false; 4090 4091 if (mergeCleanupPad(RI)) 4092 return true; 4093 4094 if (removeEmptyCleanup(RI)) 4095 return true; 4096 4097 return false; 4098 } 4099 4100 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { 4101 BasicBlock *BB = RI->getParent(); 4102 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) 4103 return false; 4104 4105 // Find predecessors that end with branches. 4106 SmallVector<BasicBlock *, 8> UncondBranchPreds; 4107 SmallVector<BranchInst *, 8> CondBranchPreds; 4108 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 4109 BasicBlock *P = *PI; 4110 Instruction *PTI = P->getTerminator(); 4111 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { 4112 if (BI->isUnconditional()) 4113 UncondBranchPreds.push_back(P); 4114 else 4115 CondBranchPreds.push_back(BI); 4116 } 4117 } 4118 4119 // If we found some, do the transformation! 4120 if (!UncondBranchPreds.empty() && DupRet) { 4121 while (!UncondBranchPreds.empty()) { 4122 BasicBlock *Pred = UncondBranchPreds.pop_back_val(); 4123 LLVM_DEBUG(dbgs() << "FOLDING: " << *BB 4124 << "INTO UNCOND BRANCH PRED: " << *Pred); 4125 (void)FoldReturnIntoUncondBranch(RI, BB, Pred); 4126 } 4127 4128 // If we eliminated all predecessors of the block, delete the block now. 4129 if (pred_empty(BB)) { 4130 // We know there are no successors, so just nuke the block. 4131 if (LoopHeaders) 4132 LoopHeaders->erase(BB); 4133 BB->eraseFromParent(); 4134 } 4135 4136 return true; 4137 } 4138 4139 // Check out all of the conditional branches going to this return 4140 // instruction. If any of them just select between returns, change the 4141 // branch itself into a select/return pair. 4142 while (!CondBranchPreds.empty()) { 4143 BranchInst *BI = CondBranchPreds.pop_back_val(); 4144 4145 // Check to see if the non-BB successor is also a return block. 4146 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && 4147 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && 4148 SimplifyCondBranchToTwoReturns(BI, Builder)) 4149 return true; 4150 } 4151 return false; 4152 } 4153 4154 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) { 4155 BasicBlock *BB = UI->getParent(); 4156 4157 bool Changed = false; 4158 4159 // If there are any instructions immediately before the unreachable that can 4160 // be removed, do so. 4161 while (UI->getIterator() != BB->begin()) { 4162 BasicBlock::iterator BBI = UI->getIterator(); 4163 --BBI; 4164 // Do not delete instructions that can have side effects which might cause 4165 // the unreachable to not be reachable; specifically, calls and volatile 4166 // operations may have this effect. 4167 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) 4168 break; 4169 4170 if (BBI->mayHaveSideEffects()) { 4171 if (auto *SI = dyn_cast<StoreInst>(BBI)) { 4172 if (SI->isVolatile()) 4173 break; 4174 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) { 4175 if (LI->isVolatile()) 4176 break; 4177 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { 4178 if (RMWI->isVolatile()) 4179 break; 4180 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { 4181 if (CXI->isVolatile()) 4182 break; 4183 } else if (isa<CatchPadInst>(BBI)) { 4184 // A catchpad may invoke exception object constructors and such, which 4185 // in some languages can be arbitrary code, so be conservative by 4186 // default. 4187 // For CoreCLR, it just involves a type test, so can be removed. 4188 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) != 4189 EHPersonality::CoreCLR) 4190 break; 4191 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && 4192 !isa<LandingPadInst>(BBI)) { 4193 break; 4194 } 4195 // Note that deleting LandingPad's here is in fact okay, although it 4196 // involves a bit of subtle reasoning. If this inst is a LandingPad, 4197 // all the predecessors of this block will be the unwind edges of Invokes, 4198 // and we can therefore guarantee this block will be erased. 4199 } 4200 4201 // Delete this instruction (any uses are guaranteed to be dead) 4202 if (!BBI->use_empty()) 4203 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 4204 BBI->eraseFromParent(); 4205 Changed = true; 4206 } 4207 4208 // If the unreachable instruction is the first in the block, take a gander 4209 // at all of the predecessors of this instruction, and simplify them. 4210 if (&BB->front() != UI) 4211 return Changed; 4212 4213 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB)); 4214 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 4215 Instruction *TI = Preds[i]->getTerminator(); 4216 IRBuilder<> Builder(TI); 4217 if (auto *BI = dyn_cast<BranchInst>(TI)) { 4218 if (BI->isUnconditional()) { 4219 assert(BI->getSuccessor(0) == BB && "Incorrect CFG"); 4220 new UnreachableInst(TI->getContext(), TI); 4221 TI->eraseFromParent(); 4222 Changed = true; 4223 } else { 4224 Value* Cond = BI->getCondition(); 4225 if (BI->getSuccessor(0) == BB) { 4226 Builder.CreateAssumption(Builder.CreateNot(Cond)); 4227 Builder.CreateBr(BI->getSuccessor(1)); 4228 } else { 4229 assert(BI->getSuccessor(1) == BB && "Incorrect CFG"); 4230 Builder.CreateAssumption(Cond); 4231 Builder.CreateBr(BI->getSuccessor(0)); 4232 } 4233 EraseTerminatorAndDCECond(BI); 4234 Changed = true; 4235 } 4236 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { 4237 SwitchInstProfUpdateWrapper SU(*SI); 4238 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) { 4239 if (i->getCaseSuccessor() != BB) { 4240 ++i; 4241 continue; 4242 } 4243 BB->removePredecessor(SU->getParent()); 4244 i = SU.removeCase(i); 4245 e = SU->case_end(); 4246 Changed = true; 4247 } 4248 } else if (auto *II = dyn_cast<InvokeInst>(TI)) { 4249 if (II->getUnwindDest() == BB) { 4250 removeUnwindEdge(TI->getParent()); 4251 Changed = true; 4252 } 4253 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 4254 if (CSI->getUnwindDest() == BB) { 4255 removeUnwindEdge(TI->getParent()); 4256 Changed = true; 4257 continue; 4258 } 4259 4260 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(), 4261 E = CSI->handler_end(); 4262 I != E; ++I) { 4263 if (*I == BB) { 4264 CSI->removeHandler(I); 4265 --I; 4266 --E; 4267 Changed = true; 4268 } 4269 } 4270 if (CSI->getNumHandlers() == 0) { 4271 BasicBlock *CatchSwitchBB = CSI->getParent(); 4272 if (CSI->hasUnwindDest()) { 4273 // Redirect preds to the unwind dest 4274 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest()); 4275 } else { 4276 // Rewrite all preds to unwind to caller (or from invoke to call). 4277 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB)); 4278 for (BasicBlock *EHPred : EHPreds) 4279 removeUnwindEdge(EHPred); 4280 } 4281 // The catchswitch is no longer reachable. 4282 new UnreachableInst(CSI->getContext(), CSI); 4283 CSI->eraseFromParent(); 4284 Changed = true; 4285 } 4286 } else if (isa<CleanupReturnInst>(TI)) { 4287 new UnreachableInst(TI->getContext(), TI); 4288 TI->eraseFromParent(); 4289 Changed = true; 4290 } 4291 } 4292 4293 // If this block is now dead, remove it. 4294 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) { 4295 // We know there are no successors, so just nuke the block. 4296 if (LoopHeaders) 4297 LoopHeaders->erase(BB); 4298 BB->eraseFromParent(); 4299 return true; 4300 } 4301 4302 return Changed; 4303 } 4304 4305 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { 4306 assert(Cases.size() >= 1); 4307 4308 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 4309 for (size_t I = 1, E = Cases.size(); I != E; ++I) { 4310 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) 4311 return false; 4312 } 4313 return true; 4314 } 4315 4316 static void createUnreachableSwitchDefault(SwitchInst *Switch) { 4317 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); 4318 BasicBlock *NewDefaultBlock = 4319 SplitBlockPredecessors(Switch->getDefaultDest(), Switch->getParent(), ""); 4320 Switch->setDefaultDest(&*NewDefaultBlock); 4321 SplitBlock(&*NewDefaultBlock, &NewDefaultBlock->front()); 4322 auto *NewTerminator = NewDefaultBlock->getTerminator(); 4323 new UnreachableInst(Switch->getContext(), NewTerminator); 4324 EraseTerminatorAndDCECond(NewTerminator); 4325 } 4326 4327 /// Turn a switch with two reachable destinations into an integer range 4328 /// comparison and branch. 4329 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) { 4330 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 4331 4332 bool HasDefault = 4333 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4334 4335 // Partition the cases into two sets with different destinations. 4336 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; 4337 BasicBlock *DestB = nullptr; 4338 SmallVector<ConstantInt *, 16> CasesA; 4339 SmallVector<ConstantInt *, 16> CasesB; 4340 4341 for (auto Case : SI->cases()) { 4342 BasicBlock *Dest = Case.getCaseSuccessor(); 4343 if (!DestA) 4344 DestA = Dest; 4345 if (Dest == DestA) { 4346 CasesA.push_back(Case.getCaseValue()); 4347 continue; 4348 } 4349 if (!DestB) 4350 DestB = Dest; 4351 if (Dest == DestB) { 4352 CasesB.push_back(Case.getCaseValue()); 4353 continue; 4354 } 4355 return false; // More than two destinations. 4356 } 4357 4358 assert(DestA && DestB && 4359 "Single-destination switch should have been folded."); 4360 assert(DestA != DestB); 4361 assert(DestB != SI->getDefaultDest()); 4362 assert(!CasesB.empty() && "There must be non-default cases."); 4363 assert(!CasesA.empty() || HasDefault); 4364 4365 // Figure out if one of the sets of cases form a contiguous range. 4366 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; 4367 BasicBlock *ContiguousDest = nullptr; 4368 BasicBlock *OtherDest = nullptr; 4369 if (!CasesA.empty() && CasesAreContiguous(CasesA)) { 4370 ContiguousCases = &CasesA; 4371 ContiguousDest = DestA; 4372 OtherDest = DestB; 4373 } else if (CasesAreContiguous(CasesB)) { 4374 ContiguousCases = &CasesB; 4375 ContiguousDest = DestB; 4376 OtherDest = DestA; 4377 } else 4378 return false; 4379 4380 // Start building the compare and branch. 4381 4382 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); 4383 Constant *NumCases = 4384 ConstantInt::get(Offset->getType(), ContiguousCases->size()); 4385 4386 Value *Sub = SI->getCondition(); 4387 if (!Offset->isNullValue()) 4388 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); 4389 4390 Value *Cmp; 4391 // If NumCases overflowed, then all possible values jump to the successor. 4392 if (NumCases->isNullValue() && !ContiguousCases->empty()) 4393 Cmp = ConstantInt::getTrue(SI->getContext()); 4394 else 4395 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 4396 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); 4397 4398 // Update weight for the newly-created conditional branch. 4399 if (HasBranchWeights(SI)) { 4400 SmallVector<uint64_t, 8> Weights; 4401 GetBranchWeights(SI, Weights); 4402 if (Weights.size() == 1 + SI->getNumCases()) { 4403 uint64_t TrueWeight = 0; 4404 uint64_t FalseWeight = 0; 4405 for (size_t I = 0, E = Weights.size(); I != E; ++I) { 4406 if (SI->getSuccessor(I) == ContiguousDest) 4407 TrueWeight += Weights[I]; 4408 else 4409 FalseWeight += Weights[I]; 4410 } 4411 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { 4412 TrueWeight /= 2; 4413 FalseWeight /= 2; 4414 } 4415 setBranchWeights(NewBI, TrueWeight, FalseWeight); 4416 } 4417 } 4418 4419 // Prune obsolete incoming values off the successors' PHI nodes. 4420 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { 4421 unsigned PreviousEdges = ContiguousCases->size(); 4422 if (ContiguousDest == SI->getDefaultDest()) 4423 ++PreviousEdges; 4424 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4425 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4426 } 4427 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { 4428 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); 4429 if (OtherDest == SI->getDefaultDest()) 4430 ++PreviousEdges; 4431 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4432 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4433 } 4434 4435 // Clean up the default block - it may have phis or other instructions before 4436 // the unreachable terminator. 4437 if (!HasDefault) 4438 createUnreachableSwitchDefault(SI); 4439 4440 // Drop the switch. 4441 SI->eraseFromParent(); 4442 4443 return true; 4444 } 4445 4446 /// Compute masked bits for the condition of a switch 4447 /// and use it to remove dead cases. 4448 static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, 4449 const DataLayout &DL) { 4450 Value *Cond = SI->getCondition(); 4451 unsigned Bits = Cond->getType()->getIntegerBitWidth(); 4452 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI); 4453 4454 // We can also eliminate cases by determining that their values are outside of 4455 // the limited range of the condition based on how many significant (non-sign) 4456 // bits are in the condition value. 4457 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1; 4458 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits; 4459 4460 // Gather dead cases. 4461 SmallVector<ConstantInt *, 8> DeadCases; 4462 for (auto &Case : SI->cases()) { 4463 const APInt &CaseVal = Case.getCaseValue()->getValue(); 4464 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) || 4465 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) { 4466 DeadCases.push_back(Case.getCaseValue()); 4467 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal 4468 << " is dead.\n"); 4469 } 4470 } 4471 4472 // If we can prove that the cases must cover all possible values, the 4473 // default destination becomes dead and we can remove it. If we know some 4474 // of the bits in the value, we can use that to more precisely compute the 4475 // number of possible unique case values. 4476 bool HasDefault = 4477 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4478 const unsigned NumUnknownBits = 4479 Bits - (Known.Zero | Known.One).countPopulation(); 4480 assert(NumUnknownBits <= Bits); 4481 if (HasDefault && DeadCases.empty() && 4482 NumUnknownBits < 64 /* avoid overflow */ && 4483 SI->getNumCases() == (1ULL << NumUnknownBits)) { 4484 createUnreachableSwitchDefault(SI); 4485 return true; 4486 } 4487 4488 if (DeadCases.empty()) 4489 return false; 4490 4491 SwitchInstProfUpdateWrapper SIW(*SI); 4492 for (ConstantInt *DeadCase : DeadCases) { 4493 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase); 4494 assert(CaseI != SI->case_default() && 4495 "Case was not found. Probably mistake in DeadCases forming."); 4496 // Prune unused values from PHI nodes. 4497 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent()); 4498 SIW.removeCase(CaseI); 4499 } 4500 4501 return true; 4502 } 4503 4504 /// If BB would be eligible for simplification by 4505 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 4506 /// by an unconditional branch), look at the phi node for BB in the successor 4507 /// block and see if the incoming value is equal to CaseValue. If so, return 4508 /// the phi node, and set PhiIndex to BB's index in the phi node. 4509 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 4510 BasicBlock *BB, int *PhiIndex) { 4511 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 4512 return nullptr; // BB must be empty to be a candidate for simplification. 4513 if (!BB->getSinglePredecessor()) 4514 return nullptr; // BB must be dominated by the switch. 4515 4516 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 4517 if (!Branch || !Branch->isUnconditional()) 4518 return nullptr; // Terminator must be unconditional branch. 4519 4520 BasicBlock *Succ = Branch->getSuccessor(0); 4521 4522 for (PHINode &PHI : Succ->phis()) { 4523 int Idx = PHI.getBasicBlockIndex(BB); 4524 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 4525 4526 Value *InValue = PHI.getIncomingValue(Idx); 4527 if (InValue != CaseValue) 4528 continue; 4529 4530 *PhiIndex = Idx; 4531 return &PHI; 4532 } 4533 4534 return nullptr; 4535 } 4536 4537 /// Try to forward the condition of a switch instruction to a phi node 4538 /// dominated by the switch, if that would mean that some of the destination 4539 /// blocks of the switch can be folded away. Return true if a change is made. 4540 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 4541 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>; 4542 4543 ForwardingNodesMap ForwardingNodes; 4544 BasicBlock *SwitchBlock = SI->getParent(); 4545 bool Changed = false; 4546 for (auto &Case : SI->cases()) { 4547 ConstantInt *CaseValue = Case.getCaseValue(); 4548 BasicBlock *CaseDest = Case.getCaseSuccessor(); 4549 4550 // Replace phi operands in successor blocks that are using the constant case 4551 // value rather than the switch condition variable: 4552 // switchbb: 4553 // switch i32 %x, label %default [ 4554 // i32 17, label %succ 4555 // ... 4556 // succ: 4557 // %r = phi i32 ... [ 17, %switchbb ] ... 4558 // --> 4559 // %r = phi i32 ... [ %x, %switchbb ] ... 4560 4561 for (PHINode &Phi : CaseDest->phis()) { 4562 // This only works if there is exactly 1 incoming edge from the switch to 4563 // a phi. If there is >1, that means multiple cases of the switch map to 1 4564 // value in the phi, and that phi value is not the switch condition. Thus, 4565 // this transform would not make sense (the phi would be invalid because 4566 // a phi can't have different incoming values from the same block). 4567 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock); 4568 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue && 4569 count(Phi.blocks(), SwitchBlock) == 1) { 4570 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition()); 4571 Changed = true; 4572 } 4573 } 4574 4575 // Collect phi nodes that are indirectly using this switch's case constants. 4576 int PhiIdx; 4577 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx)) 4578 ForwardingNodes[Phi].push_back(PhiIdx); 4579 } 4580 4581 for (auto &ForwardingNode : ForwardingNodes) { 4582 PHINode *Phi = ForwardingNode.first; 4583 SmallVectorImpl<int> &Indexes = ForwardingNode.second; 4584 if (Indexes.size() < 2) 4585 continue; 4586 4587 for (int Index : Indexes) 4588 Phi->setIncomingValue(Index, SI->getCondition()); 4589 Changed = true; 4590 } 4591 4592 return Changed; 4593 } 4594 4595 /// Return true if the backend will be able to handle 4596 /// initializing an array of constants like C. 4597 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) { 4598 if (C->isThreadDependent()) 4599 return false; 4600 if (C->isDLLImportDependent()) 4601 return false; 4602 4603 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) && 4604 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) && 4605 !isa<UndefValue>(C) && !isa<ConstantExpr>(C)) 4606 return false; 4607 4608 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 4609 if (!CE->isGEPWithNoNotionalOverIndexing()) 4610 return false; 4611 if (!ValidLookupTableConstant(CE->getOperand(0), TTI)) 4612 return false; 4613 } 4614 4615 if (!TTI.shouldBuildLookupTablesForConstant(C)) 4616 return false; 4617 4618 return true; 4619 } 4620 4621 /// If V is a Constant, return it. Otherwise, try to look up 4622 /// its constant value in ConstantPool, returning 0 if it's not there. 4623 static Constant * 4624 LookupConstant(Value *V, 4625 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 4626 if (Constant *C = dyn_cast<Constant>(V)) 4627 return C; 4628 return ConstantPool.lookup(V); 4629 } 4630 4631 /// Try to fold instruction I into a constant. This works for 4632 /// simple instructions such as binary operations where both operands are 4633 /// constant or can be replaced by constants from the ConstantPool. Returns the 4634 /// resulting constant on success, 0 otherwise. 4635 static Constant * 4636 ConstantFold(Instruction *I, const DataLayout &DL, 4637 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 4638 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 4639 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 4640 if (!A) 4641 return nullptr; 4642 if (A->isAllOnesValue()) 4643 return LookupConstant(Select->getTrueValue(), ConstantPool); 4644 if (A->isNullValue()) 4645 return LookupConstant(Select->getFalseValue(), ConstantPool); 4646 return nullptr; 4647 } 4648 4649 SmallVector<Constant *, 4> COps; 4650 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { 4651 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) 4652 COps.push_back(A); 4653 else 4654 return nullptr; 4655 } 4656 4657 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 4658 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], 4659 COps[1], DL); 4660 } 4661 4662 return ConstantFoldInstOperands(I, COps, DL); 4663 } 4664 4665 /// Try to determine the resulting constant values in phi nodes 4666 /// at the common destination basic block, *CommonDest, for one of the case 4667 /// destionations CaseDest corresponding to value CaseVal (0 for the default 4668 /// case), of a switch instruction SI. 4669 static bool 4670 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, 4671 BasicBlock **CommonDest, 4672 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, 4673 const DataLayout &DL, const TargetTransformInfo &TTI) { 4674 // The block from which we enter the common destination. 4675 BasicBlock *Pred = SI->getParent(); 4676 4677 // If CaseDest is empty except for some side-effect free instructions through 4678 // which we can constant-propagate the CaseVal, continue to its successor. 4679 SmallDenseMap<Value *, Constant *> ConstantPool; 4680 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 4681 for (Instruction &I :CaseDest->instructionsWithoutDebug()) { 4682 if (I.isTerminator()) { 4683 // If the terminator is a simple branch, continue to the next block. 4684 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator()) 4685 return false; 4686 Pred = CaseDest; 4687 CaseDest = I.getSuccessor(0); 4688 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) { 4689 // Instruction is side-effect free and constant. 4690 4691 // If the instruction has uses outside this block or a phi node slot for 4692 // the block, it is not safe to bypass the instruction since it would then 4693 // no longer dominate all its uses. 4694 for (auto &Use : I.uses()) { 4695 User *User = Use.getUser(); 4696 if (Instruction *I = dyn_cast<Instruction>(User)) 4697 if (I->getParent() == CaseDest) 4698 continue; 4699 if (PHINode *Phi = dyn_cast<PHINode>(User)) 4700 if (Phi->getIncomingBlock(Use) == CaseDest) 4701 continue; 4702 return false; 4703 } 4704 4705 ConstantPool.insert(std::make_pair(&I, C)); 4706 } else { 4707 break; 4708 } 4709 } 4710 4711 // If we did not have a CommonDest before, use the current one. 4712 if (!*CommonDest) 4713 *CommonDest = CaseDest; 4714 // If the destination isn't the common one, abort. 4715 if (CaseDest != *CommonDest) 4716 return false; 4717 4718 // Get the values for this case from phi nodes in the destination block. 4719 for (PHINode &PHI : (*CommonDest)->phis()) { 4720 int Idx = PHI.getBasicBlockIndex(Pred); 4721 if (Idx == -1) 4722 continue; 4723 4724 Constant *ConstVal = 4725 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool); 4726 if (!ConstVal) 4727 return false; 4728 4729 // Be conservative about which kinds of constants we support. 4730 if (!ValidLookupTableConstant(ConstVal, TTI)) 4731 return false; 4732 4733 Res.push_back(std::make_pair(&PHI, ConstVal)); 4734 } 4735 4736 return Res.size() > 0; 4737 } 4738 4739 // Helper function used to add CaseVal to the list of cases that generate 4740 // Result. Returns the updated number of cases that generate this result. 4741 static uintptr_t MapCaseToResult(ConstantInt *CaseVal, 4742 SwitchCaseResultVectorTy &UniqueResults, 4743 Constant *Result) { 4744 for (auto &I : UniqueResults) { 4745 if (I.first == Result) { 4746 I.second.push_back(CaseVal); 4747 return I.second.size(); 4748 } 4749 } 4750 UniqueResults.push_back( 4751 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal))); 4752 return 1; 4753 } 4754 4755 // Helper function that initializes a map containing 4756 // results for the PHI node of the common destination block for a switch 4757 // instruction. Returns false if multiple PHI nodes have been found or if 4758 // there is not a common destination block for the switch. 4759 static bool 4760 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, 4761 SwitchCaseResultVectorTy &UniqueResults, 4762 Constant *&DefaultResult, const DataLayout &DL, 4763 const TargetTransformInfo &TTI, 4764 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) { 4765 for (auto &I : SI->cases()) { 4766 ConstantInt *CaseVal = I.getCaseValue(); 4767 4768 // Resulting value at phi nodes for this case value. 4769 SwitchCaseResultsTy Results; 4770 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, 4771 DL, TTI)) 4772 return false; 4773 4774 // Only one value per case is permitted. 4775 if (Results.size() > 1) 4776 return false; 4777 4778 // Add the case->result mapping to UniqueResults. 4779 const uintptr_t NumCasesForResult = 4780 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); 4781 4782 // Early out if there are too many cases for this result. 4783 if (NumCasesForResult > MaxCasesPerResult) 4784 return false; 4785 4786 // Early out if there are too many unique results. 4787 if (UniqueResults.size() > MaxUniqueResults) 4788 return false; 4789 4790 // Check the PHI consistency. 4791 if (!PHI) 4792 PHI = Results[0].first; 4793 else if (PHI != Results[0].first) 4794 return false; 4795 } 4796 // Find the default result value. 4797 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; 4798 BasicBlock *DefaultDest = SI->getDefaultDest(); 4799 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, 4800 DL, TTI); 4801 // If the default value is not found abort unless the default destination 4802 // is unreachable. 4803 DefaultResult = 4804 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; 4805 if ((!DefaultResult && 4806 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) 4807 return false; 4808 4809 return true; 4810 } 4811 4812 // Helper function that checks if it is possible to transform a switch with only 4813 // two cases (or two cases + default) that produces a result into a select. 4814 // Example: 4815 // switch (a) { 4816 // case 10: %0 = icmp eq i32 %a, 10 4817 // return 10; %1 = select i1 %0, i32 10, i32 4 4818 // case 20: ----> %2 = icmp eq i32 %a, 20 4819 // return 2; %3 = select i1 %2, i32 2, i32 %1 4820 // default: 4821 // return 4; 4822 // } 4823 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, 4824 Constant *DefaultResult, Value *Condition, 4825 IRBuilder<> &Builder) { 4826 assert(ResultVector.size() == 2 && 4827 "We should have exactly two unique results at this point"); 4828 // If we are selecting between only two cases transform into a simple 4829 // select or a two-way select if default is possible. 4830 if (ResultVector[0].second.size() == 1 && 4831 ResultVector[1].second.size() == 1) { 4832 ConstantInt *const FirstCase = ResultVector[0].second[0]; 4833 ConstantInt *const SecondCase = ResultVector[1].second[0]; 4834 4835 bool DefaultCanTrigger = DefaultResult; 4836 Value *SelectValue = ResultVector[1].first; 4837 if (DefaultCanTrigger) { 4838 Value *const ValueCompare = 4839 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); 4840 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, 4841 DefaultResult, "switch.select"); 4842 } 4843 Value *const ValueCompare = 4844 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); 4845 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, 4846 SelectValue, "switch.select"); 4847 } 4848 4849 return nullptr; 4850 } 4851 4852 // Helper function to cleanup a switch instruction that has been converted into 4853 // a select, fixing up PHI nodes and basic blocks. 4854 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, 4855 Value *SelectValue, 4856 IRBuilder<> &Builder) { 4857 BasicBlock *SelectBB = SI->getParent(); 4858 while (PHI->getBasicBlockIndex(SelectBB) >= 0) 4859 PHI->removeIncomingValue(SelectBB); 4860 PHI->addIncoming(SelectValue, SelectBB); 4861 4862 Builder.CreateBr(PHI->getParent()); 4863 4864 // Remove the switch. 4865 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 4866 BasicBlock *Succ = SI->getSuccessor(i); 4867 4868 if (Succ == PHI->getParent()) 4869 continue; 4870 Succ->removePredecessor(SelectBB); 4871 } 4872 SI->eraseFromParent(); 4873 } 4874 4875 /// If the switch is only used to initialize one or more 4876 /// phi nodes in a common successor block with only two different 4877 /// constant values, replace the switch with select. 4878 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder, 4879 const DataLayout &DL, 4880 const TargetTransformInfo &TTI) { 4881 Value *const Cond = SI->getCondition(); 4882 PHINode *PHI = nullptr; 4883 BasicBlock *CommonDest = nullptr; 4884 Constant *DefaultResult; 4885 SwitchCaseResultVectorTy UniqueResults; 4886 // Collect all the cases that will deliver the same value from the switch. 4887 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, 4888 DL, TTI, 2, 1)) 4889 return false; 4890 // Selects choose between maximum two values. 4891 if (UniqueResults.size() != 2) 4892 return false; 4893 assert(PHI != nullptr && "PHI for value select not found"); 4894 4895 Builder.SetInsertPoint(SI); 4896 Value *SelectValue = 4897 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder); 4898 if (SelectValue) { 4899 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder); 4900 return true; 4901 } 4902 // The switch couldn't be converted into a select. 4903 return false; 4904 } 4905 4906 namespace { 4907 4908 /// This class represents a lookup table that can be used to replace a switch. 4909 class SwitchLookupTable { 4910 public: 4911 /// Create a lookup table to use as a switch replacement with the contents 4912 /// of Values, using DefaultValue to fill any holes in the table. 4913 SwitchLookupTable( 4914 Module &M, uint64_t TableSize, ConstantInt *Offset, 4915 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 4916 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName); 4917 4918 /// Build instructions with Builder to retrieve the value at 4919 /// the position given by Index in the lookup table. 4920 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 4921 4922 /// Return true if a table with TableSize elements of 4923 /// type ElementType would fit in a target-legal register. 4924 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, 4925 Type *ElementType); 4926 4927 private: 4928 // Depending on the contents of the table, it can be represented in 4929 // different ways. 4930 enum { 4931 // For tables where each element contains the same value, we just have to 4932 // store that single value and return it for each lookup. 4933 SingleValueKind, 4934 4935 // For tables where there is a linear relationship between table index 4936 // and values. We calculate the result with a simple multiplication 4937 // and addition instead of a table lookup. 4938 LinearMapKind, 4939 4940 // For small tables with integer elements, we can pack them into a bitmap 4941 // that fits into a target-legal register. Values are retrieved by 4942 // shift and mask operations. 4943 BitMapKind, 4944 4945 // The table is stored as an array of values. Values are retrieved by load 4946 // instructions from the table. 4947 ArrayKind 4948 } Kind; 4949 4950 // For SingleValueKind, this is the single value. 4951 Constant *SingleValue = nullptr; 4952 4953 // For BitMapKind, this is the bitmap. 4954 ConstantInt *BitMap = nullptr; 4955 IntegerType *BitMapElementTy = nullptr; 4956 4957 // For LinearMapKind, these are the constants used to derive the value. 4958 ConstantInt *LinearOffset = nullptr; 4959 ConstantInt *LinearMultiplier = nullptr; 4960 4961 // For ArrayKind, this is the array. 4962 GlobalVariable *Array = nullptr; 4963 }; 4964 4965 } // end anonymous namespace 4966 4967 SwitchLookupTable::SwitchLookupTable( 4968 Module &M, uint64_t TableSize, ConstantInt *Offset, 4969 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 4970 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) { 4971 assert(Values.size() && "Can't build lookup table without values!"); 4972 assert(TableSize >= Values.size() && "Can't fit values in table!"); 4973 4974 // If all values in the table are equal, this is that value. 4975 SingleValue = Values.begin()->second; 4976 4977 Type *ValueType = Values.begin()->second->getType(); 4978 4979 // Build up the table contents. 4980 SmallVector<Constant *, 64> TableContents(TableSize); 4981 for (size_t I = 0, E = Values.size(); I != E; ++I) { 4982 ConstantInt *CaseVal = Values[I].first; 4983 Constant *CaseRes = Values[I].second; 4984 assert(CaseRes->getType() == ValueType); 4985 4986 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue(); 4987 TableContents[Idx] = CaseRes; 4988 4989 if (CaseRes != SingleValue) 4990 SingleValue = nullptr; 4991 } 4992 4993 // Fill in any holes in the table with the default result. 4994 if (Values.size() < TableSize) { 4995 assert(DefaultValue && 4996 "Need a default value to fill the lookup table holes."); 4997 assert(DefaultValue->getType() == ValueType); 4998 for (uint64_t I = 0; I < TableSize; ++I) { 4999 if (!TableContents[I]) 5000 TableContents[I] = DefaultValue; 5001 } 5002 5003 if (DefaultValue != SingleValue) 5004 SingleValue = nullptr; 5005 } 5006 5007 // If each element in the table contains the same value, we only need to store 5008 // that single value. 5009 if (SingleValue) { 5010 Kind = SingleValueKind; 5011 return; 5012 } 5013 5014 // Check if we can derive the value with a linear transformation from the 5015 // table index. 5016 if (isa<IntegerType>(ValueType)) { 5017 bool LinearMappingPossible = true; 5018 APInt PrevVal; 5019 APInt DistToPrev; 5020 assert(TableSize >= 2 && "Should be a SingleValue table."); 5021 // Check if there is the same distance between two consecutive values. 5022 for (uint64_t I = 0; I < TableSize; ++I) { 5023 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); 5024 if (!ConstVal) { 5025 // This is an undef. We could deal with it, but undefs in lookup tables 5026 // are very seldom. It's probably not worth the additional complexity. 5027 LinearMappingPossible = false; 5028 break; 5029 } 5030 const APInt &Val = ConstVal->getValue(); 5031 if (I != 0) { 5032 APInt Dist = Val - PrevVal; 5033 if (I == 1) { 5034 DistToPrev = Dist; 5035 } else if (Dist != DistToPrev) { 5036 LinearMappingPossible = false; 5037 break; 5038 } 5039 } 5040 PrevVal = Val; 5041 } 5042 if (LinearMappingPossible) { 5043 LinearOffset = cast<ConstantInt>(TableContents[0]); 5044 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); 5045 Kind = LinearMapKind; 5046 ++NumLinearMaps; 5047 return; 5048 } 5049 } 5050 5051 // If the type is integer and the table fits in a register, build a bitmap. 5052 if (WouldFitInRegister(DL, TableSize, ValueType)) { 5053 IntegerType *IT = cast<IntegerType>(ValueType); 5054 APInt TableInt(TableSize * IT->getBitWidth(), 0); 5055 for (uint64_t I = TableSize; I > 0; --I) { 5056 TableInt <<= IT->getBitWidth(); 5057 // Insert values into the bitmap. Undef values are set to zero. 5058 if (!isa<UndefValue>(TableContents[I - 1])) { 5059 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 5060 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 5061 } 5062 } 5063 BitMap = ConstantInt::get(M.getContext(), TableInt); 5064 BitMapElementTy = IT; 5065 Kind = BitMapKind; 5066 ++NumBitMaps; 5067 return; 5068 } 5069 5070 // Store the table in an array. 5071 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); 5072 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 5073 5074 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true, 5075 GlobalVariable::PrivateLinkage, Initializer, 5076 "switch.table." + FuncName); 5077 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 5078 // Set the alignment to that of an array items. We will be only loading one 5079 // value out of it. 5080 Array->setAlignment(DL.getPrefTypeAlignment(ValueType)); 5081 Kind = ArrayKind; 5082 } 5083 5084 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 5085 switch (Kind) { 5086 case SingleValueKind: 5087 return SingleValue; 5088 case LinearMapKind: { 5089 // Derive the result value from the input value. 5090 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), 5091 false, "switch.idx.cast"); 5092 if (!LinearMultiplier->isOne()) 5093 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); 5094 if (!LinearOffset->isZero()) 5095 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); 5096 return Result; 5097 } 5098 case BitMapKind: { 5099 // Type of the bitmap (e.g. i59). 5100 IntegerType *MapTy = BitMap->getType(); 5101 5102 // Cast Index to the same type as the bitmap. 5103 // Note: The Index is <= the number of elements in the table, so 5104 // truncating it to the width of the bitmask is safe. 5105 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 5106 5107 // Multiply the shift amount by the element width. 5108 ShiftAmt = Builder.CreateMul( 5109 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 5110 "switch.shiftamt"); 5111 5112 // Shift down. 5113 Value *DownShifted = 5114 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift"); 5115 // Mask off. 5116 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked"); 5117 } 5118 case ArrayKind: { 5119 // Make sure the table index will not overflow when treated as signed. 5120 IntegerType *IT = cast<IntegerType>(Index->getType()); 5121 uint64_t TableSize = 5122 Array->getInitializer()->getType()->getArrayNumElements(); 5123 if (TableSize > (1ULL << (IT->getBitWidth() - 1))) 5124 Index = Builder.CreateZExt( 5125 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1), 5126 "switch.tableidx.zext"); 5127 5128 Value *GEPIndices[] = {Builder.getInt32(0), Index}; 5129 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, 5130 GEPIndices, "switch.gep"); 5131 return Builder.CreateLoad( 5132 cast<ArrayType>(Array->getValueType())->getElementType(), GEP, 5133 "switch.load"); 5134 } 5135 } 5136 llvm_unreachable("Unknown lookup table kind!"); 5137 } 5138 5139 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, 5140 uint64_t TableSize, 5141 Type *ElementType) { 5142 auto *IT = dyn_cast<IntegerType>(ElementType); 5143 if (!IT) 5144 return false; 5145 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 5146 // are <= 15, we could try to narrow the type. 5147 5148 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 5149 if (TableSize >= UINT_MAX / IT->getBitWidth()) 5150 return false; 5151 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); 5152 } 5153 5154 /// Determine whether a lookup table should be built for this switch, based on 5155 /// the number of cases, size of the table, and the types of the results. 5156 static bool 5157 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, 5158 const TargetTransformInfo &TTI, const DataLayout &DL, 5159 const SmallDenseMap<PHINode *, Type *> &ResultTypes) { 5160 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) 5161 return false; // TableSize overflowed, or mul below might overflow. 5162 5163 bool AllTablesFitInRegister = true; 5164 bool HasIllegalType = false; 5165 for (const auto &I : ResultTypes) { 5166 Type *Ty = I.second; 5167 5168 // Saturate this flag to true. 5169 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); 5170 5171 // Saturate this flag to false. 5172 AllTablesFitInRegister = 5173 AllTablesFitInRegister && 5174 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); 5175 5176 // If both flags saturate, we're done. NOTE: This *only* works with 5177 // saturating flags, and all flags have to saturate first due to the 5178 // non-deterministic behavior of iterating over a dense map. 5179 if (HasIllegalType && !AllTablesFitInRegister) 5180 break; 5181 } 5182 5183 // If each table would fit in a register, we should build it anyway. 5184 if (AllTablesFitInRegister) 5185 return true; 5186 5187 // Don't build a table that doesn't fit in-register if it has illegal types. 5188 if (HasIllegalType) 5189 return false; 5190 5191 // The table density should be at least 40%. This is the same criterion as for 5192 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. 5193 // FIXME: Find the best cut-off. 5194 return SI->getNumCases() * 10 >= TableSize * 4; 5195 } 5196 5197 /// Try to reuse the switch table index compare. Following pattern: 5198 /// \code 5199 /// if (idx < tablesize) 5200 /// r = table[idx]; // table does not contain default_value 5201 /// else 5202 /// r = default_value; 5203 /// if (r != default_value) 5204 /// ... 5205 /// \endcode 5206 /// Is optimized to: 5207 /// \code 5208 /// cond = idx < tablesize; 5209 /// if (cond) 5210 /// r = table[idx]; 5211 /// else 5212 /// r = default_value; 5213 /// if (cond) 5214 /// ... 5215 /// \endcode 5216 /// Jump threading will then eliminate the second if(cond). 5217 static void reuseTableCompare( 5218 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, 5219 Constant *DefaultValue, 5220 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) { 5221 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); 5222 if (!CmpInst) 5223 return; 5224 5225 // We require that the compare is in the same block as the phi so that jump 5226 // threading can do its work afterwards. 5227 if (CmpInst->getParent() != PhiBlock) 5228 return; 5229 5230 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); 5231 if (!CmpOp1) 5232 return; 5233 5234 Value *RangeCmp = RangeCheckBranch->getCondition(); 5235 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); 5236 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); 5237 5238 // Check if the compare with the default value is constant true or false. 5239 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5240 DefaultValue, CmpOp1, true); 5241 if (DefaultConst != TrueConst && DefaultConst != FalseConst) 5242 return; 5243 5244 // Check if the compare with the case values is distinct from the default 5245 // compare result. 5246 for (auto ValuePair : Values) { 5247 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5248 ValuePair.second, CmpOp1, true); 5249 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst)) 5250 return; 5251 assert((CaseConst == TrueConst || CaseConst == FalseConst) && 5252 "Expect true or false as compare result."); 5253 } 5254 5255 // Check if the branch instruction dominates the phi node. It's a simple 5256 // dominance check, but sufficient for our needs. 5257 // Although this check is invariant in the calling loops, it's better to do it 5258 // at this late stage. Practically we do it at most once for a switch. 5259 BasicBlock *BranchBlock = RangeCheckBranch->getParent(); 5260 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) { 5261 BasicBlock *Pred = *PI; 5262 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) 5263 return; 5264 } 5265 5266 if (DefaultConst == FalseConst) { 5267 // The compare yields the same result. We can replace it. 5268 CmpInst->replaceAllUsesWith(RangeCmp); 5269 ++NumTableCmpReuses; 5270 } else { 5271 // The compare yields the same result, just inverted. We can replace it. 5272 Value *InvertedTableCmp = BinaryOperator::CreateXor( 5273 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", 5274 RangeCheckBranch); 5275 CmpInst->replaceAllUsesWith(InvertedTableCmp); 5276 ++NumTableCmpReuses; 5277 } 5278 } 5279 5280 /// If the switch is only used to initialize one or more phi nodes in a common 5281 /// successor block with different constant values, replace the switch with 5282 /// lookup tables. 5283 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, 5284 const DataLayout &DL, 5285 const TargetTransformInfo &TTI) { 5286 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 5287 5288 Function *Fn = SI->getParent()->getParent(); 5289 // Only build lookup table when we have a target that supports it or the 5290 // attribute is not set. 5291 if (!TTI.shouldBuildLookupTables() || 5292 (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")) 5293 return false; 5294 5295 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 5296 // split off a dense part and build a lookup table for that. 5297 5298 // FIXME: This creates arrays of GEPs to constant strings, which means each 5299 // GEP needs a runtime relocation in PIC code. We should just build one big 5300 // string and lookup indices into that. 5301 5302 // Ignore switches with less than three cases. Lookup tables will not make 5303 // them faster, so we don't analyze them. 5304 if (SI->getNumCases() < 3) 5305 return false; 5306 5307 // Figure out the corresponding result for each case value and phi node in the 5308 // common destination, as well as the min and max case values. 5309 assert(!empty(SI->cases())); 5310 SwitchInst::CaseIt CI = SI->case_begin(); 5311 ConstantInt *MinCaseVal = CI->getCaseValue(); 5312 ConstantInt *MaxCaseVal = CI->getCaseValue(); 5313 5314 BasicBlock *CommonDest = nullptr; 5315 5316 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>; 5317 SmallDenseMap<PHINode *, ResultListTy> ResultLists; 5318 5319 SmallDenseMap<PHINode *, Constant *> DefaultResults; 5320 SmallDenseMap<PHINode *, Type *> ResultTypes; 5321 SmallVector<PHINode *, 4> PHIs; 5322 5323 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 5324 ConstantInt *CaseVal = CI->getCaseValue(); 5325 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 5326 MinCaseVal = CaseVal; 5327 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 5328 MaxCaseVal = CaseVal; 5329 5330 // Resulting value at phi nodes for this case value. 5331 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; 5332 ResultsTy Results; 5333 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest, 5334 Results, DL, TTI)) 5335 return false; 5336 5337 // Append the result from this case to the list for each phi. 5338 for (const auto &I : Results) { 5339 PHINode *PHI = I.first; 5340 Constant *Value = I.second; 5341 if (!ResultLists.count(PHI)) 5342 PHIs.push_back(PHI); 5343 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); 5344 } 5345 } 5346 5347 // Keep track of the result types. 5348 for (PHINode *PHI : PHIs) { 5349 ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); 5350 } 5351 5352 uint64_t NumResults = ResultLists[PHIs[0]].size(); 5353 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); 5354 uint64_t TableSize = RangeSpread.getLimitedValue() + 1; 5355 bool TableHasHoles = (NumResults < TableSize); 5356 5357 // If the table has holes, we need a constant result for the default case 5358 // or a bitmask that fits in a register. 5359 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList; 5360 bool HasDefaultResults = 5361 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, 5362 DefaultResultsList, DL, TTI); 5363 5364 bool NeedMask = (TableHasHoles && !HasDefaultResults); 5365 if (NeedMask) { 5366 // As an extra penalty for the validity test we require more cases. 5367 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). 5368 return false; 5369 if (!DL.fitsInLegalInteger(TableSize)) 5370 return false; 5371 } 5372 5373 for (const auto &I : DefaultResultsList) { 5374 PHINode *PHI = I.first; 5375 Constant *Result = I.second; 5376 DefaultResults[PHI] = Result; 5377 } 5378 5379 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) 5380 return false; 5381 5382 // Create the BB that does the lookups. 5383 Module &Mod = *CommonDest->getParent()->getParent(); 5384 BasicBlock *LookupBB = BasicBlock::Create( 5385 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest); 5386 5387 // Compute the table index value. 5388 Builder.SetInsertPoint(SI); 5389 Value *TableIndex; 5390 if (MinCaseVal->isNullValue()) 5391 TableIndex = SI->getCondition(); 5392 else 5393 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, 5394 "switch.tableidx"); 5395 5396 // Compute the maximum table size representable by the integer type we are 5397 // switching upon. 5398 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); 5399 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; 5400 assert(MaxTableSize >= TableSize && 5401 "It is impossible for a switch to have more entries than the max " 5402 "representable value of its input integer type's size."); 5403 5404 // If the default destination is unreachable, or if the lookup table covers 5405 // all values of the conditional variable, branch directly to the lookup table 5406 // BB. Otherwise, check that the condition is within the case range. 5407 const bool DefaultIsReachable = 5408 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 5409 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); 5410 BranchInst *RangeCheckBranch = nullptr; 5411 5412 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5413 Builder.CreateBr(LookupBB); 5414 // Note: We call removeProdecessor later since we need to be able to get the 5415 // PHI value for the default case in case we're using a bit mask. 5416 } else { 5417 Value *Cmp = Builder.CreateICmpULT( 5418 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize)); 5419 RangeCheckBranch = 5420 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 5421 } 5422 5423 // Populate the BB that does the lookups. 5424 Builder.SetInsertPoint(LookupBB); 5425 5426 if (NeedMask) { 5427 // Before doing the lookup, we do the hole check. The LookupBB is therefore 5428 // re-purposed to do the hole check, and we create a new LookupBB. 5429 BasicBlock *MaskBB = LookupBB; 5430 MaskBB->setName("switch.hole_check"); 5431 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup", 5432 CommonDest->getParent(), CommonDest); 5433 5434 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid 5435 // unnecessary illegal types. 5436 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); 5437 APInt MaskInt(TableSizePowOf2, 0); 5438 APInt One(TableSizePowOf2, 1); 5439 // Build bitmask; fill in a 1 bit for every case. 5440 const ResultListTy &ResultList = ResultLists[PHIs[0]]; 5441 for (size_t I = 0, E = ResultList.size(); I != E; ++I) { 5442 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue()) 5443 .getLimitedValue(); 5444 MaskInt |= One << Idx; 5445 } 5446 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); 5447 5448 // Get the TableIndex'th bit of the bitmask. 5449 // If this bit is 0 (meaning hole) jump to the default destination, 5450 // else continue with table lookup. 5451 IntegerType *MapTy = TableMask->getType(); 5452 Value *MaskIndex = 5453 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex"); 5454 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted"); 5455 Value *LoBit = Builder.CreateTrunc( 5456 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit"); 5457 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); 5458 5459 Builder.SetInsertPoint(LookupBB); 5460 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); 5461 } 5462 5463 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5464 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later, 5465 // do not delete PHINodes here. 5466 SI->getDefaultDest()->removePredecessor(SI->getParent(), 5467 /*KeepOneInputPHIs=*/true); 5468 } 5469 5470 bool ReturnedEarly = false; 5471 for (PHINode *PHI : PHIs) { 5472 const ResultListTy &ResultList = ResultLists[PHI]; 5473 5474 // If using a bitmask, use any value to fill the lookup table holes. 5475 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; 5476 StringRef FuncName = Fn->getName(); 5477 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL, 5478 FuncName); 5479 5480 Value *Result = Table.BuildLookup(TableIndex, Builder); 5481 5482 // If the result is used to return immediately from the function, we want to 5483 // do that right here. 5484 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && 5485 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { 5486 Builder.CreateRet(Result); 5487 ReturnedEarly = true; 5488 break; 5489 } 5490 5491 // Do a small peephole optimization: re-use the switch table compare if 5492 // possible. 5493 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { 5494 BasicBlock *PhiBlock = PHI->getParent(); 5495 // Search for compare instructions which use the phi. 5496 for (auto *User : PHI->users()) { 5497 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); 5498 } 5499 } 5500 5501 PHI->addIncoming(Result, LookupBB); 5502 } 5503 5504 if (!ReturnedEarly) 5505 Builder.CreateBr(CommonDest); 5506 5507 // Remove the switch. 5508 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5509 BasicBlock *Succ = SI->getSuccessor(i); 5510 5511 if (Succ == SI->getDefaultDest()) 5512 continue; 5513 Succ->removePredecessor(SI->getParent()); 5514 } 5515 SI->eraseFromParent(); 5516 5517 ++NumLookupTables; 5518 if (NeedMask) 5519 ++NumLookupTablesHoles; 5520 return true; 5521 } 5522 5523 static bool isSwitchDense(ArrayRef<int64_t> Values) { 5524 // See also SelectionDAGBuilder::isDense(), which this function was based on. 5525 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front(); 5526 uint64_t Range = Diff + 1; 5527 uint64_t NumCases = Values.size(); 5528 // 40% is the default density for building a jump table in optsize/minsize mode. 5529 uint64_t MinDensity = 40; 5530 5531 return NumCases * 100 >= Range * MinDensity; 5532 } 5533 5534 /// Try to transform a switch that has "holes" in it to a contiguous sequence 5535 /// of cases. 5536 /// 5537 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be 5538 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}. 5539 /// 5540 /// This converts a sparse switch into a dense switch which allows better 5541 /// lowering and could also allow transforming into a lookup table. 5542 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, 5543 const DataLayout &DL, 5544 const TargetTransformInfo &TTI) { 5545 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType()); 5546 if (CondTy->getIntegerBitWidth() > 64 || 5547 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth())) 5548 return false; 5549 // Only bother with this optimization if there are more than 3 switch cases; 5550 // SDAG will only bother creating jump tables for 4 or more cases. 5551 if (SI->getNumCases() < 4) 5552 return false; 5553 5554 // This transform is agnostic to the signedness of the input or case values. We 5555 // can treat the case values as signed or unsigned. We can optimize more common 5556 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values 5557 // as signed. 5558 SmallVector<int64_t,4> Values; 5559 for (auto &C : SI->cases()) 5560 Values.push_back(C.getCaseValue()->getValue().getSExtValue()); 5561 llvm::sort(Values); 5562 5563 // If the switch is already dense, there's nothing useful to do here. 5564 if (isSwitchDense(Values)) 5565 return false; 5566 5567 // First, transform the values such that they start at zero and ascend. 5568 int64_t Base = Values[0]; 5569 for (auto &V : Values) 5570 V -= (uint64_t)(Base); 5571 5572 // Now we have signed numbers that have been shifted so that, given enough 5573 // precision, there are no negative values. Since the rest of the transform 5574 // is bitwise only, we switch now to an unsigned representation. 5575 5576 // This transform can be done speculatively because it is so cheap - it 5577 // results in a single rotate operation being inserted. 5578 // FIXME: It's possible that optimizing a switch on powers of two might also 5579 // be beneficial - flag values are often powers of two and we could use a CLZ 5580 // as the key function. 5581 5582 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than 5583 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be 5584 // less than 64. 5585 unsigned Shift = 64; 5586 for (auto &V : Values) 5587 Shift = std::min(Shift, countTrailingZeros((uint64_t)V)); 5588 assert(Shift < 64); 5589 if (Shift > 0) 5590 for (auto &V : Values) 5591 V = (int64_t)((uint64_t)V >> Shift); 5592 5593 if (!isSwitchDense(Values)) 5594 // Transform didn't create a dense switch. 5595 return false; 5596 5597 // The obvious transform is to shift the switch condition right and emit a 5598 // check that the condition actually cleanly divided by GCD, i.e. 5599 // C & (1 << Shift - 1) == 0 5600 // inserting a new CFG edge to handle the case where it didn't divide cleanly. 5601 // 5602 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the 5603 // shift and puts the shifted-off bits in the uppermost bits. If any of these 5604 // are nonzero then the switch condition will be very large and will hit the 5605 // default case. 5606 5607 auto *Ty = cast<IntegerType>(SI->getCondition()->getType()); 5608 Builder.SetInsertPoint(SI); 5609 auto *ShiftC = ConstantInt::get(Ty, Shift); 5610 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base)); 5611 auto *LShr = Builder.CreateLShr(Sub, ShiftC); 5612 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift); 5613 auto *Rot = Builder.CreateOr(LShr, Shl); 5614 SI->replaceUsesOfWith(SI->getCondition(), Rot); 5615 5616 for (auto Case : SI->cases()) { 5617 auto *Orig = Case.getCaseValue(); 5618 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base); 5619 Case.setValue( 5620 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue())))); 5621 } 5622 return true; 5623 } 5624 5625 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 5626 BasicBlock *BB = SI->getParent(); 5627 5628 if (isValueEqualityComparison(SI)) { 5629 // If we only have one predecessor, and if it is a branch on this value, 5630 // see if that predecessor totally determines the outcome of this switch. 5631 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 5632 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 5633 return requestResimplify(); 5634 5635 Value *Cond = SI->getCondition(); 5636 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 5637 if (SimplifySwitchOnSelect(SI, Select)) 5638 return requestResimplify(); 5639 5640 // If the block only contains the switch, see if we can fold the block 5641 // away into any preds. 5642 if (SI == &*BB->instructionsWithoutDebug().begin()) 5643 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 5644 return requestResimplify(); 5645 } 5646 5647 // Try to transform the switch into an icmp and a branch. 5648 if (TurnSwitchRangeIntoICmp(SI, Builder)) 5649 return requestResimplify(); 5650 5651 // Remove unreachable cases. 5652 if (eliminateDeadSwitchCases(SI, Options.AC, DL)) 5653 return requestResimplify(); 5654 5655 if (switchToSelect(SI, Builder, DL, TTI)) 5656 return requestResimplify(); 5657 5658 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI)) 5659 return requestResimplify(); 5660 5661 // The conversion from switch to lookup tables results in difficult-to-analyze 5662 // code and makes pruning branches much harder. This is a problem if the 5663 // switch expression itself can still be restricted as a result of inlining or 5664 // CVP. Therefore, only apply this transformation during late stages of the 5665 // optimisation pipeline. 5666 if (Options.ConvertSwitchToLookupTable && 5667 SwitchToLookupTable(SI, Builder, DL, TTI)) 5668 return requestResimplify(); 5669 5670 if (ReduceSwitchRange(SI, Builder, DL, TTI)) 5671 return requestResimplify(); 5672 5673 return false; 5674 } 5675 5676 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) { 5677 BasicBlock *BB = IBI->getParent(); 5678 bool Changed = false; 5679 5680 // Eliminate redundant destinations. 5681 SmallPtrSet<Value *, 8> Succs; 5682 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 5683 BasicBlock *Dest = IBI->getDestination(i); 5684 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { 5685 Dest->removePredecessor(BB); 5686 IBI->removeDestination(i); 5687 --i; 5688 --e; 5689 Changed = true; 5690 } 5691 } 5692 5693 if (IBI->getNumDestinations() == 0) { 5694 // If the indirectbr has no successors, change it to unreachable. 5695 new UnreachableInst(IBI->getContext(), IBI); 5696 EraseTerminatorAndDCECond(IBI); 5697 return true; 5698 } 5699 5700 if (IBI->getNumDestinations() == 1) { 5701 // If the indirectbr has one successor, change it to a direct branch. 5702 BranchInst::Create(IBI->getDestination(0), IBI); 5703 EraseTerminatorAndDCECond(IBI); 5704 return true; 5705 } 5706 5707 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 5708 if (SimplifyIndirectBrOnSelect(IBI, SI)) 5709 return requestResimplify(); 5710 } 5711 return Changed; 5712 } 5713 5714 /// Given an block with only a single landing pad and a unconditional branch 5715 /// try to find another basic block which this one can be merged with. This 5716 /// handles cases where we have multiple invokes with unique landing pads, but 5717 /// a shared handler. 5718 /// 5719 /// We specifically choose to not worry about merging non-empty blocks 5720 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In 5721 /// practice, the optimizer produces empty landing pad blocks quite frequently 5722 /// when dealing with exception dense code. (see: instcombine, gvn, if-else 5723 /// sinking in this file) 5724 /// 5725 /// This is primarily a code size optimization. We need to avoid performing 5726 /// any transform which might inhibit optimization (such as our ability to 5727 /// specialize a particular handler via tail commoning). We do this by not 5728 /// merging any blocks which require us to introduce a phi. Since the same 5729 /// values are flowing through both blocks, we don't lose any ability to 5730 /// specialize. If anything, we make such specialization more likely. 5731 /// 5732 /// TODO - This transformation could remove entries from a phi in the target 5733 /// block when the inputs in the phi are the same for the two blocks being 5734 /// merged. In some cases, this could result in removal of the PHI entirely. 5735 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, 5736 BasicBlock *BB) { 5737 auto Succ = BB->getUniqueSuccessor(); 5738 assert(Succ); 5739 // If there's a phi in the successor block, we'd likely have to introduce 5740 // a phi into the merged landing pad block. 5741 if (isa<PHINode>(*Succ->begin())) 5742 return false; 5743 5744 for (BasicBlock *OtherPred : predecessors(Succ)) { 5745 if (BB == OtherPred) 5746 continue; 5747 BasicBlock::iterator I = OtherPred->begin(); 5748 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); 5749 if (!LPad2 || !LPad2->isIdenticalTo(LPad)) 5750 continue; 5751 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5752 ; 5753 BranchInst *BI2 = dyn_cast<BranchInst>(I); 5754 if (!BI2 || !BI2->isIdenticalTo(BI)) 5755 continue; 5756 5757 // We've found an identical block. Update our predecessors to take that 5758 // path instead and make ourselves dead. 5759 SmallPtrSet<BasicBlock *, 16> Preds; 5760 Preds.insert(pred_begin(BB), pred_end(BB)); 5761 for (BasicBlock *Pred : Preds) { 5762 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); 5763 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB && 5764 "unexpected successor"); 5765 II->setUnwindDest(OtherPred); 5766 } 5767 5768 // The debug info in OtherPred doesn't cover the merged control flow that 5769 // used to go through BB. We need to delete it or update it. 5770 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) { 5771 Instruction &Inst = *I; 5772 I++; 5773 if (isa<DbgInfoIntrinsic>(Inst)) 5774 Inst.eraseFromParent(); 5775 } 5776 5777 SmallPtrSet<BasicBlock *, 16> Succs; 5778 Succs.insert(succ_begin(BB), succ_end(BB)); 5779 for (BasicBlock *Succ : Succs) { 5780 Succ->removePredecessor(BB); 5781 } 5782 5783 IRBuilder<> Builder(BI); 5784 Builder.CreateUnreachable(); 5785 BI->eraseFromParent(); 5786 return true; 5787 } 5788 return false; 5789 } 5790 5791 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, 5792 IRBuilder<> &Builder) { 5793 BasicBlock *BB = BI->getParent(); 5794 BasicBlock *Succ = BI->getSuccessor(0); 5795 5796 // If the Terminator is the only non-phi instruction, simplify the block. 5797 // If LoopHeader is provided, check if the block or its successor is a loop 5798 // header. (This is for early invocations before loop simplify and 5799 // vectorization to keep canonical loop forms for nested loops. These blocks 5800 // can be eliminated when the pass is invoked later in the back-end.) 5801 // Note that if BB has only one predecessor then we do not introduce new 5802 // backedge, so we can eliminate BB. 5803 bool NeedCanonicalLoop = 5804 Options.NeedCanonicalLoop && 5805 (LoopHeaders && BB->hasNPredecessorsOrMore(2) && 5806 (LoopHeaders->count(BB) || LoopHeaders->count(Succ))); 5807 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator(); 5808 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 5809 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB)) 5810 return true; 5811 5812 // If the only instruction in the block is a seteq/setne comparison against a 5813 // constant, try to simplify the block. 5814 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 5815 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 5816 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5817 ; 5818 if (I->isTerminator() && 5819 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder)) 5820 return true; 5821 } 5822 5823 // See if we can merge an empty landing pad block with another which is 5824 // equivalent. 5825 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { 5826 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5827 ; 5828 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB)) 5829 return true; 5830 } 5831 5832 // If this basic block is ONLY a compare and a branch, and if a predecessor 5833 // branches to us and our successor, fold the comparison into the 5834 // predecessor and use logical operations to update the incoming value 5835 // for PHI nodes in common successor. 5836 if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold)) 5837 return requestResimplify(); 5838 return false; 5839 } 5840 5841 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { 5842 BasicBlock *PredPred = nullptr; 5843 for (auto *P : predecessors(BB)) { 5844 BasicBlock *PPred = P->getSinglePredecessor(); 5845 if (!PPred || (PredPred && PredPred != PPred)) 5846 return nullptr; 5847 PredPred = PPred; 5848 } 5849 return PredPred; 5850 } 5851 5852 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 5853 BasicBlock *BB = BI->getParent(); 5854 const Function *Fn = BB->getParent(); 5855 if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing)) 5856 return false; 5857 5858 // Conditional branch 5859 if (isValueEqualityComparison(BI)) { 5860 // If we only have one predecessor, and if it is a branch on this value, 5861 // see if that predecessor totally determines the outcome of this 5862 // switch. 5863 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 5864 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 5865 return requestResimplify(); 5866 5867 // This block must be empty, except for the setcond inst, if it exists. 5868 // Ignore dbg intrinsics. 5869 auto I = BB->instructionsWithoutDebug().begin(); 5870 if (&*I == BI) { 5871 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 5872 return requestResimplify(); 5873 } else if (&*I == cast<Instruction>(BI->getCondition())) { 5874 ++I; 5875 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 5876 return requestResimplify(); 5877 } 5878 } 5879 5880 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 5881 if (SimplifyBranchOnICmpChain(BI, Builder, DL)) 5882 return true; 5883 5884 // If this basic block has dominating predecessor blocks and the dominating 5885 // blocks' conditions imply BI's condition, we know the direction of BI. 5886 Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL); 5887 if (Imp) { 5888 // Turn this into a branch on constant. 5889 auto *OldCond = BI->getCondition(); 5890 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext()) 5891 : ConstantInt::getFalse(BB->getContext()); 5892 BI->setCondition(TorF); 5893 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 5894 return requestResimplify(); 5895 } 5896 5897 // If this basic block is ONLY a compare and a branch, and if a predecessor 5898 // branches to us and one of our successors, fold the comparison into the 5899 // predecessor and use logical operations to pick the right destination. 5900 if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold)) 5901 return requestResimplify(); 5902 5903 // We have a conditional branch to two blocks that are only reachable 5904 // from BI. We know that the condbr dominates the two blocks, so see if 5905 // there is any identical code in the "then" and "else" blocks. If so, we 5906 // can hoist it up to the branching block. 5907 if (BI->getSuccessor(0)->getSinglePredecessor()) { 5908 if (BI->getSuccessor(1)->getSinglePredecessor()) { 5909 if (HoistThenElseCodeToIf(BI, TTI)) 5910 return requestResimplify(); 5911 } else { 5912 // If Successor #1 has multiple preds, we may be able to conditionally 5913 // execute Successor #0 if it branches to Successor #1. 5914 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator(); 5915 if (Succ0TI->getNumSuccessors() == 1 && 5916 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 5917 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) 5918 return requestResimplify(); 5919 } 5920 } else if (BI->getSuccessor(1)->getSinglePredecessor()) { 5921 // If Successor #0 has multiple preds, we may be able to conditionally 5922 // execute Successor #1 if it branches to Successor #0. 5923 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator(); 5924 if (Succ1TI->getNumSuccessors() == 1 && 5925 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 5926 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) 5927 return requestResimplify(); 5928 } 5929 5930 // If this is a branch on a phi node in the current block, thread control 5931 // through this block if any PHI node entries are constants. 5932 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 5933 if (PN->getParent() == BI->getParent()) 5934 if (FoldCondBranchOnPHI(BI, DL, Options.AC)) 5935 return requestResimplify(); 5936 5937 // Scan predecessor blocks for conditional branches. 5938 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 5939 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 5940 if (PBI != BI && PBI->isConditional()) 5941 if (SimplifyCondBranchToCondBranch(PBI, BI, DL)) 5942 return requestResimplify(); 5943 5944 // Look for diamond patterns. 5945 if (MergeCondStores) 5946 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) 5947 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) 5948 if (PBI != BI && PBI->isConditional()) 5949 if (mergeConditionalStores(PBI, BI, DL)) 5950 return requestResimplify(); 5951 5952 return false; 5953 } 5954 5955 /// Check if passing a value to an instruction will cause undefined behavior. 5956 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { 5957 Constant *C = dyn_cast<Constant>(V); 5958 if (!C) 5959 return false; 5960 5961 if (I->use_empty()) 5962 return false; 5963 5964 if (C->isNullValue() || isa<UndefValue>(C)) { 5965 // Only look at the first use, avoid hurting compile time with long uselists 5966 User *Use = *I->user_begin(); 5967 5968 // Now make sure that there are no instructions in between that can alter 5969 // control flow (eg. calls) 5970 for (BasicBlock::iterator 5971 i = ++BasicBlock::iterator(I), 5972 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use)); 5973 i != UI; ++i) 5974 if (i == I->getParent()->end() || i->mayHaveSideEffects()) 5975 return false; 5976 5977 // Look through GEPs. A load from a GEP derived from NULL is still undefined 5978 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 5979 if (GEP->getPointerOperand() == I) 5980 return passingValueIsAlwaysUndefined(V, GEP); 5981 5982 // Look through bitcasts. 5983 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 5984 return passingValueIsAlwaysUndefined(V, BC); 5985 5986 // Load from null is undefined. 5987 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 5988 if (!LI->isVolatile()) 5989 return !NullPointerIsDefined(LI->getFunction(), 5990 LI->getPointerAddressSpace()); 5991 5992 // Store to null is undefined. 5993 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 5994 if (!SI->isVolatile()) 5995 return (!NullPointerIsDefined(SI->getFunction(), 5996 SI->getPointerAddressSpace())) && 5997 SI->getPointerOperand() == I; 5998 5999 // A call to null is undefined. 6000 if (auto CS = CallSite(Use)) 6001 return !NullPointerIsDefined(CS->getFunction()) && 6002 CS.getCalledValue() == I; 6003 } 6004 return false; 6005 } 6006 6007 /// If BB has an incoming value that will always trigger undefined behavior 6008 /// (eg. null pointer dereference), remove the branch leading here. 6009 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { 6010 for (PHINode &PHI : BB->phis()) 6011 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) 6012 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) { 6013 Instruction *T = PHI.getIncomingBlock(i)->getTerminator(); 6014 IRBuilder<> Builder(T); 6015 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 6016 BB->removePredecessor(PHI.getIncomingBlock(i)); 6017 // Turn uncoditional branches into unreachables and remove the dead 6018 // destination from conditional branches. 6019 if (BI->isUnconditional()) 6020 Builder.CreateUnreachable(); 6021 else 6022 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) 6023 : BI->getSuccessor(0)); 6024 BI->eraseFromParent(); 6025 return true; 6026 } 6027 // TODO: SwitchInst. 6028 } 6029 6030 return false; 6031 } 6032 6033 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) { 6034 bool Changed = false; 6035 6036 assert(BB && BB->getParent() && "Block not embedded in function!"); 6037 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 6038 6039 // Remove basic blocks that have no predecessors (except the entry block)... 6040 // or that just have themself as a predecessor. These are unreachable. 6041 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) || 6042 BB->getSinglePredecessor() == BB) { 6043 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB); 6044 DeleteDeadBlock(BB); 6045 return true; 6046 } 6047 6048 // Check to see if we can constant propagate this terminator instruction 6049 // away... 6050 Changed |= ConstantFoldTerminator(BB, true); 6051 6052 // Check for and eliminate duplicate PHI nodes in this block. 6053 Changed |= EliminateDuplicatePHINodes(BB); 6054 6055 // Check for and remove branches that will always cause undefined behavior. 6056 Changed |= removeUndefIntroducingPredecessor(BB); 6057 6058 // Merge basic blocks into their predecessor if there is only one distinct 6059 // pred, and if there is only one distinct successor of the predecessor, and 6060 // if there are no PHI nodes. 6061 if (MergeBlockIntoPredecessor(BB)) 6062 return true; 6063 6064 if (SinkCommon && Options.SinkCommonInsts) 6065 Changed |= SinkCommonCodeFromPredecessors(BB); 6066 6067 IRBuilder<> Builder(BB); 6068 6069 // If there is a trivial two-entry PHI node in this basic block, and we can 6070 // eliminate it, do so now. 6071 if (auto *PN = dyn_cast<PHINode>(BB->begin())) 6072 if (PN->getNumIncomingValues() == 2) 6073 Changed |= FoldTwoEntryPHINode(PN, TTI, DL); 6074 6075 Builder.SetInsertPoint(BB->getTerminator()); 6076 if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 6077 if (BI->isUnconditional()) { 6078 if (SimplifyUncondBranch(BI, Builder)) 6079 return true; 6080 } else { 6081 if (SimplifyCondBranch(BI, Builder)) 6082 return true; 6083 } 6084 } else if (auto *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 6085 if (SimplifyReturn(RI, Builder)) 6086 return true; 6087 } else if (auto *RI = dyn_cast<ResumeInst>(BB->getTerminator())) { 6088 if (SimplifyResume(RI, Builder)) 6089 return true; 6090 } else if (auto *RI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) { 6091 if (SimplifyCleanupReturn(RI)) 6092 return true; 6093 } else if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 6094 if (SimplifySwitch(SI, Builder)) 6095 return true; 6096 } else if (auto *UI = dyn_cast<UnreachableInst>(BB->getTerminator())) { 6097 if (SimplifyUnreachable(UI)) 6098 return true; 6099 } else if (auto *IBI = dyn_cast<IndirectBrInst>(BB->getTerminator())) { 6100 if (SimplifyIndirectBr(IBI)) 6101 return true; 6102 } 6103 6104 return Changed; 6105 } 6106 6107 bool SimplifyCFGOpt::run(BasicBlock *BB) { 6108 bool Changed = false; 6109 6110 // Repeated simplify BB as long as resimplification is requested. 6111 do { 6112 Resimplify = false; 6113 6114 // Perform one round of simplifcation. Resimplify flag will be set if 6115 // another iteration is requested. 6116 Changed |= simplifyOnce(BB); 6117 } while (Resimplify); 6118 6119 return Changed; 6120 } 6121 6122 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 6123 const SimplifyCFGOptions &Options, 6124 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) { 6125 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders, 6126 Options) 6127 .run(BB); 6128 } 6129