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