backend.cpp 12 KB

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