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