backend.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /*****************************************************************************
  2. * Project: dcc
  3. * File: backend.c
  4. * Purpose: Back-end module. Generates C code for each procedure.
  5. * (C) Cristina Cifuentes
  6. ****************************************************************************/
  7. #include <cassert>
  8. #include <string>
  9. #include "dcc.h"
  10. #include <fstream>
  11. #include <sstream>
  12. #include <string.h>
  13. #include <stdio.h>
  14. bundle cCode; /* Procedure declaration and code */
  15. using namespace std;
  16. /* Returns a unique index to the next label */
  17. int getNextLabel()
  18. {
  19. static int labelIdx = 1; /* index of the next label */
  20. return (labelIdx++);
  21. }
  22. /* displays statistics on the subroutine */
  23. void Function::displayStats ()
  24. {
  25. printf("\nStatistics - Subroutine %s\n", name.c_str());
  26. printf ("Number of Icode instructions:\n");
  27. printf (" Low-level : %4d\n", stats.numLLIcode);
  28. if (! (flg & PROC_ASM))
  29. {
  30. printf (" High-level: %4d\n", stats.numHLIcode);
  31. printf (" Percentage reduction: %2.2f%%\n", 100.0 - (stats.numHLIcode *
  32. 100.0) / stats.numLLIcode);
  33. }
  34. }
  35. /**** this proc is not required any more?? ****/
  36. #if 0
  37. static void fixupLabels (PPROC pProc)
  38. /* Checks the graph (pProc->cfg) for any nodes that have labels, and gives
  39. * a unique label number for it. This label is placed in the associated
  40. * icode for the node (pProc->Icode). The procedure is done in sequential
  41. * order of dsfLast numbering. */
  42. { int i; /* index into the dfsLast array */
  43. PBB *dfsLast; /* pointer to the dfsLast array */
  44. dfsLast = pProc->dfsLast;
  45. for (i = 0; i < pProc->numBBs; i++)
  46. if (dfsLast[i]->flg/* & BB_HAS_LABEL*/) {
  47. pProc->Icode.icode[dfsLast[i]->start].ll()->flg |= HLL_LABEL;
  48. pProc->Icode.icode[dfsLast[i]->start].ll()->hllLabNum = getNextLabel();
  49. }
  50. }
  51. #endif
  52. /* Returns the corresponding C string for the given character c. Character
  53. * constants such as carriage return and line feed, require 2 C characters. */
  54. char *cChar (uint8_t c)
  55. {
  56. static char res[3];
  57. switch (c) {
  58. case 0x8: /* backspace */
  59. sprintf (res, "\\b");
  60. break;
  61. case 0x9: /* horizontal tab */
  62. sprintf (res, "\\t");
  63. break;
  64. case 0x0A: /* new line */
  65. sprintf (res, "\\n");
  66. break;
  67. case 0x0C: /* form feed */
  68. sprintf (res, "\\f");
  69. break;
  70. case 0x0D: /* carriage return */
  71. sprintf (res, "\\r");
  72. break;
  73. default: /* any other character*/
  74. sprintf (res, "%c", c);
  75. }
  76. return (res);
  77. }
  78. /* Prints the variable's name and initial contents on the file.
  79. * Note: to get to the value of the variable:
  80. * com file: prog.Image[operand]
  81. * exe file: prog.Image[operand+0x100] */
  82. static void printGlobVar (SYM * psym)
  83. {
  84. int j;
  85. uint32_t relocOp = prog.fCOM ? psym->label : psym->label + 0x100;
  86. switch (psym->size)
  87. {
  88. case 1: cCode.appendDecl( "uint8_t\t%s = %ld;\n",
  89. psym->name, prog.Image[relocOp]);
  90. break;
  91. case 2: cCode.appendDecl( "uint16_t\t%s = %ld;\n",
  92. psym->name, LH(prog.Image+relocOp));
  93. break;
  94. case 4: if (psym->type == TYPE_PTR) /* pointer */
  95. cCode.appendDecl( "uint16_t\t*%s = %ld;\n",
  96. psym->name, LH(prog.Image+relocOp));
  97. else /* char */
  98. cCode.appendDecl(
  99. "char\t%s[4] = \"%c%c%c%c\";\n",
  100. psym->name, prog.Image[relocOp],
  101. prog.Image[relocOp+1], prog.Image[relocOp+2],
  102. prog.Image[relocOp+3]);
  103. break;
  104. default:
  105. {
  106. ostringstream strContents;
  107. for (j=0; j < psym->size; j++)
  108. strContents << cChar(prog.Image[relocOp + j]);
  109. cCode.appendDecl( "char\t*%s = \"%s\";\n", psym->name, strContents.str().c_str());
  110. }
  111. }
  112. }
  113. // Note: Not called at present.
  114. /* Writes the contents of the symbol table, along with any variable
  115. * initialization. */
  116. static void writeGlobSymTable()
  117. {
  118. char type[10];
  119. if (not symtab.empty())
  120. {
  121. cCode.appendDecl( "/* Global variables */\n");
  122. #ifdef _lint
  123. for (auto iter=symtab.begin(); iter!=symtab.end(); ++iter)
  124. {
  125. SYM &sym(*iter);
  126. #else
  127. for (SYM &sym : symtab)
  128. {
  129. #endif
  130. // pSym = &symtab[idx];
  131. if (sym.duVal.isUSE_VAL()) /* first used */
  132. printGlobVar (&sym);
  133. else { /* first defined */
  134. switch (sym.size) {
  135. case 1: strcpy (type, "uint8_t\t"); break;
  136. case 2: strcpy (type, "int\t"); break;
  137. case 4: if (sym.type == TYPE_PTR)
  138. strcpy (type, "int\t*");
  139. else
  140. strcpy (type, "char\t*");
  141. break;
  142. default: strcpy (type, "char\t*");
  143. }
  144. cCode.appendDecl( "%s%s;\t/* size = %ld */\n",
  145. type, sym.name, sym.size);
  146. }
  147. }
  148. cCode.appendDecl( "\n");
  149. }
  150. }
  151. /* Writes the header information and global variables to the output C file
  152. * fp. */
  153. static void writeHeader (std::ostream &_ios, char *fileName)
  154. {
  155. /* Write header information */
  156. newBundle (&cCode);
  157. cCode.appendDecl( "/*\n");
  158. cCode.appendDecl( " * Input file\t: %s\n", fileName);
  159. cCode.appendDecl( " * File type\t: %s\n", (prog.fCOM)?"COM":"EXE");
  160. cCode.appendDecl( " */\n\n#include \"dcc.h\"\n\n");
  161. /* Write global symbol table */
  162. /** writeGlobSymTable(); *** need to change them into locident fmt ***/
  163. writeBundle (_ios, cCode);
  164. freeBundle (&cCode);
  165. }
  166. /* Writes the registers that are set in the bitvector */
  167. static void writeBitVector (const std::bitset<32> &regi)
  168. {
  169. int j;
  170. for (j = rAX; j < INDEX_BX_SI; j++)
  171. {
  172. if (regi.test(j))
  173. printf ("%s ", allRegs[j-1]);
  174. }
  175. }
  176. // Note: Not currently called!
  177. /* Checks the given icode to determine whether it has a label associated
  178. * to it. If so, a goto is emitted to this label; otherwise, a new label
  179. * is created and a goto is also emitted.
  180. * Note: this procedure is to be used when the label is to be forward on
  181. * the code; that is, the target code has not been traversed yet. */
  182. static void emitFwdGotoLabel (ICODE * pt, int indLevel)
  183. {
  184. if ( ! pt->ll()->testFlags(HLL_LABEL) ) /* node hasn't got a lab */
  185. {
  186. /* Generate new label */
  187. pt->ll()->hllLabNum = getNextLabel();
  188. pt->ll()->setFlags(HLL_LABEL);
  189. }
  190. cCode.appendCode( "%sgoto l%ld;\n", indentStr(indLevel), pt->ll()->hllLabNum);
  191. }
  192. /* Writes the procedure's declaration (including arguments), local variables,
  193. * and invokes the procedure that writes the code of the given record *hli */
  194. void Function::codeGen (std::ostream &fs)
  195. {
  196. int numLoc;
  197. char buf[200], /* Procedure's definition */
  198. arg[30]; /* One argument */
  199. BB *pBB; /* Pointer to basic block */
  200. /* Write procedure/function header */
  201. newBundle (&cCode);
  202. if (flg & PROC_IS_FUNC) /* Function */
  203. cCode.appendDecl( "\n%s %s (", hlTypes[retVal.type],name.c_str());
  204. else /* Procedure */
  205. cCode.appendDecl( "\nvoid %s (", name.c_str());
  206. /* Write arguments */
  207. memset (buf, 0, sizeof(buf));
  208. for (size_t i = 0; i < args.sym.size(); i++)
  209. {
  210. if (args.sym[i].invalid == FALSE)
  211. {
  212. sprintf (arg,"%s %s",hlTypes[args.sym[i].type], args.sym[i].name);
  213. strcat (buf, arg);
  214. if (i < (args.sym.size() - 1))
  215. strcat (buf, ", ");
  216. }
  217. }
  218. strcat (buf, ")\n");
  219. cCode.appendDecl( "%s", buf);
  220. /* Write comments */
  221. writeProcComments();
  222. /* Write local variables */
  223. if (! (flg & PROC_ASM))
  224. {
  225. numLoc = 0;
  226. #ifdef _lint
  227. for (size_t i = 0; i < localId.csym(); i++)
  228. {
  229. ID &refId(localId.id_arr[i]);
  230. #else
  231. for (ID &refId : localId )
  232. {
  233. #endif
  234. /* Output only non-invalidated entries */
  235. if (refId.illegal == FALSE)
  236. {
  237. if (refId.loc == REG_FRAME)
  238. {
  239. /* Register variables are assigned to a local variable */
  240. if (((flg & SI_REGVAR) && (refId.id.regi == rSI)) ||
  241. ((flg & DI_REGVAR) && (refId.id.regi == rDI)))
  242. {
  243. sprintf (refId.name, "loc%ld", ++numLoc);
  244. cCode.appendDecl( "int %s;\n", refId.name);
  245. }
  246. /* Other registers are named when they are first used in
  247. * the output C code, and appended to the proc decl. */
  248. }
  249. else if (refId.loc == STK_FRAME)
  250. {
  251. /* Name local variables and output appropriate type */
  252. sprintf (refId.name, "loc%ld", ++numLoc);
  253. cCode.appendDecl( "%s %s;\n",hlTypes[refId.type], refId.name);
  254. }
  255. }
  256. }
  257. }
  258. /* Write procedure's code */
  259. if (flg & PROC_ASM) /* generate assembler */
  260. disassem (3, this);
  261. else /* generate C */
  262. m_cfg.front()->writeCode (1, this, &numLoc, MAX, UN_INIT);
  263. cCode.appendCode( "}\n\n");
  264. writeBundle (fs, cCode);
  265. freeBundle (&cCode);
  266. /* Write Live register analysis information */
  267. if (option.verbose)
  268. for (size_t i = 0; i < numBBs; i++)
  269. {
  270. pBB = m_dfsLast[i];
  271. if (pBB->flg & INVALID_BB) continue; /* skip invalid BBs */
  272. printf ("BB %d\n", i);
  273. printf (" Start = %d, end = %d\n", pBB->begin()->loc_ip, pBB->begin()->loc_ip+pBB->size());
  274. printf (" LiveUse = ");
  275. writeBitVector (pBB->liveUse);
  276. printf ("\n Def = ");
  277. writeBitVector (pBB->def);
  278. printf ("\n LiveOut = ");
  279. writeBitVector (pBB->liveOut);
  280. printf ("\n LiveIn = ");
  281. writeBitVector (pBB->liveIn);
  282. printf ("\n\n");
  283. }
  284. }
  285. /* Recursive procedure. Displays the procedure's code in depth-first order
  286. * of the call graph. */
  287. static void backBackEnd (char *filename, CALL_GRAPH * pcallGraph, std::ostream &_ios)
  288. {
  289. // IFace.Yield(); /* This is a good place to yield to other apps */
  290. /* Check if this procedure has been processed already */
  291. if ((pcallGraph->proc->flg & PROC_OUTPUT) ||
  292. (pcallGraph->proc->flg & PROC_ISLIB))
  293. return;
  294. pcallGraph->proc->flg |= PROC_OUTPUT;
  295. /* Dfs if this procedure has any successors */
  296. for (size_t i = 0; i < pcallGraph->outEdges.size(); i++)
  297. {
  298. backBackEnd (filename, pcallGraph->outEdges[i], _ios);
  299. }
  300. /* Generate code for this procedure */
  301. stats.numLLIcode = pcallGraph->proc->Icode.size();
  302. stats.numHLIcode = 0;
  303. pcallGraph->proc->codeGen (_ios);
  304. /* Generate statistics */
  305. if (option.Stats)
  306. pcallGraph->proc->displayStats ();
  307. if (! (pcallGraph->proc->flg & PROC_ASM))
  308. {
  309. stats.totalLL += stats.numLLIcode;
  310. stats.totalHL += stats.numHLIcode;
  311. }
  312. }
  313. /* Invokes the necessary routines to produce code one procedure at a time. */
  314. void BackEnd (char *fileName, CALL_GRAPH * pcallGraph)
  315. {
  316. std::ofstream fs; /* Output C file */
  317. /* Get output file name */
  318. std::string outNam(fileName);
  319. outNam = outNam.substr(0,outNam.rfind("."))+".b"; /* b for beta */
  320. /* Open output file */
  321. fs.open(outNam);
  322. if(!fs.is_open())
  323. fatalError (CANNOT_OPEN, outNam.c_str());
  324. printf ("dcc: Writing C beta file %s\n", outNam.c_str());
  325. /* Header information */
  326. writeHeader (fs, fileName);
  327. /* Initialize total Icode instructions statistics */
  328. stats.totalLL = 0;
  329. stats.totalHL = 0;
  330. /* Process each procedure at a time */
  331. backBackEnd (fileName, pcallGraph, fs);
  332. /* Close output file */
  333. fs.close();
  334. printf ("dcc: Finished writing C beta file\n");
  335. }