backend.cpp 13 KB

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