RegionInfoImpl.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- RegionInfoImpl.h - SESE region detection analysis --------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. // Detects single entry single exit regions in the control flow graph.
  14. //===----------------------------------------------------------------------===//
  15. #ifndef LLVM_ANALYSIS_REGIONINFOIMPL_H
  16. #define LLVM_ANALYSIS_REGIONINFOIMPL_H
  17. #include "llvm/ADT/GraphTraits.h"
  18. #include "llvm/ADT/PostOrderIterator.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/Analysis/LoopInfo.h"
  22. #include "llvm/Analysis/PostDominators.h"
  23. #include "llvm/Analysis/RegionInfo.h"
  24. #include "llvm/Analysis/RegionIterator.h"
  25. #include "llvm/Config/llvm-config.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <iterator>
  31. #include <memory>
  32. #include <set>
  33. #include <string>
  34. #include <type_traits>
  35. #include <vector>
  36. #define DEBUG_TYPE "region"
  37. namespace llvm {
  38. class raw_ostream;
  39. //===----------------------------------------------------------------------===//
  40. /// RegionBase Implementation
  41. template <class Tr>
  42. RegionBase<Tr>::RegionBase(BlockT *Entry, BlockT *Exit,
  43. typename Tr::RegionInfoT *RInfo, DomTreeT *dt,
  44. RegionT *Parent)
  45. : RegionNodeBase<Tr>(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
  46. template <class Tr>
  47. RegionBase<Tr>::~RegionBase() {
  48. // Only clean the cache for this Region. Caches of child Regions will be
  49. // cleaned when the child Regions are deleted.
  50. BBNodeMap.clear();
  51. }
  52. template <class Tr>
  53. void RegionBase<Tr>::replaceEntry(BlockT *BB) {
  54. this->entry.setPointer(BB);
  55. }
  56. template <class Tr>
  57. void RegionBase<Tr>::replaceExit(BlockT *BB) {
  58. assert(exit && "No exit to replace!");
  59. exit = BB;
  60. }
  61. template <class Tr>
  62. void RegionBase<Tr>::replaceEntryRecursive(BlockT *NewEntry) {
  63. std::vector<RegionT *> RegionQueue;
  64. BlockT *OldEntry = getEntry();
  65. RegionQueue.push_back(static_cast<RegionT *>(this));
  66. while (!RegionQueue.empty()) {
  67. RegionT *R = RegionQueue.back();
  68. RegionQueue.pop_back();
  69. R->replaceEntry(NewEntry);
  70. for (std::unique_ptr<RegionT> &Child : *R) {
  71. if (Child->getEntry() == OldEntry)
  72. RegionQueue.push_back(Child.get());
  73. }
  74. }
  75. }
  76. template <class Tr>
  77. void RegionBase<Tr>::replaceExitRecursive(BlockT *NewExit) {
  78. std::vector<RegionT *> RegionQueue;
  79. BlockT *OldExit = getExit();
  80. RegionQueue.push_back(static_cast<RegionT *>(this));
  81. while (!RegionQueue.empty()) {
  82. RegionT *R = RegionQueue.back();
  83. RegionQueue.pop_back();
  84. R->replaceExit(NewExit);
  85. for (std::unique_ptr<RegionT> &Child : *R) {
  86. if (Child->getExit() == OldExit)
  87. RegionQueue.push_back(Child.get());
  88. }
  89. }
  90. }
  91. template <class Tr>
  92. bool RegionBase<Tr>::contains(const BlockT *B) const {
  93. BlockT *BB = const_cast<BlockT *>(B);
  94. if (!DT->getNode(BB))
  95. return false;
  96. BlockT *entry = getEntry(), *exit = getExit();
  97. // Toplevel region.
  98. if (!exit)
  99. return true;
  100. return (DT->dominates(entry, BB) &&
  101. !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
  102. }
  103. template <class Tr>
  104. bool RegionBase<Tr>::contains(const LoopT *L) const {
  105. // BBs that are not part of any loop are element of the Loop
  106. // described by the NULL pointer. This loop is not part of any region,
  107. // except if the region describes the whole function.
  108. if (!L)
  109. return getExit() == nullptr;
  110. if (!contains(L->getHeader()))
  111. return false;
  112. SmallVector<BlockT *, 8> ExitingBlocks;
  113. L->getExitingBlocks(ExitingBlocks);
  114. for (BlockT *BB : ExitingBlocks) {
  115. if (!contains(BB))
  116. return false;
  117. }
  118. return true;
  119. }
  120. template <class Tr>
  121. typename Tr::LoopT *RegionBase<Tr>::outermostLoopInRegion(LoopT *L) const {
  122. if (!contains(L))
  123. return nullptr;
  124. while (L && contains(L->getParentLoop())) {
  125. L = L->getParentLoop();
  126. }
  127. return L;
  128. }
  129. template <class Tr>
  130. typename Tr::LoopT *RegionBase<Tr>::outermostLoopInRegion(LoopInfoT *LI,
  131. BlockT *BB) const {
  132. assert(LI && BB && "LI and BB cannot be null!");
  133. LoopT *L = LI->getLoopFor(BB);
  134. return outermostLoopInRegion(L);
  135. }
  136. template <class Tr>
  137. typename RegionBase<Tr>::BlockT *RegionBase<Tr>::getEnteringBlock() const {
  138. auto isEnteringBlock = [&](BlockT *Pred, bool AllowRepeats) -> BlockT * {
  139. assert(!AllowRepeats && "Unexpected parameter value.");
  140. return DT->getNode(Pred) && !contains(Pred) ? Pred : nullptr;
  141. };
  142. BlockT *entry = getEntry();
  143. return find_singleton<BlockT>(make_range(InvBlockTraits::child_begin(entry),
  144. InvBlockTraits::child_end(entry)),
  145. isEnteringBlock);
  146. }
  147. template <class Tr>
  148. bool RegionBase<Tr>::getExitingBlocks(
  149. SmallVectorImpl<BlockT *> &Exitings) const {
  150. bool CoverAll = true;
  151. if (!exit)
  152. return CoverAll;
  153. for (PredIterTy PI = InvBlockTraits::child_begin(exit),
  154. PE = InvBlockTraits::child_end(exit);
  155. PI != PE; ++PI) {
  156. BlockT *Pred = *PI;
  157. if (contains(Pred)) {
  158. Exitings.push_back(Pred);
  159. continue;
  160. }
  161. CoverAll = false;
  162. }
  163. return CoverAll;
  164. }
  165. template <class Tr>
  166. typename RegionBase<Tr>::BlockT *RegionBase<Tr>::getExitingBlock() const {
  167. BlockT *exit = getExit();
  168. if (!exit)
  169. return nullptr;
  170. auto isContained = [&](BlockT *Pred, bool AllowRepeats) -> BlockT * {
  171. assert(!AllowRepeats && "Unexpected parameter value.");
  172. return contains(Pred) ? Pred : nullptr;
  173. };
  174. return find_singleton<BlockT>(make_range(InvBlockTraits::child_begin(exit),
  175. InvBlockTraits::child_end(exit)),
  176. isContained);
  177. }
  178. template <class Tr>
  179. bool RegionBase<Tr>::isSimple() const {
  180. return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
  181. }
  182. template <class Tr>
  183. std::string RegionBase<Tr>::getNameStr() const {
  184. std::string exitName;
  185. std::string entryName;
  186. if (getEntry()->getName().empty()) {
  187. raw_string_ostream OS(entryName);
  188. getEntry()->printAsOperand(OS, false);
  189. } else
  190. entryName = std::string(getEntry()->getName());
  191. if (getExit()) {
  192. if (getExit()->getName().empty()) {
  193. raw_string_ostream OS(exitName);
  194. getExit()->printAsOperand(OS, false);
  195. } else
  196. exitName = std::string(getExit()->getName());
  197. } else
  198. exitName = "<Function Return>";
  199. return entryName + " => " + exitName;
  200. }
  201. template <class Tr>
  202. void RegionBase<Tr>::verifyBBInRegion(BlockT *BB) const {
  203. if (!contains(BB))
  204. report_fatal_error("Broken region found: enumerated BB not in region!");
  205. BlockT *entry = getEntry(), *exit = getExit();
  206. for (BlockT *Succ :
  207. make_range(BlockTraits::child_begin(BB), BlockTraits::child_end(BB))) {
  208. if (!contains(Succ) && exit != Succ)
  209. report_fatal_error("Broken region found: edges leaving the region must go "
  210. "to the exit node!");
  211. }
  212. if (entry != BB) {
  213. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(BB),
  214. InvBlockTraits::child_end(BB))) {
  215. if (!contains(Pred))
  216. report_fatal_error("Broken region found: edges entering the region must "
  217. "go to the entry node!");
  218. }
  219. }
  220. }
  221. template <class Tr>
  222. void RegionBase<Tr>::verifyWalk(BlockT *BB, std::set<BlockT *> *visited) const {
  223. BlockT *exit = getExit();
  224. visited->insert(BB);
  225. verifyBBInRegion(BB);
  226. for (BlockT *Succ :
  227. make_range(BlockTraits::child_begin(BB), BlockTraits::child_end(BB))) {
  228. if (Succ != exit && visited->find(Succ) == visited->end())
  229. verifyWalk(Succ, visited);
  230. }
  231. }
  232. template <class Tr>
  233. void RegionBase<Tr>::verifyRegion() const {
  234. // Only do verification when user wants to, otherwise this expensive check
  235. // will be invoked by PMDataManager::verifyPreservedAnalysis when
  236. // a regionpass (marked PreservedAll) finish.
  237. if (!RegionInfoBase<Tr>::VerifyRegionInfo)
  238. return;
  239. std::set<BlockT *> visited;
  240. verifyWalk(getEntry(), &visited);
  241. }
  242. template <class Tr>
  243. void RegionBase<Tr>::verifyRegionNest() const {
  244. for (const std::unique_ptr<RegionT> &R : *this)
  245. R->verifyRegionNest();
  246. verifyRegion();
  247. }
  248. template <class Tr>
  249. typename RegionBase<Tr>::element_iterator RegionBase<Tr>::element_begin() {
  250. return GraphTraits<RegionT *>::nodes_begin(static_cast<RegionT *>(this));
  251. }
  252. template <class Tr>
  253. typename RegionBase<Tr>::element_iterator RegionBase<Tr>::element_end() {
  254. return GraphTraits<RegionT *>::nodes_end(static_cast<RegionT *>(this));
  255. }
  256. template <class Tr>
  257. typename RegionBase<Tr>::const_element_iterator
  258. RegionBase<Tr>::element_begin() const {
  259. return GraphTraits<const RegionT *>::nodes_begin(
  260. static_cast<const RegionT *>(this));
  261. }
  262. template <class Tr>
  263. typename RegionBase<Tr>::const_element_iterator
  264. RegionBase<Tr>::element_end() const {
  265. return GraphTraits<const RegionT *>::nodes_end(
  266. static_cast<const RegionT *>(this));
  267. }
  268. template <class Tr>
  269. typename Tr::RegionT *RegionBase<Tr>::getSubRegionNode(BlockT *BB) const {
  270. using RegionT = typename Tr::RegionT;
  271. RegionT *R = RI->getRegionFor(BB);
  272. if (!R || R == this)
  273. return nullptr;
  274. // If we pass the BB out of this region, that means our code is broken.
  275. assert(contains(R) && "BB not in current region!");
  276. while (contains(R->getParent()) && R->getParent() != this)
  277. R = R->getParent();
  278. if (R->getEntry() != BB)
  279. return nullptr;
  280. return R;
  281. }
  282. template <class Tr>
  283. typename Tr::RegionNodeT *RegionBase<Tr>::getBBNode(BlockT *BB) const {
  284. assert(contains(BB) && "Can get BB node out of this region!");
  285. typename BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
  286. if (at == BBNodeMap.end()) {
  287. auto Deconst = const_cast<RegionBase<Tr> *>(this);
  288. typename BBNodeMapT::value_type V = {
  289. BB,
  290. std::make_unique<RegionNodeT>(static_cast<RegionT *>(Deconst), BB)};
  291. at = BBNodeMap.insert(std::move(V)).first;
  292. }
  293. return at->second.get();
  294. }
  295. template <class Tr>
  296. typename Tr::RegionNodeT *RegionBase<Tr>::getNode(BlockT *BB) const {
  297. assert(contains(BB) && "Can get BB node out of this region!");
  298. if (RegionT *Child = getSubRegionNode(BB))
  299. return Child->getNode();
  300. return getBBNode(BB);
  301. }
  302. template <class Tr>
  303. void RegionBase<Tr>::transferChildrenTo(RegionT *To) {
  304. for (std::unique_ptr<RegionT> &R : *this) {
  305. R->parent = To;
  306. To->children.push_back(std::move(R));
  307. }
  308. children.clear();
  309. }
  310. template <class Tr>
  311. void RegionBase<Tr>::addSubRegion(RegionT *SubRegion, bool moveChildren) {
  312. assert(!SubRegion->parent && "SubRegion already has a parent!");
  313. assert(llvm::none_of(*this,
  314. [&](const std::unique_ptr<RegionT> &R) {
  315. return R.get() == SubRegion;
  316. }) &&
  317. "Subregion already exists!");
  318. SubRegion->parent = static_cast<RegionT *>(this);
  319. children.push_back(std::unique_ptr<RegionT>(SubRegion));
  320. if (!moveChildren)
  321. return;
  322. assert(SubRegion->children.empty() &&
  323. "SubRegions that contain children are not supported");
  324. for (RegionNodeT *Element : elements()) {
  325. if (!Element->isSubRegion()) {
  326. BlockT *BB = Element->template getNodeAs<BlockT>();
  327. if (SubRegion->contains(BB))
  328. RI->setRegionFor(BB, SubRegion);
  329. }
  330. }
  331. std::vector<std::unique_ptr<RegionT>> Keep;
  332. for (std::unique_ptr<RegionT> &R : *this) {
  333. if (SubRegion->contains(R.get()) && R.get() != SubRegion) {
  334. R->parent = SubRegion;
  335. SubRegion->children.push_back(std::move(R));
  336. } else
  337. Keep.push_back(std::move(R));
  338. }
  339. children.clear();
  340. children.insert(
  341. children.begin(),
  342. std::move_iterator<typename RegionSet::iterator>(Keep.begin()),
  343. std::move_iterator<typename RegionSet::iterator>(Keep.end()));
  344. }
  345. template <class Tr>
  346. typename Tr::RegionT *RegionBase<Tr>::removeSubRegion(RegionT *Child) {
  347. assert(Child->parent == this && "Child is not a child of this region!");
  348. Child->parent = nullptr;
  349. typename RegionSet::iterator I =
  350. llvm::find_if(children, [&](const std::unique_ptr<RegionT> &R) {
  351. return R.get() == Child;
  352. });
  353. assert(I != children.end() && "Region does not exit. Unable to remove.");
  354. children.erase(children.begin() + (I - begin()));
  355. return Child;
  356. }
  357. template <class Tr>
  358. unsigned RegionBase<Tr>::getDepth() const {
  359. unsigned Depth = 0;
  360. for (RegionT *R = getParent(); R != nullptr; R = R->getParent())
  361. ++Depth;
  362. return Depth;
  363. }
  364. template <class Tr>
  365. typename Tr::RegionT *RegionBase<Tr>::getExpandedRegion() const {
  366. unsigned NumSuccessors = Tr::getNumSuccessors(exit);
  367. if (NumSuccessors == 0)
  368. return nullptr;
  369. RegionT *R = RI->getRegionFor(exit);
  370. if (R->getEntry() != exit) {
  371. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(getExit()),
  372. InvBlockTraits::child_end(getExit())))
  373. if (!contains(Pred))
  374. return nullptr;
  375. if (Tr::getNumSuccessors(exit) == 1)
  376. return new RegionT(getEntry(), *BlockTraits::child_begin(exit), RI, DT);
  377. return nullptr;
  378. }
  379. while (R->getParent() && R->getParent()->getEntry() == exit)
  380. R = R->getParent();
  381. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(getExit()),
  382. InvBlockTraits::child_end(getExit()))) {
  383. if (!(contains(Pred) || R->contains(Pred)))
  384. return nullptr;
  385. }
  386. return new RegionT(getEntry(), R->getExit(), RI, DT);
  387. }
  388. template <class Tr>
  389. void RegionBase<Tr>::print(raw_ostream &OS, bool print_tree, unsigned level,
  390. PrintStyle Style) const {
  391. if (print_tree)
  392. OS.indent(level * 2) << '[' << level << "] " << getNameStr();
  393. else
  394. OS.indent(level * 2) << getNameStr();
  395. OS << '\n';
  396. if (Style != PrintNone) {
  397. OS.indent(level * 2) << "{\n";
  398. OS.indent(level * 2 + 2);
  399. if (Style == PrintBB) {
  400. for (const auto *BB : blocks())
  401. OS << BB->getName() << ", "; // TODO: remove the last ","
  402. } else if (Style == PrintRN) {
  403. for (const RegionNodeT *Element : elements()) {
  404. OS << *Element << ", "; // TODO: remove the last ",
  405. }
  406. }
  407. OS << '\n';
  408. }
  409. if (print_tree) {
  410. for (const std::unique_ptr<RegionT> &R : *this)
  411. R->print(OS, print_tree, level + 1, Style);
  412. }
  413. if (Style != PrintNone)
  414. OS.indent(level * 2) << "} \n";
  415. }
  416. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  417. template <class Tr>
  418. void RegionBase<Tr>::dump() const {
  419. print(dbgs(), true, getDepth(), RegionInfoBase<Tr>::printStyle);
  420. }
  421. #endif
  422. template <class Tr>
  423. void RegionBase<Tr>::clearNodeCache() {
  424. BBNodeMap.clear();
  425. for (std::unique_ptr<RegionT> &R : *this)
  426. R->clearNodeCache();
  427. }
  428. //===----------------------------------------------------------------------===//
  429. // RegionInfoBase implementation
  430. //
  431. template <class Tr>
  432. RegionInfoBase<Tr>::RegionInfoBase() = default;
  433. template <class Tr>
  434. RegionInfoBase<Tr>::~RegionInfoBase() {
  435. releaseMemory();
  436. }
  437. template <class Tr>
  438. void RegionInfoBase<Tr>::verifyBBMap(const RegionT *R) const {
  439. assert(R && "Re must be non-null");
  440. for (const typename Tr::RegionNodeT *Element : R->elements()) {
  441. if (Element->isSubRegion()) {
  442. const RegionT *SR = Element->template getNodeAs<RegionT>();
  443. verifyBBMap(SR);
  444. } else {
  445. BlockT *BB = Element->template getNodeAs<BlockT>();
  446. if (getRegionFor(BB) != R)
  447. report_fatal_error("BB map does not match region nesting");
  448. }
  449. }
  450. }
  451. template <class Tr>
  452. bool RegionInfoBase<Tr>::isCommonDomFrontier(BlockT *BB, BlockT *entry,
  453. BlockT *exit) const {
  454. for (BlockT *P : make_range(InvBlockTraits::child_begin(BB),
  455. InvBlockTraits::child_end(BB))) {
  456. if (DT->dominates(entry, P) && !DT->dominates(exit, P))
  457. return false;
  458. }
  459. return true;
  460. }
  461. template <class Tr>
  462. bool RegionInfoBase<Tr>::isRegion(BlockT *entry, BlockT *exit) const {
  463. assert(entry && exit && "entry and exit must not be null!");
  464. using DST = typename DomFrontierT::DomSetType;
  465. DST *entrySuccs = &DF->find(entry)->second;
  466. // Exit is the header of a loop that contains the entry. In this case,
  467. // the dominance frontier must only contain the exit.
  468. if (!DT->dominates(entry, exit)) {
  469. for (BlockT *successor : *entrySuccs) {
  470. if (successor != exit && successor != entry)
  471. return false;
  472. }
  473. return true;
  474. }
  475. DST *exitSuccs = &DF->find(exit)->second;
  476. // Do not allow edges leaving the region.
  477. for (BlockT *Succ : *entrySuccs) {
  478. if (Succ == exit || Succ == entry)
  479. continue;
  480. if (exitSuccs->find(Succ) == exitSuccs->end())
  481. return false;
  482. if (!isCommonDomFrontier(Succ, entry, exit))
  483. return false;
  484. }
  485. // Do not allow edges pointing into the region.
  486. for (BlockT *Succ : *exitSuccs) {
  487. if (DT->properlyDominates(entry, Succ) && Succ != exit)
  488. return false;
  489. }
  490. return true;
  491. }
  492. template <class Tr>
  493. void RegionInfoBase<Tr>::insertShortCut(BlockT *entry, BlockT *exit,
  494. BBtoBBMap *ShortCut) const {
  495. assert(entry && exit && "entry and exit must not be null!");
  496. typename BBtoBBMap::iterator e = ShortCut->find(exit);
  497. if (e == ShortCut->end())
  498. // No further region at exit available.
  499. (*ShortCut)[entry] = exit;
  500. else {
  501. // We found a region e that starts at exit. Therefore (entry, e->second)
  502. // is also a region, that is larger than (entry, exit). Insert the
  503. // larger one.
  504. BlockT *BB = e->second;
  505. (*ShortCut)[entry] = BB;
  506. }
  507. }
  508. template <class Tr>
  509. typename Tr::DomTreeNodeT *
  510. RegionInfoBase<Tr>::getNextPostDom(DomTreeNodeT *N, BBtoBBMap *ShortCut) const {
  511. typename BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
  512. if (e == ShortCut->end())
  513. return N->getIDom();
  514. return PDT->getNode(e->second)->getIDom();
  515. }
  516. template <class Tr>
  517. bool RegionInfoBase<Tr>::isTrivialRegion(BlockT *entry, BlockT *exit) const {
  518. assert(entry && exit && "entry and exit must not be null!");
  519. unsigned num_successors =
  520. BlockTraits::child_end(entry) - BlockTraits::child_begin(entry);
  521. if (num_successors <= 1 && exit == *(BlockTraits::child_begin(entry)))
  522. return true;
  523. return false;
  524. }
  525. template <class Tr>
  526. typename Tr::RegionT *RegionInfoBase<Tr>::createRegion(BlockT *entry,
  527. BlockT *exit) {
  528. assert(entry && exit && "entry and exit must not be null!");
  529. if (isTrivialRegion(entry, exit))
  530. return nullptr;
  531. RegionT *region =
  532. new RegionT(entry, exit, static_cast<RegionInfoT *>(this), DT);
  533. BBtoRegion.insert({entry, region});
  534. #ifdef EXPENSIVE_CHECKS
  535. region->verifyRegion();
  536. #else
  537. LLVM_DEBUG(region->verifyRegion());
  538. #endif
  539. updateStatistics(region);
  540. return region;
  541. }
  542. template <class Tr>
  543. void RegionInfoBase<Tr>::findRegionsWithEntry(BlockT *entry,
  544. BBtoBBMap *ShortCut) {
  545. assert(entry);
  546. DomTreeNodeT *N = PDT->getNode(entry);
  547. if (!N)
  548. return;
  549. RegionT *lastRegion = nullptr;
  550. BlockT *lastExit = entry;
  551. // As only a BasicBlock that postdominates entry can finish a region, walk the
  552. // post dominance tree upwards.
  553. while ((N = getNextPostDom(N, ShortCut))) {
  554. BlockT *exit = N->getBlock();
  555. if (!exit)
  556. break;
  557. if (isRegion(entry, exit)) {
  558. RegionT *newRegion = createRegion(entry, exit);
  559. if (lastRegion)
  560. newRegion->addSubRegion(lastRegion);
  561. lastRegion = newRegion;
  562. lastExit = exit;
  563. }
  564. // This can never be a region, so stop the search.
  565. if (!DT->dominates(entry, exit))
  566. break;
  567. }
  568. // Tried to create regions from entry to lastExit. Next time take a
  569. // shortcut from entry to lastExit.
  570. if (lastExit != entry)
  571. insertShortCut(entry, lastExit, ShortCut);
  572. }
  573. template <class Tr>
  574. void RegionInfoBase<Tr>::scanForRegions(FuncT &F, BBtoBBMap *ShortCut) {
  575. using FuncPtrT = std::add_pointer_t<FuncT>;
  576. BlockT *entry = GraphTraits<FuncPtrT>::getEntryNode(&F);
  577. DomTreeNodeT *N = DT->getNode(entry);
  578. // Iterate over the dominance tree in post order to start with the small
  579. // regions from the bottom of the dominance tree. If the small regions are
  580. // detected first, detection of bigger regions is faster, as we can jump
  581. // over the small regions.
  582. for (auto DomNode : post_order(N))
  583. findRegionsWithEntry(DomNode->getBlock(), ShortCut);
  584. }
  585. template <class Tr>
  586. typename Tr::RegionT *RegionInfoBase<Tr>::getTopMostParent(RegionT *region) {
  587. while (region->getParent())
  588. region = region->getParent();
  589. return region;
  590. }
  591. template <class Tr>
  592. void RegionInfoBase<Tr>::buildRegionsTree(DomTreeNodeT *N, RegionT *region) {
  593. BlockT *BB = N->getBlock();
  594. // Passed region exit
  595. while (BB == region->getExit())
  596. region = region->getParent();
  597. typename BBtoRegionMap::iterator it = BBtoRegion.find(BB);
  598. // This basic block is a start block of a region. It is already in the
  599. // BBtoRegion relation. Only the child basic blocks have to be updated.
  600. if (it != BBtoRegion.end()) {
  601. RegionT *newRegion = it->second;
  602. region->addSubRegion(getTopMostParent(newRegion));
  603. region = newRegion;
  604. } else {
  605. BBtoRegion[BB] = region;
  606. }
  607. for (DomTreeNodeBase<BlockT> *C : *N) {
  608. buildRegionsTree(C, region);
  609. }
  610. }
  611. #ifdef EXPENSIVE_CHECKS
  612. template <class Tr>
  613. bool RegionInfoBase<Tr>::VerifyRegionInfo = true;
  614. #else
  615. template <class Tr>
  616. bool RegionInfoBase<Tr>::VerifyRegionInfo = false;
  617. #endif
  618. template <class Tr>
  619. typename Tr::RegionT::PrintStyle RegionInfoBase<Tr>::printStyle =
  620. RegionBase<Tr>::PrintNone;
  621. template <class Tr>
  622. void RegionInfoBase<Tr>::print(raw_ostream &OS) const {
  623. OS << "Region tree:\n";
  624. TopLevelRegion->print(OS, true, 0, printStyle);
  625. OS << "End region tree\n";
  626. }
  627. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  628. template <class Tr>
  629. void RegionInfoBase<Tr>::dump() const { print(dbgs()); }
  630. #endif
  631. template <class Tr> void RegionInfoBase<Tr>::releaseMemory() {
  632. BBtoRegion.clear();
  633. if (TopLevelRegion) {
  634. delete TopLevelRegion;
  635. TopLevelRegion = nullptr;
  636. }
  637. }
  638. template <class Tr>
  639. void RegionInfoBase<Tr>::verifyAnalysis() const {
  640. // Do only verify regions if explicitely activated using EXPENSIVE_CHECKS or
  641. // -verify-region-info
  642. if (!RegionInfoBase<Tr>::VerifyRegionInfo)
  643. return;
  644. TopLevelRegion->verifyRegionNest();
  645. verifyBBMap(TopLevelRegion);
  646. }
  647. // Region pass manager support.
  648. template <class Tr>
  649. typename Tr::RegionT *RegionInfoBase<Tr>::getRegionFor(BlockT *BB) const {
  650. return BBtoRegion.lookup(BB);
  651. }
  652. template <class Tr>
  653. void RegionInfoBase<Tr>::setRegionFor(BlockT *BB, RegionT *R) {
  654. BBtoRegion[BB] = R;
  655. }
  656. template <class Tr>
  657. typename Tr::RegionT *RegionInfoBase<Tr>::operator[](BlockT *BB) const {
  658. return getRegionFor(BB);
  659. }
  660. template <class Tr>
  661. typename RegionInfoBase<Tr>::BlockT *
  662. RegionInfoBase<Tr>::getMaxRegionExit(BlockT *BB) const {
  663. BlockT *Exit = nullptr;
  664. while (true) {
  665. // Get largest region that starts at BB.
  666. RegionT *R = getRegionFor(BB);
  667. while (R && R->getParent() && R->getParent()->getEntry() == BB)
  668. R = R->getParent();
  669. // Get the single exit of BB.
  670. if (R && R->getEntry() == BB)
  671. Exit = R->getExit();
  672. else {
  673. auto next = BlockTraits::child_begin(BB);
  674. ++next;
  675. if (next == BlockTraits::child_end(BB))
  676. Exit = *BlockTraits::child_begin(BB);
  677. else // No single exit exists.
  678. return Exit;
  679. }
  680. // Get largest region that starts at Exit.
  681. RegionT *ExitR = getRegionFor(Exit);
  682. while (ExitR && ExitR->getParent() &&
  683. ExitR->getParent()->getEntry() == Exit)
  684. ExitR = ExitR->getParent();
  685. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(Exit),
  686. InvBlockTraits::child_end(Exit))) {
  687. if (!R->contains(Pred) && !ExitR->contains(Pred))
  688. break;
  689. }
  690. // This stops infinite cycles.
  691. if (DT->dominates(Exit, BB))
  692. break;
  693. BB = Exit;
  694. }
  695. return Exit;
  696. }
  697. template <class Tr>
  698. typename Tr::RegionT *RegionInfoBase<Tr>::getCommonRegion(RegionT *A,
  699. RegionT *B) const {
  700. assert(A && B && "One of the Regions is NULL");
  701. if (A->contains(B))
  702. return A;
  703. while (!B->contains(A))
  704. B = B->getParent();
  705. return B;
  706. }
  707. template <class Tr>
  708. typename Tr::RegionT *
  709. RegionInfoBase<Tr>::getCommonRegion(SmallVectorImpl<RegionT *> &Regions) const {
  710. RegionT *ret = Regions.pop_back_val();
  711. for (RegionT *R : Regions)
  712. ret = getCommonRegion(ret, R);
  713. return ret;
  714. }
  715. template <class Tr>
  716. typename Tr::RegionT *
  717. RegionInfoBase<Tr>::getCommonRegion(SmallVectorImpl<BlockT *> &BBs) const {
  718. RegionT *ret = getRegionFor(BBs.back());
  719. BBs.pop_back();
  720. for (BlockT *BB : BBs)
  721. ret = getCommonRegion(ret, getRegionFor(BB));
  722. return ret;
  723. }
  724. template <class Tr>
  725. void RegionInfoBase<Tr>::calculate(FuncT &F) {
  726. using FuncPtrT = std::add_pointer_t<FuncT>;
  727. // ShortCut a function where for every BB the exit of the largest region
  728. // starting with BB is stored. These regions can be threated as single BBS.
  729. // This improves performance on linear CFGs.
  730. BBtoBBMap ShortCut;
  731. scanForRegions(F, &ShortCut);
  732. BlockT *BB = GraphTraits<FuncPtrT>::getEntryNode(&F);
  733. buildRegionsTree(DT->getNode(BB), TopLevelRegion);
  734. }
  735. } // end namespace llvm
  736. #undef DEBUG_TYPE
  737. #endif // LLVM_ANALYSIS_REGIONINFOIMPL_H
  738. #ifdef __GNUC__
  739. #pragma GCC diagnostic pop
  740. #endif