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