1 //===-- StructurizeCFG.cpp ------------------------------------------------===// 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 #include "llvm/Transforms/Scalar.h" 11 #include "llvm/ADT/MapVector.h" 12 #include "llvm/ADT/PostOrderIterator.h" 13 #include "llvm/ADT/SCCIterator.h" 14 #include "llvm/Analysis/DivergenceAnalysis.h" 15 #include "llvm/Analysis/LoopInfo.h" 16 #include "llvm/Analysis/RegionInfo.h" 17 #include "llvm/Analysis/RegionIterator.h" 18 #include "llvm/Analysis/RegionPass.h" 19 #include "llvm/IR/Module.h" 20 #include "llvm/IR/PatternMatch.h" 21 #include "llvm/Support/Debug.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include "llvm/Transforms/Utils/SSAUpdater.h" 24 25 using namespace llvm; 26 using namespace llvm::PatternMatch; 27 28 #define DEBUG_TYPE "structurizecfg" 29 30 namespace { 31 32 // Definition of the complex types used in this pass. 33 34 typedef std::pair<BasicBlock *, Value *> BBValuePair; 35 36 typedef SmallVector<RegionNode*, 8> RNVector; 37 typedef SmallVector<BasicBlock*, 8> BBVector; 38 typedef SmallVector<BranchInst*, 8> BranchVector; 39 typedef SmallVector<BBValuePair, 2> BBValueVector; 40 41 typedef SmallPtrSet<BasicBlock *, 8> BBSet; 42 43 typedef MapVector<PHINode *, BBValueVector> PhiMap; 44 typedef MapVector<BasicBlock *, BBVector> BB2BBVecMap; 45 46 typedef DenseMap<DomTreeNode *, unsigned> DTN2UnsignedMap; 47 typedef DenseMap<BasicBlock *, PhiMap> BBPhiMap; 48 typedef DenseMap<BasicBlock *, Value *> BBPredicates; 49 typedef DenseMap<BasicBlock *, BBPredicates> PredMap; 50 typedef DenseMap<BasicBlock *, BasicBlock*> BB2BBMap; 51 52 // The name for newly created blocks. 53 54 static const char *const FlowBlockName = "Flow"; 55 56 /// @brief Find the nearest common dominator for multiple BasicBlocks 57 /// 58 /// Helper class for StructurizeCFG 59 /// TODO: Maybe move into common code 60 class NearestCommonDominator { 61 DominatorTree *DT; 62 63 DTN2UnsignedMap IndexMap; 64 65 BasicBlock *Result; 66 unsigned ResultIndex; 67 bool ExplicitMentioned; 68 69 public: 70 /// \brief Start a new query 71 NearestCommonDominator(DominatorTree *DomTree) { 72 DT = DomTree; 73 Result = nullptr; 74 } 75 76 /// \brief Add BB to the resulting dominator 77 void addBlock(BasicBlock *BB, bool Remember = true) { 78 DomTreeNode *Node = DT->getNode(BB); 79 80 if (!Result) { 81 unsigned Numbering = 0; 82 for (;Node;Node = Node->getIDom()) 83 IndexMap[Node] = ++Numbering; 84 Result = BB; 85 ResultIndex = 1; 86 ExplicitMentioned = Remember; 87 return; 88 } 89 90 for (;Node;Node = Node->getIDom()) 91 if (IndexMap.count(Node)) 92 break; 93 else 94 IndexMap[Node] = 0; 95 96 assert(Node && "Dominator tree invalid!"); 97 98 unsigned Numbering = IndexMap[Node]; 99 if (Numbering > ResultIndex) { 100 Result = Node->getBlock(); 101 ResultIndex = Numbering; 102 ExplicitMentioned = Remember && (Result == BB); 103 } else if (Numbering == ResultIndex) { 104 ExplicitMentioned |= Remember; 105 } 106 } 107 108 /// \brief Is "Result" one of the BBs added with "Remember" = True? 109 bool wasResultExplicitMentioned() { 110 return ExplicitMentioned; 111 } 112 113 /// \brief Get the query result 114 BasicBlock *getResult() { 115 return Result; 116 } 117 }; 118 119 /// @brief Transforms the control flow graph on one single entry/exit region 120 /// at a time. 121 /// 122 /// After the transform all "If"/"Then"/"Else" style control flow looks like 123 /// this: 124 /// 125 /// \verbatim 126 /// 1 127 /// || 128 /// | | 129 /// 2 | 130 /// | / 131 /// |/ 132 /// 3 133 /// || Where: 134 /// | | 1 = "If" block, calculates the condition 135 /// 4 | 2 = "Then" subregion, runs if the condition is true 136 /// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow 137 /// |/ 4 = "Else" optional subregion, runs if the condition is false 138 /// 5 5 = "End" block, also rejoins the control flow 139 /// \endverbatim 140 /// 141 /// Control flow is expressed as a branch where the true exit goes into the 142 /// "Then"/"Else" region, while the false exit skips the region 143 /// The condition for the optional "Else" region is expressed as a PHI node. 144 /// The incomming values of the PHI node are true for the "If" edge and false 145 /// for the "Then" edge. 146 /// 147 /// Additionally to that even complicated loops look like this: 148 /// 149 /// \verbatim 150 /// 1 151 /// || 152 /// | | 153 /// 2 ^ Where: 154 /// | / 1 = "Entry" block 155 /// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block 156 /// 3 3 = "Flow" block, with back edge to entry block 157 /// | 158 /// \endverbatim 159 /// 160 /// The back edge of the "Flow" block is always on the false side of the branch 161 /// while the true side continues the general flow. So the loop condition 162 /// consist of a network of PHI nodes where the true incoming values expresses 163 /// breaks and the false values expresses continue states. 164 class StructurizeCFG : public RegionPass { 165 bool SkipUniformRegions; 166 DivergenceAnalysis *DA; 167 168 Type *Boolean; 169 ConstantInt *BoolTrue; 170 ConstantInt *BoolFalse; 171 UndefValue *BoolUndef; 172 173 Function *Func; 174 Region *ParentRegion; 175 176 DominatorTree *DT; 177 LoopInfo *LI; 178 179 RNVector Order; 180 BBSet Visited; 181 182 BBPhiMap DeletedPhis; 183 BB2BBVecMap AddedPhis; 184 185 PredMap Predicates; 186 BranchVector Conditions; 187 188 BB2BBMap Loops; 189 PredMap LoopPreds; 190 BranchVector LoopConds; 191 192 RegionNode *PrevNode; 193 194 void orderNodes(); 195 196 void analyzeLoops(RegionNode *N); 197 198 Value *invert(Value *Condition); 199 200 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert); 201 202 void gatherPredicates(RegionNode *N); 203 204 void collectInfos(); 205 206 void insertConditions(bool Loops); 207 208 void delPhiValues(BasicBlock *From, BasicBlock *To); 209 210 void addPhiValues(BasicBlock *From, BasicBlock *To); 211 212 void setPhiValues(); 213 214 void killTerminator(BasicBlock *BB); 215 216 void changeExit(RegionNode *Node, BasicBlock *NewExit, 217 bool IncludeDominator); 218 219 BasicBlock *getNextFlow(BasicBlock *Dominator); 220 221 BasicBlock *needPrefix(bool NeedEmpty); 222 223 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed); 224 225 void setPrevNode(BasicBlock *BB); 226 227 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node); 228 229 bool isPredictableTrue(RegionNode *Node); 230 231 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd); 232 233 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd); 234 235 void createFlow(); 236 237 void rebuildSSA(); 238 239 bool hasOnlyUniformBranches(const Region *R); 240 241 public: 242 static char ID; 243 244 StructurizeCFG() : 245 RegionPass(ID) { 246 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry()); 247 } 248 249 StructurizeCFG(bool SkipUniformRegions) : 250 RegionPass(ID), SkipUniformRegions(SkipUniformRegions) { 251 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry()); 252 } 253 254 using Pass::doInitialization; 255 bool doInitialization(Region *R, RGPassManager &RGM) override; 256 257 bool runOnRegion(Region *R, RGPassManager &RGM) override; 258 259 const char *getPassName() const override { 260 return "Structurize control flow"; 261 } 262 263 void getAnalysisUsage(AnalysisUsage &AU) const override { 264 if (SkipUniformRegions) 265 AU.addRequired<DivergenceAnalysis>(); 266 AU.addRequiredID(LowerSwitchID); 267 AU.addRequired<DominatorTreeWrapperPass>(); 268 AU.addRequired<LoopInfoWrapperPass>(); 269 AU.addPreserved<DominatorTreeWrapperPass>(); 270 RegionPass::getAnalysisUsage(AU); 271 } 272 }; 273 274 } // end anonymous namespace 275 276 char StructurizeCFG::ID = 0; 277 278 INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG", 279 false, false) 280 INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis) 281 INITIALIZE_PASS_DEPENDENCY(LowerSwitch) 282 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 283 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass) 284 INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG", 285 false, false) 286 287 /// \brief Initialize the types and constants used in the pass 288 bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) { 289 LLVMContext &Context = R->getEntry()->getContext(); 290 291 Boolean = Type::getInt1Ty(Context); 292 BoolTrue = ConstantInt::getTrue(Context); 293 BoolFalse = ConstantInt::getFalse(Context); 294 BoolUndef = UndefValue::get(Boolean); 295 296 return false; 297 } 298 299 /// \brief Build up the general order of nodes 300 void StructurizeCFG::orderNodes() { 301 RNVector TempOrder; 302 ReversePostOrderTraversal<Region*> RPOT(ParentRegion); 303 TempOrder.append(RPOT.begin(), RPOT.end()); 304 305 std::map<Loop*, unsigned> LoopBlocks; 306 307 308 // The reverse post-order traversal of the list gives us an ordering close 309 // to what we want. The only problem with it is that sometimes backedges 310 // for outer loops will be visited before backedges for inner loops. 311 for (RegionNode *RN : TempOrder) { 312 BasicBlock *BB = RN->getEntry(); 313 Loop *Loop = LI->getLoopFor(BB); 314 if (!LoopBlocks.count(Loop)) { 315 LoopBlocks[Loop] = 1; 316 continue; 317 } 318 LoopBlocks[Loop]++; 319 } 320 321 unsigned CurrentLoopDepth = 0; 322 Loop *CurrentLoop = nullptr; 323 BBSet TempVisited; 324 for (RNVector::iterator I = TempOrder.begin(), E = TempOrder.end(); I != E; ++I) { 325 BasicBlock *BB = (*I)->getEntry(); 326 unsigned LoopDepth = LI->getLoopDepth(BB); 327 328 if (std::find(Order.begin(), Order.end(), *I) != Order.end()) 329 continue; 330 331 if (LoopDepth < CurrentLoopDepth) { 332 // Make sure we have visited all blocks in this loop before moving back to 333 // the outer loop. 334 335 RNVector::iterator LoopI = I; 336 while(LoopBlocks[CurrentLoop]) { 337 LoopI++; 338 BasicBlock *LoopBB = (*LoopI)->getEntry(); 339 if (LI->getLoopFor(LoopBB) == CurrentLoop) { 340 LoopBlocks[CurrentLoop]--; 341 Order.push_back(*LoopI); 342 } 343 } 344 } 345 346 CurrentLoop = LI->getLoopFor(BB); 347 if (CurrentLoop) { 348 LoopBlocks[CurrentLoop]--; 349 } 350 351 CurrentLoopDepth = LoopDepth; 352 Order.push_back(*I); 353 } 354 355 // This pass originally used a post-order traversal and then operated on 356 // the list in reverse. Now that we are using a reverse post-order traversal 357 // rather than re-working the whole pass to operate on the list in order, 358 // we just reverse the list and continue to operate on it in reverse. 359 std::reverse(Order.begin(), Order.end()); 360 } 361 362 /// \brief Determine the end of the loops 363 void StructurizeCFG::analyzeLoops(RegionNode *N) { 364 if (N->isSubRegion()) { 365 // Test for exit as back edge 366 BasicBlock *Exit = N->getNodeAs<Region>()->getExit(); 367 if (Visited.count(Exit)) 368 Loops[Exit] = N->getEntry(); 369 370 } else { 371 // Test for sucessors as back edge 372 BasicBlock *BB = N->getNodeAs<BasicBlock>(); 373 BranchInst *Term = cast<BranchInst>(BB->getTerminator()); 374 375 for (BasicBlock *Succ : Term->successors()) 376 if (Visited.count(Succ)) 377 Loops[Succ] = BB; 378 } 379 } 380 381 /// \brief Invert the given condition 382 Value *StructurizeCFG::invert(Value *Condition) { 383 // First: Check if it's a constant 384 if (Condition == BoolTrue) 385 return BoolFalse; 386 387 if (Condition == BoolFalse) 388 return BoolTrue; 389 390 if (Condition == BoolUndef) 391 return BoolUndef; 392 393 // Second: If the condition is already inverted, return the original value 394 if (match(Condition, m_Not(m_Value(Condition)))) 395 return Condition; 396 397 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) { 398 // Third: Check all the users for an invert 399 BasicBlock *Parent = Inst->getParent(); 400 for (User *U : Condition->users()) 401 if (Instruction *I = dyn_cast<Instruction>(U)) 402 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition)))) 403 return I; 404 405 // Last option: Create a new instruction 406 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator()); 407 } 408 409 if (Argument *Arg = dyn_cast<Argument>(Condition)) { 410 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock(); 411 return BinaryOperator::CreateNot(Condition, 412 Arg->getName() + ".inv", 413 EntryBlock.getTerminator()); 414 } 415 416 llvm_unreachable("Unhandled condition to invert"); 417 } 418 419 /// \brief Build the condition for one edge 420 Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx, 421 bool Invert) { 422 Value *Cond = Invert ? BoolFalse : BoolTrue; 423 if (Term->isConditional()) { 424 Cond = Term->getCondition(); 425 426 if (Idx != (unsigned)Invert) 427 Cond = invert(Cond); 428 } 429 return Cond; 430 } 431 432 /// \brief Analyze the predecessors of each block and build up predicates 433 void StructurizeCFG::gatherPredicates(RegionNode *N) { 434 RegionInfo *RI = ParentRegion->getRegionInfo(); 435 BasicBlock *BB = N->getEntry(); 436 BBPredicates &Pred = Predicates[BB]; 437 BBPredicates &LPred = LoopPreds[BB]; 438 439 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 440 PI != PE; ++PI) { 441 442 // Ignore it if it's a branch from outside into our region entry 443 if (!ParentRegion->contains(*PI)) 444 continue; 445 446 Region *R = RI->getRegionFor(*PI); 447 if (R == ParentRegion) { 448 449 // It's a top level block in our region 450 BranchInst *Term = cast<BranchInst>((*PI)->getTerminator()); 451 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) { 452 BasicBlock *Succ = Term->getSuccessor(i); 453 if (Succ != BB) 454 continue; 455 456 if (Visited.count(*PI)) { 457 // Normal forward edge 458 if (Term->isConditional()) { 459 // Try to treat it like an ELSE block 460 BasicBlock *Other = Term->getSuccessor(!i); 461 if (Visited.count(Other) && !Loops.count(Other) && 462 !Pred.count(Other) && !Pred.count(*PI)) { 463 464 Pred[Other] = BoolFalse; 465 Pred[*PI] = BoolTrue; 466 continue; 467 } 468 } 469 Pred[*PI] = buildCondition(Term, i, false); 470 471 } else { 472 // Back edge 473 LPred[*PI] = buildCondition(Term, i, true); 474 } 475 } 476 477 } else { 478 479 // It's an exit from a sub region 480 while (R->getParent() != ParentRegion) 481 R = R->getParent(); 482 483 // Edge from inside a subregion to its entry, ignore it 484 if (*R == *N) 485 continue; 486 487 BasicBlock *Entry = R->getEntry(); 488 if (Visited.count(Entry)) 489 Pred[Entry] = BoolTrue; 490 else 491 LPred[Entry] = BoolFalse; 492 } 493 } 494 } 495 496 /// \brief Collect various loop and predicate infos 497 void StructurizeCFG::collectInfos() { 498 // Reset predicate 499 Predicates.clear(); 500 501 // and loop infos 502 Loops.clear(); 503 LoopPreds.clear(); 504 505 // Reset the visited nodes 506 Visited.clear(); 507 508 for (RNVector::reverse_iterator OI = Order.rbegin(), OE = Order.rend(); 509 OI != OE; ++OI) { 510 511 DEBUG(dbgs() << "Visiting: " << 512 ((*OI)->isSubRegion() ? "SubRegion with entry: " : "") << 513 (*OI)->getEntry()->getName() << " Loop Depth: " << LI->getLoopDepth((*OI)->getEntry()) << "\n"); 514 515 // Analyze all the conditions leading to a node 516 gatherPredicates(*OI); 517 518 // Remember that we've seen this node 519 Visited.insert((*OI)->getEntry()); 520 521 // Find the last back edges 522 analyzeLoops(*OI); 523 } 524 } 525 526 /// \brief Insert the missing branch conditions 527 void StructurizeCFG::insertConditions(bool Loops) { 528 BranchVector &Conds = Loops ? LoopConds : Conditions; 529 Value *Default = Loops ? BoolTrue : BoolFalse; 530 SSAUpdater PhiInserter; 531 532 for (BranchInst *Term : Conds) { 533 assert(Term->isConditional()); 534 535 BasicBlock *Parent = Term->getParent(); 536 BasicBlock *SuccTrue = Term->getSuccessor(0); 537 BasicBlock *SuccFalse = Term->getSuccessor(1); 538 539 PhiInserter.Initialize(Boolean, ""); 540 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default); 541 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default); 542 543 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue]; 544 545 NearestCommonDominator Dominator(DT); 546 Dominator.addBlock(Parent, false); 547 548 Value *ParentValue = nullptr; 549 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end(); 550 PI != PE; ++PI) { 551 552 if (PI->first == Parent) { 553 ParentValue = PI->second; 554 break; 555 } 556 PhiInserter.AddAvailableValue(PI->first, PI->second); 557 Dominator.addBlock(PI->first); 558 } 559 560 if (ParentValue) { 561 Term->setCondition(ParentValue); 562 } else { 563 if (!Dominator.wasResultExplicitMentioned()) 564 PhiInserter.AddAvailableValue(Dominator.getResult(), Default); 565 566 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent)); 567 } 568 } 569 } 570 571 /// \brief Remove all PHI values coming from "From" into "To" and remember 572 /// them in DeletedPhis 573 void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) { 574 PhiMap &Map = DeletedPhis[To]; 575 for (BasicBlock::iterator I = To->begin(), E = To->end(); 576 I != E && isa<PHINode>(*I);) { 577 578 PHINode &Phi = cast<PHINode>(*I++); 579 while (Phi.getBasicBlockIndex(From) != -1) { 580 Value *Deleted = Phi.removeIncomingValue(From, false); 581 Map[&Phi].push_back(std::make_pair(From, Deleted)); 582 } 583 } 584 } 585 586 /// \brief Add a dummy PHI value as soon as we knew the new predecessor 587 void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) { 588 for (BasicBlock::iterator I = To->begin(), E = To->end(); 589 I != E && isa<PHINode>(*I);) { 590 591 PHINode &Phi = cast<PHINode>(*I++); 592 Value *Undef = UndefValue::get(Phi.getType()); 593 Phi.addIncoming(Undef, From); 594 } 595 AddedPhis[To].push_back(From); 596 } 597 598 /// \brief Add the real PHI value as soon as everything is set up 599 void StructurizeCFG::setPhiValues() { 600 SSAUpdater Updater; 601 for (BB2BBVecMap::iterator AI = AddedPhis.begin(), AE = AddedPhis.end(); 602 AI != AE; ++AI) { 603 604 BasicBlock *To = AI->first; 605 BBVector &From = AI->second; 606 607 if (!DeletedPhis.count(To)) 608 continue; 609 610 PhiMap &Map = DeletedPhis[To]; 611 for (PhiMap::iterator PI = Map.begin(), PE = Map.end(); 612 PI != PE; ++PI) { 613 614 PHINode *Phi = PI->first; 615 Value *Undef = UndefValue::get(Phi->getType()); 616 Updater.Initialize(Phi->getType(), ""); 617 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef); 618 Updater.AddAvailableValue(To, Undef); 619 620 NearestCommonDominator Dominator(DT); 621 Dominator.addBlock(To, false); 622 for (BBValueVector::iterator VI = PI->second.begin(), 623 VE = PI->second.end(); VI != VE; ++VI) { 624 625 Updater.AddAvailableValue(VI->first, VI->second); 626 Dominator.addBlock(VI->first); 627 } 628 629 if (!Dominator.wasResultExplicitMentioned()) 630 Updater.AddAvailableValue(Dominator.getResult(), Undef); 631 632 for (BBVector::iterator FI = From.begin(), FE = From.end(); 633 FI != FE; ++FI) { 634 635 int Idx = Phi->getBasicBlockIndex(*FI); 636 assert(Idx != -1); 637 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(*FI)); 638 } 639 } 640 641 DeletedPhis.erase(To); 642 } 643 assert(DeletedPhis.empty()); 644 } 645 646 /// \brief Remove phi values from all successors and then remove the terminator. 647 void StructurizeCFG::killTerminator(BasicBlock *BB) { 648 TerminatorInst *Term = BB->getTerminator(); 649 if (!Term) 650 return; 651 652 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); 653 SI != SE; ++SI) { 654 655 delPhiValues(BB, *SI); 656 } 657 658 Term->eraseFromParent(); 659 } 660 661 /// \brief Let node exit(s) point to NewExit 662 void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit, 663 bool IncludeDominator) { 664 if (Node->isSubRegion()) { 665 Region *SubRegion = Node->getNodeAs<Region>(); 666 BasicBlock *OldExit = SubRegion->getExit(); 667 BasicBlock *Dominator = nullptr; 668 669 // Find all the edges from the sub region to the exit 670 for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit); 671 I != E;) { 672 673 BasicBlock *BB = *I++; 674 if (!SubRegion->contains(BB)) 675 continue; 676 677 // Modify the edges to point to the new exit 678 delPhiValues(BB, OldExit); 679 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit); 680 addPhiValues(BB, NewExit); 681 682 // Find the new dominator (if requested) 683 if (IncludeDominator) { 684 if (!Dominator) 685 Dominator = BB; 686 else 687 Dominator = DT->findNearestCommonDominator(Dominator, BB); 688 } 689 } 690 691 // Change the dominator (if requested) 692 if (Dominator) 693 DT->changeImmediateDominator(NewExit, Dominator); 694 695 // Update the region info 696 SubRegion->replaceExit(NewExit); 697 698 } else { 699 BasicBlock *BB = Node->getNodeAs<BasicBlock>(); 700 killTerminator(BB); 701 BranchInst::Create(NewExit, BB); 702 addPhiValues(BB, NewExit); 703 if (IncludeDominator) 704 DT->changeImmediateDominator(NewExit, BB); 705 } 706 } 707 708 /// \brief Create a new flow node and update dominator tree and region info 709 BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) { 710 LLVMContext &Context = Func->getContext(); 711 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() : 712 Order.back()->getEntry(); 713 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName, 714 Func, Insert); 715 DT->addNewBlock(Flow, Dominator); 716 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion); 717 return Flow; 718 } 719 720 /// \brief Create a new or reuse the previous node as flow node 721 BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) { 722 BasicBlock *Entry = PrevNode->getEntry(); 723 724 if (!PrevNode->isSubRegion()) { 725 killTerminator(Entry); 726 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end()) 727 return Entry; 728 729 } 730 731 // create a new flow node 732 BasicBlock *Flow = getNextFlow(Entry); 733 734 // and wire it up 735 changeExit(PrevNode, Flow, true); 736 PrevNode = ParentRegion->getBBNode(Flow); 737 return Flow; 738 } 739 740 /// \brief Returns the region exit if possible, otherwise just a new flow node 741 BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow, 742 bool ExitUseAllowed) { 743 if (Order.empty() && ExitUseAllowed) { 744 BasicBlock *Exit = ParentRegion->getExit(); 745 DT->changeImmediateDominator(Exit, Flow); 746 addPhiValues(Flow, Exit); 747 return Exit; 748 } 749 return getNextFlow(Flow); 750 } 751 752 /// \brief Set the previous node 753 void StructurizeCFG::setPrevNode(BasicBlock *BB) { 754 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB) 755 : nullptr; 756 } 757 758 /// \brief Does BB dominate all the predicates of Node ? 759 bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) { 760 BBPredicates &Preds = Predicates[Node->getEntry()]; 761 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end(); 762 PI != PE; ++PI) { 763 764 if (!DT->dominates(BB, PI->first)) 765 return false; 766 } 767 return true; 768 } 769 770 /// \brief Can we predict that this node will always be called? 771 bool StructurizeCFG::isPredictableTrue(RegionNode *Node) { 772 BBPredicates &Preds = Predicates[Node->getEntry()]; 773 bool Dominated = false; 774 775 // Regionentry is always true 776 if (!PrevNode) 777 return true; 778 779 for (BBPredicates::iterator I = Preds.begin(), E = Preds.end(); 780 I != E; ++I) { 781 782 if (I->second != BoolTrue) 783 return false; 784 785 if (!Dominated && DT->dominates(I->first, PrevNode->getEntry())) 786 Dominated = true; 787 } 788 789 // TODO: The dominator check is too strict 790 return Dominated; 791 } 792 793 /// Take one node from the order vector and wire it up 794 void StructurizeCFG::wireFlow(bool ExitUseAllowed, 795 BasicBlock *LoopEnd) { 796 RegionNode *Node = Order.pop_back_val(); 797 Visited.insert(Node->getEntry()); 798 799 if (isPredictableTrue(Node)) { 800 // Just a linear flow 801 if (PrevNode) { 802 changeExit(PrevNode, Node->getEntry(), true); 803 } 804 PrevNode = Node; 805 806 } else { 807 // Insert extra prefix node (or reuse last one) 808 BasicBlock *Flow = needPrefix(false); 809 810 // Insert extra postfix node (or use exit instead) 811 BasicBlock *Entry = Node->getEntry(); 812 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed); 813 814 // let it point to entry and next block 815 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow)); 816 addPhiValues(Flow, Entry); 817 DT->changeImmediateDominator(Entry, Flow); 818 819 PrevNode = Node; 820 while (!Order.empty() && !Visited.count(LoopEnd) && 821 dominatesPredicates(Entry, Order.back())) { 822 handleLoops(false, LoopEnd); 823 } 824 825 changeExit(PrevNode, Next, false); 826 setPrevNode(Next); 827 } 828 } 829 830 void StructurizeCFG::handleLoops(bool ExitUseAllowed, 831 BasicBlock *LoopEnd) { 832 RegionNode *Node = Order.back(); 833 BasicBlock *LoopStart = Node->getEntry(); 834 835 if (!Loops.count(LoopStart)) { 836 wireFlow(ExitUseAllowed, LoopEnd); 837 return; 838 } 839 840 if (!isPredictableTrue(Node)) 841 LoopStart = needPrefix(true); 842 843 LoopEnd = Loops[Node->getEntry()]; 844 wireFlow(false, LoopEnd); 845 while (!Visited.count(LoopEnd)) { 846 handleLoops(false, LoopEnd); 847 } 848 849 // If the start of the loop is the entry block, we can't branch to it so 850 // insert a new dummy entry block. 851 Function *LoopFunc = LoopStart->getParent(); 852 if (LoopStart == &LoopFunc->getEntryBlock()) { 853 LoopStart->setName("entry.orig"); 854 855 BasicBlock *NewEntry = 856 BasicBlock::Create(LoopStart->getContext(), 857 "entry", 858 LoopFunc, 859 LoopStart); 860 BranchInst::Create(LoopStart, NewEntry); 861 } 862 863 // Create an extra loop end node 864 LoopEnd = needPrefix(false); 865 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed); 866 LoopConds.push_back(BranchInst::Create(Next, LoopStart, 867 BoolUndef, LoopEnd)); 868 addPhiValues(LoopEnd, LoopStart); 869 setPrevNode(Next); 870 } 871 872 /// After this function control flow looks like it should be, but 873 /// branches and PHI nodes only have undefined conditions. 874 void StructurizeCFG::createFlow() { 875 BasicBlock *Exit = ParentRegion->getExit(); 876 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit); 877 878 DeletedPhis.clear(); 879 AddedPhis.clear(); 880 Conditions.clear(); 881 LoopConds.clear(); 882 883 PrevNode = nullptr; 884 Visited.clear(); 885 886 while (!Order.empty()) { 887 handleLoops(EntryDominatesExit, nullptr); 888 } 889 890 if (PrevNode) 891 changeExit(PrevNode, Exit, EntryDominatesExit); 892 else 893 assert(EntryDominatesExit); 894 } 895 896 /// Handle a rare case where the disintegrated nodes instructions 897 /// no longer dominate all their uses. Not sure if this is really nessasary 898 void StructurizeCFG::rebuildSSA() { 899 SSAUpdater Updater; 900 for (auto *BB : ParentRegion->blocks()) 901 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); 902 II != IE; ++II) { 903 904 bool Initialized = false; 905 for (auto I = II->use_begin(), E = II->use_end(); I != E;) { 906 Use &U = *I++; 907 Instruction *User = cast<Instruction>(U.getUser()); 908 if (User->getParent() == BB) { 909 continue; 910 911 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 912 if (UserPN->getIncomingBlock(U) == BB) 913 continue; 914 } 915 916 if (DT->dominates(&*II, User)) 917 continue; 918 919 if (!Initialized) { 920 Value *Undef = UndefValue::get(II->getType()); 921 Updater.Initialize(II->getType(), ""); 922 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef); 923 Updater.AddAvailableValue(BB, &*II); 924 Initialized = true; 925 } 926 Updater.RewriteUseAfterInsertions(U); 927 } 928 } 929 } 930 931 bool StructurizeCFG::hasOnlyUniformBranches(const Region *R) { 932 for (const BasicBlock *BB : R->blocks()) { 933 const BranchInst *Br = dyn_cast<BranchInst>(BB->getTerminator()); 934 if (!Br || !Br->isConditional()) 935 continue; 936 937 if (!DA->isUniform(Br->getCondition())) 938 return false; 939 DEBUG(dbgs() << "BB: " << BB->getName() << " has uniform terminator\n"); 940 } 941 return true; 942 } 943 944 /// \brief Run the transformation for each region found 945 bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) { 946 if (R->isTopLevelRegion()) 947 return false; 948 949 if (SkipUniformRegions) { 950 DA = &getAnalysis<DivergenceAnalysis>(); 951 // TODO: We could probably be smarter here with how we handle sub-regions. 952 if (hasOnlyUniformBranches(R)) { 953 DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R << '\n'); 954 return false; 955 } 956 } 957 958 Func = R->getEntry()->getParent(); 959 ParentRegion = R; 960 961 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 962 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 963 964 orderNodes(); 965 collectInfos(); 966 createFlow(); 967 insertConditions(false); 968 insertConditions(true); 969 setPhiValues(); 970 rebuildSSA(); 971 972 // Cleanup 973 Order.clear(); 974 Visited.clear(); 975 DeletedPhis.clear(); 976 AddedPhis.clear(); 977 Predicates.clear(); 978 Conditions.clear(); 979 Loops.clear(); 980 LoopPreds.clear(); 981 LoopConds.clear(); 982 983 return true; 984 } 985 986 Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) { 987 return new StructurizeCFG(SkipUniformRegions); 988 } 989