backend.cpp 12 KB

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