Advertisement
Guest User

sdfg

a guest
Mar 29th, 2017
572
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 20.96 KB | None | 0 0
  1. /* DV1465 / DV1505 / DV1511 Lab-task example code.
  2.    (C) Dr Andrew Moss, Erik Bergenholtz  2016, 2017
  3.    This code is released into the public domain.
  4.  
  5.    You are free to use this code as a base for your second assignment after
  6.    the lab sessions (it is not required that you do so).
  7. */
  8. #include <list>
  9. #include <set>
  10. #include <initializer_list>
  11. #include <string>
  12. #include <iostream>
  13. #include <fstream>
  14. #include <regex>
  15. #include <vector>
  16.  
  17.  
  18.  
  19. #include "binary.tab.hh"
  20. #include "node.h"
  21. extern FILE* yyin;
  22. extern Node root;
  23.  
  24.  
  25. using namespace std;
  26.  
  27. //to compile: g++ -std=c++11 your_file.cpp -o your_program
  28.  
  29. /*--------------------START OF CREATION THREEADD--------------------------*/
  30.  
  31. /************* Three Address Instructions *************/
  32. class ThreeAd
  33. {
  34. public:
  35.         string name,lhs,rhs;
  36.         char op;
  37.  
  38.         ThreeAd(string name, char op, string lhs, string rhs) :
  39.                 name(name), op(op), lhs(lhs), rhs(rhs)
  40.         {
  41.         }
  42.  
  43.         void dump()
  44.         {
  45.                 cout << name << " <- ";
  46.                 cout << lhs << " " << op << " " << rhs << endl;
  47.         }
  48.  
  49.        
  50. /*
  51.         void toAssembly(std::ofstream &afile)//converter from threewayaddress -> assembly
  52.         {
  53.           //afile << "TABB";
  54.          
  55.  
  56.           switch(op) //check operator to know what kind of operation to be done
  57.           {
  58.             case'+':
  59.               if (afile.is_open())
  60.               {
  61.                   if (std::regex_match (lhs, std::regex("[0-9]+")) && std::regex_match (rhs, std::regex("[0-9]+"))) //numbers
  62.                   {
  63.                     cout << "movq $" << lhs << ", " << "%%rax\n\t";
  64.                     cout << "movq $" << rhs << ", " << "%%rbx\n\t";
  65.                   }
  66.                   else if(std::regex_match (lhs, std::regex("[0-9]+")) && std::regex_match (rhs, std::regex("[A-Za-z]*"))) //number + letter
  67.                   {
  68.                     cout << "movq $" << lhs << ", " << "%%rax\n\t";
  69.                     cout << "movq $" << "%%[" << rhs << " ], " << "%%rbx\n\t";
  70.                   }
  71.                   else if(std::regex_match (lhs, std::regex("[A-Za-z]*")) && std::regex_match (rhs, std::regex("[0-9]+"))) //letter + number
  72.                   {
  73.                     cout << "movq $" << "%%[" << lhs << " ], " << "%%rbx\n\t";
  74.                     cout << "movq $" << rhs << ", " << "%%rbx\n\t";
  75.                   }
  76.                   else //letters
  77.                   {
  78.                     cout << "movq $" << "%%[" << lhs << " ], " << "%%rbx\n\t";
  79.                     cout << "movq $" << "%%[" << rhs << " ], " << "%%rbx\n\t";
  80.                   }
  81.                    
  82.                   cout << "addq " << "%%rbx" << ", " << "%%rax\n\t";  
  83.                   cout << "movq " << "%%rax" << ", " << "%%["<< name << "]\n\t";
  84.                  
  85.               }        
  86.             break;
  87.  
  88.  
  89.             case'-':            
  90.                      
  91.             break;
  92.  
  93.  
  94.             case'*':            
  95.                        
  96.             break;
  97.  
  98.  
  99.             case'=':            
  100.                        
  101.             break;
  102.  
  103.             default:            
  104.               cout<<"still things to do m8!";
  105.               break;
  106.           }
  107.       }
  108.       */
  109.  
  110. };
  111.  
  112.  
  113. /* Basic Blocks */
  114. class BBlock
  115. {
  116. private:
  117.         static int nCounter;
  118. public:
  119.         list<ThreeAd> instructions;
  120.         BBlock *tExit, *fExit;
  121.         string name;
  122. /*
  123.         void getList(std::ofstream &afile) // function to get list of instructions and send to assemblyConverter, called in dumpCFG
  124.         {
  125.           for(auto i : instructions)
  126.                 i.toAssembly(afile); //in threeAd
  127.         }
  128. */
  129.         BBlock() :
  130.                 tExit(NULL), fExit(NULL), name("blk" + to_string(nCounter++))
  131.         {
  132.         }
  133.  
  134.         void dump() // called on in dumpCFG
  135.         {
  136.                 cout << "BBlock @ " << this << endl;
  137.                 cout << name << endl;
  138.                 for(auto i : instructions)
  139.                         i.dump(); //calls on dump in ThreeAd
  140.                 cout << "True:  " << tExit << endl;
  141.                 cout << "False: " << fExit << endl;
  142.         }
  143.  
  144.  
  145. };
  146. int BBlock::nCounter = 0;
  147.  
  148.  
  149. /******************** Expressions ********************/
  150. class Expression
  151. {
  152. public:
  153.         string name;
  154.         static int uniqeID;
  155.  
  156.         Expression() : name("")
  157.         {
  158.  
  159.         }
  160.         virtual string makeNames()
  161.         {
  162.  
  163.           return "_t" + to_string(uniqeID++);
  164.           // Lecture 8 / slide 11.
  165.           // Virtual (but not pure) to allow overriding in the leaves.
  166.         }
  167.         virtual string convert(BBlock*) = 0; // Lecture 8 / slide 12.
  168.         virtual void print() = 0;
  169. };
  170. int Expression::uniqeID = 0; //set unique Id for name in expression for each threeaddress function
  171.  
  172. class Add : public Expression
  173. {
  174. public:
  175.         Expression *lhs, *rhs;
  176.  
  177.         Add(Expression* lhs, Expression* rhs) :
  178.                 lhs(lhs), rhs(rhs)
  179.         {
  180.         }
  181.  
  182.         string convert(BBlock* out) // out = output current block
  183.         {
  184.           print();
  185.           string tempName = makeNames();
  186.           out->instructions.push_back(ThreeAd(tempName, '+', lhs->convert(out), rhs->convert(out)));
  187.           return tempName;
  188.           //recursive add three-address-instruction to block
  189.  
  190.         }
  191.         void print()
  192.         {
  193.           cout << "ClassAdd"<<endl;
  194.          
  195.           lhs->print();
  196.           rhs->print();
  197.         }
  198.  
  199. };
  200.  
  201. class Mult : public Expression
  202. {
  203. public:
  204.         Expression *lhs, *rhs;
  205.  
  206.         Mult(Expression* lhs, Expression* rhs) :
  207.                 lhs(lhs), rhs(rhs)
  208.         {
  209.         }
  210.  
  211.         string convert(BBlock* out)
  212.         {
  213.           print();
  214.           string tempName = makeNames();
  215.           out->instructions.push_back(ThreeAd(tempName, '*', lhs->convert(out), rhs->convert(out)));
  216.           return tempName;
  217.           //recursive add three-address-instruction to block
  218.  
  219.         }
  220.         void print()
  221.         {
  222.           cout << "ClassMult: "<<lhs->name<<" "<<rhs->name<<endl;
  223.         }
  224.  
  225. };
  226.  
  227. class Div : public Expression
  228. {
  229. public:
  230.         Expression *lhs, *rhs;
  231.  
  232.         Div(Expression* lhs, Expression* rhs) :
  233.                 lhs(lhs), rhs(rhs)
  234.         {
  235.         }
  236.  
  237.         string convert(BBlock* out)
  238.         {
  239.           print();
  240.           string tempName = makeNames();
  241.           out->instructions.push_back(ThreeAd(tempName, '/', lhs->convert(out), rhs->convert(out)));
  242.           return tempName;
  243.           //recursive add three-address-instruction to block
  244.  
  245.         }
  246.         void print()
  247.         {
  248.           cout << "ClassDiv: "<<lhs->name<<" "<<rhs->name<<endl;
  249.         }
  250.  
  251. };
  252.  
  253. class Sub : public Expression
  254. {
  255. public:
  256.         Expression *lhs, *rhs;
  257.  
  258.         Sub(Expression* lhs, Expression* rhs) :
  259.                 lhs(lhs), rhs(rhs)
  260.         {
  261.         }
  262.  
  263.         string convert(BBlock* out)
  264.         {
  265.           print();
  266.           string tempName = makeNames();
  267.           out->instructions.push_back(ThreeAd(tempName, '-', lhs->convert(out), rhs->convert(out)));
  268.           return tempName;
  269.           //recursive add three-address-instruction to block
  270.  
  271.         }
  272.         void print()
  273.         {
  274.           cout << "ClassSub: "<<lhs->name<<" "<<rhs->name<<endl;
  275.         }
  276.  
  277. };
  278.  
  279.  
  280. class Equality : public Expression
  281. {
  282. public:
  283.         Expression *lhs, *rhs;
  284.  
  285.         Equality(Expression* lhs, Expression* rhs) :
  286.                 lhs(lhs), rhs(rhs)
  287.         {
  288.         }
  289.  
  290.         string convert(BBlock* out)
  291.         {
  292.           print();
  293.           string tempName = makeNames();
  294.           out->instructions.push_back(ThreeAd(tempName, 'E', lhs->convert(out), rhs->convert(out)));
  295.           return tempName;
  296.           //recursive add three-address-instruction to block
  297.  
  298.         }
  299.         void print()
  300.         {
  301.           cout << "ClassEQ: "<<lhs->name<<" "<<rhs->name<<endl;
  302.         }
  303.  
  304. };
  305.  
  306. class Variable : public Expression
  307. {
  308. public:
  309.         string aName;
  310.         Variable()
  311.         {
  312.           aName = "";
  313.         }
  314.  
  315.         Variable(string aName)
  316.         {
  317.           name = aName;
  318.         }
  319.  
  320.         string convert(BBlock* out)
  321.         {
  322.           print();
  323.           return name;
  324.         }
  325.         void print()
  326.         {
  327.           cout << "ClassVariable: "<<aName<<endl;
  328.         }
  329.  
  330. };
  331.  
  332. class Quote : public Expression
  333. {
  334. public:
  335.         string aQuote;
  336.         Quote()
  337.         {
  338.           aQuote= "\"\"";
  339.         }
  340.  
  341.         Quote(string aQuote)
  342.         {
  343.           name = aQuote;
  344.         }
  345.  
  346.         string convert(BBlock* out)
  347.         {
  348.           print();
  349.           return name;
  350.         }
  351.         void print()
  352.         {
  353.           cout << "ClassString :"<<aQuote<<endl;
  354.         }
  355.  
  356. };
  357.  
  358. class Constant : public Expression
  359. {
  360. public:
  361.         int aValue;
  362.  
  363.         Constant(int number)
  364.         {
  365.           aValue = number;
  366.           name = to_string(aValue);
  367.         }
  368.  
  369.         string convert(BBlock* out)
  370.         {
  371.           print();
  372.           return name;
  373.  
  374.         }
  375.         void print()
  376.         {
  377.           cout << "ClassNumber: "<<aValue<<endl;
  378.         }
  379.  
  380. };
  381.  
  382.  
  383.  
  384. /******************** Statements ********************/
  385. class Statement
  386. {
  387. public:
  388.         string name;
  389.  
  390.         Statement()
  391.         {
  392.  
  393.         }
  394.         virtual void convert(BBlock **) = 0;
  395. };
  396.  
  397.  
  398.  
  399.  
  400. class Assignment : public Statement //FEL  I DENNA VID creation three add constant fel för rhs?
  401. {
  402. public:
  403.         Variable *lhs;
  404.         Expression *rhs;
  405.        
  406.        /* Assignment(string lhs, Expression *rhs) :
  407.                 lhs(new Variable(lhs)), rhs(rhs)
  408.         {
  409.  
  410.         }*/
  411.         Assignment(Variable* lhs, Expression *rhs) :
  412.                 lhs(lhs), rhs(rhs)
  413.         {
  414.           //rhs->name = lhs->makeNames();
  415.           //name = lhs->makeNames();
  416.          
  417.         }
  418.  
  419.          void convert(BBlock **out)
  420.         {
  421.           cout<<"In assignmentClass"<<endl;
  422.           //string tempName = rhs->convert(*out);
  423.           lhs->print();
  424.           //rhs->print();
  425.  
  426.           //(*out)->instructions.push_back(ThreeAd(lhs->convert(*out), '=', tempName, tempName));
  427.          
  428.         }
  429. };
  430.  
  431.  
  432.  
  433. class Seq : public Statement
  434. {
  435. public:
  436.         list<Statement*> aList;
  437.        /* Seq(list<Statement*> listOfStatements)
  438.         {
  439.           aList = listOfStatements;
  440.         }*/
  441.         Seq()
  442.         {
  443.          
  444.         }
  445.         void convert(BBlock **out)
  446.         {
  447.          
  448.           for(auto i : aList) // number of statements in testcase
  449.           {
  450.             cout << "in SequenceClass/convert"<<endl<<endl;
  451.             i->convert(out);
  452.            
  453.           }
  454.         }
  455.  
  456. };
  457.  
  458. class If : public Statement
  459. {
  460. public:
  461.         Statement * case1;
  462.         Statement * case2;
  463.         Expression * compare;
  464.  
  465.         If(Expression *compare, Statement *case1, Statement * case2) :
  466.             compare(compare), case1(case1), case2(case2)
  467.         { // this->compare = other.compare
  468.  
  469.         }
  470.  
  471.         void convert(BBlock **out)
  472.         {
  473.           BBlock *blockTrue = new BBlock();
  474.           BBlock *blockFalse = new BBlock();
  475.           BBlock *blockJoin = new BBlock();
  476.  
  477.           compare->convert(*out);         // compare set to cre for current block
  478.           (*out)->tExit = blockTrue;     //first block true exit and false exit to different blocks
  479.           (*out)->fExit = blockFalse;
  480.          
  481.           case1->convert(&blockTrue); //case1 reference of blocktrue
  482.           blockTrue->tExit = blockJoin;  //true/false block undepending on case go to joining block
  483.           blockTrue->fExit = blockJoin;
  484.  
  485.           case2->convert(&blockFalse); //case2 reference of blockfalse
  486.           blockFalse->tExit = blockJoin;
  487.           blockFalse->fExit = blockJoin;
  488.  
  489.           (*out) = blockJoin; // move pointer to joinblock exit
  490.  
  491.         }
  492. };
  493. /*--------------------END OF CREATION THREEADD--------------------------*/
  494.  
  495.  
  496. /*Statement *test = new Seq({
  497.                             new Assignment(
  498.                                         "x", new Add( new Variable("x"),
  499.                                                       new Constant(1)
  500.                                                     )
  501.                                           )
  502.                           , new Assignment(
  503.                                         "y", new Add( new Variable("y"),
  504.                                                       new Constant(1)
  505.                                                     )
  506.                                           )
  507.                           , new If(
  508.                                             new Equality(
  509.                                                             new Variable("x"),
  510.                                                             new Constant(0)
  511.                                                         )
  512.                                           , new If(
  513.                                                             new Equality(
  514.                                                                           new Variable("y"),
  515.                                                                           new Constant(0)
  516.                                                                         )                      
  517.                                                  
  518.                                                           , new Assignment(
  519.                                                                       "x",  new Constant(1)
  520.                                                                           )
  521.                                                           , new Assignment(
  522.                                                                       "y",  new Constant(2)
  523.                                                                           )
  524.                                                   )
  525.  
  526.                           , new Assignment(
  527.                                            "x",  new Constant(1)
  528.                                           )
  529.                                     )
  530.  
  531.                           });*/
  532.  
  533. /*
  534.  * Iterate over each basic block that can be reached from the entry point
  535.  * exactly once, so that we can dump out the entire graph.
  536.  */
  537. void dumpCFG(BBlock *start, std::ofstream &afile)
  538. {
  539.         set<BBlock *> done, todo;
  540.         todo.insert(start);
  541.         while(todo.size()>0)
  542.         {
  543.                 // Pop an arbitrary element from todo set
  544.                 auto first = todo.begin();
  545.                 BBlock *next = *first;
  546.                 todo.erase(first);
  547.                 next->dump();
  548.                 //next->getList(afile); // new dump function to output assembly
  549.                 done.insert(next);
  550.                 if(next->tExit!=NULL && done.find(next->tExit)==done.end())
  551.                         todo.insert(next->tExit);
  552.                 if(next->fExit!=NULL && done.find(next->fExit)==done.end())
  553.                         todo.insert(next->fExit);
  554.         }
  555. }
  556.  
  557. Expression *convertExpression(Node &translateNode); //declarations
  558. Statement *convertStatement(Node &translateNode);
  559.  
  560.  
  561. /****************Expressions to convert from Parse-tree******************/
  562. Variable *convertVar(Node &translateNode) //get value from node and add to pointer
  563. {
  564.   cout << "in convertVar:"<<endl<< translateNode.value <<endl;
  565.   return new Variable(translateNode.value);
  566. }
  567.  
  568. Constant *convertConst(Node &translateNode) //get value from node and add to pointer
  569. {
  570.   cout <<"in convertConst:"<<endl;
  571.   cout <<"e "<< translateNode.value<<endl<<endl;
  572.   return new Constant(stoi(translateNode.value));
  573. }
  574.  
  575. Quote *convertQuote(Node &translateNode) //get value from node and add to pointer
  576. {
  577.   cout <<"in convertQuote:"<<endl<<endl;
  578.   return new Quote(translateNode.value);
  579. }
  580.  
  581. Add *convertAdd(Node &translateNode)
  582. {
  583.   cout <<"in convertAdd:"<<endl;
  584.   cout <<translateNode.value<<endl<<endl;
  585.   cout << translateNode.children.front().value<<" WIIIIIEIIEIIE "<<endl;
  586.   cout << translateNode.children.back().value<<" WIIIIIEIIEIIE "<<endl;
  587.   Add * hejsan = new Add(convertExpression(translateNode.children.front()),convertExpression(translateNode.children.back()));
  588.   return hejsan;
  589. }
  590.  
  591. Mult *convertMult(Node &translateNode)
  592. {
  593.   return new Mult(convertExpression(translateNode.children.front()),convertExpression(translateNode.children.back()));
  594. }
  595.  
  596. Div *convertDiv(Node &translateNode)
  597. {
  598.   return new Div(convertExpression(translateNode.children.front()),convertExpression(translateNode.children.back()));
  599. }
  600.  
  601. Sub *convertSub(Node &translateNode)
  602. {
  603.   return new Sub(convertExpression(translateNode.children.front()),convertExpression(translateNode.children.back()));
  604. }
  605.  
  606. Equality *convertEquality(Node &translateNode)
  607. {
  608.   return new Equality(convertExpression(translateNode.children.front()),convertExpression(translateNode.children.back()));
  609. }
  610.  
  611. Expression *convertExpression(Node &translateNode) //call upon and decide which expression to use
  612. {
  613.   cout <<  "in convertExpression:"<<endl;
  614.   cout << translateNode.tag<<endl;
  615.   cout << translateNode.value<<endl;
  616.  
  617.   Expression *pointer;
  618.  
  619.   if(translateNode.tag == "OP" )
  620.   {
  621.     if(translateNode.value == "ADD")
  622.     {
  623.       pointer = convertAdd(translateNode);
  624.     }
  625.     else if(translateNode.value == "SUB")
  626.     {
  627.       pointer = convertSub(translateNode);
  628.     }
  629.     else if(translateNode.value == "MUL")
  630.     {
  631.       pointer = convertMult(translateNode);
  632.     }
  633.     else if(translateNode.value == "DIV")
  634.     {
  635.       pointer = convertDiv(translateNode);
  636.     }
  637.     else if(translateNode.value == "EQ")
  638.     {
  639.       pointer = convertEquality(translateNode);
  640.     }
  641.        
  642.   }
  643.   else if(translateNode.tag == "var")
  644.   {
  645.     cout <<"--var"<<endl;
  646.     convertVar(translateNode);
  647.   }
  648.   else if(translateNode.tag == "number")
  649.   {
  650.     cout<<"--number"<<endl;
  651.     convertConst(translateNode);
  652.   }
  653.   else if(translateNode.tag == "string")
  654.   {
  655.     cout<<"--string"<<endl;
  656.     convertQuote(translateNode);
  657.   }
  658.   return pointer;
  659. }
  660. /***********************************************************************/
  661.  
  662.  
  663.  
  664.  
  665. /****************Statements to convert from Parse-tree******************/
  666.  
  667. Assignment * convertAssign(Node &translateNode) //get value from an assignment
  668. {
  669.   cout << "in covertAssign:"<<endl;
  670.   //cout << translateNode.tag << endl; //assignment node
  671.   Node& var = translateNode.children.front();
  672.   Node& exp = translateNode.children.back();
  673.   //cout << var.tag << endl; //assignment node
  674.   //cout << exp.tag << endl; //assignment node
  675.  
  676.   return new Assignment(convertVar(var),convertExpression(exp));
  677. }
  678.  
  679.  
  680.  
  681. Statement *convertStatement(Node &translateNode) //call upon and decide which expression to use
  682. {
  683.   Statement *pointer;
  684.   //cout << translateNode.children.front().tag;
  685.    
  686.   pointer = convertAssign(translateNode);
  687.  
  688.   return pointer;
  689. }
  690.  
  691.  
  692.  
  693.  
  694.  
  695.  
  696. /***********************************************************************/
  697.  
  698. Seq *convertSeq(Node &translateNode) //creating new sequence of statements, and loop through all statment children.
  699. {
  700.   Seq *pointer;
  701.   pointer = new Seq();
  702.  
  703.   Node &statement = translateNode.children.front();  //current node statement
  704.   for(auto i : statement.children) //loop through all statements
  705.   {
  706.     pointer->aList.push_back(convertStatement(i));
  707.     //cout << pointer->aList.front()<<endl;
  708.     //cout << pointer->aList.back()<<endl;
  709.   }
  710.   return pointer;
  711. }
  712.  
  713.  
  714. /*
  715.   output example:
  716.   1[label ="chunk "];
  717.   2[label ="chunk1 "];
  718.   3[label ="stat "];
  719.   4[label ="varlist "];
  720.   5[label ="var "];
  721.   6[label ="TEXT list"];
  722. --------------------------------------------
  723.   Blocks:
  724.   block0 [label="t1 <- x + y\nt2 <- t1 = 0\n...", shape="rect"];
  725.   block1 [label="...", shape="rect"];
  726.   block2 [label="...", shape="rect"];
  727.  
  728.   Arrows:
  729.   block0 -> block1 [label="true"];
  730.   block1 -> block0;
  731.   block0 -> block2 [label="false"];
  732.  
  733. */
  734.  
  735.  
  736.  
  737. void yy::parser::error(std::string const&err)
  738. {
  739.   std::cout << "ERROR " << err << std::endl;
  740. }
  741.  
  742.  
  743. int main(int argc, char **argv)
  744. {
  745.   yyin = fopen(argv[1], "r");
  746.   yy::parser parser;
  747.   if(!parser.parse())
  748.   {
  749.     std::cout << "[Parse-tree:]" << std::endl;
  750.     root.dump(); //print regular parseing
  751.   }
  752.  
  753.   cout << "--------------------------------------\n[Translate:]\n";
  754.   statement * newList;
  755.   BBlock* b = new BBlock();
  756.   BBlock* theRoot = b;
  757.  
  758.   newList = convertSeq(root.children.front()); //new List "chunk"
  759.  
  760.   cout << "--------------------------------------\n[Create:]\n";
  761.  
  762.   newList->convert(&b);
  763.  
  764.  
  765.  
  766. /*
  767.  
  768.   std::ofstream afile;
  769.   afile.open("cfg.dot");
  770.   if (afile.is_open())
  771.   {
  772.      dumpCFG(theRoot, afile); //calls blocks of instructions
  773.     //afile << "digraph {\n\t";
  774.     //afile << flowGraph();
  775.     //afile << "}";
  776.  
  777.     //BBlock* b = new BBlock();
  778.     //BBlock* theRoot = b;
  779.     //"statement"->convert(&b);
  780.  
  781.  
  782.     afile << "digraph {\n\t";
  783.     //afile << root.graph();
  784.     afile << root.graph();
  785.     afile << "}";
  786.    
  787.    
  788.     //test->convert(&b);
  789.     //dumpCFG(theRoot, afile); //calls blocks of instructions
  790.    
  791.     afile.close();
  792.   }
  793.   */
  794.   return 0;
  795. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement