1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===// 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 // This pass transforms loops that contain branches on loop-invariant conditions 11 // to have multiple loops. For example, it turns the left into the right code: 12 // 13 // for (...) if (lic) 14 // A for (...) 15 // if (lic) A; B; C 16 // B else 17 // C for (...) 18 // A; C 19 // 20 // This can increase the size of the code exponentially (doubling it every time 21 // a loop is unswitched) so we only unswitch if the resultant code will be 22 // smaller than a threshold. 23 // 24 // This pass expects LICM to be run before it to hoist invariant conditions out 25 // of the loop, to make the unswitching opportunity obvious. 26 // 27 //===----------------------------------------------------------------------===// 28 29 #define DEBUG_TYPE "loop-unswitch" 30 #include "llvm/Transforms/Scalar.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/Statistic.h" 34 #include "llvm/Analysis/CodeMetrics.h" 35 #include "llvm/Analysis/Dominators.h" 36 #include "llvm/Analysis/InstructionSimplify.h" 37 #include "llvm/Analysis/LoopInfo.h" 38 #include "llvm/Analysis/LoopPass.h" 39 #include "llvm/Analysis/ScalarEvolution.h" 40 #include "llvm/Analysis/TargetTransformInfo.h" 41 #include "llvm/IR/Constants.h" 42 #include "llvm/IR/DerivedTypes.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/Support/CommandLine.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 49 #include "llvm/Transforms/Utils/Cloning.h" 50 #include "llvm/Transforms/Utils/Local.h" 51 #include <algorithm> 52 #include <map> 53 #include <set> 54 using namespace llvm; 55 56 STATISTIC(NumBranches, "Number of branches unswitched"); 57 STATISTIC(NumSwitches, "Number of switches unswitched"); 58 STATISTIC(NumSelects , "Number of selects unswitched"); 59 STATISTIC(NumTrivial , "Number of unswitches that are trivial"); 60 STATISTIC(NumSimplify, "Number of simplifications of unswitched code"); 61 STATISTIC(TotalInsts, "Total number of instructions analyzed"); 62 63 // The specific value of 100 here was chosen based only on intuition and a 64 // few specific examples. 65 static cl::opt<unsigned> 66 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), 67 cl::init(100), cl::Hidden); 68 69 namespace { 70 71 class LUAnalysisCache { 72 73 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> > 74 UnswitchedValsMap; 75 76 typedef UnswitchedValsMap::iterator UnswitchedValsIt; 77 78 struct LoopProperties { 79 unsigned CanBeUnswitchedCount; 80 unsigned SizeEstimation; 81 UnswitchedValsMap UnswitchedVals; 82 }; 83 84 // Here we use std::map instead of DenseMap, since we need to keep valid 85 // LoopProperties pointer for current loop for better performance. 86 typedef std::map<const Loop*, LoopProperties> LoopPropsMap; 87 typedef LoopPropsMap::iterator LoopPropsMapIt; 88 89 LoopPropsMap LoopsProperties; 90 UnswitchedValsMap* CurLoopInstructions; 91 LoopProperties* CurrentLoopProperties; 92 93 // Max size of code we can produce on remained iterations. 94 unsigned MaxSize; 95 96 public: 97 98 LUAnalysisCache() : 99 CurLoopInstructions(NULL), CurrentLoopProperties(NULL), 100 MaxSize(Threshold) 101 {} 102 103 // Analyze loop. Check its size, calculate is it possible to unswitch 104 // it. Returns true if we can unswitch this loop. 105 bool countLoop(const Loop* L, const TargetTransformInfo &TTI); 106 107 // Clean all data related to given loop. 108 void forgetLoop(const Loop* L); 109 110 // Mark case value as unswitched. 111 // Since SI instruction can be partly unswitched, in order to avoid 112 // extra unswitching in cloned loops keep track all unswitched values. 113 void setUnswitched(const SwitchInst* SI, const Value* V); 114 115 // Check was this case value unswitched before or not. 116 bool isUnswitched(const SwitchInst* SI, const Value* V); 117 118 // Clone all loop-unswitch related loop properties. 119 // Redistribute unswitching quotas. 120 // Note, that new loop data is stored inside the VMap. 121 void cloneData(const Loop* NewLoop, const Loop* OldLoop, 122 const ValueToValueMapTy& VMap); 123 }; 124 125 class LoopUnswitch : public LoopPass { 126 LoopInfo *LI; // Loop information 127 LPPassManager *LPM; 128 129 // LoopProcessWorklist - Used to check if second loop needs processing 130 // after RewriteLoopBodyWithConditionConstant rewrites first loop. 131 std::vector<Loop*> LoopProcessWorklist; 132 133 LUAnalysisCache BranchesInfo; 134 135 bool OptimizeForSize; 136 bool redoLoop; 137 138 Loop *currentLoop; 139 DominatorTree *DT; 140 BasicBlock *loopHeader; 141 BasicBlock *loopPreheader; 142 143 // LoopBlocks contains all of the basic blocks of the loop, including the 144 // preheader of the loop, the body of the loop, and the exit blocks of the 145 // loop, in that order. 146 std::vector<BasicBlock*> LoopBlocks; 147 // NewBlocks contained cloned copy of basic blocks from LoopBlocks. 148 std::vector<BasicBlock*> NewBlocks; 149 150 public: 151 static char ID; // Pass ID, replacement for typeid 152 explicit LoopUnswitch(bool Os = false) : 153 LoopPass(ID), OptimizeForSize(Os), redoLoop(false), 154 currentLoop(NULL), DT(NULL), loopHeader(NULL), 155 loopPreheader(NULL) { 156 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry()); 157 } 158 159 bool runOnLoop(Loop *L, LPPassManager &LPM); 160 bool processCurrentLoop(); 161 162 /// This transformation requires natural loop information & requires that 163 /// loop preheaders be inserted into the CFG. 164 /// 165 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 166 AU.addRequiredID(LoopSimplifyID); 167 AU.addPreservedID(LoopSimplifyID); 168 AU.addRequired<LoopInfo>(); 169 AU.addPreserved<LoopInfo>(); 170 AU.addRequiredID(LCSSAID); 171 AU.addPreservedID(LCSSAID); 172 AU.addPreserved<DominatorTree>(); 173 AU.addPreserved<ScalarEvolution>(); 174 AU.addRequired<TargetTransformInfo>(); 175 } 176 177 private: 178 179 virtual void releaseMemory() { 180 BranchesInfo.forgetLoop(currentLoop); 181 } 182 183 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist, 184 /// remove it. 185 void RemoveLoopFromWorklist(Loop *L) { 186 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(), 187 LoopProcessWorklist.end(), L); 188 if (I != LoopProcessWorklist.end()) 189 LoopProcessWorklist.erase(I); 190 } 191 192 void initLoopData() { 193 loopHeader = currentLoop->getHeader(); 194 loopPreheader = currentLoop->getLoopPreheader(); 195 } 196 197 /// Split all of the edges from inside the loop to their exit blocks. 198 /// Update the appropriate Phi nodes as we do so. 199 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks); 200 201 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val); 202 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val, 203 BasicBlock *ExitBlock); 204 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L); 205 206 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, 207 Constant *Val, bool isEqual); 208 209 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val, 210 BasicBlock *TrueDest, 211 BasicBlock *FalseDest, 212 Instruction *InsertPt); 213 214 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L); 215 void RemoveBlockIfDead(BasicBlock *BB, 216 std::vector<Instruction*> &Worklist, Loop *l); 217 void RemoveLoopFromHierarchy(Loop *L); 218 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0, 219 BasicBlock **LoopExit = 0); 220 221 }; 222 } 223 224 // Analyze loop. Check its size, calculate is it possible to unswitch 225 // it. Returns true if we can unswitch this loop. 226 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI) { 227 228 std::pair<LoopPropsMapIt, bool> InsertRes = 229 LoopsProperties.insert(std::make_pair(L, LoopProperties())); 230 231 LoopProperties& Props = InsertRes.first->second; 232 233 if (InsertRes.second) { 234 // New loop. 235 236 // Limit the number of instructions to avoid causing significant code 237 // expansion, and the number of basic blocks, to avoid loops with 238 // large numbers of branches which cause loop unswitching to go crazy. 239 // This is a very ad-hoc heuristic. 240 241 // FIXME: This is overly conservative because it does not take into 242 // consideration code simplification opportunities and code that can 243 // be shared by the resultant unswitched loops. 244 CodeMetrics Metrics; 245 for (Loop::block_iterator I = L->block_begin(), 246 E = L->block_end(); 247 I != E; ++I) 248 Metrics.analyzeBasicBlock(*I, TTI); 249 250 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5); 251 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation); 252 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount; 253 254 if (Metrics.notDuplicatable) { 255 DEBUG(dbgs() << "NOT unswitching loop %" 256 << L->getHeader()->getName() << ", contents cannot be " 257 << "duplicated!\n"); 258 return false; 259 } 260 } 261 262 if (!Props.CanBeUnswitchedCount) { 263 DEBUG(dbgs() << "NOT unswitching loop %" 264 << L->getHeader()->getName() << ", cost too high: " 265 << L->getBlocks().size() << "\n"); 266 267 return false; 268 } 269 270 // Be careful. This links are good only before new loop addition. 271 CurrentLoopProperties = &Props; 272 CurLoopInstructions = &Props.UnswitchedVals; 273 274 return true; 275 } 276 277 // Clean all data related to given loop. 278 void LUAnalysisCache::forgetLoop(const Loop* L) { 279 280 LoopPropsMapIt LIt = LoopsProperties.find(L); 281 282 if (LIt != LoopsProperties.end()) { 283 LoopProperties& Props = LIt->second; 284 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation; 285 LoopsProperties.erase(LIt); 286 } 287 288 CurrentLoopProperties = NULL; 289 CurLoopInstructions = NULL; 290 } 291 292 // Mark case value as unswitched. 293 // Since SI instruction can be partly unswitched, in order to avoid 294 // extra unswitching in cloned loops keep track all unswitched values. 295 void LUAnalysisCache::setUnswitched(const SwitchInst* SI, const Value* V) { 296 (*CurLoopInstructions)[SI].insert(V); 297 } 298 299 // Check was this case value unswitched before or not. 300 bool LUAnalysisCache::isUnswitched(const SwitchInst* SI, const Value* V) { 301 return (*CurLoopInstructions)[SI].count(V); 302 } 303 304 // Clone all loop-unswitch related loop properties. 305 // Redistribute unswitching quotas. 306 // Note, that new loop data is stored inside the VMap. 307 void LUAnalysisCache::cloneData(const Loop* NewLoop, const Loop* OldLoop, 308 const ValueToValueMapTy& VMap) { 309 310 LoopProperties& NewLoopProps = LoopsProperties[NewLoop]; 311 LoopProperties& OldLoopProps = *CurrentLoopProperties; 312 UnswitchedValsMap& Insts = OldLoopProps.UnswitchedVals; 313 314 // Reallocate "can-be-unswitched quota" 315 316 --OldLoopProps.CanBeUnswitchedCount; 317 unsigned Quota = OldLoopProps.CanBeUnswitchedCount; 318 NewLoopProps.CanBeUnswitchedCount = Quota / 2; 319 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2; 320 321 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation; 322 323 // Clone unswitched values info: 324 // for new loop switches we clone info about values that was 325 // already unswitched and has redundant successors. 326 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) { 327 const SwitchInst* OldInst = I->first; 328 Value* NewI = VMap.lookup(OldInst); 329 const SwitchInst* NewInst = cast_or_null<SwitchInst>(NewI); 330 assert(NewInst && "All instructions that are in SrcBB must be in VMap."); 331 332 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst]; 333 } 334 } 335 336 char LoopUnswitch::ID = 0; 337 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops", 338 false, false) 339 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 340 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 341 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 342 INITIALIZE_PASS_DEPENDENCY(LCSSA) 343 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops", 344 false, false) 345 346 Pass *llvm::createLoopUnswitchPass(bool Os) { 347 return new LoopUnswitch(Os); 348 } 349 350 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is 351 /// invariant in the loop, or has an invariant piece, return the invariant. 352 /// Otherwise, return null. 353 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) { 354 355 // We started analyze new instruction, increment scanned instructions counter. 356 ++TotalInsts; 357 358 // We can never unswitch on vector conditions. 359 if (Cond->getType()->isVectorTy()) 360 return 0; 361 362 // Constants should be folded, not unswitched on! 363 if (isa<Constant>(Cond)) return 0; 364 365 // TODO: Handle: br (VARIANT|INVARIANT). 366 367 // Hoist simple values out. 368 if (L->makeLoopInvariant(Cond, Changed)) 369 return Cond; 370 371 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond)) 372 if (BO->getOpcode() == Instruction::And || 373 BO->getOpcode() == Instruction::Or) { 374 // If either the left or right side is invariant, we can unswitch on this, 375 // which will cause the branch to go away in one loop and the condition to 376 // simplify in the other one. 377 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed)) 378 return LHS; 379 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed)) 380 return RHS; 381 } 382 383 return 0; 384 } 385 386 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) { 387 LI = &getAnalysis<LoopInfo>(); 388 LPM = &LPM_Ref; 389 DT = getAnalysisIfAvailable<DominatorTree>(); 390 currentLoop = L; 391 Function *F = currentLoop->getHeader()->getParent(); 392 bool Changed = false; 393 do { 394 assert(currentLoop->isLCSSAForm(*DT)); 395 redoLoop = false; 396 Changed |= processCurrentLoop(); 397 } while(redoLoop); 398 399 if (Changed) { 400 // FIXME: Reconstruct dom info, because it is not preserved properly. 401 if (DT) 402 DT->runOnFunction(*F); 403 } 404 return Changed; 405 } 406 407 /// processCurrentLoop - Do actual work and unswitch loop if possible 408 /// and profitable. 409 bool LoopUnswitch::processCurrentLoop() { 410 bool Changed = false; 411 412 initLoopData(); 413 414 // If LoopSimplify was unable to form a preheader, don't do any unswitching. 415 if (!loopPreheader) 416 return false; 417 418 // Loops with indirectbr cannot be cloned. 419 if (!currentLoop->isSafeToClone()) 420 return false; 421 422 // Without dedicated exits, splitting the exit edge may fail. 423 if (!currentLoop->hasDedicatedExits()) 424 return false; 425 426 LLVMContext &Context = loopHeader->getContext(); 427 428 // Probably we reach the quota of branches for this loop. If so 429 // stop unswitching. 430 if (!BranchesInfo.countLoop(currentLoop, getAnalysis<TargetTransformInfo>())) 431 return false; 432 433 // Loop over all of the basic blocks in the loop. If we find an interior 434 // block that is branching on a loop-invariant condition, we can unswitch this 435 // loop. 436 for (Loop::block_iterator I = currentLoop->block_begin(), 437 E = currentLoop->block_end(); I != E; ++I) { 438 TerminatorInst *TI = (*I)->getTerminator(); 439 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 440 // If this isn't branching on an invariant condition, we can't unswitch 441 // it. 442 if (BI->isConditional()) { 443 // See if this, or some part of it, is loop invariant. If so, we can 444 // unswitch on it if we desire. 445 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), 446 currentLoop, Changed); 447 if (LoopCond && UnswitchIfProfitable(LoopCond, 448 ConstantInt::getTrue(Context))) { 449 ++NumBranches; 450 return true; 451 } 452 } 453 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 454 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), 455 currentLoop, Changed); 456 unsigned NumCases = SI->getNumCases(); 457 if (LoopCond && NumCases) { 458 // Find a value to unswitch on: 459 // FIXME: this should chose the most expensive case! 460 // FIXME: scan for a case with a non-critical edge? 461 Constant *UnswitchVal = NULL; 462 463 // Do not process same value again and again. 464 // At this point we have some cases already unswitched and 465 // some not yet unswitched. Let's find the first not yet unswitched one. 466 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 467 i != e; ++i) { 468 Constant* UnswitchValCandidate = i.getCaseValue(); 469 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) { 470 UnswitchVal = UnswitchValCandidate; 471 break; 472 } 473 } 474 475 if (!UnswitchVal) 476 continue; 477 478 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) { 479 ++NumSwitches; 480 return true; 481 } 482 } 483 } 484 485 // Scan the instructions to check for unswitchable values. 486 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 487 BBI != E; ++BBI) 488 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) { 489 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), 490 currentLoop, Changed); 491 if (LoopCond && UnswitchIfProfitable(LoopCond, 492 ConstantInt::getTrue(Context))) { 493 ++NumSelects; 494 return true; 495 } 496 } 497 } 498 return Changed; 499 } 500 501 /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the 502 /// loop with no side effects (including infinite loops). 503 /// 504 /// If true, we return true and set ExitBB to the block we 505 /// exit through. 506 /// 507 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB, 508 BasicBlock *&ExitBB, 509 std::set<BasicBlock*> &Visited) { 510 if (!Visited.insert(BB).second) { 511 // Already visited. Without more analysis, this could indicate an infinite 512 // loop. 513 return false; 514 } else if (!L->contains(BB)) { 515 // Otherwise, this is a loop exit, this is fine so long as this is the 516 // first exit. 517 if (ExitBB != 0) return false; 518 ExitBB = BB; 519 return true; 520 } 521 522 // Otherwise, this is an unvisited intra-loop node. Check all successors. 523 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) { 524 // Check to see if the successor is a trivial loop exit. 525 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited)) 526 return false; 527 } 528 529 // Okay, everything after this looks good, check to make sure that this block 530 // doesn't include any side effects. 531 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 532 if (I->mayHaveSideEffects()) 533 return false; 534 535 return true; 536 } 537 538 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally 539 /// leads to an exit from the specified loop, and has no side-effects in the 540 /// process. If so, return the block that is exited to, otherwise return null. 541 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) { 542 std::set<BasicBlock*> Visited; 543 Visited.insert(L->getHeader()); // Branches to header make infinite loops. 544 BasicBlock *ExitBB = 0; 545 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited)) 546 return ExitBB; 547 return 0; 548 } 549 550 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is 551 /// trivial: that is, that the condition controls whether or not the loop does 552 /// anything at all. If this is a trivial condition, unswitching produces no 553 /// code duplications (equivalently, it produces a simpler loop and a new empty 554 /// loop, which gets deleted). 555 /// 556 /// If this is a trivial condition, return true, otherwise return false. When 557 /// returning true, this sets Cond and Val to the condition that controls the 558 /// trivial condition: when Cond dynamically equals Val, the loop is known to 559 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when 560 /// Cond == Val. 561 /// 562 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val, 563 BasicBlock **LoopExit) { 564 BasicBlock *Header = currentLoop->getHeader(); 565 TerminatorInst *HeaderTerm = Header->getTerminator(); 566 LLVMContext &Context = Header->getContext(); 567 568 BasicBlock *LoopExitBB = 0; 569 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) { 570 // If the header block doesn't end with a conditional branch on Cond, we 571 // can't handle it. 572 if (!BI->isConditional() || BI->getCondition() != Cond) 573 return false; 574 575 // Check to see if a successor of the branch is guaranteed to 576 // exit through a unique exit block without having any 577 // side-effects. If so, determine the value of Cond that causes it to do 578 // this. 579 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 580 BI->getSuccessor(0)))) { 581 if (Val) *Val = ConstantInt::getTrue(Context); 582 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 583 BI->getSuccessor(1)))) { 584 if (Val) *Val = ConstantInt::getFalse(Context); 585 } 586 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) { 587 // If this isn't a switch on Cond, we can't handle it. 588 if (SI->getCondition() != Cond) return false; 589 590 // Check to see if a successor of the switch is guaranteed to go to the 591 // latch block or exit through a one exit block without having any 592 // side-effects. If so, determine the value of Cond that causes it to do 593 // this. 594 // Note that we can't trivially unswitch on the default case or 595 // on already unswitched cases. 596 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 597 i != e; ++i) { 598 BasicBlock* LoopExitCandidate; 599 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop, 600 i.getCaseSuccessor()))) { 601 // Okay, we found a trivial case, remember the value that is trivial. 602 ConstantInt* CaseVal = i.getCaseValue(); 603 604 // Check that it was not unswitched before, since already unswitched 605 // trivial vals are looks trivial too. 606 if (BranchesInfo.isUnswitched(SI, CaseVal)) 607 continue; 608 LoopExitBB = LoopExitCandidate; 609 if (Val) *Val = CaseVal; 610 break; 611 } 612 } 613 } 614 615 // If we didn't find a single unique LoopExit block, or if the loop exit block 616 // contains phi nodes, this isn't trivial. 617 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin())) 618 return false; // Can't handle this. 619 620 if (LoopExit) *LoopExit = LoopExitBB; 621 622 // We already know that nothing uses any scalar values defined inside of this 623 // loop. As such, we just have to check to see if this loop will execute any 624 // side-effecting instructions (e.g. stores, calls, volatile loads) in the 625 // part of the loop that the code *would* execute. We already checked the 626 // tail, check the header now. 627 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I) 628 if (I->mayHaveSideEffects()) 629 return false; 630 return true; 631 } 632 633 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when 634 /// LoopCond == Val to simplify the loop. If we decide that this is profitable, 635 /// unswitch the loop, reprocess the pieces, then return true. 636 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) { 637 Function *F = loopHeader->getParent(); 638 Constant *CondVal = 0; 639 BasicBlock *ExitBlock = 0; 640 641 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) { 642 // If the condition is trivial, always unswitch. There is no code growth 643 // for this case. 644 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock); 645 return true; 646 } 647 648 // Check to see if it would be profitable to unswitch current loop. 649 650 // Do not do non-trivial unswitch while optimizing for size. 651 if (OptimizeForSize || 652 F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 653 Attribute::OptimizeForSize)) 654 return false; 655 656 UnswitchNontrivialCondition(LoopCond, Val, currentLoop); 657 return true; 658 } 659 660 /// CloneLoop - Recursively clone the specified loop and all of its children, 661 /// mapping the blocks with the specified map. 662 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, 663 LoopInfo *LI, LPPassManager *LPM) { 664 Loop *New = new Loop(); 665 LPM->insertLoop(New, PL); 666 667 // Add all of the blocks in L to the new loop. 668 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 669 I != E; ++I) 670 if (LI->getLoopFor(*I) == L) 671 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase()); 672 673 // Add all of the subloops to the new loop. 674 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 675 CloneLoop(*I, New, VM, LI, LPM); 676 677 return New; 678 } 679 680 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values 681 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the 682 /// code immediately before InsertPt. 683 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val, 684 BasicBlock *TrueDest, 685 BasicBlock *FalseDest, 686 Instruction *InsertPt) { 687 // Insert a conditional branch on LIC to the two preheaders. The original 688 // code is the true version and the new code is the false version. 689 Value *BranchVal = LIC; 690 if (!isa<ConstantInt>(Val) || 691 Val->getType() != Type::getInt1Ty(LIC->getContext())) 692 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val); 693 else if (Val != ConstantInt::getTrue(Val->getContext())) 694 // We want to enter the new loop when the condition is true. 695 std::swap(TrueDest, FalseDest); 696 697 // Insert the new branch. 698 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt); 699 700 // If either edge is critical, split it. This helps preserve LoopSimplify 701 // form for enclosing loops. 702 SplitCriticalEdge(BI, 0, this, false, false, true); 703 SplitCriticalEdge(BI, 1, this, false, false, true); 704 } 705 706 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable 707 /// condition in it (a cond branch from its header block to its latch block, 708 /// where the path through the loop that doesn't execute its body has no 709 /// side-effects), unswitch it. This doesn't involve any code duplication, just 710 /// moving the conditional branch outside of the loop and updating loop info. 711 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 712 Constant *Val, 713 BasicBlock *ExitBlock) { 714 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %" 715 << loopHeader->getName() << " [" << L->getBlocks().size() 716 << " blocks] in Function " << L->getHeader()->getParent()->getName() 717 << " on cond: " << *Val << " == " << *Cond << "\n"); 718 719 // First step, split the preheader, so that we know that there is a safe place 720 // to insert the conditional branch. We will change loopPreheader to have a 721 // conditional branch on Cond. 722 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this); 723 724 // Now that we have a place to insert the conditional branch, create a place 725 // to branch to: this is the exit block out of the loop that we should 726 // short-circuit to. 727 728 // Split this block now, so that the loop maintains its exit block, and so 729 // that the jump from the preheader can execute the contents of the exit block 730 // without actually branching to it (the exit block should be dominated by the 731 // loop header, not the preheader). 732 assert(!L->contains(ExitBlock) && "Exit block is in the loop?"); 733 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this); 734 735 // Okay, now we have a position to branch from and a position to branch to, 736 // insert the new conditional branch. 737 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, 738 loopPreheader->getTerminator()); 739 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L); 740 loopPreheader->getTerminator()->eraseFromParent(); 741 742 // We need to reprocess this loop, it could be unswitched again. 743 redoLoop = true; 744 745 // Now that we know that the loop is never entered when this condition is a 746 // particular value, rewrite the loop with this info. We know that this will 747 // at least eliminate the old branch. 748 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false); 749 ++NumTrivial; 750 } 751 752 /// SplitExitEdges - Split all of the edges from inside the loop to their exit 753 /// blocks. Update the appropriate Phi nodes as we do so. 754 void LoopUnswitch::SplitExitEdges(Loop *L, 755 const SmallVector<BasicBlock *, 8> &ExitBlocks){ 756 757 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 758 BasicBlock *ExitBlock = ExitBlocks[i]; 759 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock), 760 pred_end(ExitBlock)); 761 762 // Although SplitBlockPredecessors doesn't preserve loop-simplify in 763 // general, if we call it on all predecessors of all exits then it does. 764 if (!ExitBlock->isLandingPad()) { 765 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", this); 766 } else { 767 SmallVector<BasicBlock*, 2> NewBBs; 768 SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcssa", 769 this, NewBBs); 770 } 771 } 772 } 773 774 /// UnswitchNontrivialCondition - We determined that the loop is profitable 775 /// to unswitch when LIC equal Val. Split it into loop versions and test the 776 /// condition outside of either loop. Return the loops created as Out1/Out2. 777 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val, 778 Loop *L) { 779 Function *F = loopHeader->getParent(); 780 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %" 781 << loopHeader->getName() << " [" << L->getBlocks().size() 782 << " blocks] in Function " << F->getName() 783 << " when '" << *Val << "' == " << *LIC << "\n"); 784 785 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>()) 786 SE->forgetLoop(L); 787 788 LoopBlocks.clear(); 789 NewBlocks.clear(); 790 791 // First step, split the preheader and exit blocks, and add these blocks to 792 // the LoopBlocks list. 793 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this); 794 LoopBlocks.push_back(NewPreheader); 795 796 // We want the loop to come after the preheader, but before the exit blocks. 797 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end()); 798 799 SmallVector<BasicBlock*, 8> ExitBlocks; 800 L->getUniqueExitBlocks(ExitBlocks); 801 802 // Split all of the edges from inside the loop to their exit blocks. Update 803 // the appropriate Phi nodes as we do so. 804 SplitExitEdges(L, ExitBlocks); 805 806 // The exit blocks may have been changed due to edge splitting, recompute. 807 ExitBlocks.clear(); 808 L->getUniqueExitBlocks(ExitBlocks); 809 810 // Add exit blocks to the loop blocks. 811 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end()); 812 813 // Next step, clone all of the basic blocks that make up the loop (including 814 // the loop preheader and exit blocks), keeping track of the mapping between 815 // the instructions and blocks. 816 NewBlocks.reserve(LoopBlocks.size()); 817 ValueToValueMapTy VMap; 818 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) { 819 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F); 820 821 NewBlocks.push_back(NewBB); 822 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping. 823 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L); 824 } 825 826 // Splice the newly inserted blocks into the function right before the 827 // original preheader. 828 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(), 829 NewBlocks[0], F->end()); 830 831 // Now we create the new Loop object for the versioned loop. 832 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM); 833 834 // Recalculate unswitching quota, inherit simplified switches info for NewBB, 835 // Probably clone more loop-unswitch related loop properties. 836 BranchesInfo.cloneData(NewLoop, L, VMap); 837 838 Loop *ParentLoop = L->getParentLoop(); 839 if (ParentLoop) { 840 // Make sure to add the cloned preheader and exit blocks to the parent loop 841 // as well. 842 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase()); 843 } 844 845 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 846 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]); 847 // The new exit block should be in the same loop as the old one. 848 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i])) 849 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase()); 850 851 assert(NewExit->getTerminator()->getNumSuccessors() == 1 && 852 "Exit block should have been split to have one successor!"); 853 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0); 854 855 // If the successor of the exit block had PHI nodes, add an entry for 856 // NewExit. 857 PHINode *PN; 858 for (BasicBlock::iterator I = ExitSucc->begin(); isa<PHINode>(I); ++I) { 859 PN = cast<PHINode>(I); 860 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]); 861 ValueToValueMapTy::iterator It = VMap.find(V); 862 if (It != VMap.end()) V = It->second; 863 PN->addIncoming(V, NewExit); 864 } 865 866 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) { 867 PN = PHINode::Create(LPad->getType(), 0, "", 868 ExitSucc->getFirstInsertionPt()); 869 870 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc); 871 I != E; ++I) { 872 BasicBlock *BB = *I; 873 LandingPadInst *LPI = BB->getLandingPadInst(); 874 LPI->replaceAllUsesWith(PN); 875 PN->addIncoming(LPI, BB); 876 } 877 } 878 } 879 880 // Rewrite the code to refer to itself. 881 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) 882 for (BasicBlock::iterator I = NewBlocks[i]->begin(), 883 E = NewBlocks[i]->end(); I != E; ++I) 884 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries); 885 886 // Rewrite the original preheader to select between versions of the loop. 887 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator()); 888 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] && 889 "Preheader splitting did not work correctly!"); 890 891 // Emit the new branch that selects between the two versions of this loop. 892 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR); 893 LPM->deleteSimpleAnalysisValue(OldBR, L); 894 OldBR->eraseFromParent(); 895 896 LoopProcessWorklist.push_back(NewLoop); 897 redoLoop = true; 898 899 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody 900 // deletes the instruction (for example by simplifying a PHI that feeds into 901 // the condition that we're unswitching on), we don't rewrite the second 902 // iteration. 903 WeakVH LICHandle(LIC); 904 905 // Now we rewrite the original code to know that the condition is true and the 906 // new code to know that the condition is false. 907 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false); 908 909 // It's possible that simplifying one loop could cause the other to be 910 // changed to another value or a constant. If its a constant, don't simplify 911 // it. 912 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop && 913 LICHandle && !isa<Constant>(LICHandle)) 914 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true); 915 } 916 917 /// RemoveFromWorklist - Remove all instances of I from the worklist vector 918 /// specified. 919 static void RemoveFromWorklist(Instruction *I, 920 std::vector<Instruction*> &Worklist) { 921 922 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I), 923 Worklist.end()); 924 } 925 926 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the 927 /// program, replacing all uses with V and update the worklist. 928 static void ReplaceUsesOfWith(Instruction *I, Value *V, 929 std::vector<Instruction*> &Worklist, 930 Loop *L, LPPassManager *LPM) { 931 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I); 932 933 // Add uses to the worklist, which may be dead now. 934 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 935 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i))) 936 Worklist.push_back(Use); 937 938 // Add users to the worklist which may be simplified now. 939 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 940 UI != E; ++UI) 941 Worklist.push_back(cast<Instruction>(*UI)); 942 LPM->deleteSimpleAnalysisValue(I, L); 943 RemoveFromWorklist(I, Worklist); 944 I->replaceAllUsesWith(V); 945 I->eraseFromParent(); 946 ++NumSimplify; 947 } 948 949 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop 950 /// information, and remove any dead successors it has. 951 /// 952 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB, 953 std::vector<Instruction*> &Worklist, 954 Loop *L) { 955 if (pred_begin(BB) != pred_end(BB)) { 956 // This block isn't dead, since an edge to BB was just removed, see if there 957 // are any easy simplifications we can do now. 958 if (BasicBlock *Pred = BB->getSinglePredecessor()) { 959 // If it has one pred, fold phi nodes in BB. 960 while (isa<PHINode>(BB->begin())) 961 ReplaceUsesOfWith(BB->begin(), 962 cast<PHINode>(BB->begin())->getIncomingValue(0), 963 Worklist, L, LPM); 964 965 // If this is the header of a loop and the only pred is the latch, we now 966 // have an unreachable loop. 967 if (Loop *L = LI->getLoopFor(BB)) 968 if (loopHeader == BB && L->contains(Pred)) { 969 // Remove the branch from the latch to the header block, this makes 970 // the header dead, which will make the latch dead (because the header 971 // dominates the latch). 972 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L); 973 Pred->getTerminator()->eraseFromParent(); 974 new UnreachableInst(BB->getContext(), Pred); 975 976 // The loop is now broken, remove it from LI. 977 RemoveLoopFromHierarchy(L); 978 979 // Reprocess the header, which now IS dead. 980 RemoveBlockIfDead(BB, Worklist, L); 981 return; 982 } 983 984 // If pred ends in a uncond branch, add uncond branch to worklist so that 985 // the two blocks will get merged. 986 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) 987 if (BI->isUnconditional()) 988 Worklist.push_back(BI); 989 } 990 return; 991 } 992 993 DEBUG(dbgs() << "Nuking dead block: " << *BB); 994 995 // Remove the instructions in the basic block from the worklist. 996 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 997 RemoveFromWorklist(I, Worklist); 998 999 // Anything that uses the instructions in this basic block should have their 1000 // uses replaced with undefs. 1001 // If I is not void type then replaceAllUsesWith undef. 1002 // This allows ValueHandlers and custom metadata to adjust itself. 1003 if (!I->getType()->isVoidTy()) 1004 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1005 } 1006 1007 // If this is the edge to the header block for a loop, remove the loop and 1008 // promote all subloops. 1009 if (Loop *BBLoop = LI->getLoopFor(BB)) { 1010 if (BBLoop->getLoopLatch() == BB) { 1011 RemoveLoopFromHierarchy(BBLoop); 1012 if (currentLoop == BBLoop) { 1013 currentLoop = 0; 1014 redoLoop = false; 1015 } 1016 } 1017 } 1018 1019 // Remove the block from the loop info, which removes it from any loops it 1020 // was in. 1021 LI->removeBlock(BB); 1022 1023 1024 // Remove phi node entries in successors for this block. 1025 TerminatorInst *TI = BB->getTerminator(); 1026 SmallVector<BasicBlock*, 4> Succs; 1027 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 1028 Succs.push_back(TI->getSuccessor(i)); 1029 TI->getSuccessor(i)->removePredecessor(BB); 1030 } 1031 1032 // Unique the successors, remove anything with multiple uses. 1033 array_pod_sort(Succs.begin(), Succs.end()); 1034 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end()); 1035 1036 // Remove the basic block, including all of the instructions contained in it. 1037 LPM->deleteSimpleAnalysisValue(BB, L); 1038 BB->eraseFromParent(); 1039 // Remove successor blocks here that are not dead, so that we know we only 1040 // have dead blocks in this list. Nondead blocks have a way of becoming dead, 1041 // then getting removed before we revisit them, which is badness. 1042 // 1043 for (unsigned i = 0; i != Succs.size(); ++i) 1044 if (pred_begin(Succs[i]) != pred_end(Succs[i])) { 1045 // One exception is loop headers. If this block was the preheader for a 1046 // loop, then we DO want to visit the loop so the loop gets deleted. 1047 // We know that if the successor is a loop header, that this loop had to 1048 // be the preheader: the case where this was the latch block was handled 1049 // above and headers can only have two predecessors. 1050 if (!LI->isLoopHeader(Succs[i])) { 1051 Succs.erase(Succs.begin()+i); 1052 --i; 1053 } 1054 } 1055 1056 for (unsigned i = 0, e = Succs.size(); i != e; ++i) 1057 RemoveBlockIfDead(Succs[i], Worklist, L); 1058 } 1059 1060 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has 1061 /// become unwrapped, either because the backedge was deleted, or because the 1062 /// edge into the header was removed. If the edge into the header from the 1063 /// latch block was removed, the loop is unwrapped but subloops are still alive, 1064 /// so they just reparent loops. If the loops are actually dead, they will be 1065 /// removed later. 1066 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) { 1067 LPM->deleteLoopFromQueue(L); 1068 RemoveLoopFromWorklist(L); 1069 } 1070 1071 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has 1072 // the value specified by Val in the specified loop, or we know it does NOT have 1073 // that value. Rewrite any uses of LIC or of properties correlated to it. 1074 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, 1075 Constant *Val, 1076 bool IsEqual) { 1077 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?"); 1078 1079 // FIXME: Support correlated properties, like: 1080 // for (...) 1081 // if (li1 < li2) 1082 // ... 1083 // if (li1 > li2) 1084 // ... 1085 1086 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches, 1087 // selects, switches. 1088 std::vector<Instruction*> Worklist; 1089 LLVMContext &Context = Val->getContext(); 1090 1091 1092 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC 1093 // in the loop with the appropriate one directly. 1094 if (IsEqual || (isa<ConstantInt>(Val) && 1095 Val->getType()->isIntegerTy(1))) { 1096 Value *Replacement; 1097 if (IsEqual) 1098 Replacement = Val; 1099 else 1100 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()), 1101 !cast<ConstantInt>(Val)->getZExtValue()); 1102 1103 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end(); 1104 UI != E; ++UI) { 1105 Instruction *U = dyn_cast<Instruction>(*UI); 1106 if (!U || !L->contains(U)) 1107 continue; 1108 Worklist.push_back(U); 1109 } 1110 1111 for (std::vector<Instruction*>::iterator UI = Worklist.begin(); 1112 UI != Worklist.end(); ++UI) 1113 (*UI)->replaceUsesOfWith(LIC, Replacement); 1114 1115 SimplifyCode(Worklist, L); 1116 return; 1117 } 1118 1119 // Otherwise, we don't know the precise value of LIC, but we do know that it 1120 // is certainly NOT "Val". As such, simplify any uses in the loop that we 1121 // can. This case occurs when we unswitch switch statements. 1122 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end(); 1123 UI != E; ++UI) { 1124 Instruction *U = dyn_cast<Instruction>(*UI); 1125 if (!U || !L->contains(U)) 1126 continue; 1127 1128 Worklist.push_back(U); 1129 1130 // TODO: We could do other simplifications, for example, turning 1131 // 'icmp eq LIC, Val' -> false. 1132 1133 // If we know that LIC is not Val, use this info to simplify code. 1134 SwitchInst *SI = dyn_cast<SwitchInst>(U); 1135 if (SI == 0 || !isa<ConstantInt>(Val)) continue; 1136 1137 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val)); 1138 // Default case is live for multiple values. 1139 if (DeadCase == SI->case_default()) continue; 1140 1141 // Found a dead case value. Don't remove PHI nodes in the 1142 // successor if they become single-entry, those PHI nodes may 1143 // be in the Users list. 1144 1145 BasicBlock *Switch = SI->getParent(); 1146 BasicBlock *SISucc = DeadCase.getCaseSuccessor(); 1147 BasicBlock *Latch = L->getLoopLatch(); 1148 1149 BranchesInfo.setUnswitched(SI, Val); 1150 1151 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical. 1152 // If the DeadCase successor dominates the loop latch, then the 1153 // transformation isn't safe since it will delete the sole predecessor edge 1154 // to the latch. 1155 if (Latch && DT->dominates(SISucc, Latch)) 1156 continue; 1157 1158 // FIXME: This is a hack. We need to keep the successor around 1159 // and hooked up so as to preserve the loop structure, because 1160 // trying to update it is complicated. So instead we preserve the 1161 // loop structure and put the block on a dead code path. 1162 SplitEdge(Switch, SISucc, this); 1163 // Compute the successors instead of relying on the return value 1164 // of SplitEdge, since it may have split the switch successor 1165 // after PHI nodes. 1166 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor(); 1167 BasicBlock *OldSISucc = *succ_begin(NewSISucc); 1168 // Create an "unreachable" destination. 1169 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable", 1170 Switch->getParent(), 1171 OldSISucc); 1172 new UnreachableInst(Context, Abort); 1173 // Force the new case destination to branch to the "unreachable" 1174 // block while maintaining a (dead) CFG edge to the old block. 1175 NewSISucc->getTerminator()->eraseFromParent(); 1176 BranchInst::Create(Abort, OldSISucc, 1177 ConstantInt::getTrue(Context), NewSISucc); 1178 // Release the PHI operands for this edge. 1179 for (BasicBlock::iterator II = NewSISucc->begin(); 1180 PHINode *PN = dyn_cast<PHINode>(II); ++II) 1181 PN->setIncomingValue(PN->getBasicBlockIndex(Switch), 1182 UndefValue::get(PN->getType())); 1183 // Tell the domtree about the new block. We don't fully update the 1184 // domtree here -- instead we force it to do a full recomputation 1185 // after the pass is complete -- but we do need to inform it of 1186 // new blocks. 1187 if (DT) 1188 DT->addNewBlock(Abort, NewSISucc); 1189 } 1190 1191 SimplifyCode(Worklist, L); 1192 } 1193 1194 /// SimplifyCode - Okay, now that we have simplified some instructions in the 1195 /// loop, walk over it and constant prop, dce, and fold control flow where 1196 /// possible. Note that this is effectively a very simple loop-structure-aware 1197 /// optimizer. During processing of this loop, L could very well be deleted, so 1198 /// it must not be used. 1199 /// 1200 /// FIXME: When the loop optimizer is more mature, separate this out to a new 1201 /// pass. 1202 /// 1203 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) { 1204 while (!Worklist.empty()) { 1205 Instruction *I = Worklist.back(); 1206 Worklist.pop_back(); 1207 1208 // Simple DCE. 1209 if (isInstructionTriviallyDead(I)) { 1210 DEBUG(dbgs() << "Remove dead instruction '" << *I); 1211 1212 // Add uses to the worklist, which may be dead now. 1213 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1214 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i))) 1215 Worklist.push_back(Use); 1216 LPM->deleteSimpleAnalysisValue(I, L); 1217 RemoveFromWorklist(I, Worklist); 1218 I->eraseFromParent(); 1219 ++NumSimplify; 1220 continue; 1221 } 1222 1223 // See if instruction simplification can hack this up. This is common for 1224 // things like "select false, X, Y" after unswitching made the condition be 1225 // 'false'. TODO: update the domtree properly so we can pass it here. 1226 if (Value *V = SimplifyInstruction(I)) 1227 if (LI->replacementPreservesLCSSAForm(I, V)) { 1228 ReplaceUsesOfWith(I, V, Worklist, L, LPM); 1229 continue; 1230 } 1231 1232 // Special case hacks that appear commonly in unswitched code. 1233 if (BranchInst *BI = dyn_cast<BranchInst>(I)) { 1234 if (BI->isUnconditional()) { 1235 // If BI's parent is the only pred of the successor, fold the two blocks 1236 // together. 1237 BasicBlock *Pred = BI->getParent(); 1238 BasicBlock *Succ = BI->getSuccessor(0); 1239 BasicBlock *SinglePred = Succ->getSinglePredecessor(); 1240 if (!SinglePred) continue; // Nothing to do. 1241 assert(SinglePred == Pred && "CFG broken"); 1242 1243 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- " 1244 << Succ->getName() << "\n"); 1245 1246 // Resolve any single entry PHI nodes in Succ. 1247 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin())) 1248 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM); 1249 1250 // If Succ has any successors with PHI nodes, update them to have 1251 // entries coming from Pred instead of Succ. 1252 Succ->replaceAllUsesWith(Pred); 1253 1254 // Move all of the successor contents from Succ to Pred. 1255 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(), 1256 Succ->end()); 1257 LPM->deleteSimpleAnalysisValue(BI, L); 1258 BI->eraseFromParent(); 1259 RemoveFromWorklist(BI, Worklist); 1260 1261 // Remove Succ from the loop tree. 1262 LI->removeBlock(Succ); 1263 LPM->deleteSimpleAnalysisValue(Succ, L); 1264 Succ->eraseFromParent(); 1265 ++NumSimplify; 1266 continue; 1267 } 1268 1269 if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){ 1270 // Conditional branch. Turn it into an unconditional branch, then 1271 // remove dead blocks. 1272 continue; // FIXME: Enable. 1273 1274 DEBUG(dbgs() << "Folded branch: " << *BI); 1275 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue()); 1276 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue()); 1277 DeadSucc->removePredecessor(BI->getParent(), true); 1278 Worklist.push_back(BranchInst::Create(LiveSucc, BI)); 1279 LPM->deleteSimpleAnalysisValue(BI, L); 1280 BI->eraseFromParent(); 1281 RemoveFromWorklist(BI, Worklist); 1282 ++NumSimplify; 1283 1284 RemoveBlockIfDead(DeadSucc, Worklist, L); 1285 } 1286 continue; 1287 } 1288 } 1289 } 1290