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