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