1 //===- RegionInfo.h - SESE region analysis ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Calculate a program structure tree built out of single entry single exit
12 // The basic ideas are taken from "The Program Structure Tree - Richard Johnson,
13 // David Pearson, Keshav Pingali - 1994", however enriched with ideas from "The
14 // Refined Process Structure Tree - Jussi Vanhatalo, Hagen Voelyer, Jana
16 // The algorithm to calculate these data structures however is completely
17 // different, as it takes advantage of existing information already available
18 // in (Post)dominace tree and dominance frontier passes. This leads to a simpler
19 // and in practice hopefully better performing algorithm. The runtime of the
20 // algorithms described in the papers above are both linear in graph size,
21 // O(V+E), whereas this algorithm is not, as the dominance frontier information
22 // itself is not, but in practice runtime seems to be in the order of magnitude
23 // of dominance tree calculation.
25 //===----------------------------------------------------------------------===//
27 #ifndef LLVM_ANALYSIS_REGION_INFO_H
28 #define LLVM_ANALYSIS_REGION_INFO_H
30 #include "llvm/ADT/PointerIntPair.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Analysis/PostDominators.h"
33 #include "llvm/Support/Allocator.h"
43 /// @brief Marker class to iterate over the elements of a Region in flat mode.
45 /// The class is used to either iterate in Flat mode or by not using it to not
46 /// iterate in Flat mode. During a Flat mode iteration all Regions are entered
47 /// and the iteration returns every BasicBlock. If the Flat mode is not
48 /// selected for SubRegions just one RegionNode containing the subregion is
50 template <class GraphType>
53 /// @brief A RegionNode represents a subregion or a BasicBlock that is part of a
57 RegionNode(const RegionNode &);
59 const RegionNode &operator=(const RegionNode &);
62 /// This is the entry basic block that starts this region node. If this is a
63 /// BasicBlock RegionNode, then entry is just the basic block, that this
64 /// RegionNode represents. Otherwise it is the entry of this (Sub)RegionNode.
66 /// In the BBtoRegionNode map of the parent of this node, BB will always map
67 /// to this node no matter which kind of node this one is.
69 /// The node can hold either a Region or a BasicBlock.
70 /// Use one bit to save, if this RegionNode is a subregion or BasicBlock
72 PointerIntPair<BasicBlock*, 1, bool> entry;
74 /// @brief The parent Region of this RegionNode.
79 /// @brief Create a RegionNode.
81 /// @param Parent The parent of this RegionNode.
82 /// @param Entry The entry BasicBlock of the RegionNode. If this
83 /// RegionNode represents a BasicBlock, this is the
84 /// BasicBlock itself. If it represents a subregion, this
85 /// is the entry BasicBlock of the subregion.
86 /// @param isSubRegion If this RegionNode represents a SubRegion.
87 inline RegionNode(Region* Parent, BasicBlock* Entry, bool isSubRegion = 0)
88 : entry(Entry, isSubRegion), parent(Parent) {}
90 /// @brief Get the parent Region of this RegionNode.
92 /// The parent Region is the Region this RegionNode belongs to. If for
93 /// example a BasicBlock is element of two Regions, there exist two
94 /// RegionNodes for this BasicBlock. Each with the getParent() function
95 /// pointing to the Region this RegionNode belongs to.
97 /// @return Get the parent Region of this RegionNode.
98 inline Region* getParent() const { return parent; }
100 /// @brief Get the entry BasicBlock of this RegionNode.
102 /// If this RegionNode represents a BasicBlock this is just the BasicBlock
103 /// itself, otherwise we return the entry BasicBlock of the Subregion
105 /// @return The entry BasicBlock of this RegionNode.
106 inline BasicBlock* getEntry() const { return entry.getPointer(); }
108 /// @brief Get the content of this RegionNode.
110 /// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
111 /// check the type of the content with the isSubRegion() function call.
113 /// @return The content of this RegionNode.
115 inline T* getNodeAs() const;
117 /// @brief Is this RegionNode a subregion?
119 /// @return True if it contains a subregion. False if it contains a
121 inline bool isSubRegion() const {
122 return entry.getInt();
126 /// Print a RegionNode.
127 inline raw_ostream &operator<<(raw_ostream &OS, const RegionNode &Node);
130 inline BasicBlock* RegionNode::getNodeAs<BasicBlock>() const {
131 assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
136 inline Region* RegionNode::getNodeAs<Region>() const {
137 assert(isSubRegion() && "This is not a subregion RegionNode!");
138 return reinterpret_cast<Region*>(const_cast<RegionNode*>(this));
141 //===----------------------------------------------------------------------===//
142 /// @brief A single entry single exit Region.
144 /// A Region is a connected subgraph of a control flow graph that has exactly
145 /// two connections to the remaining graph. It can be used to analyze or
146 /// optimize parts of the control flow graph.
148 /// A <em> simple Region </em> is connected to the remaing graph by just two
149 /// edges. One edge entering the Region and another one leaving the Region.
151 /// An <em> extended Region </em> (or just Region) is a subgraph that can be
152 /// transform into a simple Region. The transformation is done by adding
153 /// BasicBlocks that merge several entry or exit edges so that after the merge
154 /// just one entry and one exit edge exists.
156 /// The \e Entry of a Region is the first BasicBlock that is passed after
157 /// entering the Region. It is an element of the Region. The entry BasicBlock
158 /// dominates all BasicBlocks in the Region.
160 /// The \e Exit of a Region is the first BasicBlock that is passed after
161 /// leaving the Region. It is not an element of the Region. The exit BasicBlock,
162 /// postdominates all BasicBlocks in the Region.
164 /// A <em> canonical Region </em> cannot be constructed by combining smaller
167 /// Region A is the \e parent of Region B, if B is completely contained in A.
169 /// Two canonical Regions either do not intersect at all or one is
170 /// the parent of the other.
172 /// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
173 /// Regions in the control flow graph and E is the \e parent relation of these
179 /// A simple control flow graph, that contains two regions.
189 /// \ |/ Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
190 /// 9 Region B: 2 -> 9 {2,4,5,6,7}
193 /// You can obtain more examples by either calling
195 /// <tt> "opt -regions -analyze anyprogram.ll" </tt>
197 /// <tt> "opt -view-regions-only anyprogram.ll" </tt>
199 /// on any LLVM file you are interested in.
201 /// The first call returns a textual representation of the program structure
202 /// tree, the second one creates a graphical representation using graphviz.
203 class Region : public RegionNode {
204 friend class RegionInfo;
206 Region(const Region &);
208 const Region &operator=(const Region &);
210 // Information necessary to manage this Region.
214 // The exit BasicBlock of this region.
215 // (The entry BasicBlock is part of RegionNode)
218 typedef std::vector<Region*> RegionSet;
220 // The subregions of this region.
223 typedef std::map<BasicBlock*, RegionNode*> BBNodeMapT;
225 // Save the BasicBlock RegionNodes that are element of this Region.
226 mutable BBNodeMapT BBNodeMap;
228 /// verifyBBInRegion - Check if a BB is in this Region. This check also works
229 /// if the region is incorrectly built. (EXPENSIVE!)
230 void verifyBBInRegion(BasicBlock* BB) const;
232 /// verifyWalk - Walk over all the BBs of the region starting from BB and
233 /// verify that all reachable basic blocks are elements of the region.
235 void verifyWalk(BasicBlock* BB, std::set<BasicBlock*>* visitedBB) const;
237 /// verifyRegionNest - Verify if the region and its children are valid
238 /// regions (EXPENSIVE!)
239 void verifyRegionNest() const;
242 /// @brief Create a new region.
244 /// @param Entry The entry basic block of the region.
245 /// @param Exit The exit basic block of the region.
246 /// @param RI The region info object that is managing this region.
247 /// @param DT The dominator tree of the current function.
248 /// @param Parent The surrounding region or NULL if this is a top level
250 Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RI,
251 DominatorTree *DT, Region *Parent = 0);
253 /// Delete the Region and all its subregions.
256 /// @brief Get the entry BasicBlock of the Region.
257 /// @return The entry BasicBlock of the region.
258 BasicBlock *getEntry() const { return RegionNode::getEntry(); }
260 /// @brief Replace the entry basic block of the region with the new basic
263 /// @param BB The new entry basic block of the region.
264 void replaceEntry(BasicBlock *BB);
266 /// @brief Replace the exit basic block of the region with the new basic
269 /// @param BB The new exit basic block of the region.
270 void replaceExit(BasicBlock *BB);
272 /// @brief Get the exit BasicBlock of the Region.
273 /// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
275 BasicBlock *getExit() const { return exit; }
277 /// @brief Get the parent of the Region.
278 /// @return The parent of the Region or NULL if this is a top level
280 Region *getParent() const { return RegionNode::getParent(); }
282 /// @brief Get the RegionNode representing the current Region.
283 /// @return The RegionNode representing the current Region.
284 RegionNode* getNode() const {
285 return const_cast<RegionNode*>(reinterpret_cast<const RegionNode*>(this));
288 /// @brief Get the nesting level of this Region.
290 /// An toplevel Region has depth 0.
292 /// @return The depth of the region.
293 unsigned getDepth() const;
295 /// @brief Check if a Region is the TopLevel region.
297 /// The toplevel region represents the whole function.
298 bool isTopLevelRegion() const { return exit == NULL; }
300 /// @brief Return a new (non canonical) region, that is obtained by joining
301 /// this region with its predecessors.
303 /// @return A region also starting at getEntry(), but reaching to the next
304 /// basic block that forms with getEntry() a (non canonical) region.
305 /// NULL if such a basic block does not exist.
306 Region *getExpandedRegion() const;
308 /// @brief Is this a simple region?
310 /// A region is simple if it has exactly one exit and one entry edge.
312 /// @return True if the Region is simple.
313 bool isSimple() const;
315 /// @brief Returns the name of the Region.
316 /// @return The Name of the Region.
317 std::string getNameStr() const;
319 /// @brief Return the RegionInfo object, that belongs to this Region.
320 RegionInfo *getRegionInfo() const {
324 /// @brief Print the region.
326 /// @param OS The output stream the Region is printed to.
327 /// @param printTree Print also the tree of subregions.
328 /// @param level The indentation level used for printing.
329 void print(raw_ostream& OS, bool printTree = true, unsigned level = 0) const;
331 /// @brief Print the region to stderr.
334 /// @brief Check if the region contains a BasicBlock.
336 /// @param BB The BasicBlock that might be contained in this Region.
337 /// @return True if the block is contained in the region otherwise false.
338 bool contains(const BasicBlock *BB) const;
340 /// @brief Check if the region contains another region.
342 /// @param SubRegion The region that might be contained in this Region.
343 /// @return True if SubRegion is contained in the region otherwise false.
344 bool contains(const Region *SubRegion) const {
349 return contains(SubRegion->getEntry())
350 && (contains(SubRegion->getExit()) || SubRegion->getExit() == getExit());
353 /// @brief Check if the region contains an Instruction.
355 /// @param Inst The Instruction that might be contained in this region.
356 /// @return True if the Instruction is contained in the region otherwise false.
357 bool contains(const Instruction *Inst) const {
358 return contains(Inst->getParent());
361 /// @brief Check if the region contains a loop.
363 /// @param L The loop that might be contained in this region.
364 /// @return True if the loop is contained in the region otherwise false.
365 /// In case a NULL pointer is passed to this function the result
366 /// is false, except for the region that describes the whole function.
367 /// In that case true is returned.
368 bool contains(const Loop *L) const;
370 /// @brief Get the outermost loop in the region that contains a loop.
372 /// Find for a Loop L the outermost loop OuterL that is a parent loop of L
373 /// and is itself contained in the region.
375 /// @param L The loop the lookup is started.
376 /// @return The outermost loop in the region, NULL if such a loop does not
377 /// exist or if the region describes the whole function.
378 Loop *outermostLoopInRegion(Loop *L) const;
380 /// @brief Get the outermost loop in the region that contains a basic block.
382 /// Find for a basic block BB the outermost loop L that contains BB and is
383 /// itself contained in the region.
385 /// @param LI A pointer to a LoopInfo analysis.
386 /// @param BB The basic block surrounded by the loop.
387 /// @return The outermost loop in the region, NULL if such a loop does not
388 /// exist or if the region describes the whole function.
389 Loop *outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const;
391 /// @brief Get the subregion that starts at a BasicBlock
393 /// @param BB The BasicBlock the subregion should start.
394 /// @return The Subregion if available, otherwise NULL.
395 Region* getSubRegionNode(BasicBlock *BB) const;
397 /// @brief Get the RegionNode for a BasicBlock
399 /// @param BB The BasicBlock at which the RegionNode should start.
400 /// @return If available, the RegionNode that represents the subregion
401 /// starting at BB. If no subregion starts at BB, the RegionNode
403 RegionNode* getNode(BasicBlock *BB) const;
405 /// @brief Get the BasicBlock RegionNode for a BasicBlock
407 /// @param BB The BasicBlock for which the RegionNode is requested.
408 /// @return The RegionNode representing the BB.
409 RegionNode* getBBNode(BasicBlock *BB) const;
411 /// @brief Add a new subregion to this Region.
413 /// @param SubRegion The new subregion that will be added.
414 /// @param moveChildren Move the children of this region, that are also
415 /// contained in SubRegion into SubRegion.
416 void addSubRegion(Region *SubRegion, bool moveChildren = false);
418 /// @brief Remove a subregion from this Region.
420 /// The subregion is not deleted, as it will probably be inserted into another
422 /// @param SubRegion The SubRegion that will be removed.
423 Region *removeSubRegion(Region *SubRegion);
425 /// @brief Move all direct child nodes of this Region to another Region.
427 /// @param To The Region the child nodes will be transfered to.
428 void transferChildrenTo(Region *To);
430 /// @brief Verify if the region is a correct region.
432 /// Check if this is a correctly build Region. This is an expensive check, as
433 /// the complete CFG of the Region will be walked.
434 void verifyRegion() const;
436 /// @brief Clear the cache for BB RegionNodes.
438 /// After calling this function the BasicBlock RegionNodes will be stored at
439 /// different memory locations. RegionNodes obtained before this function is
440 /// called are therefore not comparable to RegionNodes abtained afterwords.
441 void clearNodeCache();
443 /// @name Subregion Iterators
445 /// These iterators iterator over all subregions of this Region.
447 typedef RegionSet::iterator iterator;
448 typedef RegionSet::const_iterator const_iterator;
450 iterator begin() { return children.begin(); }
451 iterator end() { return children.end(); }
453 const_iterator begin() const { return children.begin(); }
454 const_iterator end() const { return children.end(); }
457 /// @name BasicBlock Iterators
459 /// These iterators iterate over all BasicBlock RegionNodes that are
460 /// contained in this Region. The iterator also iterates over BasicBlocks
461 /// that are elements of a subregion of this Region. It is therefore called a
464 typedef df_iterator<RegionNode*, SmallPtrSet<RegionNode*, 8>, false,
465 GraphTraits<FlatIt<RegionNode*> > > block_iterator;
467 typedef df_iterator<const RegionNode*, SmallPtrSet<const RegionNode*, 8>,
468 false, GraphTraits<FlatIt<const RegionNode*> > >
469 const_block_iterator;
471 block_iterator block_begin();
472 block_iterator block_end();
474 const_block_iterator block_begin() const;
475 const_block_iterator block_end() const;
478 /// @name Element Iterators
480 /// These iterators iterate over all BasicBlock and subregion RegionNodes that
481 /// are direct children of this Region. It does not iterate over any
482 /// RegionNodes that are also element of a subregion of this Region.
484 typedef df_iterator<RegionNode*, SmallPtrSet<RegionNode*, 8>, false,
485 GraphTraits<RegionNode*> > element_iterator;
487 typedef df_iterator<const RegionNode*, SmallPtrSet<const RegionNode*, 8>,
488 false, GraphTraits<const RegionNode*> >
489 const_element_iterator;
491 element_iterator element_begin();
492 element_iterator element_end();
494 const_element_iterator element_begin() const;
495 const_element_iterator element_end() const;
499 //===----------------------------------------------------------------------===//
500 /// @brief Analysis that detects all canonical Regions.
502 /// The RegionInfo pass detects all canonical regions in a function. The Regions
503 /// are connected using the parent relation. This builds a Program Structure
505 class RegionInfo : public FunctionPass {
506 typedef DenseMap<BasicBlock*,BasicBlock*> BBtoBBMap;
507 typedef DenseMap<BasicBlock*, Region*> BBtoRegionMap;
508 typedef SmallPtrSet<Region*, 4> RegionSet;
511 RegionInfo(const RegionInfo &);
513 const RegionInfo &operator=(const RegionInfo &);
516 PostDominatorTree *PDT;
517 DominanceFrontier *DF;
519 /// The top level region.
520 Region *TopLevelRegion;
522 /// Map every BB to the smallest region, that contains BB.
523 BBtoRegionMap BBtoRegion;
525 // isCommonDomFrontier - Returns true if BB is in the dominance frontier of
526 // entry, because it was inherited from exit. In the other case there is an
527 // edge going from entry to BB without passing exit.
528 bool isCommonDomFrontier(BasicBlock* BB, BasicBlock* entry,
529 BasicBlock* exit) const;
531 // isRegion - Check if entry and exit surround a valid region, based on
532 // dominance tree and dominance frontier.
533 bool isRegion(BasicBlock* entry, BasicBlock* exit) const;
535 // insertShortCut - Saves a shortcut pointing from entry to exit.
536 // This function may extend this shortcut if possible.
537 void insertShortCut(BasicBlock* entry, BasicBlock* exit,
538 BBtoBBMap* ShortCut) const;
540 // getNextPostDom - Returns the next BB that postdominates N, while skipping
541 // all post dominators that cannot finish a canonical region.
542 DomTreeNode *getNextPostDom(DomTreeNode* N, BBtoBBMap *ShortCut) const;
544 // isTrivialRegion - A region is trivial, if it contains only one BB.
545 bool isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const;
547 // createRegion - Creates a single entry single exit region.
548 Region *createRegion(BasicBlock *entry, BasicBlock *exit);
550 // findRegionsWithEntry - Detect all regions starting with bb 'entry'.
551 void findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut);
553 // scanForRegions - Detects regions in F.
554 void scanForRegions(Function &F, BBtoBBMap *ShortCut);
556 // getTopMostParent - Get the top most parent with the same entry block.
557 Region *getTopMostParent(Region *region);
559 // buildRegionsTree - build the region hierarchy after all region detected.
560 void buildRegionsTree(DomTreeNode *N, Region *region);
562 // Calculate - detecte all regions in function and build the region tree.
563 void Calculate(Function& F);
565 void releaseMemory();
567 // updateStatistics - Update statistic about created regions.
568 void updateStatistics(Region *R);
570 // isSimple - Check if a region is a simple region with exactly one entry
571 // edge and exactly one exit edge.
572 bool isSimple(Region* R) const;
576 explicit RegionInfo();
580 /// @name FunctionPass interface
582 virtual bool runOnFunction(Function &F);
583 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
584 virtual void print(raw_ostream &OS, const Module *) const;
585 virtual void verifyAnalysis() const;
588 /// @brief Get the smallest region that contains a BasicBlock.
590 /// @param BB The basic block.
591 /// @return The smallest region, that contains BB or NULL, if there is no
592 /// region containing BB.
593 Region *getRegionFor(BasicBlock *BB) const;
595 /// @brief Set the smallest region that surrounds a basic block.
597 /// @param BB The basic block surrounded by a region.
598 /// @param R The smallest region that surrounds BB.
599 void setRegionFor(BasicBlock *BB, Region *R);
601 /// @brief A shortcut for getRegionFor().
603 /// @param BB The basic block.
604 /// @return The smallest region, that contains BB or NULL, if there is no
605 /// region containing BB.
606 Region *operator[](BasicBlock *BB) const;
608 /// @brief Return the exit of the maximal refined region, that starts at a
611 /// @param BB The BasicBlock the refined region starts.
612 BasicBlock *getMaxRegionExit(BasicBlock *BB) const;
614 /// @brief Find the smallest region that contains two regions.
616 /// @param A The first region.
617 /// @param B The second region.
618 /// @return The smallest region containing A and B.
619 Region *getCommonRegion(Region* A, Region *B) const;
621 /// @brief Find the smallest region that contains two basic blocks.
623 /// @param A The first basic block.
624 /// @param B The second basic block.
625 /// @return The smallest region that contains A and B.
626 Region* getCommonRegion(BasicBlock* A, BasicBlock *B) const {
627 return getCommonRegion(getRegionFor(A), getRegionFor(B));
630 /// @brief Find the smallest region that contains a set of regions.
632 /// @param Regions A vector of regions.
633 /// @return The smallest region that contains all regions in Regions.
634 Region* getCommonRegion(SmallVectorImpl<Region*> &Regions) const;
636 /// @brief Find the smallest region that contains a set of basic blocks.
638 /// @param BBs A vector of basic blocks.
639 /// @return The smallest region that contains all basic blocks in BBS.
640 Region* getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const;
642 Region *getTopLevelRegion() const {
643 return TopLevelRegion;
646 /// @brief Update RegionInfo after a basic block was split.
648 /// @param NewBB The basic block that was created before OldBB.
649 /// @param OldBB The old basic block.
650 void splitBlock(BasicBlock* NewBB, BasicBlock *OldBB);
652 /// @brief Clear the Node Cache for all Regions.
654 /// @see Region::clearNodeCache()
655 void clearNodeCache() {
657 TopLevelRegion->clearNodeCache();
661 inline raw_ostream &operator<<(raw_ostream &OS, const RegionNode &Node) {
662 if (Node.isSubRegion())
663 return OS << Node.getNodeAs<Region>()->getNameStr();
665 return OS << Node.getNodeAs<BasicBlock>()->getNameStr();
667 } // End llvm namespace