backend.cpp 12 KB

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