BasicBlock.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. #include <cassert>
  2. #include <string>
  3. #include <boost/range/rbegin.hpp>
  4. #include <boost/range/rend.hpp>
  5. #include <boost/range/adaptors.hpp>
  6. #include "BasicBlock.h"
  7. #include "Procedure.h"
  8. #include "dcc.h"
  9. using namespace std;
  10. using namespace boost;
  11. BB *BB::Create(void */*ctx*/, const string &/*s*/, Function *parent, BB */*insertBefore*/)
  12. {
  13. BB *pnewBB = new BB;
  14. pnewBB->Parent = parent;
  15. return pnewBB;
  16. }
  17. /**
  18. * @arg start - basic block starts here, might be parent->Icode.end()
  19. * @arg fin - last of basic block's instructions
  20. */
  21. BB *BB::Create(const rCODE &r,uint8_t _nodeType, Function *parent)
  22. {
  23. BB* pnewBB;
  24. pnewBB = new BB;
  25. pnewBB->nodeType = _nodeType; /* Initialise */
  26. pnewBB->immedDom = NO_DOM;
  27. pnewBB->loopHead = pnewBB->caseHead = pnewBB->caseTail =
  28. pnewBB->latchNode= pnewBB->loopFollow = NO_NODE;
  29. pnewBB->instructions = r;
  30. /* Mark the basic block to which the icodes belong to, but only for
  31. * real code basic blocks (ie. not interval bbs) */
  32. if(parent)
  33. {
  34. //setInBB should automatically handle if our range is empty
  35. parent->Icode.SetInBB(pnewBB->instructions, pnewBB);
  36. parent->heldBBs.push_back(pnewBB);
  37. parent->m_cfg.push_back(pnewBB);
  38. pnewBB->Parent = parent;
  39. }
  40. if ( r.begin() != parent->Icode.end() ) /* Only for code BB's */
  41. stats.numBBbef++;
  42. return pnewBB;
  43. }
  44. BB *BB::CreateIntervalBB(Function *parent)
  45. {
  46. iICODE endOfParent = parent->Icode.end();
  47. return Create(make_iterator_range(endOfParent,endOfParent),INTERVAL_NODE,parent);
  48. }
  49. static const char *const s_nodeType[] = {"branch", "if", "case", "fall", "return", "call",
  50. "loop", "repeat", "interval", "cycleHead",
  51. "caseHead", "terminate",
  52. "nowhere" };
  53. static const char *const s_loopType[] = {"noLoop", "while", "repeat", "loop", "for"};
  54. void BB::display()
  55. {
  56. printf("\nnode type = %s, ", s_nodeType[nodeType]);
  57. printf("start = %d, length = %zd, #out edges = %zd\n", begin()->loc_ip, size(), edges.size());
  58. for (size_t i = 0; i < edges.size(); i++)
  59. {
  60. if(edges[i].BBptr==0)
  61. printf(" outEdge[%2zd] = Unlinked out edge to %d\n",i, edges[i].ip);
  62. else
  63. printf(" outEdge[%2zd] = %d\n",i, edges[i].BBptr->begin()->loc_ip);
  64. }
  65. }
  66. /*****************************************************************************
  67. * displayDfs - Displays the CFG using a depth first traversal
  68. ****************************************************************************/
  69. void BB::displayDfs()
  70. {
  71. int i;
  72. assert(this);
  73. traversed = DFS_DISP;
  74. printf("node type = %s, ", s_nodeType[nodeType]);
  75. printf("start = %d, length = %zd, #in-edges = %zd, #out-edges = %zd\n",
  76. begin()->loc_ip, size(), inEdges.size(), edges.size());
  77. printf("dfsFirst = %d, dfsLast = %d, immed dom = %d\n",
  78. dfsFirstNum, dfsLastNum,
  79. immedDom == MAX ? -1 : immedDom);
  80. printf("loopType = %s, loopHead = %d, latchNode = %d, follow = %d\n",
  81. s_loopType[loopType],
  82. loopHead == MAX ? -1 : loopHead,
  83. latchNode == MAX ? -1 : latchNode,
  84. loopFollow == MAX ? -1 : loopFollow);
  85. printf ("ifFollow = %d, caseHead = %d, caseTail = %d\n",
  86. ifFollow == MAX ? -1 : ifFollow,
  87. caseHead == MAX ? -1 : caseHead,
  88. caseTail == MAX ? -1 : caseTail);
  89. if (nodeType == INTERVAL_NODE)
  90. printf("corresponding interval = %d\n", correspInt->numInt);
  91. else
  92. {
  93. int edge_idx=0;
  94. for(BB *node : inEdges)
  95. {
  96. printf (" inEdge[%d] = %d\n", edge_idx, node->begin()->loc_ip);
  97. edge_idx++;
  98. }
  99. }
  100. /* Display out edges information */
  101. i=0;
  102. for(TYPEADR_TYPE &edg : edges)
  103. {
  104. if (nodeType == INTERVAL_NODE)
  105. printf(" outEdge[%d] = %d\n", i, edg.BBptr->correspInt->numInt);
  106. else
  107. printf(" outEdge[%d] = %d\n", i, edg.BBptr->begin()->loc_ip);
  108. ++i;
  109. }
  110. printf("----\n");
  111. /* Recursive call on successors of current node */
  112. for(TYPEADR_TYPE &pb : edges)
  113. {
  114. if (pb.BBptr->traversed != DFS_DISP)
  115. pb.BBptr->displayDfs();
  116. }
  117. }
  118. /* Recursive procedure that writes the code for the given procedure, pointed
  119. * to by pBB.
  120. * Parameters: pBB: pointer to the cfg.
  121. * Icode: pointer to the Icode array for the cfg graph of the
  122. * current procedure.
  123. * indLevel: indentation level - used for formatting.
  124. * numLoc: last # assigned to local variables */
  125. ICODE* BB::writeLoopHeader(int &indLevel, Function* pProc, int *numLoc, BB *&latch, boolT &repCond)
  126. {
  127. latch = pProc->m_dfsLast[this->latchNode];
  128. std::ostringstream ostr;
  129. ICODE* picode;
  130. switch (loopType)
  131. {
  132. case WHILE_TYPE:
  133. picode = &this->back();
  134. /* Check for error in while condition */
  135. if (picode->hl()->opcode != HLI_JCOND)
  136. reportError (WHILE_FAIL);
  137. /* Check if condition is more than 1 HL instruction */
  138. if (numHlIcodes > 1)
  139. {
  140. /* Write the code for this basic block */
  141. writeBB(ostr,indLevel, pProc, numLoc);
  142. repCond = true;
  143. }
  144. /* Condition needs to be inverted if the loop body is along
  145. * the THEN path of the header node */
  146. if (edges[ELSE].BBptr->dfsLastNum == loopFollow)
  147. {
  148. picode->hl()->replaceExpr(picode->hl()->expr()->inverse());
  149. }
  150. {
  151. string e=walkCondExpr (picode->hl()->expr(), pProc, numLoc);
  152. ostr << "\n"<<indentStr(indLevel)<<"while ("<<e<<") {\n";
  153. }
  154. picode->invalidate();
  155. break;
  156. case REPEAT_TYPE:
  157. ostr << "\n"<<indentStr(indLevel)<<"do {\n";
  158. picode = &latch->back();
  159. picode->invalidate();
  160. break;
  161. case ENDLESS_TYPE:
  162. ostr << "\n"<<indentStr(indLevel)<<"for (;;) {\n";
  163. }
  164. cCode.appendCode(ostr.str());
  165. stats.numHLIcode += 1;
  166. indLevel++;
  167. return picode;
  168. }
  169. bool BB::isEndOfPath(int latch_node_idx) const
  170. {
  171. return nodeType == RETURN_NODE || nodeType == TERMINATE_NODE ||
  172. nodeType == NOWHERE_NODE || (dfsLastNum == latch_node_idx);
  173. }
  174. void BB::writeCode (int indLevel, Function * pProc , int *numLoc,int _latchNode, int _ifFollow)
  175. {
  176. int follow; /* ifFollow */
  177. BB * succ, *latch; /* Successor and latching node */
  178. ICODE * picode; /* Pointer to HLI_JCOND instruction */
  179. char *l; /* Pointer to HLI_JCOND expression */
  180. boolT emptyThen, /* THEN clause is empty */
  181. repCond; /* Repeat condition for while() */
  182. /* Check if this basic block should be analysed */
  183. if ((_ifFollow != UN_INIT) && (this == pProc->m_dfsLast[_ifFollow]))
  184. return;
  185. if (wasTraversedAtLevel(DFS_ALPHA))
  186. return;
  187. traversed = DFS_ALPHA;
  188. /* Check for start of loop */
  189. repCond = false;
  190. latch = NULL;
  191. if (loopType)
  192. {
  193. picode=writeLoopHeader(indLevel, pProc, numLoc, latch, repCond);
  194. }
  195. /* Write the code for this basic block */
  196. if (repCond == false)
  197. {
  198. std::ostringstream ostr;
  199. writeBB(ostr,indLevel, pProc, numLoc);
  200. cCode.appendCode(ostr.str());
  201. }
  202. /* Check for end of path */
  203. if (isEndOfPath(_latchNode))
  204. return;
  205. /* Check type of loop/node and process code */
  206. if ( loopType) /* there is a loop */
  207. {
  208. assert(latch);
  209. if (this != latch) /* loop is over several bbs */
  210. {
  211. if (loopType == WHILE_TYPE)
  212. {
  213. succ = edges[THEN].BBptr;
  214. if (succ->dfsLastNum == loopFollow)
  215. succ = edges[ELSE].BBptr;
  216. }
  217. else
  218. succ = edges[0].BBptr;
  219. if (succ->traversed != DFS_ALPHA)
  220. succ->writeCode (indLevel, pProc, numLoc, latch->dfsLastNum,_ifFollow);
  221. else /* has been traversed so we need a goto */
  222. succ->front().ll()->emitGotoLabel (indLevel);
  223. }
  224. /* Loop epilogue: generate the loop trailer */
  225. indLevel--;
  226. if (loopType == WHILE_TYPE)
  227. {
  228. std::ostringstream ostr;
  229. /* Check if there is need to repeat other statements involved
  230. * in while condition, then, emit the loop trailer */
  231. if (repCond)
  232. {
  233. writeBB(ostr,indLevel+1, pProc, numLoc);
  234. }
  235. ostr <<indentStr(indLevel)<< "} /* end of while */\n";
  236. cCode.appendCode(ostr.str());
  237. }
  238. else if (loopType == ENDLESS_TYPE)
  239. cCode.appendCode( "%s} /* end of loop */\n",indentStr(indLevel));
  240. else if (loopType == REPEAT_TYPE)
  241. {
  242. if (picode->hl()->opcode != HLI_JCOND)
  243. reportError (REPEAT_FAIL);
  244. {
  245. string e=walkCondExpr (picode->hl()->expr(), pProc, numLoc);
  246. cCode.appendCode( "%s} while (%s);\n", indentStr(indLevel),e.c_str());
  247. }
  248. }
  249. /* Recurse on the loop follow */
  250. if (loopFollow != MAX)
  251. {
  252. succ = pProc->m_dfsLast[loopFollow];
  253. if (succ->traversed != DFS_ALPHA)
  254. succ->writeCode (indLevel, pProc, numLoc, _latchNode, _ifFollow);
  255. else /* has been traversed so we need a goto */
  256. succ->front().ll()->emitGotoLabel (indLevel);
  257. }
  258. }
  259. else /* no loop, process nodeType of the graph */
  260. {
  261. if (nodeType == TWO_BRANCH) /* if-then[-else] */
  262. {
  263. stats.numHLIcode++;
  264. indLevel++;
  265. emptyThen = false;
  266. if (ifFollow != MAX) /* there is a follow */
  267. {
  268. /* process the THEN part */
  269. follow = ifFollow;
  270. succ = edges[THEN].BBptr;
  271. if (succ->traversed != DFS_ALPHA) /* not visited */
  272. {
  273. if (succ->dfsLastNum != follow) /* THEN part */
  274. {
  275. l = writeJcond ( *back().hl(), pProc, numLoc);
  276. cCode.appendCode( "\n%s%s", indentStr(indLevel-1), l);
  277. succ->writeCode (indLevel, pProc, numLoc, _latchNode,follow);
  278. }
  279. else /* empty THEN part => negate ELSE part */
  280. {
  281. l = writeJcondInv ( *back().hl(), pProc, numLoc);
  282. cCode.appendCode( "\n%s%s", indentStr(indLevel-1), l);
  283. edges[ELSE].BBptr->writeCode (indLevel, pProc, numLoc, _latchNode, follow);
  284. emptyThen = true;
  285. }
  286. }
  287. else /* already visited => emit label */
  288. succ->front().ll()->emitGotoLabel(indLevel);
  289. /* process the ELSE part */
  290. succ = edges[ELSE].BBptr;
  291. if (succ->traversed != DFS_ALPHA) /* not visited */
  292. {
  293. if (succ->dfsLastNum != follow) /* ELSE part */
  294. {
  295. cCode.appendCode( "%s}\n%selse {\n",
  296. indentStr(indLevel-1), indentStr(indLevel - 1));
  297. succ->writeCode (indLevel, pProc, numLoc, _latchNode, follow);
  298. }
  299. /* else (empty ELSE part) */
  300. }
  301. else if (! emptyThen) /* already visited => emit label */
  302. {
  303. cCode.appendCode( "%s}\n%selse {\n",
  304. indentStr(indLevel-1), indentStr(indLevel - 1));
  305. succ->front().ll()->emitGotoLabel (indLevel);
  306. }
  307. cCode.appendCode( "%s}\n", indentStr(--indLevel));
  308. /* Continue with the follow */
  309. succ = pProc->m_dfsLast[follow];
  310. if (succ->traversed != DFS_ALPHA)
  311. succ->writeCode (indLevel, pProc, numLoc, _latchNode,_ifFollow);
  312. }
  313. else /* no follow => if..then..else */
  314. {
  315. l = writeJcond ( *back().hl(), pProc, numLoc);
  316. cCode.appendCode( "%s%s", indentStr(indLevel-1), l);
  317. edges[THEN].BBptr->writeCode (indLevel, pProc, numLoc, _latchNode, _ifFollow);
  318. cCode.appendCode( "%s}\n%selse {\n", indentStr(indLevel-1), indentStr(indLevel - 1));
  319. edges[ELSE].BBptr->writeCode (indLevel, pProc, numLoc, _latchNode, _ifFollow);
  320. cCode.appendCode( "%s}\n", indentStr(--indLevel));
  321. }
  322. }
  323. else /* fall, call, 1w */
  324. {
  325. succ = edges[0].BBptr; /* fall-through edge */
  326. assert(succ->size()>0);
  327. if (succ->traversed != DFS_ALPHA)
  328. {
  329. succ->writeCode (indLevel, pProc,numLoc, _latchNode,_ifFollow);
  330. }
  331. }
  332. }
  333. }
  334. /* Writes the code for the current basic block.
  335. * Args: pBB: pointer to the current basic block.
  336. * Icode: pointer to the array of icodes for current procedure.
  337. * lev: indentation level - used for formatting. */
  338. void BB::writeBB(std::ostream &ostr,int lev, Function * pProc, int *numLoc)
  339. {
  340. /* Save the index into the code table in case there is a later goto
  341. * into this instruction (first instruction of the BB) */
  342. front().ll()->codeIdx = cCode.code.nextIdx();
  343. /* Generate code for each hlicode that is not a HLI_JCOND */
  344. for(ICODE &pHli : instructions)
  345. {
  346. if ((pHli.type == HIGH_LEVEL) && ( pHli.valid() )) //TODO: use filtering range here.
  347. {
  348. std::string line = pHli.hl()->write1HlIcode(pProc, numLoc);
  349. if (!line.empty())
  350. {
  351. ostr<<indentStr(lev)<<line;
  352. stats.numHLIcode++;
  353. }
  354. if (option.verbose)
  355. pHli.writeDU();
  356. }
  357. }
  358. }
  359. iICODE BB::begin()
  360. {
  361. return instructions.begin();//range_start;
  362. }
  363. iICODE BB::end() const
  364. {
  365. return instructions.end();//range_end
  366. }
  367. ICODE &BB::back()
  368. {
  369. return instructions.back();//*rbegin();
  370. }
  371. size_t BB::size()
  372. {
  373. return distance(instructions.begin(),instructions.end());
  374. }
  375. ICODE &BB::front()
  376. {
  377. return instructions.front();//*begin();
  378. }
  379. riICODE BB::rbegin()
  380. {
  381. return riICODE( instructions.end() );
  382. }
  383. riICODE BB::rend()
  384. {
  385. return riICODE( instructions.begin() );
  386. }