backend.cpp 11 KB

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