graph.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*****************************************************************************
  2. * dcc project CFG related functions
  3. * (C) Cristina Cifuentes
  4. ****************************************************************************/
  5. #include <string.h>
  6. #include <boost/range/rbegin.hpp>
  7. #include <boost/range/rend.hpp>
  8. #include <boost/range/adaptors.hpp>
  9. #include "dcc.h"
  10. #include "graph.h"
  11. #include "project.h"
  12. using namespace std;
  13. using namespace boost;
  14. extern Project g_proj;
  15. //static BB * rmJMP(Function * pProc, int marker, BB * pBB);
  16. //static void mergeFallThrough(Function * pProc, BB * pBB);
  17. //static void dfsNumbering(BB * pBB, std::vector<BB*> &dfsLast, int *first, int *last);
  18. /*****************************************************************************
  19. * createCFG - Create the basic control flow graph
  20. ****************************************************************************/
  21. void Function::createCFG()
  22. {
  23. /* Splits Icode associated with the procedure into Basic Blocks.
  24. * The links between BBs represent the control flow graph of the
  25. * procedure.
  26. * A Basic Block is defined to end on one of the following instructions:
  27. * 1) Conditional and unconditional jumps
  28. * 2) CALL(F)
  29. * 3) RET(F)
  30. * 4) On the instruction before a join (a flagged TARGET)
  31. * 5) Repeated string instructions
  32. * 6) End of procedure
  33. */
  34. BB * psBB;
  35. BB * pBB;
  36. iICODE pIcode = Icode.begin();
  37. stats.numBBbef = stats.numBBaft = 0;
  38. rICODE current_range=make_iterator_range(pIcode,++iICODE(pIcode));
  39. for (; pIcode!=Icode.end(); ++pIcode,current_range.advance_end(1))
  40. {
  41. iICODE nextIcode = ++iICODE(pIcode);
  42. pBB = nullptr;
  43. LLInst *ll = pIcode->ll();
  44. /* Only process icodes that have valid instructions */
  45. if(ll->testFlags(NO_CODE))
  46. continue;
  47. /* Stick a NOWHERE_NODE on the end if we terminate
  48. * with anything other than a ret, jump or terminate */
  49. if (nextIcode == Icode.end() and
  50. (not ll->testFlags(TERMINATES)) and
  51. (not ll->match(iJMP)) and (not ll->match(iJMPF)) and
  52. (not ll->match(iRET)) and (not ll->match(iRETF)))
  53. {
  54. pBB=BB::Create(current_range, NOWHERE_NODE, this);
  55. }
  56. else
  57. switch (ll->getOpcode()) {
  58. case iJB: case iJBE: case iJAE: case iJA:
  59. case iJL: case iJLE: case iJGE: case iJG:
  60. case iJE: case iJNE: case iJS: case iJNS:
  61. case iJO: case iJNO: case iJP: case iJNP:
  62. case iJCXZ:
  63. pBB = BB::Create(current_range, TWO_BRANCH, this);
  64. CondJumps:
  65. pBB->addOutEdge(nextIcode->loc_ip);
  66. /* This is checking for jumps off into nowhere */
  67. if ( not ll->testFlags(NO_LABEL) )
  68. pBB->addOutEdge(ll->src().getImm2());
  69. break;
  70. case iLOOP: case iLOOPE: case iLOOPNE:
  71. pBB = BB::Create(current_range, LOOP_NODE, this);
  72. goto CondJumps;
  73. case iJMPF: case iJMP:
  74. if (ll->testFlags(SWITCH))
  75. {
  76. pBB = BB::Create(current_range, MULTI_BRANCH, this);
  77. for (auto & elem : ll->caseTbl2)
  78. pBB->addOutEdge(elem);
  79. hasCase = true;
  80. }
  81. else if ((ll->getFlag() & (I | NO_LABEL)) == I) //TODO: WHY NO_LABEL TESTIT
  82. {
  83. pBB = BB::Create(current_range, ONE_BRANCH, this);
  84. pBB->addOutEdge(ll->src().getImm2());
  85. }
  86. else
  87. pBB = BB::Create(current_range, NOWHERE_NODE, this);
  88. break;
  89. case iCALLF: case iCALL:
  90. {
  91. Function * p = ll->src().proc.proc;
  92. pBB = BB::Create(current_range, CALL_NODE, this);
  93. if (p && not ((p->flg) & TERMINATES) )
  94. pBB->addOutEdge(nextIcode->loc_ip);
  95. break;
  96. }
  97. case iRET: case iRETF:
  98. pBB = BB::Create(current_range, RETURN_NODE, this);
  99. break;
  100. default:
  101. /* Check for exit to DOS */
  102. if ( ll->testFlags(TERMINATES) )
  103. {
  104. pBB = BB::Create(current_range, TERMINATE_NODE, this);
  105. }
  106. /* Check for a fall through */
  107. else if (nextIcode != Icode.end())
  108. {
  109. if (nextIcode->ll()->testFlags(TARGET | CASE))
  110. {
  111. pBB = BB::Create(current_range, FALL_NODE, this);
  112. pBB->addOutEdge(nextIcode->loc_ip);
  113. }
  114. }
  115. break;
  116. }
  117. if(pBB!=nullptr) // created a new Basic block
  118. {
  119. // restart the range
  120. // end iterator will be updated by expression in for statement
  121. current_range=make_iterator_range(nextIcode,nextIcode);
  122. }
  123. }
  124. for (auto pr : m_ip_to_bb)
  125. {
  126. BB* pBB=pr.second;
  127. for (auto & elem : pBB->edges)
  128. {
  129. int32_t ip = elem.ip;
  130. if (ip >= SYNTHESIZED_MIN)
  131. {
  132. fatalError (INVALID_SYNTHETIC_BB);
  133. return;
  134. }
  135. auto iter2=m_ip_to_bb.find(ip);
  136. if(iter2==m_ip_to_bb.end())
  137. fatalError(NO_BB, ip, name.c_str());
  138. psBB = iter2->second;
  139. elem.BBptr = psBB;
  140. psBB->inEdges.push_back((BB *)nullptr);
  141. }
  142. }
  143. }
  144. void Function::markImpure()
  145. {
  146. PROG &prog(Project::get()->prog);
  147. for(ICODE &icod : Icode)
  148. {
  149. if ( not icod.ll()->testFlags(SYM_USE | SYM_DEF))
  150. continue;
  151. //assert that case tbl has less entries then symbol table ????
  152. //WARNING: Case entries are held in symbol table !
  153. assert(Project::get()->validSymIdx(icod.ll()->caseEntry));
  154. const SYM &psym(Project::get()->getSymByIdx(icod.ll()->caseEntry));
  155. for (int c = (int)psym.label; c < (int)psym.label+psym.size; c++)
  156. {
  157. if (BITMAP(c, BM_CODE))
  158. {
  159. icod.ll()->setFlags(IMPURE);
  160. flg |= IMPURE;
  161. break;
  162. }
  163. }
  164. }
  165. }
  166. /*****************************************************************************
  167. * freeCFG - Deallocates a cfg
  168. ****************************************************************************/
  169. void Function::freeCFG()
  170. {
  171. for(auto p : m_ip_to_bb)
  172. {
  173. delete p.second;
  174. }
  175. m_ip_to_bb.clear();
  176. }
  177. /*****************************************************************************
  178. * compressCFG - Remove redundancies and add in-edge information
  179. ****************************************************************************/
  180. void Function::compressCFG()
  181. {
  182. BB *pNxt;
  183. int ip, first=0, last;
  184. /* First pass over BB list removes redundant jumps of the form
  185. * (Un)Conditional -> Unconditional jump */
  186. for (BB *pBB : m_actual_cfg) //m_cfg
  187. {
  188. if(pBB->inEdges.empty() || (pBB->nodeType != ONE_BRANCH && pBB->nodeType != TWO_BRANCH))
  189. continue;
  190. for (TYPEADR_TYPE &edgeRef : pBB->edges)
  191. {
  192. ip = pBB->rbegin()->loc_ip;
  193. pNxt = edgeRef.BBptr->rmJMP(ip, edgeRef.BBptr);
  194. if (not pBB->edges.empty()) /* Might have been clobbered */
  195. {
  196. edgeRef.BBptr = pNxt;
  197. assert(pBB->back().loc_ip==ip);
  198. pBB->back().ll()->SetImmediateOp((uint32_t)pNxt->begin()->loc_ip);
  199. //Icode[ip].SetImmediateOp((uint32_t)pNxt->begin());
  200. }
  201. }
  202. }
  203. /* Next is a depth-first traversal merging any FALL_NODE or
  204. * ONE_BRANCH that fall through to a node with that as their only
  205. * in-edge. */
  206. m_actual_cfg.front()->mergeFallThrough(Icode);
  207. /* Remove redundant BBs created by the above compressions
  208. * and allocate in-edge arrays as required. */
  209. stats.numBBaft = stats.numBBbef;
  210. bool entry_node=true;
  211. for(BB *pBB : m_actual_cfg)
  212. {
  213. if (pBB->inEdges.empty())
  214. {
  215. if (entry_node) /* Init it misses out on */
  216. pBB->index = UN_INIT;
  217. else
  218. {
  219. delete pBB;
  220. stats.numBBaft--;
  221. }
  222. }
  223. else
  224. {
  225. pBB->inEdgeCount = pBB->inEdges.size();
  226. }
  227. entry_node=false;
  228. }
  229. /* Allocate storage for dfsLast[] array */
  230. numBBs = stats.numBBaft;
  231. m_dfsLast.resize(numBBs,nullptr); // = (BB **)allocMem(numBBs * sizeof(BB *))
  232. /* Now do a dfs numbering traversal and fill in the inEdges[] array */
  233. last = numBBs - 1;
  234. m_actual_cfg.front()->dfsNumbering(m_dfsLast, &first, &last);
  235. }
  236. /****************************************************************************
  237. * rmJMP - If BB addressed is just a JMP it is replaced with its target
  238. ***************************************************************************/
  239. BB *BB::rmJMP(int marker, BB * pBB)
  240. {
  241. marker += (int)DFS_JMP;
  242. while (pBB->nodeType == ONE_BRANCH && pBB->size() == 1)
  243. {
  244. if (pBB->traversed != marker)
  245. {
  246. pBB->traversed = (eDFS)marker;
  247. pBB->inEdges.pop_back();
  248. if (not pBB->inEdges.empty())
  249. {
  250. pBB->edges[0].BBptr->inEdges.push_back((BB *)nullptr);
  251. }
  252. else
  253. {
  254. pBB->front().ll()->setFlags(NO_CODE);
  255. pBB->front().invalidate(); //pProc->Icode.SetLlInvalid(pBB->begin(), true);
  256. }
  257. pBB = pBB->edges[0].BBptr;
  258. }
  259. else
  260. {
  261. /* We are going around in circles */
  262. pBB->nodeType = NOWHERE_NODE;
  263. pBB->front().ll()->replaceSrc(LLOperand::CreateImm2(pBB->front().loc_ip));
  264. //pBB->front().ll()->src.immed.op = pBB->front().loc_ip;
  265. do {
  266. pBB = pBB->edges[0].BBptr;
  267. pBB->inEdges.pop_back(); // was --numInedges
  268. if (! pBB->inEdges.empty())
  269. {
  270. pBB->front().ll()->setFlags(NO_CODE);
  271. pBB->front().invalidate();
  272. // pProc->Icode.setFlags(pBB->start, NO_CODE);
  273. // pProc->Icode.SetLlInvalid(pBB->start, true);
  274. }
  275. } while (pBB->nodeType != NOWHERE_NODE);
  276. pBB->edges.clear();
  277. }
  278. }
  279. return pBB;
  280. }
  281. /*****************************************************************************
  282. * mergeFallThrough
  283. ****************************************************************************/
  284. void BB::mergeFallThrough( CIcodeRec &Icode)
  285. {
  286. BB * pChild;
  287. if (!this)
  288. {
  289. printf("mergeFallThrough on empty BB!\n");
  290. }
  291. while (nodeType == FALL_NODE || nodeType == ONE_BRANCH)
  292. {
  293. pChild = edges[0].BBptr;
  294. /* Jump to next instruction can always be removed */
  295. if (nodeType == ONE_BRANCH)
  296. {
  297. assert(Parent==pChild->Parent);
  298. if(back().loc_ip>pChild->front().loc_ip) // back edege
  299. break;
  300. auto iter=std::find_if(this->end(),pChild->begin(),[](ICODE &c)
  301. {return not c.ll()->testFlags(NO_CODE);});
  302. if (iter != pChild->begin())
  303. break;
  304. back().ll()->setFlags(NO_CODE);
  305. back().invalidate();
  306. nodeType = FALL_NODE;
  307. //instructions.advance_end(-1); //TODO: causes creation of empty BB
  308. }
  309. /* If there's no other edges into child can merge */
  310. if (pChild->inEdges.size() != 1)
  311. break;
  312. nodeType = pChild->nodeType;
  313. instructions = boost::make_iterator_range(begin(),pChild->end());
  314. pChild->front().ll()->clrFlags(TARGET);
  315. edges.swap(pChild->edges);
  316. pChild->inEdges.clear();
  317. pChild->edges.clear();
  318. }
  319. traversed = DFS_MERGE;
  320. /* Process all out edges recursively */
  321. for (auto & elem : edges)
  322. {
  323. if (elem.BBptr->traversed != DFS_MERGE)
  324. elem.BBptr->mergeFallThrough(Icode);
  325. }
  326. }
  327. /*****************************************************************************
  328. * dfsNumbering - Numbers nodes during first and last visits and determine
  329. * in-edges
  330. ****************************************************************************/
  331. void BB::dfsNumbering(std::vector<BB *> &dfsLast, int *first, int *last)
  332. {
  333. BB * pChild;
  334. traversed = DFS_NUM;
  335. dfsFirstNum = (*first)++;
  336. /* index is being used as an index to inEdges[]. */
  337. // for (i = 0; i < edges.size(); i++)
  338. for(auto edge : edges)
  339. {
  340. pChild = edge.BBptr;
  341. pChild->inEdges[pChild->index++] = this;
  342. /* Is this the last visit? */
  343. if (pChild->index == int(pChild->inEdges.size()))
  344. pChild->index = UN_INIT;
  345. if (pChild->traversed != DFS_NUM)
  346. pChild->dfsNumbering(dfsLast, first, last);
  347. }
  348. dfsLastNum = *last;
  349. dfsLast[(*last)--] = this;
  350. }