backend.cpp 12 KB

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