backend.cpp 13 KB

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