Gen.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package target.mips.jun;
  7. import API.BuildParams;
  8. import API.Instruction;
  9. import API.Utils;
  10. import IntermediaryCode.Block;
  11. import IntermediaryCode.Code;
  12. import compiler.IvannosysTargetArch;
  13. import java.util.ArrayList;
  14. import java.util.HashMap;
  15. import java.util.LinkedList;
  16. import java.util.Map;
  17. import java.util.logging.Level;
  18. import java.util.logging.Logger;
  19. import org.json.simple.JSONArray;
  20. import org.json.simple.JSONObject;
  21. import org.json.simple.parser.JSONParser;
  22. import target.mips.Mips;
  23. import target.mips.Registers;
  24. import target.mips.TemplateMips;
  25. import target.mips.UpdateAddressProcessor;
  26. /**
  27. * MipS tranSlation
  28. *
  29. * @author EUGENIO CARVALHO
  30. */
  31. public class Gen extends target.mips.Gen {
  32. public Gen() {
  33. super();
  34. Init();
  35. }
  36. @Override
  37. public IvannosysTargetArch Export() {
  38. try {
  39. Code Target = getTarget(), newCode;
  40. System.out.println("Export do juninho");
  41. // System.out.println("Data:" + Target.GData());
  42. Long stackBaseAddress = 0L,
  43. updateBaseAddress = 0L,
  44. size;
  45. String id,
  46. initFunction,
  47. blockName,
  48. format,
  49. cacheBlockSize = BuildParams.Get("cacheBlockSize").get(0),
  50. // base = "\\src\\results\\mipsjun\\";
  51. base = BuildParams.Get("outputDirectory").get(0);
  52. String[] parts;
  53. Block func;
  54. JSONObject profile;
  55. UpdateAddressProcessor uap = new UpdateAddressProcessor();
  56. ArrayList<String> p = BuildParams.Get("profile");
  57. if (!p.isEmpty()) {
  58. JSONArray pobject = (JSONArray) new JSONParser().parse(p.get(0));
  59. for (Object pro : pobject) {
  60. profile = (JSONObject) pro;
  61. id = (String) profile.get("id");
  62. initFunction = (String) profile.get("initFunction");
  63. parts = initFunction.replace(")", "").split("\\(");
  64. blockName = parts[0];
  65. // Busca o bloco inicial referenciado pelo usuario
  66. func = Target.getBlocks().get(blockName);
  67. if (profile.containsKey("stackBaseAddress")) {
  68. stackBaseAddress = (Long) profile.get("stackBaseAddress");
  69. } else {
  70. // System.out.println("stackBaseAddress:(" + stackBaseAddress + ")(" + MaxStackSize(func) + ")");
  71. size = MaxStackSize(func);
  72. updateBaseAddress = stackBaseAddress
  73. - size
  74. - fixCacheBlockSize(size, Long.parseLong(cacheBlockSize));
  75. }
  76. // Cria um novo codigo para armazenas as instruções do core
  77. newCode = NewCode(id);
  78. // Copia o bloco da funcao e todos os blocos que gerem dependencia
  79. CopyBlock(newCode,
  80. func,
  81. parts,
  82. stackBaseAddress,
  83. true);
  84. // Atualiza os enderecos de salto do codigo
  85. uap.Exec(newCode, null);
  86. format = (String) profile.get("filename");
  87. if (format == null) {
  88. throw new Exception("Arquivo de saida para o core `" + id + "` não definido!");
  89. }
  90. // Utils.WriteFile("\\src\\results\\mipsjun\\" + id + "\\main.dec.txt", code);
  91. SaveMips(newCode, base + "\\" + String.format(format, "mips"));
  92. SaveDec(newCode, base + "\\" + String.format(format, "dec"));
  93. stackBaseAddress = updateBaseAddress;
  94. // ExecuteCode(newCode);
  95. // break;
  96. // System.out.println("value::" + code);
  97. }
  98. // System.out.println("params:" + getTac().ast.getCompileParams().GetLists());
  99. // System.out.println("params:" + p);
  100. }
  101. // } catch (ParseException ex) {
  102. // Logger.getLogger(Gen.class.getName()).log(Level.SEVERE, null, ex);
  103. } catch (Exception ex) {
  104. Logger.getLogger(Gen.class.getName()).log(Level.SEVERE, null, ex);
  105. }
  106. return this;
  107. // return super.Export(); //To change body of generated methods, choose Tools | Templates.
  108. }
  109. // protected void ExecuteCode(Code c) {
  110. // try {
  111. // String out = "", tmp;
  112. // for (Map.Entry<String, Block> x : c.stmts.entrySet()) {
  113. //// System.out.println(x.getValue().Data());
  114. // for (Instruction instr : x.getValue().Instructions()) {
  115. // tmp = instr.G("inst.dec");
  116. // if (tmp.equals("")) {
  117. // continue;
  118. // }
  119. // out = out.concat(tmp + "\n");
  120. // }
  121. // }
  122. //
  123. // Utils.WriteFile("\\src\\tools\\mips\\memory\\mi2.memory", out);
  124. //
  125. // out = "";
  126. // for (int i = 0, y = 0; i < 2; i++) {
  127. // for (int j = 1; j <= 400; j++, y += 4) {
  128. // out = out.concat(y + ":" + j + "\n");
  129. // }
  130. // }
  131. //
  132. // Utils.WriteFile("\\src\\tools\\mips\\memory\\md2.memory", out);
  133. //
  134. // MipsProcessor sim = new tools.mips.MipsProcessor(new tools.mips.MipsSettings() {
  135. // {
  136. // debugmode = true;
  137. //// stepByStep = true;
  138. // SetInstructionMemoryFile("\\src\\tools\\mips\\memory\\mi2.memory");
  139. // SetDataMemoryFile("\\src\\tools\\mips\\memory\\md2.memory");
  140. // }
  141. // });
  142. //
  143. // sim.SetBreak("5c,84,c8")
  144. // .Run()
  145. // .Persist();
  146. //
  147. // } catch (Exception ex) {
  148. // Logger.getLogger(target.mips.Gen.class.getName()).log(Level.SEVERE, null, ex);
  149. // }
  150. // }
  151. protected Long fixCacheBlockSize(Long size, Long sizeOfBlock) {
  152. Long t = sizeOfBlock;
  153. while (true) {
  154. if (sizeOfBlock > size) {
  155. break;
  156. }
  157. sizeOfBlock += t;
  158. }
  159. return sizeOfBlock - size;
  160. }
  161. protected void SaveMips(Code newCode, String filename) throws Exception {
  162. Utils.WriteFile(filename, newCode.getCodeStream());
  163. }
  164. protected void SaveDec(Code newCode, String filename) throws Exception {
  165. String code = "", tmp;
  166. for (Map.Entry<String, Block> x : newCode.stmts.entrySet()) {
  167. for (Instruction instr : x.getValue().Instructions()) {
  168. tmp = instr.G("inst.dec");
  169. if (tmp.equals("")) {
  170. continue;
  171. }
  172. code = code.concat(Long.parseLong(tmp) + "\n");
  173. }
  174. }
  175. Utils.WriteFile(filename, code);
  176. }
  177. protected Code CopyBlock(Code newCode, Block func, String[] funcCall, Long stackBaseAddress, boolean main) throws Exception {
  178. // Instruction Ninst;
  179. int index = 1;
  180. String blockName = funcCall[0];
  181. newCode.OpenBlock(blockName);
  182. Block block = newCode.Block();
  183. // Carrega os argumentos da chamada
  184. if (funcCall.length > 1) {
  185. // System.out.println("Tinha parametro:" + funcCall[1]);
  186. String[] args = funcCall[1].split(",");
  187. int i = 0;
  188. for (String arg : args) {
  189. // Ninst = new Instruction();
  190. // Variaveis.List();
  191. // System.out.println("Variaveis.Get(arg):" + Variaveis.get("main." + args));
  192. block.Add(Mips.Instruction("addiu")
  193. .S("rs", Registers.R_ZERO)
  194. .S("rt", "a" + (i++))
  195. .S("offset", arg));
  196. }
  197. index += args.length;
  198. }
  199. for (Instruction inst : func.Instructions()) {
  200. block.Add(inst.copy());
  201. }
  202. if (main) {
  203. LinkedList<Instruction> instructions = newCode.Block().Instructions();
  204. // Atualiza o offset da pilha
  205. Instruction first = instructions.get(index);
  206. // System.out.println("CopyBlock[" + stackBaseAddress + "||" + first.getLong("offset") + "]");
  207. first.set("offset", first.getLong("offset") + stackBaseAddress);
  208. // System.out.println("instructions.get(0);" + first);
  209. // Atualiza a ultima instrucao de um retorno para ra -> stop
  210. block.Remove(instructions.get(instructions.size() - 1));
  211. block.Add(Mips.Instruction("stop")
  212. .S("comment", "end of programa"));
  213. }
  214. newCode.CloseBlock();
  215. // Adiciona as funcoes que geram dependencias
  216. HashMap<String, Block> tb = getTarget().getBlocks();
  217. ArrayList<String> deps = tb.get(blockName).GetDependences();
  218. if (!deps.isEmpty()) {
  219. for (String dep : deps) {
  220. CopyBlock(newCode, tb.get(dep), new String[]{dep}, 0l, false);
  221. }
  222. }
  223. return newCode;
  224. }
  225. protected Code NewCode(String id) {
  226. return new Code(id)
  227. .Template(new TemplateMips())
  228. .Formats(formatMips);
  229. }
  230. protected Long MaxStackSize(Block blk) {
  231. HashMap<String, Block> tb = getTarget().getBlocks();
  232. int size = blk.Data().Size();
  233. // System.out.println("data:" + blk.Data());
  234. Long childSize = 0L, tmpChildSize;
  235. ArrayList<String> deps = blk.GetDependences();
  236. if (!deps.isEmpty()) {
  237. for (String dep : deps) {
  238. tmpChildSize = MaxStackSize(tb.get(dep));
  239. if (tmpChildSize > childSize) {
  240. childSize = tmpChildSize;
  241. }
  242. }
  243. }
  244. // System.out.println("MaxStackSize:" + size + "|" + childSize);
  245. return size + childSize;
  246. }
  247. }