Registers.java 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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
  5. varsin the editor.
  6. */
  7. package targets.mips;
  8. import java.util.LinkedList;
  9. /**
  10. *
  11. * @author Eugenio
  12. */
  13. public class Registers {
  14. protected int arg = 0;
  15. public String Arg() {
  16. return "a" + (arg++);
  17. }
  18. public void ResetArgs() {
  19. arg = 0;
  20. }
  21. protected final LinkedList<String> avaliableSaved = new LinkedList<String>() {
  22. {
  23. for (int i = 0; i < 8; i++) {
  24. add("s" + i);
  25. }
  26. }
  27. };
  28. protected final LinkedList<String> avaliableTemp = new LinkedList<String>() {
  29. {
  30. for (int i = 0; i < 9; i++) {
  31. add("t" + i);
  32. }
  33. }
  34. };
  35. protected final LinkedList<String> usedSaved = new LinkedList<>();
  36. protected final LinkedList<String> usedTemp = new LinkedList<>();
  37. public Registers() {
  38. }
  39. public boolean Free(String reg) throws Exception {
  40. return exec(reg, "free") != null;
  41. }
  42. public String Lock(String reg) throws Exception {
  43. return exec(reg, "lock");
  44. }
  45. private String exec(String reg, String act) throws Exception {
  46. if (reg == null) {
  47. throw new Exception(String.format("Não foi possivel executar a ação '%s'. Registrador não pode ser null", act));
  48. }
  49. // System.out.println("Exec:" + reg + ":" + act);
  50. LinkedList<String> u, a;
  51. String r = null;
  52. switch (reg.substring(0, 1)) {
  53. case "t":
  54. u = usedTemp;
  55. a = avaliableTemp;
  56. break;
  57. case "s":
  58. u = usedSaved;
  59. a = avaliableSaved;
  60. break;
  61. default:
  62. throw new Exception("Try " + act + " register '%s'");
  63. }
  64. switch (act) {
  65. case "free":
  66. if (!u.isEmpty()) {
  67. // System.out.println("Try remove(" + reg + ") from " + u);
  68. // Encontra o registrador usado e coloca como disponivel
  69. int index = u.indexOf(reg);
  70. if (index >= 0) {
  71. r = u.remove(index);
  72. a.add(r);
  73. }
  74. }
  75. break;
  76. case "lock":
  77. if (!a.isEmpty()) {
  78. // Pega o primeiro registrador disponivel e marca como usado
  79. r = a.removeFirst();
  80. u.add(r);
  81. }
  82. break;
  83. }
  84. return r;
  85. }
  86. }