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