graph.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 (size_t i = 0; i < ll->caseTbl2.size(); i++)
  78. pBB->addOutEdge(ll->caseTbl2[i]);
  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. auto iter=heldBBs.begin();
  125. /* Convert list of BBs into a graph */
  126. for (; iter!=heldBBs.end(); ++iter)
  127. {
  128. pBB = *iter;
  129. for (size_t edeg_idx = 0; edeg_idx < pBB->edges.size(); edeg_idx++)
  130. {
  131. int32_t ip = pBB->edges[edeg_idx].ip;
  132. if (ip >= SYNTHESIZED_MIN)
  133. {
  134. fatalError (INVALID_SYNTHETIC_BB);
  135. return;
  136. }
  137. auto iter2=std::find_if(heldBBs.begin(),heldBBs.end(),
  138. [ip](BB *psBB)->bool {return psBB->begin()->loc_ip==ip;});
  139. if(iter2==heldBBs.end())
  140. fatalError(NO_BB, ip, name.c_str());
  141. psBB = *iter2;
  142. pBB->edges[edeg_idx].BBptr = psBB;
  143. psBB->inEdges.push_back((BB *)nullptr);
  144. }
  145. }
  146. }
  147. void Function::markImpure()
  148. {
  149. PROG &prog(Project::get()->prog);
  150. for(ICODE &icod : Icode)
  151. {
  152. if ( not icod.ll()->testFlags(SYM_USE | SYM_DEF))
  153. continue;
  154. //assert that case tbl has less entries then symbol table ????
  155. //WARNING: Case entries are held in symbol table !
  156. assert(Project::get()->validSymIdx(icod.ll()->caseEntry));
  157. const SYM &psym(Project::get()->getSymByIdx(icod.ll()->caseEntry));
  158. for (int c = (int)psym.label; c < (int)psym.label+psym.size; c++)
  159. {
  160. if (BITMAP(c, BM_CODE))
  161. {
  162. icod.ll()->setFlags(IMPURE);
  163. flg |= IMPURE;
  164. break;
  165. }
  166. }
  167. }
  168. }
  169. /*****************************************************************************
  170. * newBB - Allocate new BB and link to end of list
  171. *****************************************************************************/
  172. /*****************************************************************************
  173. * freeCFG - Deallocates a cfg
  174. ****************************************************************************/
  175. void Function::freeCFG()
  176. {
  177. for(BB *p : heldBBs)
  178. {
  179. delete p;
  180. }
  181. }
  182. /*****************************************************************************
  183. * compressCFG - Remove redundancies and add in-edge information
  184. ****************************************************************************/
  185. void Function::compressCFG()
  186. {
  187. BB *pNxt;
  188. int ip, first=0, last;
  189. /* First pass over BB list removes redundant jumps of the form
  190. * (Un)Conditional -> Unconditional jump */
  191. for (BB *pBB : m_actual_cfg) //m_cfg
  192. {
  193. if(pBB->inEdges.empty() || (pBB->nodeType != ONE_BRANCH && pBB->nodeType != TWO_BRANCH))
  194. continue;
  195. for (TYPEADR_TYPE &edgeRef : pBB->edges)
  196. {
  197. ip = pBB->rbegin()->loc_ip;
  198. pNxt = edgeRef.BBptr->rmJMP(ip, edgeRef.BBptr);
  199. if (not pBB->edges.empty()) /* Might have been clobbered */
  200. {
  201. edgeRef.BBptr = pNxt;
  202. assert(pBB->back().loc_ip==ip);
  203. pBB->back().ll()->SetImmediateOp((uint32_t)pNxt->begin()->loc_ip);
  204. //Icode[ip].SetImmediateOp((uint32_t)pNxt->begin());
  205. }
  206. }
  207. }
  208. /* Next is a depth-first traversal merging any FALL_NODE or
  209. * ONE_BRANCH that fall through to a node with that as their only
  210. * in-edge. */
  211. m_actual_cfg.front()->mergeFallThrough(Icode);
  212. /* Remove redundant BBs created by the above compressions
  213. * and allocate in-edge arrays as required. */
  214. stats.numBBaft = stats.numBBbef;
  215. bool entry_node=true;
  216. for(BB *pBB : m_actual_cfg)
  217. {
  218. if (pBB->inEdges.empty())
  219. {
  220. if (entry_node) /* Init it misses out on */
  221. pBB->index = UN_INIT;
  222. else
  223. {
  224. delete pBB;
  225. stats.numBBaft--;
  226. }
  227. }
  228. else
  229. {
  230. pBB->inEdgeCount = pBB->inEdges.size();
  231. }
  232. entry_node=false;
  233. }
  234. /* Allocate storage for dfsLast[] array */
  235. numBBs = stats.numBBaft;
  236. m_dfsLast.resize(numBBs,0); // = (BB **)allocMem(numBBs * sizeof(BB *))
  237. /* Now do a dfs numbering traversal and fill in the inEdges[] array */
  238. last = numBBs - 1;
  239. m_actual_cfg.front()->dfsNumbering(m_dfsLast, &first, &last);
  240. }
  241. /****************************************************************************
  242. * rmJMP - If BB addressed is just a JMP it is replaced with its target
  243. ***************************************************************************/
  244. BB *BB::rmJMP(int marker, BB * pBB)
  245. {
  246. marker += (int)DFS_JMP;
  247. while (pBB->nodeType == ONE_BRANCH && pBB->size() == 1)
  248. {
  249. if (pBB->traversed != marker)
  250. {
  251. pBB->traversed = (eDFS)marker;
  252. pBB->inEdges.pop_back();
  253. if (not pBB->inEdges.empty())
  254. {
  255. pBB->edges[0].BBptr->inEdges.push_back((BB *)nullptr);
  256. }
  257. else
  258. {
  259. pBB->front().ll()->setFlags(NO_CODE);
  260. pBB->front().invalidate(); //pProc->Icode.SetLlInvalid(pBB->begin(), true);
  261. }
  262. pBB = pBB->edges[0].BBptr;
  263. }
  264. else
  265. {
  266. /* We are going around in circles */
  267. pBB->nodeType = NOWHERE_NODE;
  268. pBB->front().ll()->replaceSrc(LLOperand::CreateImm2(pBB->front().loc_ip));
  269. //pBB->front().ll()->src.immed.op = pBB->front().loc_ip;
  270. do {
  271. pBB = pBB->edges[0].BBptr;
  272. pBB->inEdges.pop_back(); // was --numInedges
  273. if (! pBB->inEdges.empty())
  274. {
  275. pBB->front().ll()->setFlags(NO_CODE);
  276. pBB->front().invalidate();
  277. // pProc->Icode.setFlags(pBB->start, NO_CODE);
  278. // pProc->Icode.SetLlInvalid(pBB->start, true);
  279. }
  280. } while (pBB->nodeType != NOWHERE_NODE);
  281. pBB->edges.clear();
  282. }
  283. }
  284. return pBB;
  285. }
  286. /*****************************************************************************
  287. * mergeFallThrough
  288. ****************************************************************************/
  289. void BB::mergeFallThrough( CIcodeRec &Icode)
  290. {
  291. BB * pChild;
  292. if (!this)
  293. {
  294. printf("mergeFallThrough on empty BB!\n");
  295. }
  296. while (nodeType == FALL_NODE || nodeType == ONE_BRANCH)
  297. {
  298. pChild = edges[0].BBptr;
  299. /* Jump to next instruction can always be removed */
  300. if (nodeType == ONE_BRANCH)
  301. {
  302. assert(Parent==pChild->Parent);
  303. if(back().loc_ip>pChild->front().loc_ip) // back edege
  304. break;
  305. auto iter=std::find_if(this->end(),pChild->begin(),[](ICODE &c)
  306. {return not c.ll()->testFlags(NO_CODE);});
  307. if (iter != pChild->begin())
  308. break;
  309. back().ll()->setFlags(NO_CODE);
  310. back().invalidate();
  311. nodeType = FALL_NODE;
  312. //instructions.advance_end(-1); //TODO: causes creation of empty BB
  313. }
  314. /* If there's no other edges into child can merge */
  315. if (pChild->inEdges.size() != 1)
  316. break;
  317. nodeType = pChild->nodeType;
  318. instructions = boost::make_iterator_range(begin(),pChild->end());
  319. pChild->front().ll()->clrFlags(TARGET);
  320. edges.swap(pChild->edges);
  321. pChild->inEdges.clear();
  322. pChild->edges.clear();
  323. }
  324. traversed = DFS_MERGE;
  325. /* Process all out edges recursively */
  326. for (size_t i = 0; i < edges.size(); i++)
  327. {
  328. if (edges[i].BBptr->traversed != DFS_MERGE)
  329. edges[i].BBptr->mergeFallThrough(Icode);
  330. }
  331. }
  332. /*****************************************************************************
  333. * dfsNumbering - Numbers nodes during first and last visits and determine
  334. * in-edges
  335. ****************************************************************************/
  336. void BB::dfsNumbering(std::vector<BB *> &dfsLast, int *first, int *last)
  337. {
  338. BB * pChild;
  339. traversed = DFS_NUM;
  340. dfsFirstNum = (*first)++;
  341. /* index is being used as an index to inEdges[]. */
  342. // for (i = 0; i < edges.size(); i++)
  343. for(auto edge : edges)
  344. {
  345. pChild = edge.BBptr;
  346. pChild->inEdges[pChild->index++] = this;
  347. /* Is this the last visit? */
  348. if (pChild->index == int(pChild->inEdges.size()))
  349. pChild->index = UN_INIT;
  350. if (pChild->traversed != DFS_NUM)
  351. pChild->dfsNumbering(dfsLast, first, last);
  352. }
  353. dfsLastNum = *last;
  354. dfsLast[(*last)--] = this;
  355. }