Browse Source

simulation mod

eugeniucarvalho 5 years ago
parent
commit
ee0709605a
83 changed files with 3210 additions and 12597 deletions
  1. 1 1
      build/built-jar.properties
  2. BIN
      build/classes/API/Api.class
  3. BIN
      build/classes/API/Utils.class
  4. BIN
      build/classes/ast/Node.class
  5. BIN
      build/classes/ast/Semantic.class
  6. BIN
      build/classes/compiler/IVANNOSYS.class
  7. BIN
      build/classes/compiler/IvannosysCompiler.class
  8. 43 4
      build/classes/samples/program_mult.go
  9. BIN
      build/classes/tools/mips/Memory.class
  10. BIN
      build/classes/tools/mips/MipsProcessor.class
  11. BIN
      build/classes/tools/mips/RegisterBank.class
  12. 70 4096
      build/classes/tools/mips/memory/md.memory
  13. 0 800
      build/classes/tools/mips/memory/md2.memory
  14. 249 83
      build/classes/tools/mips/memory/mi.memory
  15. 0 74
      build/classes/tools/mips/memory/mi2.memory
  16. 3 1
      nbproject/project.properties
  17. 22 40
      src/API/Api.java
  18. 24 11
      src/API/CodeProcessor.java
  19. 2 2
      src/API/CodeProcessorInterface.java
  20. 91 36
      src/API/TargetGen.java
  21. 64 17
      src/API/Types.java
  22. 16 3
      src/API/Utils.java
  23. 12 9
      src/API/Variables.java
  24. 151 0
      src/Export/MemoryInitializationFile.java
  25. 0 241
      src/Export/Mif.java
  26. 13 13
      src/Export/MultCoreJun.java
  27. 23 25
      src/Export/Simulation.java
  28. 261 391
      src/IntermediaryCode/IRGenerator.java
  29. 14 33
      src/IntermediaryCode/IRTemplate.java
  30. 0 190
      src/Processors/BasicBlockProcessor.java
  31. 1 1
      src/ast/Node.java
  32. 12 12
      src/ast/Semantic.java
  33. 48 40
      src/common/Block.java
  34. 52 43
      src/common/Code.java
  35. 53 0
      src/common/DataEntry.java
  36. 216 168
      src/common/DataLayout.java
  37. 9 5
      src/common/Instruction.java
  38. 1 3
      src/common/IvannosysTargetArch.java
  39. 45 0
      src/common/Label.java
  40. 38 0
      src/common/Offset.java
  41. 7 2
      src/common/RegistroBase.java
  42. 14 12
      src/compiler/IVANNOSYS.java
  43. 1 5
      src/compiler/IvannosysCompiler.java
  44. 18 0
      src/exception/CompileException.java
  45. 19 10
      src/frontend/Ivannosys/IvannosysListener.java
  46. 198 0
      src/middlewares/BasicBlockMiddleware.java
  47. 8 10
      src/Processors/BlockBaseGroup.java
  48. 60 41
      src/Processors/BlockBaseOcorrences.java
  49. 10 10
      src/Processors/CodeOtimizadorProcessor.java
  50. 5 5
      src/Processors/DeadInstructionsProcessor.java
  51. 32 3
      src/Processors/Interval.java
  52. 7 7
      src/Processors/LoadStoreProcessor.java
  53. 1 1
      src/Processors/Ocorrence.java
  54. 6 6
      src/Processors/RemoveUnusedLabelsProcessor.java
  55. 8 8
      src/Processors/VariablesConstantsProcessor.java
  56. 4 0
      src/samples/program_jun_bit_count.go
  57. 5 6
      src/samples/program_jun_laplaciano.go
  58. 5 4
      src/samples/program_jun_mult_manycore.go
  59. 43 4
      src/samples/program_mult.go
  60. 9 8
      src/targets/mips/Mips.java
  61. 5 5
      src/targets/mips/MipsCopyDepsProcessor.java
  62. 5 5
      src/targets/mips/MipsLoadStoreProcessor.java
  63. 0 35
      src/targets/mips/MipsOTMinActivationRegister.java
  64. 5 5
      src/targets/mips/MipsOtimizationProcessor.java
  65. 42 43
      src/targets/mips/MipsRegisterAllocProcessor.java
  66. 12 30
      src/targets/mips/MipsTemplate.java
  67. 100 0
      src/targets/mips/MipsUpdateAddressMiddleware.java
  68. 0 92
      src/targets/mips/MipsUpdateAddressProcessor.java
  69. 0 210
      src/targets/mips/TemplateFunctions.java
  70. 316 296
      src/targets/mips/Gen.java
  71. 6 2
      src/templates/Functions.java
  72. 19 3
      src/templates/RenderStmt.java
  73. 16 3
      src/templates/TListener.java
  74. 1 1
      src/templates/Template.java
  75. 109 72
      src/tools/mips/Memory.java
  76. 30 0
      src/tools/mips/MemoryImportExportInterface.java
  77. 145 257
      src/tools/mips/MipsProcessor.java
  78. 1 1
      src/tools/mips/RegisterBank.java
  79. 70 4096
      src/tools/mips/memory/md.memory
  80. 0 800
      src/tools/mips/memory/md2.memory
  81. 249 83
      src/tools/mips/memory/mi.memory
  82. 0 74
      src/tools/mips/memory/mi2.memory
  83. 85 0
      test/MemoryJUnitTest.java

+ 1 - 1
build/built-jar.properties

@@ -1,4 +1,4 @@
-#Fri, 06 Jul 2018 00:49:37 -0300
+#Tue, 10 Jul 2018 00:19:26 -0300
 
 
 C\:\\Users\\EUGENIO\ CARVALHO\\Desktop\\projects\\Ivannosys=

BIN
build/classes/API/Api.class


BIN
build/classes/API/Utils.class


BIN
build/classes/ast/Node.class


BIN
build/classes/ast/Semantic.class


BIN
build/classes/compiler/IVANNOSYS.class


BIN
build/classes/compiler/IvannosysCompiler.class


+ 43 - 4
build/classes/samples/program_mult.go

@@ -1,18 +1,20 @@
 // Aplica o back-end do juninho
 @target          : mips 
 // Especifica o tipo de metodo empregado para salvar o resultado da compilação
+//@export          : MultCoreJun
 @export          : simulation
 
+
 package main;
 
 const (
     LIN  = 2
-    COL  = 2 
+    COL  = 2
 )
 var (
-    matrizA [LIN][COL]int 
-    matrizB [LIN][COL]int
-    matrizR [LIN][COL]int
+    matrizA [LIN][COL]int32
+    matrizB [LIN][COL]int32
+    matrizR [LIN][COL]int32
 )
 
 func preenche(){
@@ -43,3 +45,40 @@ func main() {
     preenche()
     multiplica()
 }
+
+
+/**
+load (int32) i		  T< load >		
+10:	 9:		_T4 := i --Copy value of index		  T< copy >		
+11:	10:		_T5 := _T4 << 1		  T< assign >		
+12:	11:		load (int32) j		  T< load >		
+13:	12:		_T7 := j --Copy value of index		  T< copy >		
+14:	13:		_T5 := _T5 + _T7 --colls shift		  T< assign >		
+15:	14:		_T11 := _T5 << 4		  T< assign >		
+16:	15:		load (int32) aux		  T< load >		
+17:	16:		matrizA[_T11] := aux		  T< indexed_assign >		
+
+[2][2]
+    i  j  t4  t5   t7  t11 
+9   1  1  1
+10            2    
+11  
+12                 1
+13                     3
+14  
+15  
+16  
+17  
+
+                sll t6,t4,4		.14 -- _T11 = _T5 << 4
+60:  2413101056	lw s5,fp,0		.15 -- load content from _V1 in s5
+64:  0000000000	sll zero,zero,0		.15 -- Nop
+68:  0059666465	addu t6,gp,t6		.16
+6c:  2916417536	sw s5,t6,0		.16 -- store content of t6 in _G13[_T11]
+    t6 tem o deslocamento em bytes
+    
+
+*/
+
+
+

BIN
build/classes/tools/mips/Memory.class


BIN
build/classes/tools/mips/MipsProcessor.class


BIN
build/classes/tools/mips/RegisterBank.class


File diff suppressed because it is too large
+ 70 - 4096
build/classes/tools/mips/memory/md.memory


+ 0 - 800
build/classes/tools/mips/memory/md2.memory

@@ -1,800 +0,0 @@
-0:1
-4:2
-8:3
-12:4
-16:5
-20:6
-24:7
-28:8
-32:9
-36:10
-40:11
-44:12
-48:13
-52:14
-56:15
-60:16
-64:17
-68:18
-72:19
-76:20
-80:21
-84:22
-88:23
-92:24
-96:25
-100:26
-104:27
-108:28
-112:29
-116:30
-120:31
-124:32
-128:33
-132:34
-136:35
-140:36
-144:37
-148:38
-152:39
-156:40
-160:41
-164:42
-168:43
-172:44
-176:45
-180:46
-184:47
-188:48
-192:49
-196:50
-200:51
-204:52
-208:53
-212:54
-216:55
-220:56
-224:57
-228:58
-232:59
-236:60
-240:61
-244:62
-248:63
-252:64
-256:65
-260:66
-264:67
-268:68
-272:69
-276:70
-280:71
-284:72
-288:73
-292:74
-296:75
-300:76
-304:77
-308:78
-312:79
-316:80
-320:81
-324:82
-328:83
-332:84
-336:85
-340:86
-344:87
-348:88
-352:89
-356:90
-360:91
-364:92
-368:93
-372:94
-376:95
-380:96
-384:97
-388:98
-392:99
-396:100
-400:101
-404:102
-408:103
-412:104
-416:105
-420:106
-424:107
-428:108
-432:109
-436:110
-440:111
-444:112
-448:113
-452:114
-456:115
-460:116
-464:117
-468:118
-472:119
-476:120
-480:121
-484:122
-488:123
-492:124
-496:125
-500:126
-504:127
-508:128
-512:129
-516:130
-520:131
-524:132
-528:133
-532:134
-536:135
-540:136
-544:137
-548:138
-552:139
-556:140
-560:141
-564:142
-568:143
-572:144
-576:145
-580:146
-584:147
-588:148
-592:149
-596:150
-600:151
-604:152
-608:153
-612:154
-616:155
-620:156
-624:157
-628:158
-632:159
-636:160
-640:161
-644:162
-648:163
-652:164
-656:165
-660:166
-664:167
-668:168
-672:169
-676:170
-680:171
-684:172
-688:173
-692:174
-696:175
-700:176
-704:177
-708:178
-712:179
-716:180
-720:181
-724:182
-728:183
-732:184
-736:185
-740:186
-744:187
-748:188
-752:189
-756:190
-760:191
-764:192
-768:193
-772:194
-776:195
-780:196
-784:197
-788:198
-792:199
-796:200
-800:201
-804:202
-808:203
-812:204
-816:205
-820:206
-824:207
-828:208
-832:209
-836:210
-840:211
-844:212
-848:213
-852:214
-856:215
-860:216
-864:217
-868:218
-872:219
-876:220
-880:221
-884:222
-888:223
-892:224
-896:225
-900:226
-904:227
-908:228
-912:229
-916:230
-920:231
-924:232
-928:233
-932:234
-936:235
-940:236
-944:237
-948:238
-952:239
-956:240
-960:241
-964:242
-968:243
-972:244
-976:245
-980:246
-984:247
-988:248
-992:249
-996:250
-1000:251
-1004:252
-1008:253
-1012:254
-1016:255
-1020:256
-1024:257
-1028:258
-1032:259
-1036:260
-1040:261
-1044:262
-1048:263
-1052:264
-1056:265
-1060:266
-1064:267
-1068:268
-1072:269
-1076:270
-1080:271
-1084:272
-1088:273
-1092:274
-1096:275
-1100:276
-1104:277
-1108:278
-1112:279
-1116:280
-1120:281
-1124:282
-1128:283
-1132:284
-1136:285
-1140:286
-1144:287
-1148:288
-1152:289
-1156:290
-1160:291
-1164:292
-1168:293
-1172:294
-1176:295
-1180:296
-1184:297
-1188:298
-1192:299
-1196:300
-1200:301
-1204:302
-1208:303
-1212:304
-1216:305
-1220:306
-1224:307
-1228:308
-1232:309
-1236:310
-1240:311
-1244:312
-1248:313
-1252:314
-1256:315
-1260:316
-1264:317
-1268:318
-1272:319
-1276:320
-1280:321
-1284:322
-1288:323
-1292:324
-1296:325
-1300:326
-1304:327
-1308:328
-1312:329
-1316:330
-1320:331
-1324:332
-1328:333
-1332:334
-1336:335
-1340:336
-1344:337
-1348:338
-1352:339
-1356:340
-1360:341
-1364:342
-1368:343
-1372:344
-1376:345
-1380:346
-1384:347
-1388:348
-1392:349
-1396:350
-1400:351
-1404:352
-1408:353
-1412:354
-1416:355
-1420:356
-1424:357
-1428:358
-1432:359
-1436:360
-1440:361
-1444:362
-1448:363
-1452:364
-1456:365
-1460:366
-1464:367
-1468:368
-1472:369
-1476:370
-1480:371
-1484:372
-1488:373
-1492:374
-1496:375
-1500:376
-1504:377
-1508:378
-1512:379
-1516:380
-1520:381
-1524:382
-1528:383
-1532:384
-1536:385
-1540:386
-1544:387
-1548:388
-1552:389
-1556:390
-1560:391
-1564:392
-1568:393
-1572:394
-1576:395
-1580:396
-1584:397
-1588:398
-1592:399
-1596:400
-1600:1
-1604:2
-1608:3
-1612:4
-1616:5
-1620:6
-1624:7
-1628:8
-1632:9
-1636:10
-1640:11
-1644:12
-1648:13
-1652:14
-1656:15
-1660:16
-1664:17
-1668:18
-1672:19
-1676:20
-1680:21
-1684:22
-1688:23
-1692:24
-1696:25
-1700:26
-1704:27
-1708:28
-1712:29
-1716:30
-1720:31
-1724:32
-1728:33
-1732:34
-1736:35
-1740:36
-1744:37
-1748:38
-1752:39
-1756:40
-1760:41
-1764:42
-1768:43
-1772:44
-1776:45
-1780:46
-1784:47
-1788:48
-1792:49
-1796:50
-1800:51
-1804:52
-1808:53
-1812:54
-1816:55
-1820:56
-1824:57
-1828:58
-1832:59
-1836:60
-1840:61
-1844:62
-1848:63
-1852:64
-1856:65
-1860:66
-1864:67
-1868:68
-1872:69
-1876:70
-1880:71
-1884:72
-1888:73
-1892:74
-1896:75
-1900:76
-1904:77
-1908:78
-1912:79
-1916:80
-1920:81
-1924:82
-1928:83
-1932:84
-1936:85
-1940:86
-1944:87
-1948:88
-1952:89
-1956:90
-1960:91
-1964:92
-1968:93
-1972:94
-1976:95
-1980:96
-1984:97
-1988:98
-1992:99
-1996:100
-2000:101
-2004:102
-2008:103
-2012:104
-2016:105
-2020:106
-2024:107
-2028:108
-2032:109
-2036:110
-2040:111
-2044:112
-2048:113
-2052:114
-2056:115
-2060:116
-2064:117
-2068:118
-2072:119
-2076:120
-2080:121
-2084:122
-2088:123
-2092:124
-2096:125
-2100:126
-2104:127
-2108:128
-2112:129
-2116:130
-2120:131
-2124:132
-2128:133
-2132:134
-2136:135
-2140:136
-2144:137
-2148:138
-2152:139
-2156:140
-2160:141
-2164:142
-2168:143
-2172:144
-2176:145
-2180:146
-2184:147
-2188:148
-2192:149
-2196:150
-2200:151
-2204:152
-2208:153
-2212:154
-2216:155
-2220:156
-2224:157
-2228:158
-2232:159
-2236:160
-2240:161
-2244:162
-2248:163
-2252:164
-2256:165
-2260:166
-2264:167
-2268:168
-2272:169
-2276:170
-2280:171
-2284:172
-2288:173
-2292:174
-2296:175
-2300:176
-2304:177
-2308:178
-2312:179
-2316:180
-2320:181
-2324:182
-2328:183
-2332:184
-2336:185
-2340:186
-2344:187
-2348:188
-2352:189
-2356:190
-2360:191
-2364:192
-2368:193
-2372:194
-2376:195
-2380:196
-2384:197
-2388:198
-2392:199
-2396:200
-2400:201
-2404:202
-2408:203
-2412:204
-2416:205
-2420:206
-2424:207
-2428:208
-2432:209
-2436:210
-2440:211
-2444:212
-2448:213
-2452:214
-2456:215
-2460:216
-2464:217
-2468:218
-2472:219
-2476:220
-2480:221
-2484:222
-2488:223
-2492:224
-2496:225
-2500:226
-2504:227
-2508:228
-2512:229
-2516:230
-2520:231
-2524:232
-2528:233
-2532:234
-2536:235
-2540:236
-2544:237
-2548:238
-2552:239
-2556:240
-2560:241
-2564:242
-2568:243
-2572:244
-2576:245
-2580:246
-2584:247
-2588:248
-2592:249
-2596:250
-2600:251
-2604:252
-2608:253
-2612:254
-2616:255
-2620:256
-2624:257
-2628:258
-2632:259
-2636:260
-2640:261
-2644:262
-2648:263
-2652:264
-2656:265
-2660:266
-2664:267
-2668:268
-2672:269
-2676:270
-2680:271
-2684:272
-2688:273
-2692:274
-2696:275
-2700:276
-2704:277
-2708:278
-2712:279
-2716:280
-2720:281
-2724:282
-2728:283
-2732:284
-2736:285
-2740:286
-2744:287
-2748:288
-2752:289
-2756:290
-2760:291
-2764:292
-2768:293
-2772:294
-2776:295
-2780:296
-2784:297
-2788:298
-2792:299
-2796:300
-2800:301
-2804:302
-2808:303
-2812:304
-2816:305
-2820:306
-2824:307
-2828:308
-2832:309
-2836:310
-2840:311
-2844:312
-2848:313
-2852:314
-2856:315
-2860:316
-2864:317
-2868:318
-2872:319
-2876:320
-2880:321
-2884:322
-2888:323
-2892:324
-2896:325
-2900:326
-2904:327
-2908:328
-2912:329
-2916:330
-2920:331
-2924:332
-2928:333
-2932:334
-2936:335
-2940:336
-2944:337
-2948:338
-2952:339
-2956:340
-2960:341
-2964:342
-2968:343
-2972:344
-2976:345
-2980:346
-2984:347
-2988:348
-2992:349
-2996:350
-3000:351
-3004:352
-3008:353
-3012:354
-3016:355
-3020:356
-3024:357
-3028:358
-3032:359
-3036:360
-3040:361
-3044:362
-3048:363
-3052:364
-3056:365
-3060:366
-3064:367
-3068:368
-3072:369
-3076:370
-3080:371
-3084:372
-3088:373
-3092:374
-3096:375
-3100:376
-3104:377
-3108:378
-3112:379
-3116:380
-3120:381
-3124:382
-3128:383
-3132:384
-3136:385
-3140:386
-3144:387
-3148:388
-3152:389
-3156:390
-3160:391
-3164:392
-3168:393
-3172:394
-3176:395
-3180:396
-3184:397
-3188:398
-3192:399
-3196:400

+ 249 - 83
build/classes/tools/mips/memory/mi.memory

@@ -1,83 +1,249 @@
-0666763216
-0001962017
-0605028352
-2949644288
-0605103921
-2949709840
-0605159425
-2945581056
-0605224960
-2949840928
-0134217758
-0000000000
-2413035536
-0000000000
-0001318945
-0201326632
-0000000000
-0000155681
-2413101056
-0000000000
-0044869665
-2949971968
-2413166608
-0000000000
-0651558914
-2950037520
-2413232160
-0000000000
-0653721601
-2950103072
-2412773408
-0000000000
-0604962826
-0034541603
-0071368681
-0000000000
-2412838912
-0000000000
-0001118241
-4294967295
-0666763232
-0001962017
-2412773376
-0000000000
-2948857856
-0605093888
-2949709840
-2412773376
-0000000000
-0033558563
-0406847509
-0000000000
-0134217798
-0000000000
-2412904464
-0000000000
-0642908161
-2949775376
-2412969984
-0000000000
-0644677631
-2412969984
-0000000000
-0040671268
-2949840896
-0000000000
-2412969984
-0000000000
-0308281347
-0000000000
-0134217782
-0000000000
-2408841220
-2413101072
-0000000000
-0043360289
-2945712132
-2413101072
-0000000000
-0001380385
-0666697760
-0001962017
-0065011720
+-- Copyright (C) 1991-2014 Altera Corporation. All rights reserved.
+-- Your use of Altera Corporation's design tools, logic functions
+-- and other software and tools, and its AMPP partner logic
+-- functions, and any output files from any of the foregoing
+-- (including device programming or simulation files), and any
+-- associated documentation or information are expressly subject
+-- to the terms and conditions of the Altera Program License
+-- Subscription Agreement, the Altera Quartus II License Agreement,
+-- the Altera MegaCore Function License Agreement, or other
+-- (including device programming or simulation files), and any
+-- applicable license agreement, including, without limitation,
+-- that your use is for the sole purpose of programming logic 
+-- devices manufactured by Altera and sold by Altera or its 
+-- authorized distributors.  Please refer to the applicable 
+-- agreement for further details.
+-- Quartus II generated Memory Initialization File (.mif)
+
+WIDTH = 32;
+DEPTH = 16384;
+
+ADDRESS_RADIX = DEC;
+DATA_RADIX = BIN;
+
+CONTENT
+BEGIN
+000:	00001100000000000000000000000101;	% dec 201326597 %
+004:	00000000000000000000000000000000;	% dec 0 %
+008:	00001100000000000000000001011000;	% dec 201326680 %
+012:	00000000000000000000000000000000;	% dec 0 %
+016:	11111111111111111111111111111111;	% dec 4294967295 %
+020:	00100111101111011111111111101000;	% dec 666763240 %
+024:	00000000000111011111000000100001;	% dec 1962017 %
+028:	00100100000100000000000000000001;	% dec 605028353 %
+032:	10101111110100000000000000000000;	% dec 2949644288 %
+036:	00100100000100010000000000000100;	% dec 605093892 %
+040:	10101111110100010000000000000100;	% dec 2949709828 %
+044:	00100100000100100000000000000100;	% dec 605159428 %
+048:	10101111110100100000000000001000;	% dec 2949775368 %
+052:	00100100000100110000000000000000;	% dec 605224960 %
+056:	10101111110100110000000000001100;	% dec 2949840908 %
+060:	00001000000000000000000001001111;	% dec 134217807 %
+064:	00000000000000000000000000000000;	% dec 0 %
+068:	00100100000101000000000000000000;	% dec 605290496 %
+072:	10101111110101000000000000010000;	% dec 2949906448 %
+076:	00001000000000000000000001000101;	% dec 134217797 %
+080:	00000000000000000000000000000000;	% dec 0 %
+084:	10001111110101010000000000001100;	% dec 2413101068 %
+088:	00000000000000000000000000000000;	% dec 0 %
+092:	00010010101000000000000000000110;	% dec 312475654 %
+096:	00000000000000000000000000000000;	% dec 0 %
+100:	10001111110101100000000000001100;	% dec 2413166604 %
+104:	10001111110101110000000000000100;	% dec 2413232132 %
+108:	00000000000000000000000000000000;	% dec 0 %
+112:	00010010110101110000000000010110;	% dec 316080150 %
+116:	00000000000000000000000000000000;	% dec 0 %
+120:	00100100000100000000000000000000;	% dec 605028352 %
+124:	10101111110100000000000000010100;	% dec 2949644308 %
+128:	10001111110100010000000000010000;	% dec 2412838928 %
+132:	00000000000000000000000000000000;	% dec 0 %
+136:	00010010001000000000000000000110;	% dec 304087046 %
+140:	00000000000000000000000000000000;	% dec 0 %
+144:	10001111110100100000000000010000;	% dec 2412904464 %
+148:	10001111110100110000000000001000;	% dec 2412969992 %
+152:	00000000000000000000000000000000;	% dec 0 %
+156:	00010010010100110000000000001011;	% dec 307429387 %
+160:	00000000000000000000000000000000;	% dec 0 %
+164:	00100100000101000000000000000000;	% dec 605290496 %
+168:	10101111110101000000000000010100;	% dec 2949906452 %
+172:	10001111110101010000000000000000;	% dec 2413101056 %
+176:	00000000000000000000000000000000;	% dec 0 %
+180:	00000000000101011010000000100001;	% dec 1417249 %
+184:	10101111110101000000000000010100;	% dec 2949906452 %
+188:	10001111110101010000000000000000;	% dec 2413101056 %
+192:	00000000000000000000000000000000;	% dec 0 %
+196:	00100110101101010000000000000001;	% dec 649396225 %
+200:	10101111110101010000000000000000;	% dec 2949971968 %
+204:	10001111110101100000000000001100;	% dec 2413166604 %
+208:	00000000000000000000000000000000;	% dec 0 %
+212:	00000000000101100100100000100001;	% dec 1460257 %
+216:	00000000000010010101000010000000;	% dec 610432 %
+220:	00000001001010100100100000100001;	% dec 19548193 %
+224:	10001111110101110000000000010000;	% dec 2413232144 %
+228:	00000000000000000000000000000000;	% dec 0 %
+232:	00000000000101110101100000100001;	% dec 1529889 %
+236:	00000001001010110100100000100001;	% dec 19613729 %
+240:	00000000000010010110000010000000;	% dec 614528 %
+244:	10001111110100000000000000010100;	% dec 2412773396 %
+248:	00000000000000000000000000000000;	% dec 0 %
+252:	00000011100011000110000000100001;	% dec 59531297 %
+256:	10101101100100000000000000000000;	% dec 2911895552 %
+260:	10001111110101110000000000010000;	% dec 2413232144 %
+264:	00000000000000000000000000000000;	% dec 0 %
+268:	00100110111101110000000000000001;	% dec 653721601 %
+272:	10101111110101110000000000010000;	% dec 2950103056 %
+276:	10001111110100100000000000010000;	% dec 2412904464 %
+280:	00000000000000000000000000000000;	% dec 0 %
+284:	00100100000011100000000000000101;	% dec 604897285 %
+288:	00000010010011100001000000100011;	% dec 38670371 %
+292:	00000100010000001111111111001011;	% dec 71368651 %
+296:	00000000000000000000000000000000;	% dec 0 %
+300:	10001111110100110000000000001100;	% dec 2412969996 %
+304:	00000000000000000000000000000000;	% dec 0 %
+308:	00100110011100110000000000000001;	% dec 645070849 %
+312:	10101111110100110000000000001100;	% dec 2949840908 %
+316:	10001111110101000000000000001100;	% dec 2413035532 %
+320:	00000000000000000000000000000000;	% dec 0 %
+324:	00100100000110000000000000000101;	% dec 605552645 %
+328:	00000010100110000001000000100011;	% dec 43520035 %
+332:	00000100010000001111111110111101;	% dec 71368637 %
+336:	00000000000000000000000000000000;	% dec 0 %
+340:	00100111101111010000000000011000;	% dec 666697752 %
+344:	00000000000111011111000000100001;	% dec 1962017 %
+348:	00000011111000000000000000001000;	% dec 65011720 %
+352:	00100111101111011111111111101100;	% dec 666763244 %
+356:	00000000000111011111000000100001;	% dec 1962017 %
+360:	00100100000100000000000000000100;	% dec 605028356 %
+364:	10101111110100000000000000000000;	% dec 2949644288 %
+368:	00100100000100010000000000000100;	% dec 605093892 %
+372:	10101111110100010000000000000100;	% dec 2949709828 %
+376:	00100100000100100000000000000001;	% dec 605159425 %
+380:	10101111110100100000000000001000;	% dec 2949775368 %
+384:	00001000000000000000000011010110;	% dec 134217942 %
+388:	00000000000000000000000000000000;	% dec 0 %
+392:	00100100000100110000000000000001;	% dec 605224961 %
+396:	10101111110100110000000000001100;	% dec 2949840908 %
+400:	00001000000000000000000011001100;	% dec 134217932 %
+404:	00000000000000000000000000000000;	% dec 0 %
+408:	10001111110101000000000000001000;	% dec 2413035528 %
+412:	00000000000000000000000000000000;	% dec 0 %
+416:	00100110100011011111111111111111;	% dec 646840319 %
+420:	00000000000011010111000010000000;	% dec 880768 %
+424:	00000001101011100110100000100001;	% dec 28207137 %
+428:	10001111110101010000000000001100;	% dec 2413101068 %
+432:	00000000000000000000000000000000;	% dec 0 %
+436:	00000000000101010111100000100001;	% dec 1407009 %
+440:	00000001101011110110100000100001;	% dec 28272673 %
+444:	00000000000011011100000010000000;	% dec 901248 %
+448:	00000011100110001100000000100001;	% dec 60342305 %
+452:	10001111000010000000000000000000;	% dec 2399666176 %
+456:	10001111110101000000000000001000;	% dec 2413035528 %
+460:	00000000000000000000000000000000;	% dec 0 %
+464:	00000000000101000100100000100001;	% dec 1329185 %
+468:	00000000000010010101000010000000;	% dec 610432 %
+472:	00000001001010100100100000100001;	% dec 19548193 %
+476:	10001111110101010000000000001100;	% dec 2413101068 %
+480:	00000000000000000000000000000000;	% dec 0 %
+484:	00100110101011001111111111111111;	% dec 648871935 %
+488:	00000001001011000100100000100001;	% dec 19679265 %
+492:	00000000000010010111000010000000;	% dec 618624 %
+496:	00000011100011100111000000100001;	% dec 59666465 %
+500:	10001101110101110000000000000000;	% dec 2379677696 %
+504:	00000000000000000000000000000000;	% dec 0 %
+508:	00000000000101110111100000100001;	% dec 1538081 %
+512:	00000001000011110110100000100001;	% dec 17786913 %
+516:	10001111110101000000000000001000;	% dec 2413035528 %
+520:	00000000000000000000000000000000;	% dec 0 %
+524:	00000000000101001100000000100001;	% dec 1359905 %
+528:	00000000000110000101000010000000;	% dec 1593472 %
+532:	00000011000010101100000000100001;	% dec 51036193 %
+536:	10001111110101010000000000001100;	% dec 2413101068 %
+540:	00000000000000000000000000000000;	% dec 0 %
+544:	00100110101011000000000000000001;	% dec 648806401 %
+548:	00000011000011001100000000100001;	% dec 51167265 %
+552:	00000000000110000100100010000000;	% dec 1591424 %
+556:	00000011100010010100100000100001;	% dec 59328545 %
+560:	10001101001100000000000000000000;	% dec 2368733184 %
+564:	00000000000000000000000000000000;	% dec 0 %
+568:	00000000000100000111000000100001;	% dec 1077281 %
+572:	00000001101011100100000000100001;	% dec 28196897 %
+576:	10001111110101000000000000001000;	% dec 2413035528 %
+580:	00000000000000000000000000000000;	% dec 0 %
+584:	00100110100010100000000000000001;	% dec 646578177 %
+588:	00000000000010100101100010000000;	% dec 678016 %
+592:	00000001010010110101000000100001;	% dec 21712929 %
+596:	10001111110101010000000000001100;	% dec 2413101068 %
+600:	00000000000000000000000000000000;	% dec 0 %
+604:	00000000000101010110000000100001;	% dec 1400865 %
+608:	00000001010011000101000000100001;	% dec 21778465 %
+612:	00000000000010101100000010000000;	% dec 704640 %
+616:	00000011100110001100000000100001;	% dec 60342305 %
+620:	10001111000100010000000000000000;	% dec 2400256000 %
+624:	00000000000000000000000000000000;	% dec 0 %
+628:	00000000000100010100100000100001;	% dec 1132577 %
+632:	00000001000010010110100000100001;	% dec 17393697 %
+636:	10001111110101000000000000001000;	% dec 2413035528 %
+640:	00000000000000000000000000000000;	% dec 0 %
+644:	00000000000101000111000000100001;	% dec 1339425 %
+648:	00000000000011100111100010000000;	% dec 948352 %
+652:	00000001110011110111000000100001;	% dec 30371873 %
+656:	10001111110101010000000000001100;	% dec 2413101068 %
+660:	00000000000000000000000000000000;	% dec 0 %
+664:	00000000000101010101100000100001;	% dec 1398817 %
+668:	00000001110010110111000000100001;	% dec 30109729 %
+672:	00000000000011100110000010000000;	% dec 942208 %
+676:	00000011100011000110000000100001;	% dec 59531297 %
+680:	10001101100100100000000000000000;	% dec 2375155712 %
+684:	00000000000000000000000000000000;	% dec 0 %
+688:	00000000000100100101000000100001;	% dec 1200161 %
+692:	00100100000110000000000000000100;	% dec 605552644 %
+696:	00000001010110000100000000011000;	% dec 22560792 %
+700:	00000000000000000100000000010010;	% dec 16402 %
+704:	00000001101010001001100000100011;	% dec 27826211 %
+708:	10101111110100110000000000010000;	% dec 2949840912 %
+712:	10001111110100110000000000010000;	% dec 2412970000 %
+716:	00000000000000000000000000000000;	% dec 0 %
+720:	00100100000010010000000011111111;	% dec 604569855 %
+724:	00000010011010010001000000100011;	% dec 40439843 %
+728:	00011000010000000000000000000011;	% dec 406847491 %
+732:	00000000000000000000000000000000;	% dec 0 %
+736:	00100100000101100000000011111111;	% dec 605421823 %
+740:	10101111110101100000000000010000;	% dec 2950037520 %
+744:	10001111110101110000000000001000;	% dec 2413232136 %
+748:	00000000000000000000000000000000;	% dec 0 %
+752:	00000000000101110101100000100001;	% dec 1529889 %
+756:	00000000000010110111000010000000;	% dec 749696 %
+760:	00000001011011100101100000100001;	% dec 24008737 %
+764:	10001111110100000000000000001100;	% dec 2412773388 %
+768:	00000000000000000000000000000000;	% dec 0 %
+772:	00000000000100000110000000100001;	% dec 1073185 %
+776:	00000001011011000101100000100001;	% dec 23877665 %
+780:	00000000000010110101000010000000;	% dec 741504 %
+784:	10001111110100010000000000010000;	% dec 2412838928 %
+788:	00000000000000000000000000000000;	% dec 0 %
+792:	00000011100010100101000000100001;	% dec 59396129 %
+796:	10101101010100010000000001100100;	% dec 2907766884 %
+800:	10001111110100000000000000001100;	% dec 2412773388 %
+804:	00000000000000000000000000000000;	% dec 0 %
+808:	00100110000100000000000000000001;	% dec 638582785 %
+812:	10101111110100000000000000001100;	% dec 2949644300 %
+816:	10001111110101010000000000001100;	% dec 2413101068 %
+820:	10001111110100100000000000000100;	% dec 2412904452 %
+824:	00000000000000000000000000000000;	% dec 0 %
+828:	00000010101100100001000000100011;	% dec 45223971 %
+832:	00000100010000001111111110010101;	% dec 71368597 %
+836:	00000000000000000000000000000000;	% dec 0 %
+840:	10001111110100110000000000001000;	% dec 2412969992 %
+844:	00000000000000000000000000000000;	% dec 0 %
+848:	00100110011100110000000000000001;	% dec 645070849 %
+852:	10101111110100110000000000001000;	% dec 2949840904 %
+856:	10001111110101100000000000001000;	% dec 2413166600 %
+860:	10001111110101110000000000000000;	% dec 2413232128 %
+864:	00000000000000000000000000000000;	% dec 0 %
+868:	00000010110101110001000000100011;	% dec 47648803 %
+872:	00000100010000001111111110000111;	% dec 71368583 %
+876:	00000000000000000000000000000000;	% dec 0 %
+880:	00100111101111010000000000010100;	% dec 666697748 %
+884:	00000000000111011111000000100001;	% dec 1962017 %
+888:	00000011111000000000000000001000;	% dec 65011720 %
+END;

+ 0 - 74
build/classes/tools/mips/memory/mi2.memory

@@ -1,74 +0,0 @@
-0604241920
-0666763232
-2948464664
-2948530204
-0001962017
-2948857856
-2412773376
-0605093888
-0638713861
-0001087521
-0134217786
-0605290496
-0134217782
-0605356032
-0134217767
-0001269793
-0000811136
-0000813184
-0026042401
-0001404961
-0026107937
-0000817280
-0059734049
-2381709312
-0001490977
-0001392673
-0000540800
-0000542848
-0017383457
-0001331233
-0017448993
-0000546944
-0059463713
-2373387840
-0001533985
-0051212312
-0000028690
-0036603937
-0649396225
-0604962836
-0045027363
-0071368677
-0001263649
-0000608384
-0000610432
-0019548193
-0001327137
-0019417121
-0000612480
-0059463713
-2909867136
-0605093888
-2949709828
-0647233537
-0604897300
-0042864675
-0071368660
-0645070849
-0041029667
-0071368655
-0605421584
-2945848000
-0201326660
-2948726816
-2411593752
-2411659292
-0666697760
-4294967295
-0666763260
-0001962017
-0605028353
-0001052705
-0666697732
-0065011720

+ 3 - 1
nbproject/project.properties

@@ -48,7 +48,9 @@ javac.source=1.8
 javac.target=1.8
 javac.test.classpath=\
     ${javac.classpath}:\
-    ${build.classes.dir}
+    ${build.classes.dir}:\
+    ${libs.junit_4.classpath}:\
+    ${libs.hamcrest.classpath}
 javac.test.processorpath=\
     ${javac.test.classpath}
 javadoc.additionalparam=

+ 22 - 40
src/API/Api.java

@@ -34,52 +34,34 @@ public class Api {
         /*Inicializando tipos*/
         Types._init();
 
-//
-//        Types.Add(Types.INTEGER, new Node(Types.INTEGER)
-//                .Set("type", Types.INTEGER)
-//                .S("size", 1)
-//                .Set("file", "std")
-//                .Set("scope", "")
-//                .Set("primitive", "true")
-//                .Set("class", "type")
-//                .Set("public", "true")
-//        );
-//        Types.Add(Types.BOOLEAN, new Node(Types.BOOLEAN)
-//                .Set("type", Types.BOOLEAN)
-//                .S("size", 1)
-//                .Set("file", "std")
-//                .Set("scope", "")
-//                .Set("primitive", "true")
-//                .Set("class", "type")
-//                .Set("public", "true")
-//        );
-//        Types.Add(Types.CHAR, new Node(Types.CHAR)
-//                .Set("type", Types.CHAR)
-//                .S("size", 1)
-//                .Set("file", "std")
-//                .Set("scope", "")
-//                .Set("primitive", "true")
-//                .Set("class", "type")
-//                .Set("public", "true")
-//        );
         // Registra os processadores de codigo padrão
-        CodeProcessor.Add("ir.clear.labels", new Processors.RemoveUnusedLabelsProcessor());
-        CodeProcessor.Add("ir.basic.blocks", new Processors.BasicBlockProcessor());
-        CodeProcessor.Add("ir.o.load_store", new Processors.LoadStoreProcessor());
-        CodeProcessor.Add("ir.o.VariablesConstants", new Processors.VariablesConstantsProcessor());
-        CodeProcessor.Add("ir.o.DeadInstructions", new Processors.DeadInstructionsProcessor());
-        CodeProcessor.Add("ir.o.copies", new Processors.CodeOtimizadorProcessor(true));
+        Middleware.Add("ir.clear.labels", new middlewares.RemoveUnusedLabelsMiddleware());
+        Middleware.Add("ir.basic.blocks", new middlewares.BasicBlockMiddleware());
+        Middleware.Add("ir.o.load_store", new middlewares.LoadStoreMiddleware());
+        Middleware.Add("ir.o.VariablesConstants", new middlewares.VariablesConstantsMiddleware());
+        Middleware.Add("ir.o.DeadInstructions", new middlewares.DeadInstructionsMiddleware());
+        Middleware.Add("ir.o.copies", new middlewares.CodeOtimizadorMiddleware(true));
 
         // Processadores do alvo mips
-        CodeProcessor.Add("mips.copy.dep", new targets.mips.MipsCopyDepsProcessor());
-        CodeProcessor.Add("mips.register.alloc", new targets.mips.MipsRegisterAllocProcessor());
-        CodeProcessor.Add("mips.o.L1", new targets.mips.MipsOtimizationProcessor());
-        CodeProcessor.Add("mips.update.address", new targets.mips.MipsUpdateAddressProcessor());
+        Middleware.Add("mips.copy.dep", new targets.mips.MipsCopyDepsMiddleware());
+        Middleware.Add("mips.register.alloc", new targets.mips.MipsRegisterAllocMiddleware());
+        Middleware.Add("mips.o.L1", new targets.mips.MipsOtimizationMiddleware());
+        Middleware.Add("mips.update.address", new targets.mips.MipsUpdateAddressMiddleware());
+
+        Middleware.Add("print.data", (c, cp) -> {
+
+            System.out.println("@@@@@@DATA_LAYOUT:\n\n"
+                    + c.Block().GlobalContext()
+                    + c.Block().Context().toString());
+
+        });
+
+        Middleware.On("IR", "close.block", "print.data");
 
         // Define os processadores padrão da IR
-        CodeProcessor.On(
+        Middleware.On(
                 "IR",
-                "CloseBlock",
+                "close.block",
                 // Remove labels não referenciadas
                 "ir.clear.labels,"
                 // Remove copias

+ 24 - 11
src/API/CodeProcessor.java

@@ -7,6 +7,7 @@ package API;
 
 import common.Instruction;
 import common.Log;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 
@@ -14,29 +15,37 @@ import java.util.LinkedHashMap;
  *
  * @author Eugenio
  */
-public class CodeProcessor {
+public class Middleware {
 
     // Todos os processors serão armazenados aqui, e cada evendo possui uma lista de processors separada por virgula
-    protected static LinkedHashMap<String, API.CodeProcessorInterface> processors = new LinkedHashMap<>();
-    protected static HashMap<String, HashMap<String, String>> events = new HashMap<>();
+    protected static LinkedHashMap<String, API.MiddlewareInterface> processors = new LinkedHashMap<>();
+    protected static HashMap<String, HashMap<String, ArrayList<String>>> events = new HashMap<>();
 
     public static void _init() {
 
     }
 
     public static void On(String selectors, String event, String processors) {
+        HashMap<String, ArrayList<String>> s;
+        ArrayList<String> processorsList = ProcToList(processors);
         for (String selector : selectors.split(",")) {
             if (!events.containsKey(selector)) {
-                events.put(selector, new HashMap<String, String>());
+                events.put(selector, new HashMap<>());
             }
-            events.get(selector).put(event, processors);
+            s = events.get(selector);
+
+            if (!s.containsKey(event)) {
+                s.put(event, new ArrayList<>());
+            }
+
+            s.get(event).addAll(processorsList);
         }
     }
 
     public static void Trigger(common.Code c, String selector, String event) throws Exception {
 //        System.out.println("Try trigger:" + selector);
         if (events.containsKey(selector)) {
-            HashMap<String, String> t = events.get(selector);
+            HashMap<String, ArrayList<String>> t = events.get(selector);
             if (t.containsKey(event)) {
                 ProcessorExecute(c, t.get(event));
             }
@@ -44,7 +53,7 @@ public class CodeProcessor {
 
     }
 
-    public static void Add(String id, API.CodeProcessorInterface p) throws Exception {
+    public static void Add(String id, API.MiddlewareInterface p) throws Exception {
         if (processors.containsKey(id)) {
             Log.PrintWarning(
                     "Code Processor",
@@ -54,13 +63,17 @@ public class CodeProcessor {
         processors.put(id, p);
     }
 
-    protected static String[] ProcToList(String events) {
+    protected static ArrayList<String> ProcToList(String events) {
 //        System.out.println("events:" + events);
-        return events.replaceAll("\\s+", "").split(",");
+        ArrayList<String> r = new ArrayList<>();
+        for (String p : events.replaceAll("\\s+", "").split(",")) {
+            r.add(p);
+        }
+        return r;
     }
 
-    public static void ProcessorExecute(common.Code c, String eventList) throws Exception {
-        for (String x : ProcToList(eventList)) {
+    public static void ProcessorExecute(common.Code c, ArrayList<String> eventList) throws Exception {
+        for (String x : eventList) {
 
             if (x.equals("")) {
                 continue;

+ 2 - 2
src/API/CodeProcessorInterface.java

@@ -12,7 +12,7 @@ import java.util.LinkedHashMap;
  *
  * @author EUGENIO CARVALHO
  */
-public interface CodeProcessorInterface {
+public interface MiddlewareInterface {
 
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception;
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception;
 }

+ 91 - 36
src/API/TargetGen.java

@@ -7,10 +7,12 @@ package API;
 
 import common.Block;
 import common.Code;
+import common.DataLayout;
 import common.Instruction;
 import common.IvannosysTargetArch;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Map;
 import java.util.Set;
@@ -27,11 +29,51 @@ public abstract class TargetGen implements IvannosysTargetArch {
     protected Code target;
     protected Code IR;
     protected Instruction prev = null, next = null;
+    protected Instruction currentIrInstruction;
+    protected Instruction currentTargetInstruction;
 
     public TargetGen(String id) {
         BaseGenInit(id);
     }
 
+    /**
+     * Like Sprintf
+     *
+     * @param format
+     * @param args
+     * @return
+     */
+    protected String F(String format, Object... args) {
+        return String.format(format, args);
+    }
+
+    /**
+     * Retorna o contexto do bloco atual
+     *
+     * @return
+     */
+    public DataLayout Context() {
+        return Context("");
+    }
+
+    /**
+     * Retorna o contexto do bloco atual <br>
+     * Se var contem "G" retorna o contexto global
+     *
+     * @param var
+     * @return
+     */
+    public DataLayout Context(String var) {
+        if (var.contains("G")) {
+            return IR.GlobalContext();
+        }
+        return IR.Block().Context();
+    }
+
+    public common.Offset Offset(String var) throws Exception {
+        return Context(var).Offset(var);
+    }
+
     public void BaseGenInit(String id) {
         target = new Code(id);
     }
@@ -67,7 +109,7 @@ public abstract class TargetGen implements IvannosysTargetArch {
         return exportMethods;
     }
 
-    public IvannosysTargetArch SetTAC(Code tac) throws Exception {
+    public IvannosysTargetArch Init(Code tac) throws Exception {
         // Verifica se o codigo gerado vai ser util caso contrario aborta o processo;
         ArrayList<String> methods = BuildParams.Get("export");
 
@@ -76,13 +118,19 @@ public abstract class TargetGen implements IvannosysTargetArch {
         }
 
         IR = tac;
-        target.GlobalData().copy(tac.GlobalData());
+//        target.GlobalContext().copy(tac.GlobalContext());
         target.Parent = IR;
         return this;
     }
 
     protected Instruction Add(Instruction inst) {
+        if (currentIrInstruction != null) {
+            inst.Set("tac.position", currentIrInstruction.Get("block.position"));
+        }
         target.Block().Add(inst);
+
+        currentTargetInstruction = inst;
+
         return inst;
     }
 
@@ -94,7 +142,7 @@ public abstract class TargetGen implements IvannosysTargetArch {
     @Override
     public IvannosysTargetArch Format() {
         try {
-            String code = target.getCodeStream();
+            String code = target.Dump();
             System.out.println("Target[" + target.Name() + "]:\n" + code);
 
         } catch (Exception ex) {
@@ -118,32 +166,37 @@ public abstract class TargetGen implements IvannosysTargetArch {
     protected void Translate() throws Exception {
         String targetID = target.Name(), id;
         target.Parent = IR;
+        Block block;
+        Middleware.Trigger(target, targetID, "before.translate");
 
-        CodeProcessor.Trigger(target, targetID, "BeforeTranslate");
-
-        for (Map.Entry<String, Block> b : IR.getBlocks().entrySet()) {
+        for (Map.Entry<String, Block> b : IR.Blocks().entrySet()) {
             id = b.getKey();
+            block = b.getValue();
+
+            if (block.Type() == Block.TYPE_CTRL) {
+                continue;
+            }
 
             IR.Use(id);
 
             target.OpenBlock(id);
 
-            CodeProcessor.Trigger(target, targetID, "BeforeTranslateBlock");
+            Middleware.Trigger(target, targetID, "before.translate.block");
 
             Prolog(id);
 
-            TranslateBlock(b.getValue());
+            TranslateBlock(block);
 
             Epilog(id);
 
             target.CloseBlock();
 
-            target.UpdatePositions();
-
-            CodeProcessor.Trigger(target, targetID, "AfterTranslateBlock");
+            Middleware.Trigger(target, targetID, "after.translate.block");
         }
 
-        CodeProcessor.Trigger(target, targetID, "AfterTranslate");
+        target.UpdatePositions();
+
+        Middleware.Trigger(target, targetID, "after.translate");
     }
 
     @Override
@@ -160,11 +213,11 @@ public abstract class TargetGen implements IvannosysTargetArch {
 //        System.out.println("Translate block:" + b.getName() + "::" + b.Instructions().size());
         LinkedList<Instruction> instructions = b.Instructions();
         Integer index = 0, limit = instructions.size(), nextIndex;
-        for (Instruction inst : instructions) {
+        for (Iterator<Instruction> it = instructions.iterator(); it.hasNext();) {
+            currentIrInstruction = it.next();
             nextIndex = index + 1;
             next = (nextIndex < limit) ? instructions.get(nextIndex) : null;
-
-//            System.out.println("Translate: " + inst.Get("global.position") + "::read["
+            //            System.out.println("Translate: " + inst.Get("global.position") + "::read["
 //                    + inst.Get("reg.dst.load")
 //                    + "|"
 //                    + inst.Get("reg.p1.load")
@@ -179,62 +232,64 @@ public abstract class TargetGen implements IvannosysTargetArch {
 //                    + "]"
 //                    + inst.Get("type")
 //            );
-//            
-            switch (inst.Get("type")) {
+//
+            switch (currentIrInstruction.Get("type")) {
+                case "alloc":
+                    break;
                 case "label":
-                    if (!inst.Get("label").equals(getTarget().Block().getName())) {
-                        TranslateLabel(inst);
+                    if (!currentIrInstruction.Get("label").equals(getTarget().Block().getName())) {
+                        TranslateLabel(currentIrInstruction);
                     }
                     break;
                 case "assign":
-                    TranslateAssign(inst);
+                    TranslateAssign(currentIrInstruction);
                     break;
                 case "unary":
-                    TranslateUnary(inst);
+                    TranslateUnary(currentIrInstruction);
                     break;
                 case "copy":
-                    TranslateCopy(inst);
+                    TranslateCopy(currentIrInstruction);
                     break;
                 case "jump":
-                    TranslateJump(inst);
+                    TranslateJump(currentIrInstruction);
                     break;
                 case "call":
-                    TranslateCall(inst);
+                    TranslateCall(currentIrInstruction);
                     break;
                 case "return":
-                    TranslateReturn(inst);
+                    TranslateReturn(currentIrInstruction);
                     break;
                 case "push_param":
-                    TranslatePushParam(inst);
+                    TranslatePushParam(currentIrInstruction);
                     break;
                 case "push_return":
-                    TranslatePushReturn(inst);
+                    TranslatePushReturn(currentIrInstruction);
                     break;
                 case "pop_return":
-                    TranslatePopReturn(inst);
+                    TranslatePopReturn(currentIrInstruction);
                     break;
                 case "pop_param":
-                    TranslatePopParam(inst);
+                    TranslatePopParam(currentIrInstruction);
                     break;
                 case "branch":
-                    TranslateBranch(inst);
+                    TranslateBranch(currentIrInstruction);
                     break;
                 case "indexed_assign":
-                    TranslateIndexedAssignment(inst);
+                    TranslateIndexedAssignment(currentIrInstruction);
                     break;
                 case "pointer_assign":
-                    TranslatePointerAssignment(inst);
+                    TranslatePointerAssignment(currentIrInstruction);
                     break;
                 case "store":
-                    TranslateStore(inst);
+                    TranslateStore(currentIrInstruction);
                     break;
                 case "load":
-                    TranslateLoad(inst);
+                    TranslateLoad(currentIrInstruction);
                     break;
                 default:
-                    throw new Exception(String.format("TAC instruction type '%s' not defined", inst.Get("type")));
+                    throw new Exception(String.format("TAC instruction type '%s' not defined", currentIrInstruction.Get("type")));
             }
-            prev = inst;
+            prev = currentIrInstruction;
             index++;
         }
     }

+ 64 - 17
src/API/Types.java

@@ -10,6 +10,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Set;
+import java.util.TreeMap;
 
 /**
  *
@@ -25,6 +26,10 @@ public class Types {
     public static HashMap<String, Integer> primitiveTypes = new HashMap<>();
     public static HashMap<String, HashMap<String, String>> _propList = new HashMap<>();
     public static HashMap<String, Integer> _offsetList = new HashMap<>();
+    public static HashMap<String, TreeMap<Integer, ArrayList<String>>> baseLayoutMeta = new HashMap<>();
+
+    // Tamanho de um ponteiro em bytes
+    public static Integer PTR_SIZE = 4;
 
     public static HashMap<String, Integer> getSizes() {
         return _sizes;
@@ -94,29 +99,72 @@ public class Types {
 
             // Completa a definicao da struct importando os atributos herdados
             for (Node t : type.findAll("type", "class", 1)) {
-
                 def = Get(t.Get("type"));
-
                 for (Node attr : def.findAll("attr", "class")) {
                     attr.Set("path", def.getText());
                     type.addFilho(attr);
                 }
             }
-            UpdateSize(type);
+
+            LayoutType(type);
         }
 
     }
 
-    protected static void UpdateSize(Node type) throws Exception {
-        // Atualiza o tamanho to tipo
-        int size = 0;
+    protected static void LayoutType(Node type) throws Exception {
+//        System.out.println("type:" + type);
+        String id, t = type.Get("type");
+        Integer size,
+                // Atualiza o tamanho to tipo
+                structSize = 0;
 
-        for (Node attr : type.findAll("attr", "class")) {
-            size += Size(attr.childrens().get(0).Get("type"));
+        if (baseLayoutMeta.containsKey(t)) {
+            return;
         }
-        _sizes.put(type.getText(), size);
+
+        TreeMap<Integer, ArrayList<String>> layout = new TreeMap<>();
+
+        baseLayoutMeta.put(t, layout);
+
+        for (Node attr : type.findAll("attr", "class", 1)) {
+            id = attr.Get("value");
+            size = Size(attr.find("type").Get("type"));
+            if (!layout.containsKey(size)) {
+                layout.put(size, new ArrayList<>());
+            }
+            layout.get(size).add(id);
+
+            switch (attr.Get("pointer")) {
+                case "*":
+                    structSize += PTR_SIZE;
+                    break;
+                default:
+                    structSize += Size(attr.childrens().get(0).Get("type"));
+            }
+        }
+//        System.out.println("map:" + layout);
+        _sizes.put(type.getText(), structSize);
+    }
+
+    protected static void LayoutType(String type) {
+
     }
 
+//    protected static void UpdateSize(Node type) throws Exception {
+//
+//        for (Node attr : type.findAll("attr", "class")) {
+//
+//            switch (attr.Get("pointer")) {
+//                case "*":
+//                    size += PTR_SIZE;
+//                    break;
+//                default:
+//                    size += Size(attr.childrens().get(0).Get("type"));
+//            }
+//
+//        }
+//        _sizes.put(type.getText(), structSize);
+//    }
     /**
      * Adiciona um tipo a linguagem
      *
@@ -137,7 +185,7 @@ public class Types {
                 .Set("value", id);
 
         if (type.Has("size")) {
-            _sizes.put(id, type.getInt("size"));
+            _sizes.put(id, type.GetInt("size"));
         }
 
         _types.put(id, type);
@@ -170,24 +218,23 @@ public class Types {
         System.out.println("Types:\n\t" + _sizes);
     }
 
-    public static int Size(String type) throws Exception {
+    public static Integer Size(String type) throws Exception {
         if (!_sizes.containsKey(type)) {
             Node t = Get(type);
-            UpdateSize(t);
+            LayoutType(t);
         }
-//        System.out.println("Size of <" + type + ">" + _sizes.);
         return _sizes.get(type);
     }
 
-    public static int Shift(String type, ArrayList<String> path) throws Exception {
+    public static Integer Shift(String type, ArrayList<String> path) throws Exception {
         return Shift(type, path.get(path.size() - 1));
     }
 
-    public static int Shift(String type, String attrib) throws Exception {
+    public static Integer Shift(String type, String attrib) throws Exception {
 
         Node T = Get(type);
         String attrType;
-        int shift = 0;
+        Integer shift = 0;
 //        System.out.println("Shift header:" + type + ":" + attrib + ":" + T);
 //        System.out.println("Shift:{");
         for (Node attr : T.findAll("attr", "class", 1)) {
@@ -217,7 +264,7 @@ public class Types {
     public static String[] getPrimitiveTypesList() {
         Set<String> set = primitiveTypes.keySet();
         String[] ret = new String[set.size()];
-        int i = 0;
+        Integer i = 0;
         for (String s : set) {
             ret[i++] = s;
         }

+ 16 - 3
src/API/Utils.java

@@ -62,19 +62,22 @@ public class Utils {
 //    protected String PAD(String value, String replace, int i) {
 //        return String.format("%" + i + "s", value).replace(" ", replace);
 //    }
+    public static String PAD_LEFT = "1$";
+    public static String PAD_RIGHT = "1$-";
+
     /**
      *
      * @param str
-     * @param replace
+     * @param pad
      * @param direction (padRight = '1$-' | padLeft = '1$')
      * @param size
      * @return
      */
-    public static String Pad(String str, String replace, String direction, int size) {
+    public static String Pad(String str, String pad, String direction, int size) {
         if (size == 0) {
             return str;
         }
-        return String.format("%" + direction + size + "s", str).replace(" ", replace);
+        return String.format("%" + direction + size + "s", str).replace(" ", pad);
     }
 
     public static String Pad(int size, String str) {
@@ -308,4 +311,14 @@ public class Utils {
 //    public String hex(String value) {
 //        return Integer.toHexString(Integer.parseInt(value));
 //    }
+    /**
+     * Retorna uma lista de substrings do tamanho definido
+     *
+     * @param src - String a ser dividida
+     * @param each - Quantidade de caracteres de cada parte
+     * @return
+     */
+    public static String[] SplitEach(String src, int each) {
+        return src.split("(?<=\\G.{" + each + "})");
+    }
 }

+ 12 - 9
src/API/Variables.java

@@ -27,7 +27,9 @@ public class Variables {
     public static String UNDEFINED = "undefined";
     public static String currentKey;
     public static Pattern BASEVEXPR = Pattern.compile("(\\w+(\\.@\\w+)*\\.\\w+)");
-    public static String CLEARBASEVAR = "(\\w+(\\.@\\w+)*\\.)";
+    public static String CLEARBASEVAR = "(\\w+)(\\.@\\w+)*(\\.)";
+    public static String SCOPE_LEVE = "(\\.@\\w+)((\\.\\w)*)";
+    public static String VARNAME = "(\\.\\w*)+";
 
     public static void _init() {
         vars = new HashMap<>();
@@ -42,6 +44,7 @@ public class Variables {
 //            throw new Exception("'" + id + "' previamente declarado em na linha " + vars.Get(id).Get("line", ""));
         }
         var.Set("public", Base.IsPublic(var.Get("name")) ? "true" : "false");
+//        System.out.println("Add var:" + var.Get("name"));
         vars.put(id, var);
     }
 
@@ -75,11 +78,11 @@ public class Variables {
 //            System.out.println("TypeOf:\n" + varname + "\n" + var + "\n" + var.contem("scope", "."));
             String path;
             if (var.contem("scope", ".")) {
-                path = varname.replace(var.Get("name"), "");
+                path = varname.replace(var.Get("fullname"), "");
             } else {
 
                 ArrayList<String> parts = new ArrayList<>();
-                for (String s : var.Get("name").split("\\.")) {
+                for (String s : var.Get("fullname").split("\\.")) {
                     parts.add(s);
                 }
                 parts.add(1, "(\\.@\\w+)+\\.");
@@ -87,7 +90,7 @@ public class Variables {
                 path = varname.replaceFirst(Utils.Join(parts, ""), "");
             }
 
-//            System.out.println("path:" + var.Get("name") + "---" + path);
+//            System.out.println("path:" + var.Get("fullname") + "---" + path);
             // Sem path
             if (path.length() > 0) {
                 ArrayList<String> parts = new ArrayList<>(Arrays.asList(path.split("\\.")));
@@ -126,7 +129,7 @@ public class Variables {
     }
 
     public static Node Get(String id) {
-
+//        System.out.println("Get VAR:" + id);
         String x = id;
         id = BaseVar(id);
 
@@ -506,7 +509,7 @@ public class Variables {
 //        for (Node indice : acessoIndices) {
 //            if (indice.IsNumber("value")) {
 //                limit = Integer.parseInt(decIndices.Get(i));
-//                acesso = indice.getInt("value");
+//                acesso = indice.GetInt("value");
 //                if (acesso >= limit || acesso < 0) {
 //                    throw new Exception("Acesso indevido a um array, limite {"
 //                            + (limit - 1) + "} enquanto a tentativa foi {"
@@ -565,7 +568,7 @@ public class Variables {
 //        int size = 1;
 //        if (null != indices) {
 //            for (Node indice : indices.filhos()) {
-//                size *= indice.getInt("value");
+//                size *= indice.GetInt("value");
 //            }
 //        }
 //        return size;
@@ -654,8 +657,8 @@ public class Variables {
 //                AnalizadorSemantico.testExist(indice);
 //                continue;
 //            } else if (!eDeclaracao) {
-//                limit = tipoIndices.Get(i).getInt("value");
-//                acesso = indice.getInt("value");
+//                limit = tipoIndices.Get(i).GetInt("value");
+//                acesso = indice.GetInt("value");
 //                if (acesso >= limit || acesso < 0) {
 //                    throw new Exception("Acesso indevido a um array, limite {"
 //                            + (limit - 1) + "} enquanto a tentativa foi {"

+ 151 - 0
src/Export/MemoryInitializationFile.java

@@ -0,0 +1,151 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package Export;
+
+import API.Utils;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.TreeMap;
+import tools.mips.Memory;
+import tools.mips.MemoryImportExportInterface;
+
+/**
+ *
+ * @author Eugenio
+ */
+public class MemoryInitializationFile implements MemoryImportExportInterface {
+
+    public MemoryInitializationFile() {
+
+    }
+
+    @Override
+    public void FromFile(Memory memory) throws Exception {
+        String value;
+        String[] parts;
+        Scanner sc;
+        String current = Paths.get(".").toAbsolutePath().normalize().toString();
+        // Tenta carregar o arquivo
+        boolean read = false;
+        try {
+            sc = new Scanner(new File(current + memory.File()));
+        } catch (FileNotFoundException e) {
+            throw new Exception(String.format("O arquivo da memoria não foi encontrado. %s", memory.File()));
+        }
+
+        while (sc.hasNextLine()) {
+            value = sc.nextLine();
+            if (value.equals("")) {
+                continue;
+                // Se encontra o fim do arquivo
+            } else if (value.equals("END;")) {
+                break;
+            } else if (!read) {
+                // Se ainda não iniciou a leitura
+                // Busca o inicio das palavras
+                if (value.equals("BEGIN")) {
+                    read = true;
+                }
+                continue;
+                //Se for o inicio de um intervalo vazio de palavras
+            } else if (value.charAt(0) == '[') {
+                continue;
+            }
+            // trata e escreve o valor na memória
+            parts = value.replaceAll("\\s+", "").split(":");
+            memory.W(Long.parseLong(parts[0], 10), parts[1], 4);
+        }
+    }
+
+    @Override
+    public String DumpFile(Memory memory) throws Exception {
+
+        String out = Header(memory);
+
+        Long address, base = 0L;
+        ArrayList<String> buffer = new ArrayList<>();
+        TreeMap<Long, String> data = memory.Data();
+        Integer pad = data.lastKey().toString().length();
+
+        for (Map.Entry<Long, String> o : data.entrySet()) {
+            address = o.getKey();
+
+            if (address % memory.WORD_BYTES_COUNT == 0) {
+                out += Append(base, buffer, pad);
+
+                if ((address - base) > memory.WORD_BYTES_COUNT) {
+                    out += String.format(
+                            "[%d..%d]:\t00000000000000000000000000000000;\n",
+                            base + memory.WORD_BYTES_COUNT,
+                            address - memory.WORD_BYTES_COUNT
+                    );
+                }
+                base = address;
+                buffer = new ArrayList<>();
+            }
+            buffer.add(o.getValue());
+
+        }
+
+        out += Append(base, buffer, pad);
+
+        out += Footer(memory);
+
+        return out;
+    }
+
+    protected static String Append(Long base, ArrayList<String> buffer, Integer pad) {
+        String out = "", bin;
+        if (!buffer.isEmpty()) {
+            bin = Utils.Join(buffer, "");
+            out = Utils.Pad(pad, "" + base)
+                    + ":\t"
+                    + bin
+                    + ";\t% dec "
+                    + Long.parseLong(bin, 2)
+                    + " %\n";
+        }
+        return out;
+    }
+
+    protected static String Header(Memory m) {
+        return "-- Copyright (C) 1991-2014 Altera Corporation. All rights reserved.\n"
+                .concat("-- Your use of Altera Corporation's design tools, logic functions\n")
+                .concat("-- and other software and tools, and its AMPP partner logic\n")
+                .concat("-- functions, and any output files from any of the foregoing\n")
+                .concat("-- (including device programming or simulation files), and any\n")
+                .concat("-- associated documentation or information are expressly subject\n")
+                .concat("-- to the terms and conditions of the Altera Program License\n")
+                .concat("-- Subscription Agreement, the Altera Quartus II License Agreement,\n")
+                .concat("-- the Altera MegaCore Function License Agreement, or other\n")
+                .concat("-- (including device programming or simulation files), and any\n")
+                .concat("-- applicable license agreement, including, without limitation,\n")
+                .concat("-- that your use is for the sole purpose of programming logic \n")
+                .concat("-- devices manufactured by Altera and sold by Altera or its \n")
+                .concat("-- authorized distributors.  Please refer to the applicable \n")
+                .concat("-- agreement for further details.\n")
+                .concat("-- Quartus II generated Memory Initialization File (.mif)\n")
+                .concat("\n")
+                .concat("WIDTH = " + m.WordBitSize() + ";\n")
+                .concat("DEPTH = " + m.Size() + ";\n\n")
+                .concat("ADDRESS_RADIX = DEC;\n")
+                .concat("DATA_RADIX = BIN;\n\n")
+                .concat("CONTENT\nBEGIN\n");
+    }
+
+    protected static String Footer(Memory m) {
+//        String inst = Utils.Pad(wordSize, "");
+//
+//        appendLine("\t[" + seHex(InstructionCount(), 0)
+//                + ".." + seHex(size - 1, 0) + "]\t:\t" + seHex(inst, 8) + ";");
+        return "END;";
+    }
+
+}

+ 0 - 241
src/Export/Mif.java

@@ -1,241 +0,0 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package Export;
-
-import API.Api;
-import common.Instruction;
-import API.Utils;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-
-/**
- *
- * @author Eugenio
- */
-public class Mif {
-
-    protected ArrayList<Instruction> instrucoes;
-    protected int size = 1024;
-    protected StringBuilder sb;
-    protected int line = 0;
-    protected int wordSize = 32;
-    protected boolean showHeader = false;
-    protected boolean hex = false;
-    protected String ext = "mif";
-
-    public Mif() {
-        instrucoes = new ArrayList<>();
-        sb = new StringBuilder();
-    }
-
-    public void setExt(String ext) {
-        this.ext = ext;
-    }
-
-    public Mif(int size) {
-        instrucoes = new ArrayList<>();
-        sb = new StringBuilder();
-        this.size = size;
-    }
-
-    public void save(String path) throws IOException {
-        try (FileWriter fw = new FileWriter(new File(path + "." + ext))) {
-            fw.write(getCodeStream());
-        }
-    }
-
-    /**
-     * Adiciona uma inStrução ao mif no proximo endereco diSponivel
-     *
-     * @param instrucao
-     * @throws Exception
-     */
-    public void Add(Instruction instrucao) throws Exception {
-        if (instrucoes.size() == size) {
-            throw new Exception("Mif Completo. Não existe espaço para um nova instrução.");
-        }
-        instrucoes.add(instrucao);
-    }
-
-    /**
-     * adiciona uma inStrução ao mif em um endereço conhecido
-     *
-     * @param endereco
-     * @param instrucao
-     * @throws Exception
-     */
-    void Add(String endereco, Instruction instrucao) throws Exception {
-        if (instrucoes.size() == size) {
-            throw new Exception("Mif Completo. Não existe espaço para um nova instrução.");
-        }
-//        int end = Integer.parseInt(endereco);
-//        int dif = end - instrucoes.size();
-//        if (dif >= 0) {
-//            for (int i = 0; i < dif; i++) {
-//                instrucoes.Add(nullLine());
-//            }
-//        }
-        System.out.println("SizeFinal[" + instrucoes.size() + ":" + endereco + "]");
-        instrucoes.add(Integer.parseInt(endereco), instrucao);
-
-//        } catch (Exception e) {
-//            Pattern p = Pattern.compile("[0-9]+");
-//            Matcher m = p.matcher(e.getMessage());
-//            while (m.find()) {
-//                System.out.println(m.group(0));
-//            }
-//            System.out.println("Ex:" + e.getMessage());
-//
-//            instrucoes.Add(, instrucao);
-//        }
-    }
-
-    protected Instruction nullLine() {
-        Instruction r = new Instruction();
-        r.Set("text", Api.num2bin(0, 32) + ";");
-        return r;
-    }
-
-    @Override
-    public String toString() {
-        return getCodeStream();
-    }
-
-    public int InstructionCount() {
-        return instrucoes.size();
-    }
-
-    protected String seHex(int valor, int pad) {
-        if (hex) {
-            String s = Utils.int2hex(valor);
-            return Utils.Pad(pad, s);
-        } else {
-            return "" + valor;
-        }
-    }
-
-    protected String seHex(String valor) {
-//        if (hex) {
-//            String Set = ivannosysUtils.int2hex(valor);
-//            return ivannosysUtils.Pad(wordSize / 4, Set);
-//        } else {
-//            return "" + valor;
-//        }
-        return (hex) ? Api.bin2Hex(valor, wordSize / 4) : "" + valor;
-//        return (hex) ? MifFactory.bin2Hex(valor) : "" + valor;
-    }
-
-    protected String seHex(String valor, int pad) {
-        String s = seHex(valor);
-//        System.out.println("HEX:" + Set + "Z" + Pad);
-        return Utils.Pad(pad, s);
-    }
-
-    protected String getCodeStream() {
-        sb = new StringBuilder();
-        addHeader();
-        appendLine("WIDTH=" + wordSize + ";");
-        appendLine("DEPTH=" + size + ";");
-
-        appendLine("ADDRESS_RADIX=UNS;");
-        appendLine("DATA_RADIX=BIN;");
-
-        appendLine("CONTENT BEGIN");
-        String inst;
-        String linha;
-        int sizeInstruction;
-
-//        System.out.println("Gerar:" + hex);
-        int ln;
-        int i = 0;
-        for (Instruction instrucao : instrucoes) {
-//            ln = getLineNumber();
-            linha = seHex(i++, 0);
-//            System.out.println("LN:" + ln + ">LINHA:" + linha);
-            inst = seHex(format(instrucao));
-
-            sizeInstruction = inst.replace(" ", "").length();
-            appendLine("\t" + linha + "\t:\t" + inst
-                    //                    + " [" + sizeInstruction + "]"
-                    + instrucao.Get("comment"));
-        }
-
-        addFooter();
-
-        return sb.toString();
-    }
-
-    protected int getLineNumber() {
-        return line++;
-    }
-
-    protected void appendLine(String line) {
-        sb.append(line + "\n");
-    }
-
-    protected String format(Instruction instrucao) {
-        String formato = "";
-        switch (instrucao.Get("type")) {
-            case "R":
-//                formato = "{codop} {rs} {rt} {rd} {sa} {funct}";
-                formato = "{codop}{rs}{rt}{rd}{sa}{func}";
-                break;
-            case "I":
-//                formato = "{codop} {rs} {rt} {constant}";
-                formato = "{codop}{rs}{rt}{constant}";
-                break;
-            case "J":
-//                formato = "{codop} {target}";
-                formato = "{codop}{target}";
-                break;
-            default:
-                formato = "{text}";
-                break;
-        }
-        return instrucao.format(formato);
-    }
-
-    protected void addHeader() {
-        if (!showHeader) {
-            return;
-        }
-        appendLine("-- Copyright (C) 1991-2014 Altera Corporation. All rights reserved.");
-        appendLine("-- Your use of Altera Corporation's design tools, logic functions");
-        appendLine("-- and other software and tools, and its AMPP partner logic");
-        appendLine("-- functions, and any output files from any of the foregoing");
-        appendLine("-- (including device programming or simulation files), and any");
-        appendLine("-- associated documentation or information are expressly subject");
-
-        appendLine("-- to the terms and conditions of the Altera Program License");
-        appendLine("-- Subscription Agreement, the Altera Quartus II License Agreement,");
-        appendLine("-- the Altera MegaCore Function License Agreement, or other");
-        appendLine("-- (including device programming or simulation files), and any");
-
-        appendLine("-- applicable license agreement, including, without limitation,");
-        appendLine("-- that your use is for the sole purpose of programming logic ");
-        appendLine("-- devices manufactured by Altera and sold by Altera or its ");
-        appendLine("-- authorized distributors.  Please refer to the applicable ");
-        appendLine("-- agreement for further details.");
-
-        appendLine("-- Quartus II generated Memory Initialization File (.mif)");
-
-    }
-
-    protected void addFooter() {
-        String inst = Utils.Pad(wordSize, "");
-
-        appendLine("\t[" + seHex(InstructionCount(), 0)
-                + ".." + seHex(size - 1, 0) + "]\t:\t" + seHex(inst, 8) + ";");
-        appendLine("END;");
-    }
-
-    public void setHexMode(boolean hex) {
-        this.hex = hex;
-    }
-
-}

+ 13 - 13
src/Export/MultCoreJun.java

@@ -20,9 +20,9 @@ import java.util.logging.Logger;
 import org.json.simple.JSONArray;
 import org.json.simple.JSONObject;
 import org.json.simple.parser.JSONParser;
-import targets.mips.Mips;
-import targets.mips.MipsTemplate;
-import targets.mips.MipsUpdateAddressProcessor;
+import targets.mips.Descriprion;
+import targets.mips.MipsTemplateDescription;
+import targets.mips.MipsUpdateAddressMiddleware;
 
 /**
  * MipS tranSlation
@@ -58,7 +58,7 @@ public class MultCoreJun implements ExportInterface {
             Block func;
             JSONObject profile;
 
-            MipsUpdateAddressProcessor uap = new MipsUpdateAddressProcessor();
+            MipsUpdateAddressMiddleware uap = new MipsUpdateAddressMiddleware();
 
             ArrayList<String> p = BuildParams.Get("profile");
 
@@ -73,7 +73,7 @@ public class MultCoreJun implements ExportInterface {
                     parts = initFunction.replace(")", "").split("\\(");
                     blockName = parts[0];
                     // Busca o bloco inicial referenciado pelo usuario
-                    func = Target.getBlocks().get(blockName);
+                    func = Target.Blocks().get(blockName);
 
                     if (profile.containsKey("stackBaseAddress")) {
                         stackBaseAddress = (Long) profile.get("stackBaseAddress");
@@ -134,7 +134,7 @@ public class MultCoreJun implements ExportInterface {
     }
 
     protected void SaveMips(Code newCode, String filename) throws Exception {
-        Utils.WriteFile(filename, newCode.getCodeStream());
+        Utils.WriteFile(filename, newCode.Dump());
     }
 
     protected void SaveDec(Code newCode, String filename) throws Exception {
@@ -169,7 +169,7 @@ public class MultCoreJun implements ExportInterface {
 //                Ninst = new Instruction();
 //                Variaveis.List();
 //                System.out.println("Variaveis.Get(arg):" + Variaveis.Get("main." + args));
-                block.Add(Mips.Instruction("addiu")
+                block.Add(Descriprion.Instruction("addiu")
                         .Set("rs", "zero")
                         .Set("rt", "a" + (i++))
                         .Set("offset", arg));
@@ -192,13 +192,13 @@ public class MultCoreJun implements ExportInterface {
             // System.out.println("instructions.Get(0);" + first);
             // Atualiza a ultima instrucao de um retorno para ra -> stop
             block.Remove(instructions.get(instructions.size() - 1));
-            block.Add(Mips.Instruction("stop")
+            block.Add(Descriprion.Instruction("stop")
                     .Set("comment", "end of programa"));
         }
         newCode.CloseBlock();
 
         // Adiciona as funcoes que geram dependencias 
-        HashMap<String, Block> tb = target.getBlocks();
+        HashMap<String, Block> tb = target.Blocks();
         ArrayList<String> deps = tb.get(blockName).GetDependences();
 
         if (!deps.isEmpty()) {
@@ -211,13 +211,13 @@ public class MultCoreJun implements ExportInterface {
     }
 
     protected Code NewCode(String id) throws Exception {
-        return new Code(id).Template(new MipsTemplate());
+        return new Code(id).Template(new MipsTemplateDescription());
     }
 
     protected Long MaxStackSize(Block blk) {
-        HashMap<String, Block> tb = target.getBlocks();
-        int size = blk.Data().Size();
-//        System.out.println("data:" + blk.Data());
+        HashMap<String, Block> tb = target.Blocks();
+        int size = blk.Context().Size();
+//        System.out.println("data:" + blk.Context());
         Long childSize = 0L, tmpChildSize;
 
         ArrayList<String> deps = blk.GetDependences();

+ 23 - 25
src/Export/Simulation.java

@@ -11,9 +11,7 @@ import common.Block;
 import common.Code;
 import common.Instruction;
 import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import targets.mips.Gen;
+import tools.mips.Memory;
 import tools.mips.MipsSettings;
 
 /**
@@ -32,37 +30,37 @@ public class Simulation implements ExportInterface {
     @Override
     public void Exec(Code IR, Code Target) throws Exception {
 //        Integer index;
-//        System.out.println(Target.GData());
-        String tmp, out = "";
+//        System.out.println(Target.GlobalContext());
+        String bin;
+
+        Memory memory = new Memory(
+                settings.Get("memory.instruction"),
+                settings.GetInt("memory.instruction.size")
+        );
+
+        memory.SetIO(new MemoryInitializationFile());
 
         for (Map.Entry<String, Block> x : Target.stmts.entrySet()) {
-//            System.out.println(x.getValue().Data());
-//            index = 0;
             for (Instruction instr : x.getValue().Instructions()) {
-                tmp = instr.Get("inst.dec");
-                if (tmp.equals("")) {
+                bin = instr.Get("inst.bin");
+
+                if (bin.equals("")) {
                     continue;
                 }
-                out = out.concat(tmp + "\n");
-                //                        .concat(Integer.toHexString(index))
-                //                        .concat(":")
-                //                        .concat(String.format("%X\n", tmp.trim()) + "\n");
-//                index++;
+                // Divide os bytes da instrução binaria e escreve na memoria
+                for (String sbyte : Utils.SplitEach(bin, 8)) {
+                    memory.WB(sbyte);
+                }
             }
         }
 
-//        Utils.WriteFile("\\src\\tools\\mips\\memory\\mi.memory", out);
-        try {
-            // Grava resutlado no arquivo de memoria do simulador
-            Utils.WriteFile(settings.Get("memory.instruction"), out);
-
-            new tools.mips.MipsProcessor(settings)
-                    .Run()
-                    .Persist();
+        // Grava resutlado no arquivo de memoria do simulador
+        memory.Save();
 
-        } catch (Exception ex) {
-            Logger.getLogger(Gen.class.getName()).log(Level.SEVERE, null, ex);
-        }
+        // Instancia um simulador, executa e salva a memoria
+        new tools.mips.MipsProcessor(settings)
+                .Run()
+                .Persist();
     }
 
 }

File diff suppressed because it is too large
+ 261 - 391
src/IntermediaryCode/IRGenerator.java


+ 14 - 33
src/IntermediaryCode/IRTemplate.java

@@ -29,39 +29,27 @@ public class IRTemplate implements templates.TemplateDescription {
                         + "{[T(2)]}"
                         + "{[basicBlock]}";
 
-                put("label", "{[PAD(global.position,G.addressLen,' ')]':'}{[T(2)]}{'<'[label]'>'}':'");
-                put("assign", base + "{[dst]}' := '{[TYPE('p1')]' '}{[p1]' '}{[op]' '}{[TYPE('p2')]' '}{[p2]}" + end);
-                put("pointer_assign", base + "{[dst.pointer]}{[dst]' := '}{[op]' '}{[TYPE('p1')]' '}{[p1]}" + end);
-                put("unary", base + " {[dst]} ' := '{[op]' '}{[TYPE('p1')]' '}{[p1]}" + end);
-                put("copy", base + " {[dst]} ' := '{[TYPE('p1')]' '}{[p1]}" + end);
+                put("label", "{[T(2)]}{'<'[label]'>'}':'");
+                put("alloc", "{[T(3)]} 'alloc ' {[TYPE('p1')]', '} {[numElements]' '} {[p1]}"  + end);
+
+                put("assign", base + "{[dst]}' := '{[p1]' '}{[op]' '}{[p2]}" + end);
+                put("pointer_assign", base + "{[dst.pointer]}{[dst]' := '}{[op]' '}{[p1]}" + end);
+                put("unary", base + " {[dst]} ' := '{[op]' '}{[p1]}" + end);
+                put("copy", base + " {[dst]} ' := '{[p1]}" + end);
                 put("memory", base + " {[type]' '}{[TYPE('p1')]' '}{[p1]}" + end);
                 put("jump", base + " 'goto ' {'<'[label]'>'}" + end);
-                put("branch", base + " 'if '{[TYPE('p1')]' '}{[p1]} {' '[op]' '}{[TYPE('p2')]' '}{[p2]} ' goto ' {'<'[label]'>'}" + end);
+                put("branch", base + " 'if '{[p1]} {' '[op]' '}{[p2]} ' goto ' {'<'[label]'>'}" + end);
 //                put("call", base + " {[dst]' := '} 'call <' {[funcname]} '>, ' {[nump]}" + end);
                 put("call", base + "'call <' {[funcname]} '>, ' {[nump]}" + end);
-                put("return", base + " 'return '{[TYPE('p1')]' '}{[p1]}" + end);
-                put("push_param", base + " 'push_param '{[TYPE('p1')]' '}{[p1]}" + end);
-                put("push_return", base + " 'push_return '{[TYPE('p1')]' '}{[p1]}" + end);
-                put("pop_param", base + " 'pop_param '{[TYPE('p1')]' '}{[p1]}" + end);
-                put("pop_return", base + " 'pop_return '{[TYPE('p1')]' '}{[p1]}" + end);
+                put("return", base + " 'return '{[p1]}" + end);
+                put("push_param", base + " 'push_param '{[p1]}" + end);
+                put("push_return", base + " 'push_return '{[p1]}" + end);
+                put("pop_param", base + " 'pop_param '{[p1]}" + end);
+                put("pop_return", base + " 'pop_return '{[p1]}" + end);
             }
         };
     }
 
-    public HashMap<String, String> aliases = new HashMap<String, String>() {
-        {
-            put("char", "i8");
-            put("bool", "i8");
-            put("byte", "i8");
-            put("int8", "i8");
-            put("int16", "i16");
-            put("int32", "i32");
-            put("int64", "i64");
-            put("float32", "f32");
-            put("float64", "f64");
-        }
-    };
-
     public HashMap<String, FunctionInterface> Functions() throws Exception {
         return new HashMap<String, FunctionInterface>() {
             {
@@ -70,14 +58,7 @@ public class IRTemplate implements templates.TemplateDescription {
                     if (!ctx.Has(attr)) {
                         return "";
                     }
-
-                    String type = ctx.Get(attr);
-
-                    if (!aliases.containsKey(type)) {
-                        throw new Exception(String.format("Nenhum alias foi definido para o tipo '%s'", type));
-                    }
-
-                    return "(" + aliases.get(type) + ")";
+                    return "(" + ctx.Get(args.get(0) + ".type") + ")";
                 });
             }
         };

+ 0 - 190
src/Processors/BasicBlockProcessor.java

@@ -1,190 +0,0 @@
-package Processors;
-
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-import API.CodeProcessorInterface;
-import API.Utils;
-import common.Code;
-import common.Instruction;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-/**
- *
- * @author EUGENIO CARVALHO
- */
-public class BasicBlockProcessor implements CodeProcessorInterface {
-
-//    protected LinkedHashMap<String, ArrayList<ArrayList<Integer>>> basicBlocks = new LinkedHashMap<>();
-//    protected String basicBlockName;
-//    protected Integer basicBlockCount = 0;
-    protected BlockBaseGroup group;
-    protected HashMap<String, BlockBaseGroup> groups = new HashMap<>();
-    protected Integer nextLeader;
-    protected LinkedHashMap<Integer, Integer> leaders;
-
-    //OK
-//    protected HashMap<String, BlockBaseOcorrences> blocks = new HashMap<>();
-    protected BlockBaseOcorrences block;
-    public static Pattern addresspattern = Pattern.compile("\\_[VTGC].*", Pattern.CASE_INSENSITIVE);
-    private ArrayList<Integer> leadersList;
-
-    public BasicBlockProcessor() {
-
-    }
-
-    public BlockBaseGroup getBasicBlockGroup(String id) {
-        return groups.get(id);
-    }
-
-    public HashMap<String, BlockBaseGroup> getGroups() {
-        return groups;
-    }
-
-//    public HashMap<String, BlockBaseOcorrences> getBlocks() {
-//        return blocks;
-//    }
-//
-//    public void setBlocks(HashMap<String, BlockBaseOcorrences> blocks) {
-//        this.blocks = blocks;
-//    }
-    public BlockBaseOcorrences getBlock() {
-        return block;
-    }
-
-    public void setBlock(BlockBaseOcorrences block) {
-        this.block = block;
-    }
-
-    public static Pattern getAddresspattern() {
-        return addresspattern;
-    }
-
-    public static void setAddresspattern(Pattern addresspattern) {
-        BasicBlockProcessor.addresspattern = addresspattern;
-    }
-
-//    protected void IncrementBasicBlockCount() {
-//        basicBlockCount++;
-//    }
-    @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
-        String name = c.Block().getName();
-        BlockBaseGroup g = new BlockBaseGroup(name);
-        group = g;
-        groups.put(name, g);
-//        block = new BlockBaseOcorrences(name);
-//        ArrayList<ArrayList<Integer>> bbs = new ArrayList<>();
-//        ArrayList<Integer> bb = null;
-
-//        basicBlockName = name;
-//        basicBlockCount = 0;
-//            protected ArrayList<ArrayList<Integer>> basicBlock = new ArrayList<>();
-//        basicBlocks.put(name, bbs);
-//        blocks.put(name, block);
-        leaders = new LinkedHashMap<>();
-
-//        block.LastPosition = c.Block().CurrentAddress - 1;
-//Step 1. Identify the leaders in the code. Leaders are instructions which come under any of the following 3 categories :
-//
-//The first instruction is a leader.
-//The target of a conditional or an unconditional goto/jump instruction is a leader.
-//The instruction that immediately follows a conditional or an unconditional goto/jump instruction is a leader.
-        Instruction x;
-        LinkedList<Instruction> instructions = c.Block().Instructions();
-        int instructionPosition = 0,
-                fix,
-                lastLeader = -1,
-                limit = instructions.size() - 2;
-
-        for (int i = 0; i < limit; i++) {
-            x = instructions.get(i);
-            fix = 0;
-            switch (x.Get("type")) {
-                case "jump":
-                case "call":
-                case "branch":
-                    fix = 1;
-                case "label":
-                    if (lastLeader >= 0) {
-                        leaders.put(lastLeader, instructionPosition);
-                    }
-
-                    if (!instructions.get(i + 1).in("type", new String[]{"jump", "label"})) {
-
-                        lastLeader = instructionPosition + fix;
-                        leaders.put(lastLeader, 0);
-                    }
-            }
-
-            if (!x.eq("type", "label")) {
-                instructionPosition++;
-            }
-        }
-
-        leaders.put(lastLeader, instructionPosition);
-        // reseta a posicao da instrução
-        instructionPosition = 0;
-//        System.out.println("basicBlock:::::::::::::" + leaders);
-        leadersList = new ArrayList<>();
-
-        for (Map.Entry<Integer, Integer> entry : leaders.entrySet()) {
-            leadersList.add(entry.getKey());
-        }
-
-        System.out.println("leadersList:" + leadersList);
-
-        nextLeader = leadersList.remove(0);
-
-        // Registra primeiro bloco basico
-        RegBasicBlock();
-        // Atribui o segundo leder como 
-
-//        block.LastPosition = nextLeader - 1;
-        for (Instruction inst : instructions) {
-            switch (inst.Get("type")) {
-                case "label":
-                    break;
-                default:
-//                    System.out.println("Ins:(" + instructionPosition + ")(" + nextLeader + ")");
-                    // Registra 
-                    if (instructionPosition == nextLeader) {
-//                        block.CloseAllIntervals();
-//                        nextLeader = leadersList.remove(0);
-//                        block.LastPosition = nextLeader - 1;
-                        RegBasicBlock();
-                    }
-                    // Registra os acessos de leitura e escrita dos enderecos da instrucao
-                    group.ParseInstruction(inst, "dst,p1,p2");
-
-                    instructionPosition++;
-            }
-        }
-        group.Close();
-//        // Atualiza todos os encerramentos de intervalo para a ultima ocorrencia da variavel;
-//        block.CloseAllIntervals();
-
-        System.out.println("block:" + group);
-    }
-
-    protected void RegBasicBlock() {
-
-//        System.out.println("RegBasicBlock:(" + nextLeader + ")(" + ((leaders.Get(nextLeader) - nextLeader) + 1) + ")");
-        group.RegisterBlock(nextLeader, (leaders.get(nextLeader) - nextLeader) + 1);
-        if (!leadersList.isEmpty()) {
-            nextLeader = leadersList.remove(0);
-        }
-    }
-
-    public static boolean IsAddress(String alias) {
-//        System.out.println("Is Address:" + alias + "::" + addresspattern.matcher(alias).matches());
-        return !Utils.Empty(alias) && addresspattern.matcher(alias).matches();
-    }
-}

+ 1 - 1
src/ast/Node.java

@@ -214,7 +214,7 @@ public class Node extends RegistroBase {
         return childrens.get(size - 1);
     }
 
-    public Node copy(String atrib, Node r) {
+    public Node Copy(String atrib, Node r) {
         if (r != null) {
             for (String a : atrib.split(",")) {
                 this.Set(a, r.Get(a));

+ 12 - 12
src/ast/Semantic.java

@@ -186,8 +186,8 @@ public class Semantic extends Log {
                                 continue;
                             }
 
-                            icallval = ical.getInt("value");
-                            idecval = idec.getInt("value");
+                            icallval = ical.GetInt("value");
+                            idecval = idec.GetInt("value");
 
                             if (idec.isNumber("value") && icallval >= idecval) {
                                 throw new Exception(String.format("Index ['%s'] fora do intervalo ['%s'] em %s", icallval, idecval, current.getText()));
@@ -465,10 +465,10 @@ public class Semantic extends Log {
 //                .closest("atributos,dec::function,dec::thread,dec::globais,trap", "class")
 //                .encontreTodos("dec::var", "class");
 ////                filtrarFilhosPorClass();
-//        int cId = current.getInt("id");
+//        int cId = current.GetInt("id");
 //        int tId;
 //        for (Node node : declaracoes) {
-//            tId = node.getInt("id");
+//            tId = node.GetInt("id");
 //            if (tId >= cId) {
 //                break;
 //            }
@@ -491,10 +491,10 @@ public class Semantic extends Log {
 //    protected void _checkRedeclaracaoFuncao() throws Exception {
 //        String nomeFuncao = current.getText();
 //        ArrayList<Node> funcoes = current.parent.filtrarFilhosPorClass("dec::function");
-//        int cId = current.getInt("id");
+//        int cId = current.GetInt("id");
 //        int tId;
 //        for (Node node : funcoes) {
-//            tId = node.getInt("id");
+//            tId = node.GetInt("id");
 //            if (tId >= cId) {
 //                break;
 //            }
@@ -553,7 +553,7 @@ public class Semantic extends Log {
 //        if (!indices.temFilho(ind)) {
 //            return;
 //        }
-//        int numEle = indices.getFilho(ind).getInt("value");
+//        int numEle = indices.getFilho(ind).GetInt("value");
 //        int numAtrib = valor.getChildrenCount();
 //
 //        if (numeroIndices == 1) {  //diz que e um vetor;
@@ -728,7 +728,7 @@ public class Semantic extends Log {
 //
 //    protected boolean _$redeclaracao(String nome, String tipo, String onde, int id) throws Exception {
 //        for (Node c : program().encontre(onde).filhos()) {
-//            if (nome.equals(c.getText()) && id > c.getInt("id")) {
+//            if (nome.equals(c.getText()) && id > c.GetInt("id")) {
 //                AddErrorWithPosition(" Redeclaração [ " + tipo + " {" + nome + "}]. Primeira definição na linha {" + c.Get("line") + "}");
 //                return true;
 //            }
@@ -744,7 +744,7 @@ public class Semantic extends Log {
 //    protected void chkConstante() throws Exception {
 //        /*Verificar se constante foi redeclarada*/
 //
-////        if (_$redeclaracao(current.getText(), "Constante", "constantes", current.getInt("id"))) {
+////        if (_$redeclaracao(current.getText(), "Constante", "constantes", current.GetInt("id"))) {
 ////            return;
 ////        }
 //    }
@@ -806,7 +806,7 @@ public class Semantic extends Log {
 //        if (Variables.existe(current)) {
 //            AddErrorWithPosition("Declaração invalida. Função com mesmo nome de uma variavel {" + nomeFuncao + "}.");
 //        }
-//        _$redeclaracao(nomeFuncao, "Funções", "funcoes", current.getInt("id"));
+//        _$redeclaracao(nomeFuncao, "Funções", "funcoes", current.GetInt("id"));
 ////        _checkRedeclaracaoFuncao();
 //        //        _checkRetornoFuncao();
 //    }
@@ -995,8 +995,8 @@ public class Semantic extends Log {
 //            }
 //
 //            /* Quantidade de indices da chamada */
-//            valIndAce = indice.getInt("value");
-//            valIndDec = decIndice.getInt("value");
+//            valIndAce = indice.GetInt("value");
+//            valIndDec = decIndice.GetInt("value");
 //
 //            if (valIndAce >= valIndDec) {
 //                AddErrorWithPosition(" Indice erro. Indice [" + (i + 1) + "], valor maximo {" + (valIndDec - 1) + "}, atribuido {" + valIndAce + "}.");

+ 48 - 40
src/common/Block.java

@@ -12,32 +12,45 @@ import java.util.Map;
 
 public class Block {
 
+    protected HashMap<String, Boolean> ctrlTypes = new HashMap<String, Boolean>() {
+        {
+            put("label", true);
+            put("alloc", true);
+        }
+    };
+
     public static int uniq = 0;
     public LinkedList<Instruction> instructions = new LinkedList<>();
     protected String name;
     protected Code code;
     protected HashMap<String, Instruction> labels = new HashMap<>();
     protected HashMap<String, Boolean> dependences = new HashMap<>();
-    protected DataLayout Data;
+    protected DataLayout Context;
     public int BaseAddress = 0;
     public int CurrentAddress = 0;
+    public int AddressIncrement = 1;
     public boolean HasCall;
     public int nonLabelCount;
+    public int type;
+
+    public static int TYPE_INSTRUCTIONS = 0;
+    public static int TYPE_CTRL = 1;
 
     Block(String name, Code c) {
-//        System.out.println("Open block:" + name + ":" + c.PosicaoLabel);
         code = c;
         BaseAddress = c.Position();
-//        BaseAddress = c.PosicaoLabel;
+        AddressIncrement = c.AddressIncrement;
         this.name = name;
-        Data = new DataLayout(name, code.GlobalData());
+        type = TYPE_INSTRUCTIONS;
+        Context = new DataLayout(name);
+    }
 
-//        labels = new HashMap<>();
-//        Data = new LinkedHashMap<>();
-//        constants = new LinkedHashMap<>();
-//        reverseName = new HashMap<>();
-//        pointers = new HashMap<>();
-//        ocorrencesPerBlocks = new LinkedHashMap<>();
+    public int Type() {
+        return type;
+    }
+
+    public void Type(int type) {
+        this.type = type;
     }
 
     public LinkedList<Instruction> Instructions() {
@@ -48,25 +61,17 @@ public class Block {
         return HasCall;
     }
 
-    public Block Add(Instruction nr) {
-        int pos = CurrentAddress;
-        if (!nr.eq("type", "label")) {
-//            nr.Set("reference.position", pos);
-//        } else {
-            nr.Set("block.position", pos);
-            nr.Set("block.position.origin", pos);
-            CurrentAddress++;
-        } else {
+    public Block Add(int position, Instruction inst) {
+        this.instructions.add(position, inst);
+        return this;
+    }
 
-        }
-//        System.out.println("Add:" + nr);
+    public Block Add(Instruction nr) {
         this.instructions.add(nr);
-
         return this;
     }
 
     public Block Remove(Instruction instruction) throws Exception {
-//        System.out.println("Remove indtruction do block:" + instruction);
         this.instructions.remove(instruction);
         return this;
     }
@@ -80,8 +85,8 @@ public class Block {
      *
      * @return
      */
-    public DataLayout Data() {
-        return this.Data;
+    public DataLayout Context() {
+        return this.Context;
     }
 
     /**
@@ -89,14 +94,13 @@ public class Block {
      *
      * @return
      */
-    public DataLayout GData() {
-        return this.code.GlobalData();
-    }
-
-    public DataLayout Data(DataLayout d) {
-        return this.Data.copy(d);
+    public DataLayout GlobalContext() {
+        return this.code.GlobalContext();
     }
 
+//    public DataLayout Context(DataLayout d) {
+//        return this.Context.copy(d);
+//    }
     public void Close() throws Exception {
         Update();
     }
@@ -105,18 +109,23 @@ public class Block {
         CurrentAddress = 0;
 
         for (Instruction n : instructions) {
-//            System.out.println("Update->:" + CurrentAddress + ":" + code.Position());
-            if (!n.eq("type", "label")) {
-                n.Set("block.position", CurrentAddress)
-                        .Set("block.position.origin", CurrentAddress++)
-                        .Set("global.position", code.PositionInc());
-            } else {
+            if (ctrlTypes.containsKey(n.Get("type"))) {
+
                 n.Set("reference.position", CurrentAddress)
                         .Set("global.reference.position", code.Position());
-                code.RegisterLabelAddress(n.Get("label"));
+
+                if (n.eq("type", "label")) {
+                    code.RegisterLabelAddress(n.Get("label"));
+                }
+
+            } else {
+
+                n.Set("block.position", CurrentAddress)
+                        .Set("block.position.origin", CurrentAddress)
+                        .Set("global.position", code.PositionInc());
+                CurrentAddress += AddressIncrement;
             }
         }
-//        System.out.println("}");
     }
 
     public int LastAddress() {
@@ -124,7 +133,6 @@ public class Block {
     }
 
     public Instruction RemoveLast() {
-//        System.out.println("Remove indtruction do block:");
         return instructions.removeLast();
     }
 

+ 52 - 43
src/common/Code.java

@@ -5,9 +5,8 @@
  */
 package common;
 
-import API.CodeProcessor;
+import API.Middleware;
 import ast.AbstractSyntaxTree;
-import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
@@ -29,7 +28,7 @@ public class Code {
     protected Boolean limparCodigo = true;
     protected HashMap<Integer, Integer> leaders = new HashMap<>();
     protected Integer gline;
-    protected Integer PositionIncrement = 1;
+//    protected Integer PositionIncrement = 1;
     protected LinkedList<String> currentBlock = new LinkedList<>();
     protected RegistroBase ctx = new Instruction();
     protected String name;
@@ -39,10 +38,13 @@ public class Code {
     public Block current;
     public Code Parent;
     public DataLayout Data;
-    public HashMap<String, ArrayList<String>> labels = new HashMap<>();
+    public HashMap<String, Label> labels = new HashMap<>();
     public HashMap<String, Integer> labelsReferenceCount = new HashMap<>();
     public Integer PosicaoLabel = 0;
     public LinkedHashMap<String, Block> stmts = new LinkedHashMap<>();
+    public int AddressIncrement = 1;
+    public String[] ControlInstructions = "label".split(",");
+    public String DEFAULT_WORD_TYPE = "int32";
 
 //    public HashMap<String, String> vars;
 //    protected HashMap<String, String> templates = new HashMap<>();
@@ -53,24 +55,37 @@ public class Code {
     public Code(String id, AbstractSyntaxTree tree) {
         name = id;
         ast = tree;
-        Data = new DataLayout(id, null);
-    }
-
-    public boolean HasCall() {
-        return HasCall;
+        Data = new DataLayout(id);
     }
 
     public Code(String id) {
         name = id;
 //        currentBlock = new LinkedList<>();
 //        stmts = new HashMap<>();
-        Data = new DataLayout(id, null);
+        Data = new DataLayout(id);
+    }
+
+    public int getAddressIncrement() {
+        return AddressIncrement;
+    }
+
+    public Code setAddressIncrement(int AddressIncrement) {
+        this.AddressIncrement = AddressIncrement;
+        return this;
     }
 
-    public DataLayout GlobalData() {
+    public boolean HasCall() {
+        return HasCall;
+    }
+
+    public DataLayout GlobalContext() {
         return Data;
     }
 
+    public void GlobalContext(DataLayout data) {
+        Data = data;
+    }
+
     public void SetData(DataLayout Data) {
         this.Data = Data;
     }
@@ -91,7 +106,7 @@ public class Code {
         currentBlock.push(id);
         current = new Block(id, this);
         stmts.put(id, current);
-        CodeProcessor.Trigger(this, this.Name(), "OpenBlock");
+        Middleware.Trigger(this, this.Name(), "open.block");
 
 //        incEndereco = 0;
 //        ocorrences = new LinkedHashMap<>();
@@ -113,7 +128,7 @@ public class Code {
 
     public void CloseBlock() throws Exception {
 //        AfterClose();
-        CodeProcessor.Trigger(this, this.Name(), "CloseBlock");
+        Middleware.Trigger(this, this.Name(), "close.block");
         Block().Close();
         currentBlock.pop();
         Use(currentBlock.peek());
@@ -143,28 +158,27 @@ public class Code {
         return current;
     }
 
-    public String getCodeStream() throws Exception {
+    public String Dump() throws Exception {
 
         // Parametro para formatacao dos enderecos
         ctx.Set("G.addressLen", (PosicaoLabel + "").length() + "");
-
+        Label L;
         // Definicao dos enderecos dos labels
-        for (Map.Entry<String, ArrayList<String>> x : labels.entrySet()) {
-            ctx.Set("G." + x.getKey(), x.getValue().get(0));
-            ctx.Set("G.label." + x.getKey(), x.getValue().get(1));
+        for (Map.Entry<String, Label> x : labels.entrySet()) {
+            L = x.getValue();
+            ctx.Set("G." + x.getKey(), L.GetGlobalPosition());
+            ctx.Set("G.label." + x.getKey(), L.GetLabel());
         }
-
+//        System.out.println("CTX:" + ctx);
         StringBuilder s = new StringBuilder();
 
         for (Map.Entry<String, Block> entry : stmts.entrySet()) {
-
-            s.append(getCodeStream(entry.getKey()));
-
+            s.append(Code.this.Dump(entry.getKey()));
         }
         return s.toString();
     }
 
-    public String getCodeStream(String bloco) throws Exception {
+    public String Dump(String bloco) throws Exception {
         StringBuilder s = new StringBuilder();
         String f;
 
@@ -232,11 +246,6 @@ public class Code {
             String label = ur.Get("label");
             switch (ur.Get("format")) {
                 case "label":
-////                    nr.Set("line", "" + (posicaoLabel--));
-////                    nr.Set("value", label + "  " + nr.getText());
-////                    nr.Set("label", label);
-////                    corrente.remove(ur);
-////                    RegisterLabelAddress(label);
                     break;
                 case "jump":
                     /**
@@ -266,6 +275,10 @@ public class Code {
         return nr;
     }
 
+    public void Add(int i, Instruction inst) {
+        current.Add(i, inst);
+    }
+
     public Instruction Last() {
         if (current == null) {
             return null;
@@ -287,13 +300,13 @@ public class Code {
         System.out.println(Data);
 
         for (Map.Entry<String, Block> entry : stmts.entrySet()) {
-            System.out.println(entry.getValue().Data());
+            System.out.println(entry.getValue().Context());
         }
     }
 
     public void Print() throws Exception {
         System.out.println("INSTRUNCTIONS FRAME ...................");
-        System.out.println(getCodeStream());
+        System.out.println(Dump());
     }
 
     public String Format() throws Exception {
@@ -303,7 +316,7 @@ public class Code {
     protected int LocalPosition() throws Exception {
         return 0;
 //todo verificar metodo todo
-        //        return posicaoLabel - pointerCorrente.getInt("initAddress");
+        //        return posicaoLabel - pointerCorrente.GetInt("initAddress");
     }
 
     public String RegisterLabelAddress(String label) {
@@ -311,13 +324,14 @@ public class Code {
 //        if (!labels.containsKey(label)) {
 //        System.out.println("Registerlabel:" + label.replaceAll("\\+_i\\d+", "+" + Block().CurrentAddress));
 //            System.out.println("label:" + label);
-        String translated = label.replaceAll("\\+_i\\d+", "+" + Block().CurrentAddress);
-        ArrayList<String> p = new ArrayList<>();
-        p.add(Position() + "");
-        p.add(translated);
+        Label p = new Label();
+        p.SetGlobalPosition((long) Position())
+                .SetLabel(label)
+                .SetPosition((long) Block().CurrentAddress);
 //        System.out.println("Register label:" + label + "|" + Block().CurrentAddress);
         labels.put(label, p);
-//        }
+
+        String translated = label.replaceAll("\\+_i\\d+", "+" + Block().CurrentAddress);
         return translated;
     }
 
@@ -325,14 +339,9 @@ public class Code {
         return reverseName.get(var.replaceAll("(\\..*|\\[.*)", ""));
     }
 
-    public HashMap<String, Block> getBlocks() {
+    public HashMap<String, Block> Blocks() {
         return this.stmts;
     }
-//
-//    public Code Formats(HashMap<String, String> templates) {
-//        this.templates = templates;
-//        return this;
-//    }
 
     public String Name() {
         return this.name;
@@ -356,7 +365,7 @@ public class Code {
 
     public int PositionInc() {
         int cur = PosicaoLabel;
-        PosicaoLabel += PositionIncrement;
+        PosicaoLabel += AddressIncrement;
         return cur;
     }
 

+ 53 - 0
src/common/DataEntry.java

@@ -0,0 +1,53 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package common;
+
+import java.util.ArrayList;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class DataEntry {
+
+    protected Long size = 0L;
+    protected Long Address = 0L;
+    protected ArrayList<Integer> values = new ArrayList<>();
+
+    DataEntry(Long size) {
+        this.size = size;
+    }
+
+    public Long getAddress() {
+        return Address;
+    }
+
+    public void SetAddress(Long Address) {
+        this.Address = Address;
+    }
+
+    public Long getSize() {
+        return size;
+    }
+
+    public void setSize(Long size) {
+        this.size = size;
+    }
+
+    public ArrayList<Integer> getValues() {
+        return values;
+    }
+
+    public void setValues(ArrayList<Integer> values) {
+        this.values = values;
+    }
+
+    @Override
+    public String toString() {
+        return "Size: " + size + " Address: " + Address;
+    }
+
+}

+ 216 - 168
src/common/DataLayout.java

@@ -5,11 +5,9 @@
  */
 package common;
 
+import API.Types;
 import API.Utils;
 import ast.Node;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.regex.Matcher;
@@ -21,171 +19,69 @@ import java.util.regex.Pattern;
  */
 public class DataLayout {
 
-    protected String name;
+    protected String ID;
     protected LinkedHashMap<String, Node> values = new LinkedHashMap<>();
     // address guarda o endereço de cada variavel
-    protected LinkedHashMap<String, Integer> address = new LinkedHashMap<>();
-    protected boolean initialized = false;
-    protected Pattern normalId = Pattern.compile("(?<id>[\\w_]+)(\\[(?<index>\\w+)\\])?");
+    protected LinkedHashMap<String, DataEntry> entrys = new LinkedHashMap<>();
 
-//    protected LinkedList<Node> values = new LinkedList<>();//Map< String, String> copy = new TreeMap<>();
-//    protected HashMap<String, Integer> size = new LinkedHashMap<>();
-//    protected HashMap<String, Integer> type = new LinkedHashMap<>();
-//    protected HashMap<String, Integer> _offset_ = new LinkedHashMap<>();
-//    protected static AbstractSyntaxTree ast;
-    public static int TYPE_ARGUMENT = 0;
-    public static int TYPE_VAR = 1;
-    public static int TYPE_RETURN = 2;
-    public static int TYPE_STACK = 3;
+    protected LinkedHashMap<String, Integer> addressMap = new LinkedHashMap<>();
+    // Quantidade minima de bytes que
+    protected Integer minWordSize = 1, // 8 bits
+            // Quantidade maximo de bytes que corresponde a uma palavra
+            maxWordSize = 4; // 32 bits
 
-    public int offsetctrl = 0;
+    protected boolean initialized = false;
+    protected Pattern normalId = Pattern.compile("(?<id>[\\w_]+)(\\[(?<index>\\w+)\\])?");
 
-    protected DataLayout global;
+    //Endereço base do conjunto
+    public Long BaseAddress = 0L;
+//    public int offsetctrl = 0;
 
+//    protected DataLayout global = null;
     // Guarda a quantidade de palavras do frame
     // É atualizado sempre que o mapeamento dos endereços sofre alteração.
-    private int frameSize;
-    // Tamanho de uma palavra de memoria em bytes 
-    // 4 bytes = 32 bits
-    protected int WordInBytes = 4;
-
-    public DataLayout(String name, DataLayout data) {
-        this.name = name;
-        this.global = data;
+    protected int FrameSize = 0;
+    protected Long FP = 0L;
+
+    public DataLayout(String ID) {
+        this.ID = ID;
     }
 
     public void SetInitialized(boolean init) {
         initialized = init;
     }
 
-    public void Set(String vname, Node copy) throws Exception {
-        values.put(
-                vname,
-                copy
-        );
-
-        address.put(vname, frameSize);
-        frameSize += copy.getInt("size");
-    }
-
-    public DataLayout Add(String alias, Node var, int elements) throws Exception {
-        //        System.out.println("Add global to frame:" + var);
-//        int vSize = 1;
-//        int size = var.getInt("size"), vSize = 1;
-//        boolean isArray = var.eq("array", "true");
-//        if (isArray) {
-//            vSize = Tipos.Size(var.Get("type"));
-//        }
-        ArrayList<String> defaults = var.getList("default.values");
-
-        Integer defSize = defaults.size();
-        String vname;
-        Node copy;
-        for (int i = 0; i < elements; i++) {
-            vname = alias + "." + i;
-            copy = var.copy().Set("default.value", (i < defSize ? defaults.get(i) : "0"));
-            Set(vname, copy);
-//            values.put(
-//                    vname,
-//                    copy
-//            );
-//
-//            address.put(vname, frameSize);
-//            frameSize += copy.getInt("size");
-        }
-
-        return this;
-    }
-
-    public LinkedHashMap<String, Node> values() {
-        return values;
-    }
-
-    public boolean has(String id) {
-        return values.containsKey(id);
-//        for (Map.Entry<String, Node> x : values.entrySet()) {
-//            if (x.getKey().equals(id)) {
-//                return true;
-//            }
-//        }
-//        return false;
-    }
-
-//    public static void setAbstractSyntaxTree(AbstractSyntaxTree ast) {
-//        DataLayout.ast = ast;
-//    }
     public int Size() {
-        return frameSize;
-//        int val = 0;
-//        for (Map.Entry<String, Node> v : values.entrySet()) {
-//            try {
-//                val += v.getValue().getInt("size");
-//            } catch (Exception ex) {
-//                Logger.getLogger(DataLayout.class.getName()).log(Level.SEVERE, null, ex);
-//            }
-//        }
-//        return val;
+        return FrameSize;
     }
 
     @Override
     public String toString() {
-        StringBuilder s = new StringBuilder("Data Frame <" + name + ">:" + Size() + "\n");
-        Node value;
-        for (Map.Entry<String, Node> x : values.entrySet()) {
+        StringBuilder s = new StringBuilder("Data Frame <" + ID + ">:" + Size() + "\n");
+        DataEntry value;
+        for (Map.Entry<String, DataEntry> x : entrys.entrySet()) {
             value = x.getValue();
-
-//            System.out.println("Value:" + value);
             s.append(x.getKey())
                     .append(": ")
-                    .append(value.Get("name"))
-                    .append("\tsize:")
-                    .append(value.Get("size"))
-                    .append("\tvalue:")
-                    .append(value.Get("default.value"))
+                    .append(value.toString())
                     .append("\n");
-//            break;
+
         }
 
         return s.toString();
     }
 
-    /**
-     * Formata oS haSh para a impreSSão no metoglobalo toString
-     *
-     * @param hash
-     * @return
-     */
-    protected String hashToString(HashMap<String, Node> hash) {
-        String r = "";
-        for (Map.Entry<String, Node> entry : hash.entrySet()) {
-            String name = entry.getKey();
-            Node value = entry.getValue();
-//            int type = this.type.Get(name);
-            r += "{" + name + ":" + value + "},";
-        }
-        return r;
-    }
-
-    public int Offset(String id) throws Exception {
-        int offset = 0;
-        if (id.contains("_G") && global != null) {
-            return global.Offset(id);
-        }
-        id = normalize(id);
-        try {
-            offset = address.get(id);
-        } catch (Exception e) {
-            System.out.println("address(" + id + ")[" + frameSize + "].:"
-                    + address
-                    + values
-            );
-            throw new Exception("Invalid offset!");
+    protected String baseName(String id) {
+        Matcher m = normalId.matcher(id);
+        if (m.find()) {
+            id = m.group("id");
         }
-        return offset;
+        return id;
     }
 
     protected String normalize(String id) {
         String shift = "0", index;
+
         Matcher m = normalId.matcher(id);
         if (m.find()) {
             id = m.group("id");
@@ -202,22 +98,8 @@ public class DataLayout {
         return id;
     }
 
-    public DataLayout copy(DataLayout data) {
-        String k;
-        for (Map.Entry<String, Node> x : data.values().entrySet()) {
-            System.out.println("Copy:" + x.getKey() + "-" + x.getValue());
-            k = x.getKey();
-            values.put(k, x.getValue());
-            address.put(k, data.address.get(x));
-        }
-        frameSize = data.frameSize;
-        return this;
-    }
-
-    public void Replace(String dst, String p1) {
+    public void Replace(String dst, String ori) {
         String rest;
-//        System.out.println("Replace >> " + this.values);
-
         LinkedHashMap<String, Node> add = new LinkedHashMap<>();
 
         for (Map.Entry<String, Node> x : this.values.entrySet()) {
@@ -225,7 +107,7 @@ public class DataLayout {
             rest = x.getKey().replace(dst, "");
 
             if (rest.equals("") || rest.substring(0, 1).equals(".")) {
-                add.put(p1 + rest, x.getValue());
+                add.put(ori + rest, x.getValue());
             } else {
                 add.put(x.getKey(), x.getValue());
             }
@@ -234,29 +116,195 @@ public class DataLayout {
     }
 
     void Remove(String dst) throws Exception {
-        boolean init = false;
-        Iterator<String> it = values.keySet().iterator();
-        String next;
-        int diff = 0;
-        while (it.hasNext()) {
-            next = it.next();
-            if (next.contains(dst)) {
-                if (!init) {
-                    init = true;
-                }
-                diff += values().get(next).getInt("size");
-                it.remove();
-                continue;
+        String alias;
+        DataEntry de;
+        Boolean updateFP = false;
+        Long diff = 0L;
+        for (Map.Entry<String, DataEntry> entry : entrys.entrySet()) {
+            alias = entry.getKey();
+            de = entry.getValue();
+
+            if (alias.equals(dst)) {
+                diff = de.getSize();
+                FrameSize -= diff;
+                entrys.remove(de);
+                updateFP = true;
             }
 
-            if (init) {
-                address.put(next, address.get(next) - diff);
+            if (updateFP) {
+                de.SetAddress(de.getAddress() - diff);
+            }
+
+        }
+        FP -= diff;
+        System.out.println("Remove:" + dst + "\n" + values);
+    }
+
+    // Pra baixo OK
+    public Long Shift(String id) throws Exception {
+        Long shift = 0L;
+        Matcher m = normalId.matcher(id);
+        if (m.find()) {
+            String index = m.group("index");
+            if (Utils.IsNumber(index)) {
+                shift = Long.parseLong(index);
             }
         }
+        return shift;
+    }
 
-        frameSize -= diff;
+    public Offset Offset(String id) throws Exception {
+        String var = baseName(id);
+        Long offset = 0L, shift = Shift(id);
+//        if (id.contains("_G") && global != null) {
+//            return global.Offset(id);
+//        }
 
-        System.out.println("Remove:" + dst + "\n" + values);
+        try {
+            offset = entrys.get(var).getAddress();
+//            System.out.println("Offset from " + var);
+//            System.out.println("Offset:" + id + ":\n" + offset);
+        } catch (Exception e) {
+//            System.out.println("address(" + id + ")[" + frameSize + "].:" + address + values);    
+//            System.out.println("ERROR:" + e.getMessage());
+            throw new Exception(String.format("Invalid offset %s in context %s.", var, ID));
+        }
+        return new Offset(offset, shift);
     }
 
+    public DataEntry Add(String alias, String type, Integer numElements) throws Exception {
+
+        if (entrys.containsKey(alias)) {
+            throw new Exception("A variavel '%s' previamente definida no frame.");
+        }
+
+        Long size = AllocSizeOf(type) * numElements;
+        DataEntry de = new DataEntry(size);
+
+        de.SetAddress(FP);
+        // Atualiza o frame pointer
+        FP += size;
+        FrameSize += size;
+        entrys.put(alias, de);
+        return de;
+    }
+
+    protected Long AllocSizeOf(String type) throws Exception {
+        // Se o tipo for um ponteiro retorna o tamanho maximo de uma palavra em bytes
+        if (type.contains("*")) {
+            return maxWordSize.longValue();
+        }
+
+        Integer size = Types.Size(type), i = maxWordSize;
+
+        while (i < size) {
+            i += maxWordSize;
+        }
+        return i.longValue();
+    }
+
+    public boolean contains(String id) {
+        return entrys.get(id) != null;
+    }
 }
+//            System.out.println("Value:" + value);
+//            s.append(x.getKey())
+//                    .append(": ")
+//                    .append(value.Get("ID"))
+//                    .append("\tsize:")
+//                    .append(value.Get("size"))
+//                    .append("\tvalue:")
+//                    .append(value.Get("default.value"))
+//                    .append("\n");
+//            break;
+//    protected LinkedList<Node> values = new LinkedList<>();//Map< String, String> Copy = new TreeMap<>();
+//    protected HashMap<String, Integer> size = new LinkedHashMap<>();
+//    protected HashMap<String, Integer> type = new LinkedHashMap<>();
+//    protected HashMap<String, Integer> _offset_ = new LinkedHashMap<>();
+//    protected static AbstractSyntaxTree ast;
+//    public static int TYPE_ARGUMENT = 0;
+//    public static int TYPE_VAR = 1;
+//    public static int TYPE_RETURN = 2;
+//    public static int TYPE_STACK = 3;
+//
+//    /**
+//     * Formata oS haSh para a impreSSão no metoglobalo toString
+//     *
+//     * @param hash
+//     * @return
+//     */
+//    protected String hashToString(HashMap<String, Node> hash) {
+//        String r = "";
+//        for (Map.Entry<String, Node> entry : hash.entrySet()) {
+//            String ID = entry.getKey();
+//            Node value = entry.getValue();
+////            int type = this.type.Get(ID);
+//            r += "{" + ID + ":" + value + "},";
+//        }
+//        return r;
+//    }
+//    public DataLayout copy(DataLayout data) {
+//        String k;
+//        for (Map.Entry<String, Node> x : data.values().entrySet()) {
+//            System.out.println("Copy:" + x.getKey() + "-" + x.getValue());
+//            k = x.getKey();
+//            values.put(k, x.getValue());
+//            address.put(k, data.address.get(x));
+//        }
+//        frameSize = data.frameSize;
+//        return this;
+//    }
+//
+//    public void Set(String vname, Node copy) throws Exception {
+//        values.put(
+//                vname,
+//                copy
+//        );
+//        address.put(vname, frameSize);
+//        frameSize += copy.getInt("size");
+//    }
+//    public DataLayout Add(String alias, Node var, int elements) throws Exception {
+//        //        System.out.println("Add global to frame:" + var);
+////        int vSize = 1;
+////        int size = var.getInt("size"), vSize = 1;
+////        boolean isArray = var.eq("array", "true");
+////        if (isArray) {
+////            vSize = Tipos.Size(var.Get("type"));
+////        }
+//        ArrayList<String> defaults = var.getList("default.values");
+//
+//        Integer defSize = defaults.size();
+//        String vname;
+//        Node copy;
+//        for (int i = 0; i < elements; i++) {
+//            vname = alias + "." + i;
+//            copy = var.copy().Set("default.value", (i < defSize ? defaults.get(i) : "0"));
+//            Set(vname, copy);
+////            values.put(
+////                    vname,
+////                    Copy
+////            );
+////
+////            address.put(vname, frameSize);
+////            frameSize += Copy.getInt("size");
+//        }
+//
+//        return this;
+//    }
+//
+//    public LinkedHashMap<String, Node> values() {
+//        return values;
+//    }
+//
+//    public boolean has(String id) {
+//        return values.containsKey(id);
+////        for (Map.Entry<String, Node> x : values.entrySet()) {
+////            if (x.getKey().equals(id)) {
+////                return true;
+////            }
+////        }
+////        return false;
+//    }
+//    public static void setAbstractSyntaxTree(AbstractSyntaxTree ast) {
+//        DataLayout.ast = ast;
+//    }

+ 9 - 5
src/common/Instruction.java

@@ -25,6 +25,12 @@ public class Instruction extends RegistroBase {
     public Instruction() {
     }
 
+    @Override
+    public Instruction Set(String attrib, Boolean valor) {
+        super.Set(attrib, valor); //To change body of generated methods, choose Tools | Templates.
+        return this;
+    }
+
     @Override
     public Instruction Set(String attrib, int valor) {
         super.Set(attrib, valor); //To change body of generated methods, choose Tools | Templates.
@@ -43,12 +49,10 @@ public class Instruction extends RegistroBase {
         return this;
     }
 
-   
 //    public Instruction S(String attrib, int value) {
 //        super.Set(attrib, value); //To change body of generated methods, choose Tools | Templates.
 //        return this;
 //    }
-
     @Override
     public String toString() {
         return "Instruction {\n" + super.toString() + "\n}\n"; //To change body of generated methods, choose Tools | Templates.
@@ -68,19 +72,19 @@ public class Instruction extends RegistroBase {
         if (!isNumber(atributo)) {
             return false;
         }
-        return getInt(atributo) > i;
+        return GetInt(atributo) > i;
     }
 
     public boolean menor(String atributo, int i) throws Exception {
         if (!isNumber(atributo)) {
             return false;
         }
-        return getInt(atributo) < i;
+        return GetInt(atributo) < i;
     }
 
     public int getInt(String indice, int val) {
         try {
-            return getInt(indice);
+            return GetInt(indice);
         } catch (Exception e) {
             return val;
         }

+ 1 - 3
src/common/IvannosysTargetArch.java

@@ -12,9 +12,7 @@ package common;
  */
 public interface IvannosysTargetArch {
 
-    public void Init() throws Exception;
-
-    public IvannosysTargetArch SetTAC(Code tac) throws Exception;
+    public IvannosysTargetArch Init(Code tac) throws Exception;
 
     public IvannosysTargetArch Compile() throws Exception;
 

+ 45 - 0
src/common/Label.java

@@ -0,0 +1,45 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package common;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class Label {
+
+    protected Long Position,
+            GlobalPosition;
+    protected String label;
+
+    public Long GetPosition() {
+        return Position;
+    }
+
+    public Label SetPosition(Long Position) {
+        this.Position = Position;
+        return this;
+    }
+
+    public Long GetGlobalPosition() {
+        return GlobalPosition;
+    }
+
+    public Label SetGlobalPosition(Long GlobalPosition) {
+        this.GlobalPosition = GlobalPosition;
+        return this;
+    }
+
+    public String GetLabel() {
+        return label.replaceAll("\\+_i\\d+", "+" + Position);
+    }
+
+    public Label SetLabel(String label) {
+        this.label = label;
+        return this;
+    }
+
+}

+ 38 - 0
src/common/Offset.java

@@ -0,0 +1,38 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package common;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class Offset {
+
+    protected Long address = 0L;
+    protected Long shift = 0L;
+
+    public Offset(Long address, Long shift) {
+        this.address = address;
+        this.shift = shift;
+    }
+
+    public Long getAddress() {
+        return address;
+    }
+
+    public void setAddress(Long address) {
+        this.address = address;
+    }
+
+    public Long getShift() {
+        return shift;
+    }
+
+    public void setShift(Long shift) {
+        this.shift = shift;
+    }
+
+}

+ 7 - 2
src/common/RegistroBase.java

@@ -128,7 +128,7 @@ public class RegistroBase {
             Set(atributo, i);
         } else {
             try {
-                int nu = getInt(atributo);
+                int nu = GetInt(atributo);
                 Set(atributo, nu + i);
             } catch (Exception e) {
                 e.printStackTrace();
@@ -146,6 +146,11 @@ public class RegistroBase {
         return this;
     }
 
+    public RegistroBase Set(String attrib, Boolean valor) {
+        RegistroBase.this.Set(attrib, "" + valor);
+        return this;
+    }
+
     public String getText() {
         return Get("value");
     }
@@ -170,7 +175,7 @@ public class RegistroBase {
         attr.remove(atrib);
     }
 
-    public int getInt(String atributo) throws Exception {
+    public int GetInt(String atributo) throws Exception {
         String l = "";
         try {
             l = Get(atributo);

+ 14 - 12
src/compiler/IVANNOSYS.java

@@ -8,14 +8,14 @@ package compiler;
  */
 import API.Api;
 import API.BuildParams;
-import API.CodeProcessor;
+import API.Middleware;
 import API.Target;
 import Export.MultCoreJun;
 import Export.Simulation;
 import IntermediaryCode.IRGenerator;
 import java.util.logging.Level;
 import java.util.logging.Logger;
-import targets.mips.Gen;
+import targets.mips.Translate;
 
 /**
  *
@@ -62,24 +62,25 @@ public class IVANNOSYS {
                     BuildParams.Add("mode", "developement");
 
                     // Especifica a classe de geração de código alvo mips
-                    Gen Mips = new targets.mips.Gen();
+                    Translate Mips = new targets.mips.Translate();
                     // Adiciona dois metodos de exportação ao alvo mips 
                     // Metodo de simualcao
                     Mips.AddExportOption("simulation", new Simulation(new tools.mips.MipsSettings() {
                         {
                             // Não executar passo a passo
-                            Set("stepByStep", "false");
+                            Set("step.by.step", "false");
                             // Necessario para poder usar os breakpoints
                             Set("mode", "debug");
                             // Determina os pontos de para no codigo alvo
-                            Set("breakpoints", "94");
+//                            Set("breakpoints", "94-9c");
+//                            Set("breakpoints", "10");
                             // Caminho do arquivo de memoria de instrucoes
                             Set("memory.instruction", "\\src\\tools\\mips\\memory\\mi.memory");
-                            // Tamanho da memorua de instrucoes
+                            // Tamanho da memorua de instrucoes 16 kb
                             Set("memory.instruction.size", 16 * 1024);
                             // Caminho do arquivo de memoria de dados
                             Set("memory.data", "\\src\\tools\\mips\\memory\\md.memory");
-                            // Tamanho da memorua de dados
+                            // Tamanho da memorua de dados 16 kb
                             Set("memory.data.size", 16 * 1024);
 
                         }
@@ -92,16 +93,17 @@ public class IVANNOSYS {
 
                     // Registra os processadores para o alvo mips
                     // Executa alocacao de registradores antes de traduzir cada bloco
-                    CodeProcessor.On("mips", "BeforeTranslateBlock", "mips.register.alloc");
-                    CodeProcessor.On("mips", "AfterTranslateBlock", "mips.o.L1,mips.copy.dep");
-                    // Atualiza os enderecos
-                    CodeProcessor.On("mips", "AfterTranslate", "mips.update.address");
+                    Middleware.On("mips", "before.translate.block", "mips.register.alloc");
+                    Middleware.On("mips", "after.translate.block", "mips.o.L1,mips.copy.dep");
+                    // Atualiza os enderecos de saltos e set no campo offset
+                    Middleware.On("mips", "after.translate", "mips.update.address");
 
                     // file = "src\\samples\\program.go";
                     // file = "src\\samples\\program.go";
                     // file = "src\\samples\\program_mult_jon.go";
 //                    file = "src\\samples\\program_mult.go";
-                    file = "src\\samples\\program_jun_bit_count.go";
+//                    file = "src\\samples\\program_jun_bit_count.go";
+                    file = "src\\samples\\program_jun_laplaciano.go";
 //                    file = "src\\samples\\program_jun_mult_manycore.go";
 
                     // Compila o arquivo de entrada

+ 1 - 5
src/compiler/IvannosysCompiler.java

@@ -162,11 +162,7 @@ public final class IvannosysCompiler {
 
     public void Generate(String arch, Code code) throws Exception {
 
-        Target.Get(arch)
-                .SetTAC(code)
-                .Compile()
-                .Format()
-                .Export();
+        Target.Get(arch).Init(code).Compile().Format().Export();
     }
 
     protected void DisplayAST(IvannosysGrammarParser parser) throws Exception {

+ 18 - 0
src/exception/CompileException.java

@@ -0,0 +1,18 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package exception;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class CompileException extends Exception {
+
+    public CompileException(String message, Object... args) {
+        super(String.format(message, args));
+    }
+
+}

+ 19 - 10
src/frontend/Ivannosys/IvannosysListener.java

@@ -308,21 +308,26 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
 //        System.out.println("types:" + types);
         for (Node var : node.find("ids").childrens()) {
             varname = scopeStack.peek() + "." + var.getText();
+
             t = types.get(i);
+
             var.Set("type", t)
                     .Set("value", varname)
+                    .Set("fullname", varname)
+                    .Set("name", var.getText())
                     .Set("class", "ID")
                     .Set("array", "" + (indexes.get(i).size() > 0))
                     .Set("array_size", "" + ArraySize(indexes.get(i)))
-                    .copy("pointer", type);
+                    .Copy("pointer", type);
 
-            variable = new Node()
+            variable = new Node(varname)
                     .Set("global", "" + (scopeStack.peek().split("\\.").length == 1))
+                    .Set("fullname", varname)
                     .Set("name", var.getText())
                     .Set("class", "selector")
                     .Set("subclass", "operand");
 
-            variable.copy("type,value,pointer,array,array_size", var);
+            variable.Copy("type,value,pointer,array,array_size", var);
             variable.addList("default.values", valuesGroup.get(i));
 
             astBaseSet(ctx, variable);
@@ -352,7 +357,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         int result = 1, v;
         for (Node index : indexes) {
             if (index.isNumber("value")) {
-                v = index.getInt("value");
+                v = index.GetInt("value");
             } else {
                 v = 1;
             }
@@ -398,12 +403,14 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         Node value = childrens.get(1);
 
         String varID = scopeStack.peek() + "." + id;
-        Node var = new Node(varID).Set("name", id)
+        Node var = new Node(varID)
+                .Set("fullname", varID)
+                .Set("name", id)
                 .Set("default.value", value.getText())
                 .Set("constant", "true")
                 .Set("pointer", "false")
                 .Set("array", "false")
-                .copy("file,scope,line,col,type", value);
+                .Copy("file,scope,line,col,type", value);
         try {
 
             Variables.Add(varID, var);
@@ -924,9 +931,11 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         String varname = parts.get(0).getText();
         String fullname = scopeStack.peek() + "." + varname;
 //        astBaseSet(ctx);
-        Node var = new Node(fullname);
         parts.get(0).Set("value", fullname);
-        var.Set("name", varname)
+
+        Node var = new Node(fullname)
+                .Set("fullname", fullname)
+                .Set("name", varname)
                 .Set("pointer", parts.get(1).Get("pointer"))
                 .Set("type", parts.get(1).Get("type"));
 
@@ -1404,7 +1413,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
                 case ">>":
                     classe = "expr";
                     subclasse = "arith";
-                    type = "int";
+                    type = "int32";
                 //Aritimeticas
 
             }
@@ -1449,7 +1458,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
             } else {
                 Node var = Variables.Get(ctx.ID().getText());
                 type = var.Get("type");
-                operand.copy("pointer", var);
+                operand.Copy("pointer", var);
             }
             operand.Set("class", "operand").Set("type", type);
 

+ 198 - 0
src/middlewares/BasicBlockMiddleware.java

@@ -0,0 +1,198 @@
+package middlewares;
+
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+import API.MiddlewareInterface;
+import API.Utils;
+import common.Block;
+import common.Code;
+import common.Instruction;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.regex.Pattern;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class BasicBlockMiddleware implements MiddlewareInterface {
+
+    protected static Integer nextLeader;
+    protected static BlockBaseGroup group;
+    protected static HashMap<String, BlockBaseGroup> groups = new HashMap<>();
+    protected static LinkedHashMap<Integer, Integer> leaders;
+    //OK
+    protected static Block block;
+    protected static ArrayList<Integer> leadersList;
+
+    public static Pattern addresspattern = Pattern.compile("\\_[VTGC].*", Pattern.CASE_INSENSITIVE);
+    protected Integer instructionPosition;
+    protected Integer lastLeader;
+    protected LinkedList<Instruction> instructions;
+    protected Instruction instruction;
+    protected String[] ignore = "label,alloc".split(","),
+            nextIsJump = "jump,label".split(",");
+
+    public BasicBlockMiddleware() {
+
+    }
+
+    protected void SetLeader(Integer position, Integer fix) {
+
+        // Se existe um leader anterior, atualiza a ultima instrução do bloco basico
+        if (lastLeader >= 0) {
+
+            leaders.put(lastLeader, (fix == 0 ? (instructionPosition - 1) : instructionPosition));
+        }
+        // Marca o proximo leader
+        // Se a proxima instrução  não foir um jump ou label
+        if (instructions.get(position + 1).in("type", nextIsJump)) {
+            return;
+        }
+        // Seta o novo leader
+        lastLeader = instructionPosition + fix;
+        leaders.put(lastLeader, 0);
+
+    }
+
+    @Override
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
+
+        String name = c.Block().getName();
+
+        BlockBaseGroup g = new BlockBaseGroup(name);
+        block = c.Block();
+        group = g;
+        groups.put(name, g);
+        instructionPosition = 0;
+        lastLeader = -1;
+        leaders = new LinkedHashMap<>();
+        //Step 1. Identify the leaders in the code. Leaders are instructions which come under any of the following 3 categories :
+        //The first instruction is a leader.
+        //The target of a conditional or an unconditional goto/jump instruction is a leader.
+        //The instruction that immediately follows a conditional or an unconditional goto/jump instruction is a leader.
+        instructions = block.Instructions();
+
+        // Remove da quantidade o label inicial e final
+        Integer limit = instructions.size() - 2;
+
+        for (int i = 0; i < limit; i++) {
+            instruction = instructions.get(i);
+            // Correcao quando for um salto
+            switch (instruction.Get("type")) {
+                // Ignora a instrução de alocacao de memoria
+                case "alloc":
+                    continue;
+                case "label":
+                    SetLeader(i, 0);
+                    break;
+                // Cria um novo bloco basico
+                case "jump":
+                case "call":
+                case "branch":
+                    SetLeader(i, 1);
+            }
+            // Se a instrução não faz parte do grupo de instrucoes 
+            // de controle incrementa a posicao do contador
+            if (!instruction.in("type", ignore)) {
+                instructionPosition++;
+            }
+        }
+        leaders.put(lastLeader, instructionPosition);
+
+        VerifyOcorrences();
+        System.out.println(group);
+    }
+
+    protected void RegBasicBlock() {
+//        System.out.println("leaders:" + leaders);
+//        System.out.println("RegBasicBlock:(" + nextLeader + ")(" + ((leaders.Get(nextLeader) - nextLeader) + 1) + ")");
+
+        group.RegisterBlock(nextLeader, (leaders.get(nextLeader) - nextLeader) + 1);
+
+        if (!leadersList.isEmpty()) {
+            nextLeader = leadersList.remove(0);
+        }
+    }
+
+    public static boolean IsAddress(String alias) {
+        return !Utils.Empty(alias) && addresspattern.matcher(alias).matches();
+    }
+
+    public BlockBaseGroup getBasicBlockGroup(String id) {
+        return groups.get(id);
+    }
+
+    public HashMap<String, BlockBaseGroup> getGroups() {
+        return groups;
+    }
+
+    public static Pattern getAddresspattern() {
+        return addresspattern;
+    }
+
+    public static void setAddresspattern(Pattern addresspattern) {
+        BasicBlockMiddleware.addresspattern = addresspattern;
+    }
+
+    protected void VerifyOcorrences() throws Exception {
+
+        // reseta a posicao da instrução
+        instructionPosition = 0;
+        leadersList = new ArrayList<>();
+
+        leaders.entrySet().forEach((entry) -> {
+            leadersList.add(entry.getKey());
+        });
+
+        System.out.println("leadersList:" + leadersList);
+
+        nextLeader = leadersList.remove(0);
+
+        // Registra primeiro bloco basico
+        RegBasicBlock();
+        // Atribui o segundo leder como 
+//        block.LastPosition = nextLeader - 1;
+
+        for (Iterator<Instruction> it = instructions.iterator(); it.hasNext();) {
+            instruction = it.next();
+            if (!instruction.in("type", ignore)) {
+
+//                System.out.println("Ins:(" + instructionPosition + ")(" + nextLeader + ")");
+                // Registra 
+                if (instructionPosition == nextLeader) {
+//                        block.CloseAllIntervals();
+//                        nextLeader = leadersList.remove(0);
+//                        block.LastPosition = nextLeader - 1;
+                    RegBasicBlock();
+                }
+                // Registra os acessos de leitura e escrita dos enderecos da instrucao
+                group.ParseInstruction(instruction, "dst,p1,p2");
+
+                instructionPosition++;
+            }
+        }
+        // Finaliza o grupo de blocos
+        group.Close();
+
+//        // Atualiza todos os encerramentos de intervalo para a ultima ocorrencia da variavel;
+//        block.CloseAllIntervals();
+//        System.out.println("block:" + groups);
+    }
+
+}
+//        block = new BlockBaseOcorrences(name);
+//        ArrayList<ArrayList<Integer>> bbs = new ArrayList<>();
+//        ArrayList<Integer> bb = null;
+
+//        basicBlockName = name;
+//        basicBlockCount = 0;
+//            protected ArrayList<ArrayList<Integer>> basicBlock = new ArrayList<>();
+//        basicBlocks.put(name, bbs);
+//        blocks.put(name, block);

+ 8 - 10
src/Processors/BlockBaseGroup.java

@@ -3,7 +3,7 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package Processors;
+package middlewares;
 
 import common.Instruction;
 import java.util.LinkedList;
@@ -58,25 +58,23 @@ public class BlockBaseGroup {
         return current;
     }
 
-    public void ParseInstruction(Instruction inst, String attrs) {
+    public void ParseInstruction(Instruction inst, String attrs) throws Exception {
         for (String attr : attrs.split(",")) {
-            RegisterInstruction(inst, attr);
+            current.Register(inst, attr);
         }
         current.Position++;
     }
 
-    public BlockBaseGroup RegisterInstruction(Instruction inst, String attr) {
-//        System.out.println("RegisterInstruction:" + attr);
-        current.Register(inst, attr);
-        return this;
-    }
-
+//    public BlockBaseGroup RegisterInstruction(Instruction inst, String attr) {
+//        current.Register(inst, attr);
+//        return this;
+//    }
     @Override
     public String toString() {
         StringBuilder sb = new StringBuilder();
 
         for (BlockBaseOcorrences blockBaseOcorrences : bbs) {
-            sb.append(blockBaseOcorrences);
+            sb.append(blockBaseOcorrences).append("\n");
         }
 
         return sb.toString();

+ 60 - 41
src/Processors/BlockBaseOcorrences.java

@@ -3,9 +3,8 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package Processors;
+package middlewares;
 
-import Processors.BasicBlockProcessor;
 import API.Utils;
 import common.Instruction;
 import java.util.ArrayList;
@@ -62,7 +61,7 @@ public class BlockBaseOcorrences {
         return false;
     }
 
-    public boolean Inside(String var, int i) {
+    public boolean Inside(String var, int i) throws Exception {
         return Get(var, i) != null;
     }
 
@@ -75,48 +74,63 @@ public class BlockBaseOcorrences {
 
     protected void OpenInterval(String alias) {
         if (!intervals.containsKey(alias)) {
-            intervals.put(alias, new LinkedList<Interval>());
+            intervals.put(alias, new LinkedList<>());
         }
 //        System.out.println("Open interval:(" + alias + "):" + Position + ":" + LastPosition);
-        intervals.get(alias).add(new Interval(Position, LastPosition));
+        intervals.get(alias).add(new Interval(Position, LastPosition, Position));
     }
 
     protected void CloseAllIntervals() {
-        LastPosition = Position;
-//        System.out.println("CloseAllIntervals:");
+        LastPosition = Position - 1;
+
+//        System.out.println("//////// CloseAllIntervals(" + leader + "):" + LastPosition);
+        // Para cada variavel
         for (Map.Entry<String, LinkedList<Interval>> x : intervals.entrySet()) {
+            // Pega o ultimo intervalo
             interval = x.getValue().peekLast();
-//            System.out.println("Check interval:" + x.getKey() + Position + ":" + interval);
 
-            if (interval.Alive(Position)) {
-//                System.out.println("Interval:" + x.getKey() + ":open:" + ocorrences.Get(x.getKey()).peekLast());
-                interval.Close(ocorrences.get(x.getKey()).peekLast());
+//            System.out.println("Check interval("
+//                    + interval.Alive(Position)
+//                    + "): "
+//                    + x.getKey()
+//                    + "  >  "
+//                    + Position
+//                    + "  >  "
+//                    + interval);
+            if (interval.Alive(LastPosition)) {
+//                System.out.println("Interval:" + x.getKey() + ":open:" + ocorrences.get(x.getKey()).peekLast());
+                interval.Close();
             }
         }
     }
 
-    void Register(Instruction x, String attr) {
+    public void Register(Instruction x, String attr) throws Exception {
         String alias = x.Get(attr);
-        if (!BasicBlockProcessor.IsAddress(alias)) {
+        ArrayList<String> aliases;
+
+        if (!BasicBlockMiddleware.IsAddress(alias)) {
             return;
         }
-        alias = ToAliase(x, attr);
 
-        ArrayList<String> aliases = new ArrayList<>();
+        aliases = new ArrayList<>();
+        alias = ToAliase(x, attr);
 
         aliases.add(alias);
         String index = attr + ".indice";
+
         if (x.Has(index) && !x.isNumber(index)) {
             aliases.add(x.Get(index));
         }
+
         for (String a : aliases) {
             if (!ocorrences.containsKey(a)) {
-                ocorrences.put(a, new LinkedList<Integer>());
+                ocorrences.put(a, new LinkedList<>());
             }
             ocorrences.get(a).add(Position);
             if (!Alive(a)) {
                 OpenInterval(a);
             }
+            Get(a, Position).setLastOcorrence(Position);
         }
     }
 
@@ -128,7 +142,7 @@ public class BlockBaseOcorrences {
         return null;
     }
 
-    public Interval Get(String var, int i) {
+    public Interval Get(String var, int i) throws Exception {
         LinkedList<Interval> intervls = Get(var);
         if (intervls != null) {
             for (Interval inter : intervls) {
@@ -138,11 +152,12 @@ public class BlockBaseOcorrences {
             }
         }
         return null;
+//        throw new CompileException("Intervalo não definido para a variável %s na posição %d", var, i);
     }
 
     // Busca por um intervalo expirado ou que esteja disponivel para ser subdividido
     // Retorna a primeira parte intervalo que foi dividido
-    public Interval Spill(int position) {
+    public Interval Spill(int position) throws Exception {
 //        System.out.println("Spill:[" + position + "]{");
         HashMap<String, Interval> is = new HashMap<>();
         Interval inter = null;
@@ -150,15 +165,15 @@ public class BlockBaseOcorrences {
 
         for (Map.Entry<String, LinkedList<Interval>> I : intervals.entrySet()) {
             var = I.getKey();
+
             inter = Get(var, position);
-            System.out.println("Interval:" + inter);
             // Tem intervalo nessa posicao agora deve verificar se ela não ocorre nessa instrucao;
             if (inter != null && !ocorrences.get(var).contains(position)) {
                 is.put(var, inter);
             }
         }
         inter = null;
-//        System.out.println("Spill disp:" + is.size());
+        System.out.println("Spill disp: " + is.size());
         // is Contem todos os intervalos que podem ser divididos;
         // o intervalo escolhido é o que possui a ocorrencia mais longe
         int pos = 0, pos1, interpos;
@@ -171,12 +186,12 @@ public class BlockBaseOcorrences {
                 inter = x.getValue();
             }
         }
-//        System.out.println("Spill inter:" + var + "|" + inter);
+        System.out.println("Spill inter: " + var + "|" + inter);
         // Se encontrou um intervalo para ser dividido executa a divisao
         if (inter != null) {
             LinkedList<Interval> lintervals = intervals.get(var);
             interpos = lintervals.indexOf(inter);
-            lintervals.add(interpos + 1, new Interval(pos, inter.getEnd()));
+            lintervals.add(interpos + 1, new Interval(pos, inter.getEnd(), pos));
             inter.Close(position);
         }
 //        System.out.println("End spill}");
@@ -221,31 +236,35 @@ public class BlockBaseOcorrences {
         String append, var, reg;
         Interval inter;
 
-        for (Map.Entry<String, LinkedList<Integer>> x : ocorrences.entrySet()) {
-            var = x.getKey();
-            buffer.append(Utils.Pad(var, " ", "-", 11));
+        try {
+            for (Map.Entry<String, LinkedList<Integer>> x : ocorrences.entrySet()) {
+                var = x.getKey();
+                buffer.append(Utils.Pad(var, " ", "-", 11));
 
 //            for (int i = 0; i <= Position; i++) {
-            for (int i = 0; i < Position; i++) {
-//                System.out.println("OCOR:" +);
-                reg = "";
-                append = "---";
-                if (x.getValue().contains(i)) {
+                for (int i = 0; i < Position; i++) {
+                    //                System.out.println("OCOR:" +);
+                    reg = "";
+                    append = "---";
+                    if (x.getValue().contains(i)) {
 //                    append = Get(var, i).getRegister() + "##"; // Ocorrencia da variavel
-                    append = "###"; // Ocorrencia da variavel
-                } else if (Inside(var, i)) {
-                    append = "+++"; // dentro do intervalo
-                }
+                        append = "###"; // Ocorrencia da variavel
+                    } else if (Inside(var, i)) {
+                        append = "+++"; // dentro do intervalo
+                    }
 
-                inter = Get(x.getKey(), i);
-                if (inter != null) {
-                    reg = inter.getRegister();
+                    inter = Get(x.getKey(), i);
+                    if (inter != null) {
+                        reg = inter.getRegister();
+                    }
+
+                    buffer.append(reg + append.substring(0, append.length() - reg.length()));
                 }
 
-                buffer.append(reg + append.substring(0, append.length() - reg.length()));
+                buffer.append("\n");
             }
-
-            buffer.append("\n");
+        } catch (Exception ex) {
+//            Logger.getLogger(BlockBaseOcorrences.class.getName()).log(Level.SEVERE, null, ex);
         }
 
         return buffer.toString();
@@ -255,7 +274,7 @@ public class BlockBaseOcorrences {
 
 //    protected void Register(Instruction x, String attr) {
 //        String alias = x.Get(attr);
-//        if (!BasicBlockProcessor.IsAddress(alias)) {
+//        if (!BasicBlockMiddleware.IsAddress(alias)) {
 //            return;
 //        }
 //        alias = ToAliase(x, attr);

+ 10 - 10
src/Processors/CodeOtimizadorProcessor.java

@@ -1,6 +1,5 @@
-package Processors;
+package middlewares;
 
-import API.CodeProcessorInterface;
 import common.Block;
 import common.Code;
 import common.Instruction;
@@ -8,18 +7,19 @@ import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
+import API.MiddlewareInterface;
 
 /**
  *
  * @author Eugenio
  */
-public class CodeOtimizadorProcessor implements CodeProcessorInterface {
+public class CodeOtimizadorMiddleware implements MiddlewareInterface {
 
     protected Code code;
 //    protected ArrayList<Filtros> filtros = new ArrayList<Filtros>();
     protected boolean enable = true;
 
-    public CodeOtimizadorProcessor(boolean enabled) {
+    public CodeOtimizadorMiddleware(boolean enabled) {
         enable = enabled;
     }
 //
@@ -30,7 +30,7 @@ public class CodeOtimizadorProcessor implements CodeProcessorInterface {
 //    }
 
     @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
         if (!enable) {
             return;
         }
@@ -44,7 +44,7 @@ public class CodeOtimizadorProcessor implements CodeProcessorInterface {
         while (interator.hasNext()) {
             Instruction inst = interator.next();
 //            System.out.println("Otimizando 3 enderecos:" + inst);
-//            System.out.println("CodeOtimizadorProcessor:" + inst.Get("type"));
+//            System.out.println("CodeOtimizadorMiddleware:" + inst.Get("type"));
             switch (inst.Get("cat")) {
                 /*Se for uma expressão aritimetica*/
                 case "exp":
@@ -86,8 +86,8 @@ public class CodeOtimizadorProcessor implements CodeProcessorInterface {
 
                 // Se o destino da copia não for indexado então pode executar 
                 // o replace da ocorrencia e remover a instrucao de copia
-                //                    if (!inst.eq("dst_indexed", "true") && inst.eq("p1value", "false")) {
-                //                    if (!inst.eq("dst_indexed", "true")) {
+                //                    if (!inst.eq("dst.indexed", "true") && inst.eq("p1value", "false")) {
+                //                    if (!inst.eq("dst.indexed", "true")) {
                 ////                        System.out.println("Otimizacao - replace " + inst.Get("p1") + " -> " + inst.Get("dst"));
                 //                        if (inst.eq("p1value", "true")) {
                 //                            block.ReplaceVar(inst.Get("dst"), inst.Get("p1"));
@@ -113,7 +113,7 @@ public class CodeOtimizadorProcessor implements CodeProcessorInterface {
             }
         }
         c.PosicaoLabel = block.BaseAddress;
-        block.Update();
+//        block.Update();
     }
 
     private boolean ReplaceVarAndRemoveInstruction(LinkedList<Instruction> instructions, Instruction inst, int index, Block block) {
@@ -146,7 +146,7 @@ public class CodeOtimizadorProcessor implements CodeProcessorInterface {
             index++;
         }
 
-        block.Data().Replace(dst, p1);
+        block.Context().Replace(dst, p1);
 
 //        System.out.println("ReplaceVarAndRemoveInstruction:" + dst + ":" +);
 //        

+ 5 - 5
src/Processors/DeadInstructionsProcessor.java

@@ -3,9 +3,8 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package Processors;
+package middlewares;
 
-import API.CodeProcessorInterface;
 import common.Block;
 import common.Code;
 import common.Instruction;
@@ -14,20 +13,21 @@ import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.regex.Pattern;
+import API.MiddlewareInterface;
 
 /**
  *
  * @author EUGENIO CARVALHO
  */
-public class DeadInstructionsProcessor implements CodeProcessorInterface {
+public class DeadInstructionsMiddleware implements MiddlewareInterface {
 
     public static Pattern varPattern = Pattern.compile("\\_[VT].*", Pattern.CASE_INSENSITIVE);
 
-    public DeadInstructionsProcessor() {
+    public DeadInstructionsMiddleware() {
     }
 
     @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
         String dst;
         Instruction instruction;
         Block block = c.Block();

+ 32 - 3
src/Processors/Interval.java

@@ -3,7 +3,7 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package Processors;
+package middlewares;
 
 /**
  *
@@ -11,14 +11,21 @@ package Processors;
  */
 public class Interval {
 
+    // Define a primeira ocorrencia do intervalo
     public int Start;
+    // Define a primeira ocorrencia do intervalo
     public int End;
+    // Define a ultima ocorrencia registrada no intervalo
+    protected Integer LastOcorrence;
+    // Define o registrador do intervalo
     public String Register = "";
+
     protected boolean persist;
 
-    Interval(int start, int end) {
+    public Interval(Integer start, Integer end, Integer last) {
         Start = start;
         End = end;
+        LastOcorrence = last;
         persist = false;
     }
 
@@ -51,12 +58,18 @@ public class Interval {
     }
 
     void Close(int position) {
+//        System.out.println("Close with position " + position);
         End = position;
     }
 
+    void Close() {
+//        System.out.println("Close with last");
+        End = LastOcorrence;
+    }
+
     @Override
     public String toString() {
-        return "[" + Start + ", " + End + ", " + Register + "]";
+        return "[S: " + Start + ", L: " + LastOcorrence + ", E: " + End + ", R:" + Register + "]";
     }
 
     public boolean Inside(int i) {
@@ -75,4 +88,20 @@ public class Interval {
         return this.persist = p;
     }
 
+    public Integer getLastOcorrence() {
+        return LastOcorrence;
+    }
+
+    public void setLastOcorrence(Integer LastOcorrence) {
+        this.LastOcorrence = LastOcorrence;
+    }
+
+    public boolean isPersist() {
+        return persist;
+    }
+
+    public void setPersist(boolean persist) {
+        this.persist = persist;
+    }
+
 }

+ 7 - 7
src/Processors/LoadStoreProcessor.java

@@ -3,9 +3,8 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package Processors;
+package middlewares;
 
-import API.CodeProcessorInterface;
 import common.Block;
 import common.Code;
 import common.Instruction;
@@ -13,23 +12,24 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
+import API.MiddlewareInterface;
 
 /**
  *
  * @author EUGENIO CARVALHO
  */
-public class LoadStoreProcessor implements CodeProcessorInterface {
+public class LoadStoreMiddleware implements MiddlewareInterface {
 
-    protected BasicBlockProcessor basicBlocks;
+    protected BasicBlockMiddleware basicBlocks;
 
     private BlockBaseGroup group;
 
-    public LoadStoreProcessor() {
+    public LoadStoreMiddleware() {
     }
 
     @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
-        this.basicBlocks = (BasicBlockProcessor) cp.get("ir.basic.blocks");
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
+        this.basicBlocks = (BasicBlockMiddleware) cp.get("ir.basic.blocks");
         
         BlockBaseOcorrences g;
         Integer leader, limit, lposition;

+ 1 - 1
src/Processors/Ocorrence.java

@@ -3,7 +3,7 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package Processors;
+package middlewares;
 
 import java.util.HashMap;
 import java.util.LinkedHashMap;

+ 6 - 6
src/Processors/RemoveUnusedLabelsProcessor.java

@@ -3,9 +3,8 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package Processors;
+package middlewares;
 
-import API.CodeProcessorInterface;
 import API.Utils;
 import common.Block;
 import common.Code;
@@ -15,23 +14,24 @@ import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
+import API.MiddlewareInterface;
 
 /**
  *
  * @author EUGENIO CARVALHO
  */
-public class RemoveUnusedLabelsProcessor implements CodeProcessorInterface {
+public class RemoveUnusedLabelsMiddleware implements MiddlewareInterface {
 
     protected HashMap<String, HashMap<String, ArrayList<Instruction>>> labelMap = new HashMap<>();
     protected String currentBlock;
     private Block block;
 
-    public RemoveUnusedLabelsProcessor() {
+    public RemoveUnusedLabelsMiddleware() {
 
     }
 
     @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
         String label;
         Instruction instruction = null;
         block = c.Block();
@@ -44,7 +44,7 @@ public class RemoveUnusedLabelsProcessor implements CodeProcessorInterface {
         Instruction branch = null, last = null;
         int position = 0;
 
-        System.out.println("block:" + block.getName() + "-------------------------------");
+//        System.out.println("block:" + block.getName() + "-------------------------------");
 //        System.out.println("\n\n####referenceCount:" + referenceCount + "\n\n");
 
         // Salta o primeiro label

+ 8 - 8
src/Processors/VariablesConstantsProcessor.java

@@ -3,10 +3,10 @@
  * To change this template file, choose Tools | Templates
  * and open the template in the editor.
  */
-package Processors;
+package middlewares;
 
+import API.MiddlewareInterface;
 import API.Utils;
-import API.CodeProcessorInterface;
 import common.Block;
 import common.Code;
 import common.Instruction;
@@ -19,17 +19,17 @@ import java.util.LinkedList;
  *
  * @author EUGENIO CARVALHO
  */
-public class VariablesConstantsProcessor implements CodeProcessorInterface {
+public class VariablesConstantsMiddleware implements MiddlewareInterface {
 
     private Block block;
     private Iterator<Instruction> interator;
     private Instruction instruction;
 
-    public VariablesConstantsProcessor() {
+    public VariablesConstantsMiddleware() {
     }
 
     @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
 //        String label, dst;
         String dst;
 
@@ -73,8 +73,8 @@ public class VariablesConstantsProcessor implements CodeProcessorInterface {
     }
 
     protected String Resolve(Instruction instruction) throws Exception {
-        System.out.println("instruction:"+ instruction);
-        int value = instruction.getInt("p1");
+//        System.out.println("instruction:"+ instruction);
+        int value = instruction.GetInt("p1");
         
         switch (instruction.Get("cat")) {
             case "exp":
@@ -82,7 +82,7 @@ public class VariablesConstantsProcessor implements CodeProcessorInterface {
                     value = Utils.ResolveExpr(
                             instruction.Get("op"),
                             value,
-                            instruction.getInt("p2"));
+                            instruction.GetInt("p2"));
 
                 }
         }

+ 4 - 0
src/samples/program_jun_bit_count.go

@@ -51,6 +51,10 @@ import "sync"
 
 type x struct {
     a int32
+    b bool
+    c int32
+    d bool
+    e byte
 }
 
 var (

+ 5 - 6
src/samples/program_jun_laplaciano.go

@@ -1,7 +1,7 @@
 // Aplica o back-end do juninho
 @target          : mips 
 // Especifica o tipo de metodo empregado para salvar o resultado da compilação
-@export          : MultCoreJun
+@export          : simulation //MultCoreJun
 
 // Diretorio onde o resultado da compilação será gravado
 @outputDirectory : `C:\Users\EUGENIO CARVALHO\Desktop\tmp\laplaciano`
@@ -53,14 +53,14 @@ const (
 )
 
 var (
-    origin [LIN][COL]int
-    result [LIN][COL]int
+    origin [LIN][COL]int32
+    result [LIN][COL]int32
 )
 
 func preenche_matriz() {
     var (
         w = 1
-        value int
+        value int32
     )
     
     LM1 := LIN - 1
@@ -84,8 +84,7 @@ func preenche_matriz() {
 
 func laplaciano() {
     var (
-        l int
-        //LM1,CM1 int
+        l int32
     )
     LM1 := LIN - 1
     CM1 := COL - 1

+ 5 - 4
src/samples/program_jun_mult_manycore.go

@@ -54,15 +54,16 @@ const (
 )
 
 var (
-    matrizA [LIN][COL]int
-    matrizB [LIN][COL]int
-    matrizR [LIN][COL]int
+    matrizA [LIN][COL]int32
+    matrizB [LIN][COL]int32
+    matrizR [LIN][COL]int32
 )
 
-func multiplica(initial int) {
+func multiplica(initial int32) {
     tmp   := 10
     aux   := 0
     limit := initial + NUM_LINHAS_MULT
+
     for i := initial; i < limit; i++ {
         for j := 0; j < COL; j++ {
             for k := 0; k < LIN; k++ {

+ 43 - 4
src/samples/program_mult.go

@@ -1,18 +1,20 @@
 // Aplica o back-end do juninho
 @target          : mips 
 // Especifica o tipo de metodo empregado para salvar o resultado da compilação
+//@export          : MultCoreJun
 @export          : simulation
 
+
 package main;
 
 const (
     LIN  = 2
-    COL  = 2 
+    COL  = 2
 )
 var (
-    matrizA [LIN][COL]int 
-    matrizB [LIN][COL]int
-    matrizR [LIN][COL]int
+    matrizA [LIN][COL]int32
+    matrizB [LIN][COL]int32
+    matrizR [LIN][COL]int32
 )
 
 func preenche(){
@@ -43,3 +45,40 @@ func main() {
     preenche()
     multiplica()
 }
+
+
+/**
+load (int32) i		  T< load >		
+10:	 9:		_T4 := i --Copy value of index		  T< copy >		
+11:	10:		_T5 := _T4 << 1		  T< assign >		
+12:	11:		load (int32) j		  T< load >		
+13:	12:		_T7 := j --Copy value of index		  T< copy >		
+14:	13:		_T5 := _T5 + _T7 --colls shift		  T< assign >		
+15:	14:		_T11 := _T5 << 4		  T< assign >		
+16:	15:		load (int32) aux		  T< load >		
+17:	16:		matrizA[_T11] := aux		  T< indexed_assign >		
+
+[2][2]
+    i  j  t4  t5   t7  t11 
+9   1  1  1
+10            2    
+11  
+12                 1
+13                     3
+14  
+15  
+16  
+17  
+
+                sll t6,t4,4		.14 -- _T11 = _T5 << 4
+60:  2413101056	lw s5,fp,0		.15 -- load content from _V1 in s5
+64:  0000000000	sll zero,zero,0		.15 -- Nop
+68:  0059666465	addu t6,gp,t6		.16
+6c:  2916417536	sw s5,t6,0		.16 -- store content of t6 in _G13[_T11]
+    t6 tem o deslocamento em bytes
+    
+
+*/
+
+
+

+ 9 - 8
src/targets/mips/Mips.java

@@ -12,13 +12,8 @@ import java.util.LinkedHashMap;
  *
  * @author EUGENIO CARVALHO
  */
-public class Mips {
+public class Descriprion {
 
-//    public static HashMap<String, String> Templates = new HashMap<String, String>() {
-//        {
-//
-//        }
-//    };
     public static LinkedHashMap<String, Instruction> instOperators = new LinkedHashMap<String, Instruction>() {
         {
             put("+", new Instruction()
@@ -431,13 +426,13 @@ public class Mips {
 
             put("lh", new Instruction()
                     .Set("type", "I")
-                    .Set("inst", "lb")
+                    .Set("inst", "lh")
                     .Set("codop", "100001")
                     .Set("format", "I2"));
 
             put("lhu", new Instruction()
                     .Set("type", "I")
-                    .Set("inst", "lbu")
+                    .Set("inst", "lhu")
                     .Set("codop", "100101")
                     .Set("format", "I2"));
 
@@ -483,6 +478,12 @@ public class Mips {
                     .Set("codop", "101011")
                     .Set("format", "I0"));
 
+            put("sb", new Instruction()
+                    .Set("type", "I")
+                    .Set("inst", "sb")
+                    .Set("codop", "101000")
+                    .Set("format", "I0"));
+
             put("xori", new Instruction()
                     .Set("type", "I")
                     .Set("inst", "xori")

+ 5 - 5
src/targets/mips/MipsCopyDepsProcessor.java

@@ -5,26 +5,26 @@
  */
 package targets.mips;
 
-import API.CodeProcessorInterface;
 import common.Block;
 import common.Code;
 import java.util.LinkedHashMap;
+import API.MiddlewareInterface;
 
 /**
  *
  * @author EUGENIO CARVALHO
  */
-public class MipsCopyDepsProcessor implements CodeProcessorInterface {
+public class MipsCopyDepsMiddleware implements MiddlewareInterface {
 
     protected Code tac;
 
-    public MipsCopyDepsProcessor() {
+    public MipsCopyDepsMiddleware() {
     }
 
     @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
         Block currentBlock = c.Block(),
-                tacBlock = c.Parent.getBlocks().get(currentBlock.getName());
+                tacBlock = c.Parent.Blocks().get(currentBlock.getName());
 //        System.out.println("EXEC COPY DEPS:" + currentBlock.getName() + "\n" + tacBlock.GetDependences());
         for (String dep : tacBlock.GetDependences()) {
             currentBlock.AddDependence(dep);

+ 5 - 5
src/targets/mips/MipsLoadStoreProcessor.java

@@ -5,22 +5,22 @@
  */
 package targets.mips;
 
-import Processors.BasicBlockProcessor;
-import API.CodeProcessorInterface;
+import middlewares.BasicBlockMiddleware;
 import common.Code;
 import java.util.LinkedHashMap;
+import API.MiddlewareInterface;
 
 /**
  *
  * @author EUGENIO CARVALHO
  */
-class MipsLoadStoreProcessor implements CodeProcessorInterface {
+class MipsLoadStoreMiddleware implements MiddlewareInterface {
 
-    public MipsLoadStoreProcessor(BasicBlockProcessor ocorrences) {
+    public MipsLoadStoreMiddleware(BasicBlockMiddleware ocorrences) {
     }
 
     @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
 //        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
     }
 

+ 0 - 35
src/targets/mips/MipsOTMinActivationRegister.java

@@ -1,35 +0,0 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package targets.mips;
-
-import common.Block;
-import common.Code;
-import API.CodeProcessorInterface;
-import common.DataLayout;
-import Processors.BasicBlockProcessor;
-import java.util.LinkedHashMap;
-
-/**
- *
- * @author EUGENIO CARVALHO
- */
-public class MipsOTMinActivationRegister implements CodeProcessorInterface {
-
-    protected BasicBlockProcessor ocorrences;
-
-    MipsOTMinActivationRegister(BasicBlockProcessor ocorrences) {
-        this.ocorrences = ocorrences;
-    }
-
-    @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
-        Block B = c.Block();
-        DataLayout D = B.Data();
-//        BlockBaseOcorrences o = ocorrences.getBlocks().get(B.getName());
-//        System.out.println("o:" + o.All());
-    }
-
-}

+ 5 - 5
src/targets/mips/MipsOtimizationProcessor.java

@@ -5,24 +5,24 @@
  */
 package targets.mips;
 
-import API.CodeProcessorInterface;
 import common.Code;
 import common.Instruction;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.ListIterator;
+import API.MiddlewareInterface;
 
 /**
  *
  * @author EUGENIO CARVALHO
  */
-public class MipsOtimizationProcessor implements CodeProcessorInterface {
+public class MipsOtimizationMiddleware implements MiddlewareInterface {
 
-    public MipsOtimizationProcessor() {
+    public MipsOtimizationMiddleware() {
     }
 
     @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
         Instruction last = new Instruction();
 //        ArrayList<Instruction> remove = new ArrayList<>();
         ListIterator<Instruction> instructions = c.Block().Instructions().listIterator();
@@ -58,7 +58,7 @@ public class MipsOtimizationProcessor implements CodeProcessorInterface {
 //        }
 
 //        for (Instruction instruction : remove) {
-//            System.out.println("Remover MipsOtimizationProcessor:" + instruction);
+//            System.out.println("Remover MipsOtimizationMiddleware:" + instruction);
 //            instructions.remove(instruction);
 //        }
     }

+ 42 - 43
src/targets/mips/MipsRegisterAllocProcessor.java

@@ -6,79 +6,76 @@
 package targets.mips;
 
 import API.Api;
-import API.CodeProcessorInterface;
-import Processors.BasicBlockProcessor;
-import Processors.BlockBaseGroup;
-import Processors.BlockBaseOcorrences;
-import Processors.Interval;
+import API.MiddlewareInterface;
 import common.AllocatorInterface;
 import common.Code;
 import common.Instruction;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
+import middlewares.BasicBlockMiddleware;
+import middlewares.BlockBaseGroup;
+import middlewares.BlockBaseOcorrences;
+import middlewares.Interval;
 
 /**
  *
  * @author EUGENIO CARVALHO
  */
-public class MipsRegisterAllocProcessor implements AllocatorInterface, CodeProcessorInterface {
+public class MipsRegisterAllocMiddleware implements AllocatorInterface, MiddlewareInterface {
 
     protected int instructionPosition;
     protected Code tac;
     protected Registers registers;
     protected BlockBaseGroup group;
     protected LinkedList<String> free = new LinkedList<>();
-    protected BasicBlockProcessor blockProcessor;
+    protected BasicBlockMiddleware blockProcessor;
+    protected String[] withoutRegister = "jump,call,return".split(",");
 
-    public MipsRegisterAllocProcessor() {
+    public MipsRegisterAllocMiddleware() {
 
     }
 
     @Override
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
-
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
+        BlockBaseOcorrences bb;
         System.out.println("AllocatorMipsProcessor:");
-        String blockname = c.Block().getName();
         Code IR = c.Parent;
+
+        String blockname = c.Block().getName();
         IR.Use(blockname);
 
-        BlockBaseOcorrences bb;
         registers = new Registers();
-        blockProcessor = (BasicBlockProcessor) cp.get("ir.basic.blocks");
-
+        blockProcessor = (BasicBlockMiddleware) cp.get("ir.basic.blocks");
         instructionPosition = 0;
         group = blockProcessor.getBasicBlockGroup(IR.Block().getName());
+
         group.Init();
 
         for (Instruction inst : IR.Block().Instructions()) {
-//            System.out.println("Alloc:(" + IR.Block().getName() + ")" + inst);
-            // tipos onde não se usa registrador
-            switch (inst.Get("type")) {
-                case "jump":
-                case "call":
-                case "return":
-                    instructionPosition++;
-                case "label":
-                    continue;
-                default:
-                    // Se a instruncao pertence ao proximo bloco basico atualiza o grupo
-                    bb = group.getBasicBlocks(1);
+            // ignora se a instrução for do tipo controle 
+            if (inst.in("type", IR.ControlInstructions)) {
+                continue;
+            }
+            // Se a instrução possui enderecamento de registradores
+            if (!inst.in("type", withoutRegister)) {
+                // Se a instruncao pertence ao proximo bloco basico atualiza o grupo
+                bb = group.getBasicBlocks(1);
 
 //                    System.out.println("###ASSIGN:(" + instructionPosition + ")(" + group.getBasicBlocks(1).getLeader() + ")");
-                    if (bb != null && instructionPosition >= bb.getLeader()) {
-                        group.NextBlock();
+                if (bb != null && instructionPosition >= bb.getLeader()) {
+                    group.NextBlock();
 //                        System.out.println(">>>>> Mudei para bloco basico:" + group.Current().getName());
-                    }
-
-                    // Libera registradores alocados temporariamente
-                    while (!free.isEmpty()) {
-                        registers.Free(free.pop());
-                    }
-                    // Atribui os registradores a instrucao
-                    Assign(inst);
-                    // Incrimenta o ponteiro para a proxima instrucao
-                    instructionPosition++;
+                }
+
+                // Libera registradores alocados temporariamente
+                while (!free.isEmpty()) {
+                    registers.Free(free.pop());
+                }
+                // Atribui os registradores a instrucao
+                Assign(inst);
             }
+            // Incrimenta o ponteiro para a proxima instrucao
+            instructionPosition++;
         }
 
         System.out.println(group);
@@ -91,12 +88,13 @@ public class MipsRegisterAllocProcessor implements AllocatorInterface, CodeProce
 
     protected void Assign(Instruction inst) throws Exception {
 
+//        System.out.println("Assign:" + inst.Get("type") + ":" + inst.Get("local.position"));
         String reg;
         String[] opDeslocamento = "<<,>>".split(",");
 
         for (String param : new String[]{"p1", "p2", "dst.indice", "p1.indice"}) {
 
-            if (!inst.Has(param) || (inst.in("op", opDeslocamento) && param.equals("p2"))) {
+            if (!inst.Has(param) || ((inst.in("op", opDeslocamento) && param.equals("p2")))) {
                 continue;
             }
 
@@ -107,8 +105,6 @@ public class MipsRegisterAllocProcessor implements AllocatorInterface, CodeProce
                 reg = registers.Lock("t");
                 free.push(reg);
                 Load(inst, param);
-//                System.out.println("Push:" + reg + "-");
-//            } else if () {
 
             } else {
 
@@ -135,7 +131,7 @@ public class MipsRegisterAllocProcessor implements AllocatorInterface, CodeProce
         BlockBaseOcorrences bb = group.Current();
 
         String reg, addr = bb.ToAliase(x, address);
-        int position = x.getInt("block.position"), leader = bb.getLeader();
+        int position = x.GetInt("block.position"), leader = bb.getLeader();
         // Corrige a posicao para iniciar de 0 para cada bloco basico referente ao lider de cada bloco.
         position = (leader == 0) ? position : position - leader;
 
@@ -146,7 +142,7 @@ public class MipsRegisterAllocProcessor implements AllocatorInterface, CodeProce
 //                + " : "
 //                + position
 //                + " : "
-//                + leader + "] {");
+//                + leader + "]");
 //        System.out.println(x);
         Interval interval = bb.Get(addr, position);
 
@@ -168,6 +164,9 @@ public class MipsRegisterAllocProcessor implements AllocatorInterface, CodeProce
 
             // Libera um registrador ocupado
             if (reg == null) {
+
+                System.out.println("spill" + bb + " P:" + position + " b:" + bb.Spill(position));
+
                 reg = bb.Spill(position).getRegister();
             }
             // Vincula o registrador com o intervalo

+ 12 - 30
src/targets/mips/MipsTemplate.java

@@ -17,11 +17,11 @@ import templates.Functions;
  *
  * @author EUGENIO CARVALHO
  */
-public class MipsTemplate implements templates.TemplateDescription {
+public class MipsTemplateDescription implements templates.TemplateDescription {
 
     public HashMap<String, String> Formats() throws Exception {
         String base = "{[HEX(global.position,G.addressLen,' ')]':  '}{[INSTDEC()]}{[T(1)]}{[inst]' '}",
-                end = "{[T(1)]}{'.'[tac.position]'.'}{'--'[comment]}";
+                end = "{[T(2)]}{'.'[tac.position]}{' -- '[comment]}";
 
         return new HashMap<String, String>() {
             {
@@ -62,11 +62,11 @@ public class MipsTemplate implements templates.TemplateDescription {
             {
                 put("OFFSET", (ctx, args) -> args.get(0) + "(" + args.get(1) + ")");
 
-                put("INSTHEX", (ctx, args) -> MipsTemplate.ConvertBin("hex", ctx, args));
+                put("INSTHEX", (ctx, args) -> MipsTemplateDescription.ConvertBin("hex", ctx, args));
 
-                put("INSTDEC", (ctx, args) -> MipsTemplate.ConvertBin("dec", ctx, args));
+                put("INSTDEC", (ctx, args) -> MipsTemplateDescription.ConvertBin("dec", ctx, args));
 
-                put("INSTBIN", (ctx, args) -> MipsTemplate.INSTBIN(ctx, args));
+                put("INSTBIN", (ctx, args) -> MipsTemplateDescription.INSTBIN(ctx, args));
 
                 put("RBIN", (ctx, args) -> {
                     String reg = args.get(0);
@@ -74,21 +74,20 @@ public class MipsTemplate implements templates.TemplateDescription {
                         reg = "0";
                     }
                     if (!Utils.IsNumber(reg)) {
-                        reg = Mips.Register(reg);
+                        reg = Descriprion.Register(reg);
                     }
                     return Api.num2bin(reg, Integer.parseInt(args.get(1)));
                 });
 
                 put("LM", (ctx, args) -> {
-                    if (args.get(0).equals("")) {
-                        return "";
-                    }
+
                     String label = args.get(0).trim();
                     if (label.equals("")) {
                         return label;
                     }
 //                    System.out.println("RUN LM: " + args + ctx);
                     String prefix = "G.";
+
                     String format = (args.size() > 1) ? args.get(1) : "dec",
                             // Corresponde ao nome do label que marca o inicio do bloco 
                             base = ctx.Get(prefix + "label." + label).split("\\+")[0],
@@ -98,33 +97,16 @@ public class MipsTemplate implements templates.TemplateDescription {
                             laddress = ctx.Get(prefix + label);
 
 //        System.out.printf("TemplateListener:{%s\n %s\n %s\n %s\n}\n", base, baseAddress, label, laddress);
-                    int value = Integer.parseInt(laddress);
-                    int fromStart = value - Integer.parseInt(baseAddress);
+                    Long value = Long.parseLong(laddress);
+                    Long fromStart = value - Long.parseLong(baseAddress);
 
                     switch (ctx.Get("type")) {
                         case "I": // (bne...) Salta para posicao em relacao ao pc atual
-
-//                System.out.println("TemplateListenerLabel::" + base + "|" + laddress + "|" + baseAddress + "|\n" + ctx);
-//                System.out.println("I Branch:{{\n" + base
-//                        + "\n:" + Integer.parseInt(ctx.Get(base))
-//                        + "\n:" + label
-//                        + "\n:" + value
-//                        + "\n:" + FormatNum(value, format)
-//                        + "\n}}");
-//                System.out.println("Tranalate>>>>>>>>> I:[" + address + "]" + ctx);
-                            //                address -= Integer.parseInt(ctx.Get("block.position"));
-                            break;
                         case "J": // (j | jal) Salta para o endereco de destino
-//                System.out.println(">>>>" + label + ":" + format + ":" + value + ":" + FormatNum(value, format));
-//                address = valueint;
                             break;
                         default:
                             System.out.println(String.format("Label type '%s' not defined", ctx.Get("type")));
                     }
-//        address = address * this.AddressGap;
-//        value = value * this.AddressGap;
-//        System.out.println("============LaBEL:" + label + ":" + format + ":" + value + ":" + base);
-//        System.out.println("============LaBEL:" + value + ":" + address);
 
                     return laddress.trim().equals("")
                             ? ""
@@ -142,7 +124,7 @@ public class MipsTemplate implements templates.TemplateDescription {
     protected static String ConvertBin(String inst, RegistroBase ctx, ArrayList<String> args) {
         try {
             Integer size;
-            String bin = MipsTemplate.INSTBIN(ctx, args);
+            String bin = MipsTemplateDescription.INSTBIN(ctx, args);
 
             if (Utils.Empty(bin)) {
                 return "";
@@ -199,10 +181,10 @@ public class MipsTemplate implements templates.TemplateDescription {
                 ctx.Set("target", Functions.BIN("" + shift, 26));
                 break;
             case "I": // (bne...) Salta para posicao em relacao ao pc atual + 4
+
 //                System.out.println("BIN iiiiii" + ctx);
 //                shift = (Long.parseLong(ctx.Get(ctx.Get("label")), 10) >> 2);
 //                ctx.Set("target", BIN("" + shift, 26));
-
 //                if (ctx.Get("offset").equals("") && !ctx.Get("label").equals("")) {
 //
 //                    int target = Integer.parseInt(ctx.Get(ctx.Get("label")));

+ 100 - 0
src/targets/mips/MipsUpdateAddressMiddleware.java

@@ -0,0 +1,100 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package targets.mips;
+
+import API.MiddlewareInterface;
+import common.Block;
+import common.Code;
+import common.Instruction;
+import common.Label;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class MipsUpdateAddressMiddleware implements MiddlewareInterface {
+
+    protected HashMap<String, Boolean> updateOffsetShift = new HashMap<String, Boolean>() {
+        {
+            put("beq", true);
+            put("bne", true);
+            put("blez", true);
+            put("bltz", true);
+            put("bgez", true);
+            put("bgtz", true);
+        }
+    };
+
+    public MipsUpdateAddressMiddleware() {
+    }
+
+    @Override
+
+    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
+        Long offset = 0L;
+        Label label;
+        for (Map.Entry<String, Block> x : c.Blocks().entrySet()) {
+            for (Instruction inst : x.getValue().Instructions()) {
+
+                // Atualziza o offset das instruições de branch
+                if (!updateOffsetShift.containsKey(inst.Get("inst"))) {
+                    continue;
+                }
+//                System.out.println("UPDATE ADDRESS: " + inst.Get("label") + " c.labels:" + c.labels);
+                label = c.labels.get(inst.Get("label"));
+//                offset = Integer.parseInt(def.get(0));
+//                offset = Integer.parseInt(def.get(1).split(""));
+
+//                System.out.println("Offset:" + +"----" +);
+//                offset = Integer.parseInt(def.get(0));
+//                offset = ((offset - inst.GetInt("global.position")) / 4) - 1;
+//                System.out.println("LABEL:"
+//                        + label.GetGlobalPosition()
+//                        + "/"
+//                        + Utils.FormatNum(label.GetGlobalPosition(), "hex")
+//                        + "/"
+//                        + inst.GetInt("global.position")
+//                        + "/"
+//                        + Utils.FormatNum(inst.GetInt("global.position"), "hex")
+//                );
+                offset = ((label.GetGlobalPosition() - inst.GetInt("global.position")) / 4) - 1;
+
+//                System.out.println("OffsetCalculado:" + offset);
+                inst.Set("offset", offset);
+            }
+        }
+
+//        System.out.println("Labels:" + c.labels);
+//        String[] parts;
+//        int index;
+        // Update address of labels
+//        for (Map.Entry<String, ArrayList<String>> entry : c.labels.entrySet()) {
+//            ArrayList<String> labeldata = entry.getValue();
+//            labeldata.set(0, (Integer.parseInt(labeldata.get(0)) * 4) + "");
+//            try {
+//                parts = labeldata.get(1).split("(\\+)");
+//                if (parts.length > 1) {
+//                    index = Integer.parseInt(parts[1]);
+//                    labeldata.set(1, parts[0] + "+" + (index * 4));
+//                }
+//            } catch (Exception e) {
+//            }
+//        }
+    }
+
+}
+// atualiza o indice da instrução de pc + 4
+//                if (inst.isNumber("global.position")) {
+//                    inst.Set("block.position", inst.GetInt("block.position") * 4);
+//                    inst.Set("global.position", inst.GetInt("global.position") * 4);
+//                } else if (inst.eq("type", "label")) {
+//                    // atualiza o endereco dos labels
+//                    inst.Set("reference.position", inst.GetInt("reference.position") * 4);
+//                    inst.Set("global.reference.position", inst.GetInt("global.reference.position") * 4);
+//                }

+ 0 - 92
src/targets/mips/MipsUpdateAddressProcessor.java

@@ -1,92 +0,0 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package targets.mips;
-
-import API.CodeProcessorInterface;
-import common.Block;
-import common.Code;
-import common.Instruction;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- *
- * @author EUGENIO CARVALHO
- */
-public class MipsUpdateAddressProcessor implements CodeProcessorInterface {
-
-    protected HashMap<String, Boolean> updateOffsetShift;/*
-            
-     public MipsUpdateAddressProcessor() {
-     }
-
-     (parseInt("2c",10) * 4).toString(16)
-     */
-
-
-    public MipsUpdateAddressProcessor() {
-        this.updateOffsetShift = new HashMap<String, Boolean>() {
-            {
-                put("beq", true);
-                put("bne", true);
-                put("blez", true);
-                put("bltz", true);
-                put("bgez", true);
-                put("bgtz", true);
-            }
-        };
-    }
-
-    @Override
-
-    public void Exec(Code c, LinkedHashMap<String, CodeProcessorInterface> cp) throws Exception {
-        Integer offset;
-        for (Map.Entry<String, Block> x : c.getBlocks().entrySet()) {
-            for (Instruction inst : x.getValue().Instructions()) {
-                // atualiza o indice da instrução de pc + 4
-                if (inst.isNumber("global.position")) {
-                    inst.Set("block.position", inst.getInt("block.position") * 4);
-                    inst.Set("global.position", inst.getInt("global.position") * 4);
-                } else if (inst.eq("type", "label")) {
-                    // atualiza o endereco dos labels
-                    inst.Set("reference.position", inst.getInt("reference.position") * 4);
-                    inst.Set("global.reference.position", inst.getInt("global.reference.position") * 4);
-                }
-                // Atualziza o offset das instruições de branch
-                if (updateOffsetShift.containsKey(inst.Get("inst"))) {
-
-//                    System.out.println("UPDATE ADDRESS: " + inst.Get("label") + " c.labels:" + c.labels);
-
-                    offset = Integer.parseInt(c.labels.get(inst.Get("label")).get(0)) * 4;
-//                    System.out.println("Offset:" + offset + "--" + y.getInt("global.position"));
-                    offset = ((offset - inst.getInt("global.position")) / 4) - 1;
-//                    System.out.println("OffsetCalculado:" + offset);
-                    inst.Set("offset", offset);
-                }
-            }
-        }
-
-//        System.out.println("Labels:" + c.labels);
-        String[] parts;
-        int index;
-        // Update address of labels
-        for (Map.Entry<String, ArrayList<String>> entry : c.labels.entrySet()) {
-            ArrayList<String> labeldata = entry.getValue();
-            labeldata.set(0, (Integer.parseInt(labeldata.get(0)) * 4) + "");
-            try {
-                parts = labeldata.get(1).split("(\\+)");
-                if (parts.length > 1) {
-                    index = Integer.parseInt(parts[1]);
-                    labeldata.set(1, parts[0] + "+" + (index * 4));
-                }
-            } catch (Exception e) {
-            }
-        }
-    }
-
-}

+ 0 - 210
src/targets/mips/TemplateFunctions.java

@@ -1,210 +0,0 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package targets.mips;
-
-/**
- *
- * @author EUGENIO CARVALHO
- */
-//class TemplateFunctions extends templates.TListener {
-//
-//    public HashMap<String, TPLInterface> templates;
-////    public int AddressGap = 1;
-//
-//    public TemplateFunctions(TemplateCtx ctx, TemplateCtx gctx) {
-//        super(ctx, gctx);
-//    }
-//
-//    @Override
-//    public void exitCall(TemplateParser.CallContext ctx) {
-//        try {
-//            ArrayList<String> arguments = ExecCall(ctx);
-//
-//            if (Utils.Empty(this.returnCall)) {
-//                switch (ctx.ID().getText()) {
-//                    case "OFFSET":
-//                        this.returnCall = OFFSET(arguments);
-//                        break;
-//                    case "INSTHEX":
-//                        this.returnCall = INSTHEX(arguments);
-//                        break;
-//                    case "INSTDEC":
-//                        this.returnCall = INSTDEC(arguments);
-//                        break;
-//                    case "INSTBIN":
-//                        this.returnCall = INSTBIN(arguments);
-//                        break;
-//                    case "BIN":
-//                        this.returnCall = BIN(arguments);
-//                    case "RBIN":
-//                        this.returnCall = RBIN(arguments);
-//                        break;
-//                }
-//            }
-//        } catch (Exception ex) {
-//            Logger.getLogger(TemplateFunctions.class.getName()).log(Level.SEVERE, null, ex);
-//        }
-//    }
-//
-////    public String OFFSET(ArrayList<String> args) {
-////        return args.get(0) + "(" + args.get(1) + ")";
-////    }
-//
-////    @Override
-////    protected String L(ArrayList<String> arguments) {
-////
-////        String label = arguments.get(0).trim();
-////
-////        if (label.equals("")) {
-////            return label;
-////        }
-////
-////        String format = (arguments.size() > 1) ? arguments.get(1) : "dec",
-////                // Corresponde ao nome do label que marca o inicio do bloco 
-////                base = gctx.G("label." + label).split("\\+")[0],
-////                // Corresponde ao endereco do label base (decimal)
-////                baseAddress = gctx.G(base),
-////                // Corresponde a posicao do label destino (decimal)
-////                laddress = gctx.G(label);
-////
-//////        System.out.printf("TemplateListener:{%s\n %s\n %s\n %s\n}\n", base, baseAddress, label, laddress);
-////        int value = Integer.parseInt(laddress);
-////        int fromStart = value - Integer.parseInt(baseAddress);
-////
-////        switch (ctx.Get("type")) {
-////            case "I": // (bne...) Salta para posicao em relacao ao pc atual
-////
-//////                System.out.println("TemplateListenerLabel::" + base + "|" + laddress + "|" + baseAddress + "|\n" + ctx);
-//////                System.out.println("I Branch:{{\n" + base
-//////                        + "\n:" + Integer.parseInt(gctx.Get(base))
-//////                        + "\n:" + label
-//////                        + "\n:" + value
-//////                        + "\n:" + FormatNum(value, format)
-//////                        + "\n}}");
-//////                System.out.println("Tranalate>>>>>>>>> I:[" + address + "]" + ctx);
-////                //                address -= Integer.parseInt(ctx.Get("block.position"));
-////                break;
-////            case "J": // (j | jal) Salta para o endereco de destino
-//////                System.out.println(">>>>" + label + ":" + format + ":" + value + ":" + FormatNum(value, format));
-//////                address = valueint;
-////                break;
-////            default:
-////                System.out.println(String.format("Label type '%s' not defined", ctx.Get("type")));
-////        }
-//////        address = address * this.AddressGap;
-//////        value = value * this.AddressGap;
-//////        System.out.println("============LaBEL:" + label + ":" + format + ":" + value + ":" + base);
-//////        System.out.println("============LaBEL:" + value + ":" + address);
-////
-////        return laddress.trim().equals("")
-////                ? ""
-////                : (FormatNum(value, format) + " <" + base + "+0x" + FormatNum(fromStart, format) + ">");
-////    }
-//
-//    // Converte um binario para hex
-////    protected String INSTHEX(ArrayList<String> arguments) {
-////        try {
-////            String bin = INSTBIN(arguments);
-////            if (Utils.Empty(bin)) {
-////                return "";
-////            }
-////            String hex = PAD(Long.toString(Long.parseLong(bin, 2), 16), "0", 8);
-////            ctx.Set("inst.hex", hex);
-////            return hex;
-////
-////        } catch (Exception e) {
-////            if (ctx.Get("inst").equals("bgtz")) {
-////                System.out.println("hex-Error:" + e.getMessage());
-////                e.printStackTrace();
-////            }
-////            return "error!";
-////        }
-////    }
-//
-////    100111101111011111111111111000 == addiu sp,sp,-8
-////    protected String INSTDEC(ArrayList<String> arguments) {
-////        try {
-////            String bin = INSTBIN(arguments);
-////            if (Utils.Empty(bin)) {
-////                return "";
-////            }
-////
-//////            System.out.println("Convertendo bin :" + arguments + ":" + bin + ":dec:" + Long.parseLong(bin, 2));
-////            String dec = PAD("" + Long.parseLong(bin, 2), "0", 10);
-////            ctx.Set("inst.dec", dec);
-////            return dec;
-////
-////        } catch (Exception e) {
-////            if (ctx.Get("inst").equals("bgtz")) {
-////                System.out.println("hex-Error:" + e.getMessage());
-////                e.printStackTrace();
-////            }
-////            return "error!";
-////        }
-////
-////    }
-//
-////    protected String INSTBIN(ArrayList<String> arguments) {
-////        String type = ctx.Get("type");
-////        if (type.equals("label")) {
-////            return "";
-////        }
-////
-////        long shift;
-////        //
-////        switch (type) {
-////            case "S": // (j | jal) Salta para o endereco de destino
-//////                System.out.println("instbin:" + ctx);
-////                break;
-////            case "J": // (j | jal) Salta para o endereco de destino
-//////                System.out.println("JUMP:" + gctx.Get(ctx.Get("label")) + ":"
-//////                        + (Long.parseLong(gctx.Get(ctx.Get("label")), 10) >> 2));
-////
-////                shift = (Long.parseLong(gctx.G(ctx.Get("label")), 10) >> 2);
-////                ctx.Set("target", BIN("" + shift, 26));
-////                break;
-////            case "I": // (bne...) Salta para posicao em relacao ao pc atual + 4
-//////                System.out.println("BIN iiiiii" + ctx);
-//////                shift = (Long.parseLong(gctx.Get(ctx.Get("label")), 10) >> 2);
-//////                ctx.Set("target", BIN("" + shift, 26));
-////
-//////                if (ctx.Get("offset").equals("") && !ctx.Get("label").equals("")) {
-//////
-//////                    int target = Integer.parseInt(gctx.Get(ctx.Get("label")));
-//////                    int position = Integer.parseInt(ctx.Get("global.position")) + 1;
-//////
-////////                    System.out.println("INSTBIN:->" + FormatNum(target - position, "hex"));
-//////                    ctx.Set("offset", (target - position) + "");
-//////
-//////                }
-//////                System.out.println("INSTBIN[" + type + ":" + bin + "]:" + ctx);
-////                break;
-////            case "R": // (bne...) Salta para posicao em relacao ao pc atual
-//////                System.out.println("INSTBIN[" + type + "]:" + ctx);
-////                break;
-////            default:
-////        }
-////        String bin = templates.get("bin." + type).Render(ctx);
-////        ctx.Set("inst.bin", bin);
-//////        System.out.println("bin." + type + "::" + bin);
-////        return bin;
-////    }
-//
-
-//
-////    protected String RBIN(ArrayList<String> arguments) {
-//////        System.out.println("RBIN(" + arguments + ")");
-////        String reg = arguments.get(0);
-////        if (reg.equals("")) {
-////            reg = "0";
-////        }
-////        if (!Utils.isNumber(reg)) {
-////            reg = Mips.Register(reg);
-////        }
-////        return Api.num2bin(reg, Integer.parseInt(arguments.get(1)));
-////    }
-//
-//}

File diff suppressed because it is too large
+ 316 - 296
src/targets/mips/Gen.java


+ 6 - 2
src/templates/Functions.java

@@ -8,6 +8,7 @@ package templates;
 import API.Api;
 import API.Utils;
 import common.RegistroBase;
+import exception.CompileException;
 import java.util.ArrayList;
 import java.util.HashMap;
 
@@ -71,8 +72,11 @@ public class Functions {
     }
 
     public static String Call(String id, RegistroBase ctx, ArrayList<String> args) throws Exception {
-//        System.out.println("Call " + id + " with args:" + args + ":" + ctx);
-        return Get(id).Call(ctx, args);
+        try {
+            return Get(id).Call(ctx, args);
+        } catch (Exception e) {
+            throw new CompileException("Erro na chamada '%s': %s", id, e.getMessage());
+        }
     }
 
     // Utils functions

+ 19 - 3
src/templates/RenderStmt.java

@@ -6,6 +6,7 @@
 package templates;
 
 import common.RegistroBase;
+import exception.CompileException;
 import org.antlr.v4.runtime.ANTLRInputStream;
 import org.antlr.v4.runtime.CommonTokenStream;
 import org.antlr.v4.runtime.TokenStream;
@@ -19,9 +20,13 @@ public class RenderStmt {
 
     protected ParseTreeWalker walker;
     protected TemplateParser.InitContext tree;
+    public final String ID;
+    private final String Format;
 
-    public RenderStmt(String format) {
-        ANTLRInputStream input = new ANTLRInputStream(format);
+    RenderStmt(String id, String format) {
+        ID = id;
+        Format = format;
+        ANTLRInputStream input = new ANTLRInputStream(Format);
         TemplateLexer lexer = new TemplateLexer(input);
         lexer.removeErrorListeners();
 
@@ -33,11 +38,22 @@ public class RenderStmt {
         walker = new ParseTreeWalker();
     }
 
-    public String Render(RegistroBase ctx) {
+    public String Render(RegistroBase ctx) throws CompileException {
 //        System.out.println("ctx:" + ctx);
 //        throw new Exception("assssssssssss");
         TListener listener = new TListener(ctx);
         walker.walk(listener, tree);
+        if (listener.hasError()) {
+//            System.out.println("ctx:" + ctx);
+
+            throw new CompileException(
+                    "Render: %s\nFormat: %s)\nError: %s",
+                    ID,
+                    Format,
+                    //                    ctx.Get("block.position"),
+                    listener.GetError()
+            );
+        }
         return listener.toString();
     }
 }

+ 16 - 3
src/templates/TListener.java

@@ -10,8 +10,7 @@ import common.RegistroBase;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.Stack;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+import templates.TemplateParser.CallContext;
 
 /**
  *
@@ -26,11 +25,16 @@ public class TListener extends TemplateBaseListener {
     protected String append;
     protected String returnCall;
     protected boolean suspend;
+    protected String Error = null;
 
     public TListener(RegistroBase ctx) {
         this.ctx = ctx;
     }
 
+    public String GetError() {
+        return Error;
+    }
+
     @Override
     public String toString() {
         return sb.toString(); //To change body of generated methods, choose Tools | Templates.
@@ -91,8 +95,9 @@ public class TListener extends TemplateBaseListener {
 
             super.exitCall(ctx); //To change body of generated methods, choose Tools | Templates.
         } catch (Exception ex) {
-            Logger.getLogger(TListener.class.getName()).log(Level.SEVERE, null, ex);
+            ThrowError(ctx, ex.getMessage());
         }
+
     }
 
     @Override
@@ -143,4 +148,12 @@ public class TListener extends TemplateBaseListener {
 
         super.exitArg(ctx); //To change body of generated methods, choose Tools | Templates.
     }
+
+    private void ThrowError(CallContext ctx, String message) {
+        Error = "<" + ctx.getStart().getLine() + ":" + ctx.getStart().getCharPositionInLine() + "> " + message;
+    }
+
+    public boolean hasError() {
+        return Error != null;
+    }
 }

+ 1 - 1
src/templates/Template.java

@@ -29,7 +29,7 @@ public abstract class Template {
 
     public static RenderStmt FormatRender(String id) throws Exception {
         if (!renders.containsKey(id)) {
-            renders.put(id, new RenderStmt(Format(id)));
+            renders.put(id, new RenderStmt(id, Format(id)));
         }
         return renders.get(id);
     }

+ 109 - 72
src/tools/mips/Memory.java

@@ -6,13 +6,7 @@
 package tools.mips;
 
 import API.Utils;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.nio.file.Paths;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Scanner;
+import java.util.TreeMap;
 
 /**
  *
@@ -20,115 +14,158 @@ import java.util.Scanner;
  */
 public class Memory {
 
+    public Integer WORD_BYTES_COUNT = 4;
+    protected String EMPTY_BYTE = "00000000";
     protected boolean writable;
     protected String file;
-    protected Integer size;
-    protected LinkedHashMap<Long, Long> data = new LinkedHashMap<>();
-    public boolean AllAddress = false;
+    protected Long size = 0L, localAddress = 0L;
+    protected TreeMap<Long, String> data = new TreeMap<>();
+    protected MemoryImportExportInterface io;
 
     public Memory ReadOnly() {
         this.writable = false;
         return this;
     }
 
+    public int WordBitSize() {
+        return WORD_BYTES_COUNT * 8;
+    }
+
     public Memory Writable() {
         this.writable = true;
         return this;
     }
 
-    public Memory(String filename, int size, boolean all) throws IOException {
-        this.file = filename;
+    public void Reset() {
+        data.entrySet().forEach((entry) -> {
+            entry.setValue(EMPTY_BYTE);
+        });
+    }
+
+    public Memory(long size) {
         this.size = size;
-        this.AllAddress = all;
-        if (all) {
-            for (long i = 0; i < size; i += 4) {
-                data.put(i, (long) 0);
-            }
-        }
+    }
 
-        if (!filename.equals("")) {
-            ReadFile();
+    public Memory(String filename, long size) throws Exception {
+        if (filename.equals("")) {
+            throw new Exception("Empty file not allowed.");
         }
+        this.file = filename;
+        this.size = size;
     }
 
-    public void Reset() {
-        for (long i = 0; i < size; i += 4) {
-            data.put(i, (long) 0);
-        }
+    public TreeMap<Long, String> Data() {
+        return data;
     }
 
     @Override
     public String toString() {
-        String out = "";
-        for (Map.Entry<Long, Long> o : data.entrySet()) {
-            out = out.concat(o.getKey() + "\t:\t" + o.getValue() + "\n");
+        try {
+            return Dump();
+        } catch (Exception ex) {
+            return ex.getMessage();
         }
+    }
 
-        return out;
-    }
-
-    protected void ReadFile() throws FileNotFoundException, IOException {
-        String current = Paths.get(".").toAbsolutePath().normalize().toString();
-//        String content = new String(Files.readAllBytes(Paths.get(current + file)));
-//        System.out.println("current + this.file:" + current + this.file);
-        long addr = -4;
-        Scanner sc = new Scanner(new File(current + this.file));
-        String value;
-        String[] parts;
-        while (sc.hasNextLine()) {
-//            content += sc.nextLine() + "\n";
-            value = sc.nextLine();
-            if (value.equals("")) {
-                continue;
-            }
-
-            parts = value.replaceAll("\\s+", "").split(":");
-//            System.out.println("parts:" + new ArrayList<String>(Arrays.asList(parts)));
-            if (parts.length == 1) {
-                addr += 4;
-            } else {
-                addr = Long.parseLong(parts[0], 10);
-                value = parts[1];
-            }
-
-//            System.out.println("Read:" + (long) addr + ":" + Long.parseLong(value, 10));
-
-            data.put((long) addr, Long.parseLong(value, 10));
-//            System.out.println("ReadFile:" + data.get(0));
+    protected void CheckIOSet() throws Exception {
+        if (io == null) {
+            throw new Exception("Interface de IO da memória não definida.");
         }
-//        System.out.println("ReadFiel:" + content);
     }
 
-    public long R(long address) throws Exception {
+    public String Dump() throws Exception {
+        CheckIOSet();
+        return io.DumpFile(this);
+    }
+
+    protected void ReadFile() throws Exception {
+        CheckIOSet();
+        io.FromFile(this);
+    }
+
+    public Long ReadLong(long address, int rsize) throws Exception {
+        return Long.parseLong(R(address, rsize), 2);
+    }
+
+    public String R(long address, int rsize) throws Exception {
         valid(address);
-        return data.get((address + size) % size);
+        String buffer = "";
+        for (int i = 0; i < rsize; i++) {
+            buffer += RB(address + i);
+        }
+        return Utils.Pad(buffer, "0", Utils.PAD_LEFT, 32);
     }
 
-    public void W(long address, long value) throws Exception {
+    public String RB(long address) throws Exception {
         valid(address);
-        data.put((address + size) % size, value);
+        address = (address + size) % size;
+        if (!data.containsKey(address)) {
+            data.put(address, EMPTY_BYTE);
+        }
+        return data.get(address);
     }
 
     protected void valid(long address) throws Exception {
-
-//        System.out.println("VALID:" + address + ":" + size);
         if (Math.abs(address) > size) {
             throw new Exception("Address '" + address + "' out of range limit " + size + "!");
         }
     }
 
-    public Memory Save() {
-        return Save(file);
+    public void WB(String sbyte) throws Exception {
+        WB(localAddress++, sbyte);
     }
 
-    public Memory Save(String filename) {
-        String out = "";
-        for (Map.Entry<Long, Long> entry : data.entrySet()) {
-            out = out.concat(Utils.Pad(4, "" + entry.getKey()) + ":\t" + entry.getValue() + "\n");
+    public void WB(Long address, String sbyte) throws Exception {
+        valid(address);
+
+        int len = sbyte.length();
+
+        if (len > 8) {
+            sbyte = sbyte.substring(sbyte.length() - 8);
+        } else if (len < 8) {
+            sbyte = Utils.Pad(sbyte, "0", Utils.PAD_LEFT, 8);
         }
-        Utils.WriteFile(filename, out);
 
+        data.put((address + size) % size, sbyte);
+    }
+
+    public void W(long address, long value, int wsize) throws Exception {
+        W(address, Long.toBinaryString(value), wsize);
+    }
+
+    public void W(long address, String bin, int wsize) throws Exception {
+        valid(address);
+        int bpos = 4 - wsize;
+
+        bin = Utils.Pad(bin, "0", Utils.PAD_LEFT, 32);
+
+        String[] bytes = Utils.SplitEach(bin, 8);
+
+        for (int i = 0; i < wsize; i++) {
+            WB(address + i, bytes[bpos + i]);
+        }
+    }
+
+    public Memory Save() throws Exception {
+        return Save(file);
+    }
+
+    public Memory Save(String filename) throws Exception {
+        // Grava o conteudo no arquivo
+        Utils.WriteFile(filename, Dump());
         return this;
     }
 
+    public void SetIO(MemoryImportExportInterface memoryInitializationFile) {
+        io = memoryInitializationFile;
+    }
+
+    public String File() {
+        return file;
+    }
+
+    public long Size() {
+        return size;
+    }
+
 }

+ 30 - 0
src/tools/mips/MemoryImportExportInterface.java

@@ -0,0 +1,30 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package tools.mips;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public interface MemoryImportExportInterface {
+
+    /**
+     * Lê o arquivo e preenche a memoria
+     *
+     * @param memory
+     * @throws Exception
+     */
+    public void FromFile(Memory memory) throws Exception;
+
+    /**
+     * Salva em arquivo o conteudo da memoria
+     *
+     * @param memory
+     * @throws Exception
+     */
+    public String DumpFile(Memory memory) throws Exception;
+
+}

+ 145 - 257
src/tools/mips/MipsProcessor.java

@@ -6,14 +6,13 @@
 package tools.mips;
 
 import API.Utils;
+import Export.MemoryInitializationFile;
 import common.Instruction;
 import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import targets.mips.Mips;
+import targets.mips.Descriprion;
 
 /**
  *
@@ -22,10 +21,11 @@ import targets.mips.Mips;
 public class MipsProcessor {
 
     public String ID = "default";
+    public Integer WORD = 4, BYTE = 1;
     public MipsSettings settings;
-    public Memory MD;
-    public Memory MI;
-    public long PC = 0;
+    public Memory DataMemory;
+    public Memory InstructionMemory;
+    public Long PC = 0L;
     public RegisterBank RBank;
     public HashMap<String, Instruction> instructions;
 
@@ -34,22 +34,25 @@ public class MipsProcessor {
     public MipsProcessor(MipsSettings settings) throws Exception {
 
         this.settings = new MipsSettings();
-        this.settings.Set("mode", "debug").Set("stepByStep", "false");
+        this.settings.Set("mode", "debug").Set("step.by.step", "false");
 
-        MI = new Memory(
+        InstructionMemory = new Memory(
                 settings.Get("memory.instruction"),
-                settings.getInt("memory.instruction.size"),
-                false
+                settings.GetInt("memory.instruction.size")
         );
-        MD = new Memory(
+        InstructionMemory.SetIO(new MemoryInitializationFile());
+        
+        DataMemory = new Memory(
                 settings.Get("memory.data"),
-                settings.getInt("memory.data.size"),
-                true
+                settings.GetInt("memory.data.size")
         );
+        DataMemory.SetIO(new MemoryInitializationFile());
+
+        WORD = 4;
 
         // Limpa todos os dados armazenados 
-//        MD.Reset();
-//        System.out.println("Init Md:" + MD.R(0L));
+//        DataMemory.Reset();
+//        System.out.println("Init Md:" + DataMemory.R(0L));
         RBank = new RegisterBank(32);
 
         InitInstructions();
@@ -57,7 +60,7 @@ public class MipsProcessor {
         this.settings.copy(
                 "debugmode,"
                 + "mode,"
-                + "stepByStep,"
+                + "step.by.step,"
                 + "breakpoints,"
                 + "memory.instruction,"
                 + "memory.instruction.size,"
@@ -66,22 +69,21 @@ public class MipsProcessor {
                 settings);
 
         SetBreak(this.settings.Get("breakpoints"));
-//        SetBreak("44,48,58,5c");
-//        InitInstructions2();
     }
 
     public MipsProcessor SetBreak(String address) {
-        for (String addr : address.split(",")) {
-            if (!addr.equals("")) {
-                breakPoint.put(addr, true);
+        for (String addrs : address.split(",")) {
+            if (!addrs.equals("")) {
+                for (String addr : addrs.split("-")) {
+                    breakPoint.put(addr, true);
+                }
             }
         }
         return this;
     }
 
-    public MipsProcessor Persist() {
-        MD.Save();
-
+    public MipsProcessor Persist() throws Exception {
+        DataMemory.Save();
         return this;
     }
 
@@ -89,63 +91,64 @@ public class MipsProcessor {
         if (!settings.eq("mode", "debug")) {
             return;
         }
-        if (breakPoint.size() > 0 && !breakPoint.containsKey(Integer.toHexString((int) PC))) {
+
+        if (breakPoint.size() > 0 && !breakPoint.containsKey(Long.toHexString(PC))) {
             return;
         }
 
         System.out.println(msg);
     }
 
-    public MipsProcessor Run() {
-        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
+    public MipsProcessor Run() throws Exception {
+        Instruction instruction;
+        Integer interation = 0;
+        String cAddress;
+        BufferedReader br = null;
+        Boolean stepByStep = settings.eq("step.by.step", "true");
+
+        if (stepByStep) {
+            br = new BufferedReader(new InputStreamReader(System.in));
+        }
+        // Carrega o conteudo das memorias
+        InstructionMemory.ReadFile();
+        DataMemory.ReadFile();
+
         // Fetch
-//        System.out.println("MI:" + MI);
+//        System.out.println("InstructionMemory:" + InstructionMemory);
         System.out.println("Start simulation ... " + ID);
-        System.out.println();
 
-        try {
-            Instruction instruction;
-            int i = 0;
-            String cAddress;
-            while (true) {
-                long inst = MI.R(PC);
+        while (true) {
 
-                instruction = Decode(inst);
+            instruction = Decode(InstructionMemory.R(PC, WORD));
 
-                if (instruction.eq("inst", "stop")) {
-                    break;
-                }
+            // Quando encontra a instrucao stop para a simulacao
+            if (instruction.eq("inst", "stop")) {
+                break;
+            }
 
-                cAddress = Integer.toHexString((int) PC);
+            cAddress = Long.toHexString(PC);
 
-                Log("Interation(" + (i++) + ")["
-                        + cAddress + "]"
-                        + instruction.Get("inst"));
+            Log("Interation(" + (interation++) + ")[" + cAddress + "]" + instruction.Get("inst"));
 
-                Execute(instruction);
+            // Executa a instrucao
+            Execute(instruction);
 
-                Log("Registradores(\n" + RBank
-                        + ")\b nextPC:" + Integer.toHexString((int) PC));
+            Log("Registradores(\n" + RBank + ")\n Next PC:" + Long.toHexString(PC));
 
-                if (settings.eq("stepByStep", "true")
-                        || breakPoint.containsKey(cAddress)) {
-                    br.readLine();
-                }
-                // Decode
-                // Exec
-                // Persist
-            } //        return true;
-        } catch (Exception ex) {
-            Logger.getLogger(MipsProcessor.class.getName()).log(Level.SEVERE, null, ex);
+            // Verifica o controle de execução do simulador
+            if ((stepByStep || breakPoint.containsKey(cAddress)) && br != null) {
+                br.readLine();
+            }
         }
         return this;
     }
 
-    public Instruction Decode(long instruction) {
-        int val = (int) instruction;
-        String bin = Utils.Pad(32, Integer.toBinaryString(val));
+    public Instruction Decode(String bin) {
+//        int val = (int) instruction;
+//        String bin = Utils.Pad(32, Integer.toBinaryString(val));
 //        System.out.println("Run:" + bin + ":" + bin.length());
         String codop = bin.substring(0, 6), key, func = "";
+
         if (codop.equals("000000")) {
             func = bin.substring(26);
             key = "@" + func;
@@ -153,12 +156,6 @@ public class MipsProcessor {
             key = codop;
         }
 
-//        System.out.println(">>: "
-//                //                + "\n" + instruction
-//                + "\n" + bin
-//                //                //                + "\n" + val
-//                //                + "\nKey:" + key
-//                + "\n" + instructions.Get(key));
         if (!instructions.containsKey(key)) {
             System.out.println("Não encontrou a instrução " + key);
             return null;
@@ -192,23 +189,16 @@ public class MipsProcessor {
                 i.Set("rt", Long.parseLong(rt, 2));
                 i.Set("imm", bin32ToDec(bin.substring(16)));
 
-//                System.out.println("II:" + bin.substring(16)
-//                        + "\n:" + bin32ToDec(Utils.padPreserveSignal(32, bin.substring(16)))
-//                        + "\n:" + (Long.parseLong(Utils.padPreserveSignal(32, bin.substring(16)), 2) >> 0)
-//                );
-//                System.out.println("IIII:" + bin32ToDec(bin.substring(16)));
                 break;
             case "J":
                 i.Set("addr.bin", bin.substring(6));
                 i.Set("imm", bin32ToDec(bin.substring(6)));
-//                System.out.println("JJJJ:" + bin32ToDec(bin.substring(6)));
         }
         return i;
     }
 
     public static long bin32ToDec(String bin) {
         bin = Utils.padPreserveSignal(32, bin);
-//        System.out.println("BIN32DEC:" + bin);
 
         if (bin.charAt(0) == '0') {
             return Long.parseLong(bin, 2);
@@ -223,18 +213,14 @@ public class MipsProcessor {
 
     }
 
-    public String IntToHexStr(Integer n) {
-        return IntToHexStr(n) + "";
-    }
-
     public Integer IntToHex(Integer n) {
         return Integer.valueOf(String.valueOf(n), 16);
     }
 
     protected void InitInstructions() {
-        instructions = new HashMap<String, Instruction>();
+        instructions = new HashMap<>();
         String key;
-        for (Map.Entry<String, Instruction> entry : Mips.Codops.entrySet()) {
+        for (Map.Entry<String, Instruction> entry : Descriprion.Codops.entrySet()) {
 //            String string = entry.getKey();
             Instruction instruction = entry.getValue();
 
@@ -243,14 +229,11 @@ public class MipsProcessor {
             if (instruction.eq("codop", "000000")) {
                 key = "@" + instruction.Get("func");
             }
-//            System.out.println("Add_Instruction: " + key + "\n");
-//            System.out.println("===" + entry.getKey());
             instructions.put(key, instruction);
         };
     }
 
     private void Execute(Instruction inst) throws Exception {
-//        System.out.println("Exec :" + inst);
 
         long rs = 0,
                 rt = 0,
@@ -261,12 +244,12 @@ public class MipsProcessor {
 
         switch (inst.Get("type")) {
             case "R":
-                rd = inst.getInt("rd");
-                shamt = inst.getInt("shamt");
+                rd = inst.GetInt("rd");
+                shamt = inst.GetInt("shamt");
                 hasImm = false;
             case "I":
-                rs = inst.getInt("rs");
-                rt = inst.getInt("rt");
+                rs = inst.GetInt("rs");
+                rt = inst.GetInt("rt");
             case "J":
                 if (hasImm) {
 //                    System.out.println("HAS_IMM:" + inst.Get("imm"));
@@ -403,9 +386,38 @@ public class MipsProcessor {
             case "lui":
                 RBank.W(rt, imm);
                 break;
+
+            case "lb":
+                RBank.W(
+                        rt,
+                        DataMemory.ReadLong(
+                                RBank.R(rs) + imm,
+                                BYTE // Apenas 1 byte
+                        ));
+
+                Log(String.format(
+                        "Load endereco '%d' <- '%d'\n",
+                        RBank.R(rs) + imm,
+                        DataMemory.ReadLong(RBank.R(rs) + imm, BYTE)
+                ));
+                break;
             case "lw":
-                RBank.W(rt, MD.R(RBank.R(rs) + imm));
-                Log(String.format("Load endereco '%d' <- '%d'\n", RBank.R(rs) + imm, MD.R(RBank.R(rs) + imm)));
+                // Escreve no banco de registradores no registrador enderecado por rt
+                RBank.W(
+                        rt,
+                        // Lê da memoria de dados uma palavra de 4 bytes
+                        DataMemory.ReadLong(
+                                // Endereco de leitura equivale ao conteudo do registrador rs + imediato
+                                RBank.R(rs) + imm,
+                                WORD
+                        ));
+
+                Log(String.format(
+                        "Load endereco '%d' <- '%d'\n",
+                        RBank.R(rs) + imm,
+                        DataMemory.ReadLong(RBank.R(rs) + imm, WORD)
+                ));
+
                 break;
             case "ori":
                 RBank.W(rt, RBank.R(rs) | imm);
@@ -413,8 +425,13 @@ public class MipsProcessor {
             case "slti":
 //            case "sltiu":
             case "sw":
+                DataMemory.W(
+                        RBank.R(rs) + imm,
+                        RBank.R(rt),
+                        WORD // uma palavra inteira
+                );
+
                 Log(String.format("Store '%d' no endereco '%d'\n", RBank.R(rt), RBank.R(rs) + imm));
-                MD.W(RBank.R(rs) + imm, RBank.R(rt));
                 break;
 //            case "xori":
             // J
@@ -426,176 +443,47 @@ public class MipsProcessor {
             default:
                 throw new Exception("Instrução " + inst.Get("inst") + " não definida!");
         }
-        PC += 4;
+        PC += WORD;
     }
 }
 
-//    protected void InitInstructions2() {
-//        HashMap<String, Integer> x = new HashMap<String, Integer>();
-//        //Constantes da instruções (Codop e Funct)
-//        x.put("FUNCT_ADD", 32);
-//        x.put("FUNCT_ADDU", 33);
-//        x.put("FUNCT_SUB", 34);
-//        x.put("FUNCT_SUBU", 35);
-//        x.put("FUNCT_MULT", 24);
-//        x.put("FUNCT_MULTU", 25);
-//        x.put("FUNCT_AND", 36);
-//        x.put("FUNCT_OR", 37);
-//        x.put("FUNCT_XOR", 38);
-//        x.put("FUNCT_NOR", 39);
-//        x.put("FUNCT_DIV", 26);
-//        x.put("FUNCT_DIVU", 27);
-//        x.put("FUNCT_SLT", 42);
-//
-//        x.put("FUNCT_SRL", 2);
-//        x.put("FUNCT_SLL", 0);
-//        x.put("FUNCT_SRA", 3);
-//        x.put("FUNCT_SRLV", 6);
-//        x.put("FUNCT_SLLV", 4);
-//        x.put("FUNCT_SRAV", 7);
-//
-//        x.put("FUNCT_MFHI", 16);
-//        x.put("FUNCT_MFLO", 18);
-//        x.put("FUNCT_JR", 8);
-//
-//        x.put("FUNCT_NOP", 63);
-//        x.put("NOP", 63);
-//
-////Constante dos CODOPs
-//        x.put("CODOP_ADDI", 8);
-//        x.put("CODOP_ADDIU", 9);
-//        x.put("CODOP_SLTI", 10);
-//        x.put("CODOP_SLTIU", 11);
-//        x.put("CODOP_ANDI", 12);
-//        x.put("CODOP_ORI", 13);
-//        x.put("CODOP_LUI", 15);
-//
-//        x.put("CODOP_LB", 32);
-//        x.put("CODOP_LH", 33);
-//        x.put("CODOP_LW", 35);
-//        x.put("CODOP_LBU", 36);
-//        x.put("CODOP_LHU", 37);
-//        x.put("CODOP_SB", 40);
-//        x.put("CODOP_SH", 41);
-//        x.put("CODOP_SW", 43);
-//
-//        x.put("CODOP_BGEZ", 1);
-//        x.put("CODOP_BEQ", 4);
-//        x.put("CODOP_BNE", 5);
-//        x.put("CODOP_BGTZ", 7);
-//
-//        x.put("CODOP_JUMP", 2);
-//        x.put("CODOP_JAL", 3);
-//
-//        x.put("CODOP_STOP", 63);
-////Constante das operações da ULA
-//        x.put("SOMA", 1);
-//        x.put("SUBTRACAO", 2);
-//        x.put("MULTIPLICACAO", 3);
-//        x.put("AND", 4);
-//        x.put("OR", 5);
-//        x.put("XOR", 6);
-//        x.put("NOR", 7);
-//        x.put("DIVISAO", 8);
-//        x.put("SLT", 9);
-//        x.put("SLTU", 10);
-//        x.put("LUI", 11);
-//
-//        x.put("SRL", 12);  //Faz o shift usando o campo shamt
-//        x.put("SLL", 13); //Faz o shift usando o campo shamt
-//        x.put("SRA", 14); //Faz o shift usando o campo shamt
-//
-//        x.put("SRLV", 15); //Faz o shift usando registrador
-//        x.put("SLLV", 16); //Faz o shift usando registrador
-//        x.put("SRAV", 17); //Faz o shift usando registrador
-//        x.put("MOVE", 18);
-//
-//        for (Map.Entry<String, Integer> entry : x.entrySet()) {
-//            String string = entry.getKey();
-//            System.out.println(string + ":" + Utils.Pad(6, Integer.toBinaryString(entry.getValue())));
-//        }
-//    }
-//CODOP_JUMP:000010
-//CODOP_LBU:100100
-//NOP:111111
-//CODOP_STOP:111111
-//FUNCT_DIVU:011011
-//CODOP_LH:100001
-//MULTIPLICACAO:000011
-//SRLV:001111
-//NOR:000111
-//SLL:001101
-//FUNCT_SRA:000011
-//CODOP_ANDI:001100
-//AND:000100
-//FUNCT_SRL:000010
-//CODOP_ORI:001101
-//SRAV:010001
-//SLT:001001
-//SUBTRACAO:000010
-//CODOP_LW:100011
-//FUNCT_ADD:100000
-//SOMA:000001
-//FUNCT_MULTU:011001
-//CODOP_SLTI:001010
-//SLLV:010000
-//SLTU:001010
-//FUNCT_MULT:011000
-//CODOP_ADDIU:001001
-//LUI:001011
-//CODOP_SH:101001
-//XOR:000110
-//FUNCT_MFLO:010010
-//FUNCT_SRAV:000111
-//DIVISAO:001000
-//SRL:001100
-//SRA:001110
-//CODOP_SB:101000
-//CODOP_ADDI:001000
-//FUNCT_JR:001000
-//FUNCT_MFHI:010000
-//FUNCT_NOR:100111
-//FUNCT_NOP:111111
-//FUNCT_SUBU:100011
-//FUNCT_OR:100101
-//FUNCT_AND:100100
-//FUNCT_XOR:100110
-//FUNCT_DIV:011010
-//FUNCT_SRLV:000110
-//FUNCT_ADDU:100001
-//CODOP_LUI:001111
-//CODOP_BGEZ:000001
-//MOVE:010010
-//CODOP_SLTIU:001011
-//CODOP_JAL:000011
-//OR:000101
-//CODOP_SW:101011
-//FUNCT_SUB:100010
-//FUNCT_SLLV:000100
-//CODOP_LB:100000
-//CODOP_BNE:000101
-//FUNCT_SLL:000000
-//CODOP_LHU:100101
-//CODOP_BGTZ:000111
-//CODOP_BEQ:000100
-//FUNCT_SLT:101010
-
-/*
-
- 1652044928
- 1100010011110000011010010000000
- 1100010011110000011010010000000
- 011000 10011110000011010010000000
- 011000
- 596080229
-
- 00100011100001110111011001100101 - js
- 100011100001110111011001100101
- 
- c
- 10010110000010000000001000101001 
-
+/**
+ * <main>: 0: 0201326595	jal c <preenche+0x0>	.0 -- jump to <preenche>
+ * 4: 0000000000	sll zero,zero,0	.0 -- Nop 8: 4294967295	stop -- End of programa
+ * <preenche>: c: 0666763252	addiu sp,sp,-12	-- prolog| push stack frame 10:
+ * 0001962017	addu fp,zero,sp	-- prolog|copy fp ← sp 14: 0605028353	addiu
+ * s0,zero,1	.0 -- copy _V1 ← 1 18: 2949644288	sw s0,fp,0	.1 -- store content of
+ * s0 in _V1 1c: 0605093888	addiu s1,zero,0	.2 -- copy _V2 ← 0 20: 2949709828	sw
+ * s1,fp,4	.3 -- store content of s1 in _V2 24: 0134217774	j b8 <preenche+0xac>
+ * .4 -- jump to preenche+_i3 28: 0000000000	sll zero,zero,0	.4 -- Nop 2c:
+ * 0605159424	addiu s2,zero,0	.5 -- copy _V3 ← 0 30: 2949775368	sw s2,fp,8	.6 --
+ * store content of s2 in _V3 34: 0134217764	j 90 <preenche+0x84>	.7 -- jump to
+ * preenche+_i7 38: 0000000000	sll zero,zero,0	.7 -- Nop 3c: 2412969988	lw
+ * s3,fp,4	.8 -- load content from _V2 in s3 40: 0000000000	sll zero,zero,0	.8
+ * -- Nop 44: 0001267745	addu t3,zero,s3	.9 -- copy _T4 ← _V2 48: 0000745536	sll
+ * t4,t3,1	.10 -- _T5 = _T4 << 1 4c: 2413035528	lw s4,fp,8	.11 -- load content
+ * from _V3 in s4 50: 0000000000	sll zero,zero,0	.11 -- Nop 54: 0001337377	addu
+ * t5,zero,s4	.12 -- copy _T7 ← _V3 58: 0026042401	addu t4,t4,t5	.13 -- _T5 =
+ * _T5 + _T7 5c: 0000815232	sll t6,t4,2	.14 -- _T11 = _T5 << 2 60: 2413101056	lw
+ * s5,fp,0	.15 -- load content from _V1 in s5 64: 0000000000	sll zero,zero,0	.15
+ * -- Nop 68: 0059666465	addu t6,gp,t6	.16 6c: 2916417536	sw s5,t6,0	.16 --
+ * store content of t6 in _G13[_T11] 70: 2413101056	lw s5,fp,0	.17 -- load
+ * content from _V1 in s5 74: 0000000000	sll zero,zero,0	.17 -- Nop 78:
+ * 0649396225	addiu s5,s5,1	.18 -- _V1 = _V1 + 1 7c: 2949971968	sw s5,fp,0	.19
+ * -- store content of s5 in _V1 80: 2413035528	lw s4,fp,8	.20 -- load content
+ * from _V3 in s4 84: 0000000000	sll zero,zero,0	.20 -- Nop 88: 0647233537	addiu
+ * s4,s4,1	.21 -- _V3 = _V3 + 1 8c: 2949906440	sw s4,fp,8	.22 -- store content
+ * of s4 in _V3 90: 2413232136	lw s7,fp,8	.23 -- load content from _V3 in s7 94:
+ * 0000000000	sll zero,zero,0	.23 -- Nop 98: 0604504066	addiu t0,zero,2	.24 9c:
+ * 0048762915	subu v0,s7,t0	.24 a0: 0071368678	bltz v0,3c <preenche+0x30>	.24 --
+ * branch if register < 0 a4: 0000000000	sll zero,zero,0	.24 -- Nop a8:
+ * 2412773380	lw s0,fp,4	.25 -- load content from _V2 in s0 ac: 0000000000	sll
+ * zero,zero,0	.25 -- Nop b0: 0638582785	addiu s0,s0,1	.26 -- _V2 = _V2 + 1 b4:
+ * 2949644292	sw s0,fp,4	.27 -- store content of s0 in _V2 b8: 2412838916	lw
+ * s1,fp,4	.28 -- load content from _V2 in s1 bc: 0000000000	sll zero,zero,0	.28
+ * -- Nop c0: 0604635138	addiu t2,zero,2	.29 c4: 0036311075	subu v0,s1,t2	.29
+ * c8: 0071368664	bltz v0,2c <preenche+0x20>	.29 -- branch if register < 0 cc:
+ * 0000000000	sll zero,zero,0	.29 -- Nop d0: 0666697740	addiu sp,sp,12	--
+ * epilog| pop stack frame d4: 0001962017	addu fp,zero,sp	-- epilog| pop stack
+ * frame d8: 0065011720	jr ra	-- epilog| return
  */
-//1652044928 -> 01010010000001000100100100101000 ->
-
-//0:  0062783480	addiu sp,sp,-8	

+ 1 - 1
src/tools/mips/RegisterBank.java

@@ -27,7 +27,7 @@ class RegisterBank {
         REG_HI = i;
         REG_LO = i + 1;
 
-        for (Map.Entry<String, String> en : targets.mips.Mips.registers.entrySet()) {
+        for (Map.Entry<String, String> en : targets.mips.Descriprion.registers.entrySet()) {
             names.add(en.getKey());
         }
         names.add("hi");

File diff suppressed because it is too large
+ 70 - 4096
src/tools/mips/memory/md.memory


+ 0 - 800
src/tools/mips/memory/md2.memory

@@ -1,800 +0,0 @@
-0:1
-4:2
-8:3
-12:4
-16:5
-20:6
-24:7
-28:8
-32:9
-36:10
-40:11
-44:12
-48:13
-52:14
-56:15
-60:16
-64:17
-68:18
-72:19
-76:20
-80:21
-84:22
-88:23
-92:24
-96:25
-100:26
-104:27
-108:28
-112:29
-116:30
-120:31
-124:32
-128:33
-132:34
-136:35
-140:36
-144:37
-148:38
-152:39
-156:40
-160:41
-164:42
-168:43
-172:44
-176:45
-180:46
-184:47
-188:48
-192:49
-196:50
-200:51
-204:52
-208:53
-212:54
-216:55
-220:56
-224:57
-228:58
-232:59
-236:60
-240:61
-244:62
-248:63
-252:64
-256:65
-260:66
-264:67
-268:68
-272:69
-276:70
-280:71
-284:72
-288:73
-292:74
-296:75
-300:76
-304:77
-308:78
-312:79
-316:80
-320:81
-324:82
-328:83
-332:84
-336:85
-340:86
-344:87
-348:88
-352:89
-356:90
-360:91
-364:92
-368:93
-372:94
-376:95
-380:96
-384:97
-388:98
-392:99
-396:100
-400:101
-404:102
-408:103
-412:104
-416:105
-420:106
-424:107
-428:108
-432:109
-436:110
-440:111
-444:112
-448:113
-452:114
-456:115
-460:116
-464:117
-468:118
-472:119
-476:120
-480:121
-484:122
-488:123
-492:124
-496:125
-500:126
-504:127
-508:128
-512:129
-516:130
-520:131
-524:132
-528:133
-532:134
-536:135
-540:136
-544:137
-548:138
-552:139
-556:140
-560:141
-564:142
-568:143
-572:144
-576:145
-580:146
-584:147
-588:148
-592:149
-596:150
-600:151
-604:152
-608:153
-612:154
-616:155
-620:156
-624:157
-628:158
-632:159
-636:160
-640:161
-644:162
-648:163
-652:164
-656:165
-660:166
-664:167
-668:168
-672:169
-676:170
-680:171
-684:172
-688:173
-692:174
-696:175
-700:176
-704:177
-708:178
-712:179
-716:180
-720:181
-724:182
-728:183
-732:184
-736:185
-740:186
-744:187
-748:188
-752:189
-756:190
-760:191
-764:192
-768:193
-772:194
-776:195
-780:196
-784:197
-788:198
-792:199
-796:200
-800:201
-804:202
-808:203
-812:204
-816:205
-820:206
-824:207
-828:208
-832:209
-836:210
-840:211
-844:212
-848:213
-852:214
-856:215
-860:216
-864:217
-868:218
-872:219
-876:220
-880:221
-884:222
-888:223
-892:224
-896:225
-900:226
-904:227
-908:228
-912:229
-916:230
-920:231
-924:232
-928:233
-932:234
-936:235
-940:236
-944:237
-948:238
-952:239
-956:240
-960:241
-964:242
-968:243
-972:244
-976:245
-980:246
-984:247
-988:248
-992:249
-996:250
-1000:251
-1004:252
-1008:253
-1012:254
-1016:255
-1020:256
-1024:257
-1028:258
-1032:259
-1036:260
-1040:261
-1044:262
-1048:263
-1052:264
-1056:265
-1060:266
-1064:267
-1068:268
-1072:269
-1076:270
-1080:271
-1084:272
-1088:273
-1092:274
-1096:275
-1100:276
-1104:277
-1108:278
-1112:279
-1116:280
-1120:281
-1124:282
-1128:283
-1132:284
-1136:285
-1140:286
-1144:287
-1148:288
-1152:289
-1156:290
-1160:291
-1164:292
-1168:293
-1172:294
-1176:295
-1180:296
-1184:297
-1188:298
-1192:299
-1196:300
-1200:301
-1204:302
-1208:303
-1212:304
-1216:305
-1220:306
-1224:307
-1228:308
-1232:309
-1236:310
-1240:311
-1244:312
-1248:313
-1252:314
-1256:315
-1260:316
-1264:317
-1268:318
-1272:319
-1276:320
-1280:321
-1284:322
-1288:323
-1292:324
-1296:325
-1300:326
-1304:327
-1308:328
-1312:329
-1316:330
-1320:331
-1324:332
-1328:333
-1332:334
-1336:335
-1340:336
-1344:337
-1348:338
-1352:339
-1356:340
-1360:341
-1364:342
-1368:343
-1372:344
-1376:345
-1380:346
-1384:347
-1388:348
-1392:349
-1396:350
-1400:351
-1404:352
-1408:353
-1412:354
-1416:355
-1420:356
-1424:357
-1428:358
-1432:359
-1436:360
-1440:361
-1444:362
-1448:363
-1452:364
-1456:365
-1460:366
-1464:367
-1468:368
-1472:369
-1476:370
-1480:371
-1484:372
-1488:373
-1492:374
-1496:375
-1500:376
-1504:377
-1508:378
-1512:379
-1516:380
-1520:381
-1524:382
-1528:383
-1532:384
-1536:385
-1540:386
-1544:387
-1548:388
-1552:389
-1556:390
-1560:391
-1564:392
-1568:393
-1572:394
-1576:395
-1580:396
-1584:397
-1588:398
-1592:399
-1596:400
-1600:1
-1604:2
-1608:3
-1612:4
-1616:5
-1620:6
-1624:7
-1628:8
-1632:9
-1636:10
-1640:11
-1644:12
-1648:13
-1652:14
-1656:15
-1660:16
-1664:17
-1668:18
-1672:19
-1676:20
-1680:21
-1684:22
-1688:23
-1692:24
-1696:25
-1700:26
-1704:27
-1708:28
-1712:29
-1716:30
-1720:31
-1724:32
-1728:33
-1732:34
-1736:35
-1740:36
-1744:37
-1748:38
-1752:39
-1756:40
-1760:41
-1764:42
-1768:43
-1772:44
-1776:45
-1780:46
-1784:47
-1788:48
-1792:49
-1796:50
-1800:51
-1804:52
-1808:53
-1812:54
-1816:55
-1820:56
-1824:57
-1828:58
-1832:59
-1836:60
-1840:61
-1844:62
-1848:63
-1852:64
-1856:65
-1860:66
-1864:67
-1868:68
-1872:69
-1876:70
-1880:71
-1884:72
-1888:73
-1892:74
-1896:75
-1900:76
-1904:77
-1908:78
-1912:79
-1916:80
-1920:81
-1924:82
-1928:83
-1932:84
-1936:85
-1940:86
-1944:87
-1948:88
-1952:89
-1956:90
-1960:91
-1964:92
-1968:93
-1972:94
-1976:95
-1980:96
-1984:97
-1988:98
-1992:99
-1996:100
-2000:101
-2004:102
-2008:103
-2012:104
-2016:105
-2020:106
-2024:107
-2028:108
-2032:109
-2036:110
-2040:111
-2044:112
-2048:113
-2052:114
-2056:115
-2060:116
-2064:117
-2068:118
-2072:119
-2076:120
-2080:121
-2084:122
-2088:123
-2092:124
-2096:125
-2100:126
-2104:127
-2108:128
-2112:129
-2116:130
-2120:131
-2124:132
-2128:133
-2132:134
-2136:135
-2140:136
-2144:137
-2148:138
-2152:139
-2156:140
-2160:141
-2164:142
-2168:143
-2172:144
-2176:145
-2180:146
-2184:147
-2188:148
-2192:149
-2196:150
-2200:151
-2204:152
-2208:153
-2212:154
-2216:155
-2220:156
-2224:157
-2228:158
-2232:159
-2236:160
-2240:161
-2244:162
-2248:163
-2252:164
-2256:165
-2260:166
-2264:167
-2268:168
-2272:169
-2276:170
-2280:171
-2284:172
-2288:173
-2292:174
-2296:175
-2300:176
-2304:177
-2308:178
-2312:179
-2316:180
-2320:181
-2324:182
-2328:183
-2332:184
-2336:185
-2340:186
-2344:187
-2348:188
-2352:189
-2356:190
-2360:191
-2364:192
-2368:193
-2372:194
-2376:195
-2380:196
-2384:197
-2388:198
-2392:199
-2396:200
-2400:201
-2404:202
-2408:203
-2412:204
-2416:205
-2420:206
-2424:207
-2428:208
-2432:209
-2436:210
-2440:211
-2444:212
-2448:213
-2452:214
-2456:215
-2460:216
-2464:217
-2468:218
-2472:219
-2476:220
-2480:221
-2484:222
-2488:223
-2492:224
-2496:225
-2500:226
-2504:227
-2508:228
-2512:229
-2516:230
-2520:231
-2524:232
-2528:233
-2532:234
-2536:235
-2540:236
-2544:237
-2548:238
-2552:239
-2556:240
-2560:241
-2564:242
-2568:243
-2572:244
-2576:245
-2580:246
-2584:247
-2588:248
-2592:249
-2596:250
-2600:251
-2604:252
-2608:253
-2612:254
-2616:255
-2620:256
-2624:257
-2628:258
-2632:259
-2636:260
-2640:261
-2644:262
-2648:263
-2652:264
-2656:265
-2660:266
-2664:267
-2668:268
-2672:269
-2676:270
-2680:271
-2684:272
-2688:273
-2692:274
-2696:275
-2700:276
-2704:277
-2708:278
-2712:279
-2716:280
-2720:281
-2724:282
-2728:283
-2732:284
-2736:285
-2740:286
-2744:287
-2748:288
-2752:289
-2756:290
-2760:291
-2764:292
-2768:293
-2772:294
-2776:295
-2780:296
-2784:297
-2788:298
-2792:299
-2796:300
-2800:301
-2804:302
-2808:303
-2812:304
-2816:305
-2820:306
-2824:307
-2828:308
-2832:309
-2836:310
-2840:311
-2844:312
-2848:313
-2852:314
-2856:315
-2860:316
-2864:317
-2868:318
-2872:319
-2876:320
-2880:321
-2884:322
-2888:323
-2892:324
-2896:325
-2900:326
-2904:327
-2908:328
-2912:329
-2916:330
-2920:331
-2924:332
-2928:333
-2932:334
-2936:335
-2940:336
-2944:337
-2948:338
-2952:339
-2956:340
-2960:341
-2964:342
-2968:343
-2972:344
-2976:345
-2980:346
-2984:347
-2988:348
-2992:349
-2996:350
-3000:351
-3004:352
-3008:353
-3012:354
-3016:355
-3020:356
-3024:357
-3028:358
-3032:359
-3036:360
-3040:361
-3044:362
-3048:363
-3052:364
-3056:365
-3060:366
-3064:367
-3068:368
-3072:369
-3076:370
-3080:371
-3084:372
-3088:373
-3092:374
-3096:375
-3100:376
-3104:377
-3108:378
-3112:379
-3116:380
-3120:381
-3124:382
-3128:383
-3132:384
-3136:385
-3140:386
-3144:387
-3148:388
-3152:389
-3156:390
-3160:391
-3164:392
-3168:393
-3172:394
-3176:395
-3180:396
-3184:397
-3188:398
-3192:399
-3196:400

+ 249 - 83
src/tools/mips/memory/mi.memory

@@ -1,83 +1,249 @@
-0666763216
-0001962017
-0605028352
-2949644288
-0605103921
-2949709840
-0605159425
-2945581056
-0605224960
-2949840928
-0134217758
-0000000000
-2413035536
-0000000000
-0001318945
-0201326632
-0000000000
-0000155681
-2413101056
-0000000000
-0044869665
-2949971968
-2413166608
-0000000000
-0651558914
-2950037520
-2413232160
-0000000000
-0653721601
-2950103072
-2412773408
-0000000000
-0604962826
-0034541603
-0071368681
-0000000000
-2412838912
-0000000000
-0001118241
-4294967295
-0666763232
-0001962017
-2412773376
-0000000000
-2948857856
-0605093888
-2949709840
-2412773376
-0000000000
-0033558563
-0406847509
-0000000000
-0134217798
-0000000000
-2412904464
-0000000000
-0642908161
-2949775376
-2412969984
-0000000000
-0644677631
-2412969984
-0000000000
-0040671268
-2949840896
-0000000000
-2412969984
-0000000000
-0308281347
-0000000000
-0134217782
-0000000000
-2408841220
-2413101072
-0000000000
-0043360289
-2945712132
-2413101072
-0000000000
-0001380385
-0666697760
-0001962017
-0065011720
+-- Copyright (C) 1991-2014 Altera Corporation. All rights reserved.
+-- Your use of Altera Corporation's design tools, logic functions
+-- and other software and tools, and its AMPP partner logic
+-- functions, and any output files from any of the foregoing
+-- (including device programming or simulation files), and any
+-- associated documentation or information are expressly subject
+-- to the terms and conditions of the Altera Program License
+-- Subscription Agreement, the Altera Quartus II License Agreement,
+-- the Altera MegaCore Function License Agreement, or other
+-- (including device programming or simulation files), and any
+-- applicable license agreement, including, without limitation,
+-- that your use is for the sole purpose of programming logic 
+-- devices manufactured by Altera and sold by Altera or its 
+-- authorized distributors.  Please refer to the applicable 
+-- agreement for further details.
+-- Quartus II generated Memory Initialization File (.mif)
+
+WIDTH = 32;
+DEPTH = 16384;
+
+ADDRESS_RADIX = DEC;
+DATA_RADIX = BIN;
+
+CONTENT
+BEGIN
+000:	00001100000000000000000000000101;	% dec 201326597 %
+004:	00000000000000000000000000000000;	% dec 0 %
+008:	00001100000000000000000001011000;	% dec 201326680 %
+012:	00000000000000000000000000000000;	% dec 0 %
+016:	11111111111111111111111111111111;	% dec 4294967295 %
+020:	00100111101111011111111111101000;	% dec 666763240 %
+024:	00000000000111011111000000100001;	% dec 1962017 %
+028:	00100100000100000000000000000001;	% dec 605028353 %
+032:	10101111110100000000000000000000;	% dec 2949644288 %
+036:	00100100000100010000000000000100;	% dec 605093892 %
+040:	10101111110100010000000000000100;	% dec 2949709828 %
+044:	00100100000100100000000000000100;	% dec 605159428 %
+048:	10101111110100100000000000001000;	% dec 2949775368 %
+052:	00100100000100110000000000000000;	% dec 605224960 %
+056:	10101111110100110000000000001100;	% dec 2949840908 %
+060:	00001000000000000000000001001111;	% dec 134217807 %
+064:	00000000000000000000000000000000;	% dec 0 %
+068:	00100100000101000000000000000000;	% dec 605290496 %
+072:	10101111110101000000000000010000;	% dec 2949906448 %
+076:	00001000000000000000000001000101;	% dec 134217797 %
+080:	00000000000000000000000000000000;	% dec 0 %
+084:	10001111110101010000000000001100;	% dec 2413101068 %
+088:	00000000000000000000000000000000;	% dec 0 %
+092:	00010010101000000000000000000110;	% dec 312475654 %
+096:	00000000000000000000000000000000;	% dec 0 %
+100:	10001111110101100000000000001100;	% dec 2413166604 %
+104:	10001111110101110000000000000100;	% dec 2413232132 %
+108:	00000000000000000000000000000000;	% dec 0 %
+112:	00010010110101110000000000010110;	% dec 316080150 %
+116:	00000000000000000000000000000000;	% dec 0 %
+120:	00100100000100000000000000000000;	% dec 605028352 %
+124:	10101111110100000000000000010100;	% dec 2949644308 %
+128:	10001111110100010000000000010000;	% dec 2412838928 %
+132:	00000000000000000000000000000000;	% dec 0 %
+136:	00010010001000000000000000000110;	% dec 304087046 %
+140:	00000000000000000000000000000000;	% dec 0 %
+144:	10001111110100100000000000010000;	% dec 2412904464 %
+148:	10001111110100110000000000001000;	% dec 2412969992 %
+152:	00000000000000000000000000000000;	% dec 0 %
+156:	00010010010100110000000000001011;	% dec 307429387 %
+160:	00000000000000000000000000000000;	% dec 0 %
+164:	00100100000101000000000000000000;	% dec 605290496 %
+168:	10101111110101000000000000010100;	% dec 2949906452 %
+172:	10001111110101010000000000000000;	% dec 2413101056 %
+176:	00000000000000000000000000000000;	% dec 0 %
+180:	00000000000101011010000000100001;	% dec 1417249 %
+184:	10101111110101000000000000010100;	% dec 2949906452 %
+188:	10001111110101010000000000000000;	% dec 2413101056 %
+192:	00000000000000000000000000000000;	% dec 0 %
+196:	00100110101101010000000000000001;	% dec 649396225 %
+200:	10101111110101010000000000000000;	% dec 2949971968 %
+204:	10001111110101100000000000001100;	% dec 2413166604 %
+208:	00000000000000000000000000000000;	% dec 0 %
+212:	00000000000101100100100000100001;	% dec 1460257 %
+216:	00000000000010010101000010000000;	% dec 610432 %
+220:	00000001001010100100100000100001;	% dec 19548193 %
+224:	10001111110101110000000000010000;	% dec 2413232144 %
+228:	00000000000000000000000000000000;	% dec 0 %
+232:	00000000000101110101100000100001;	% dec 1529889 %
+236:	00000001001010110100100000100001;	% dec 19613729 %
+240:	00000000000010010110000010000000;	% dec 614528 %
+244:	10001111110100000000000000010100;	% dec 2412773396 %
+248:	00000000000000000000000000000000;	% dec 0 %
+252:	00000011100011000110000000100001;	% dec 59531297 %
+256:	10101101100100000000000000000000;	% dec 2911895552 %
+260:	10001111110101110000000000010000;	% dec 2413232144 %
+264:	00000000000000000000000000000000;	% dec 0 %
+268:	00100110111101110000000000000001;	% dec 653721601 %
+272:	10101111110101110000000000010000;	% dec 2950103056 %
+276:	10001111110100100000000000010000;	% dec 2412904464 %
+280:	00000000000000000000000000000000;	% dec 0 %
+284:	00100100000011100000000000000101;	% dec 604897285 %
+288:	00000010010011100001000000100011;	% dec 38670371 %
+292:	00000100010000001111111111001011;	% dec 71368651 %
+296:	00000000000000000000000000000000;	% dec 0 %
+300:	10001111110100110000000000001100;	% dec 2412969996 %
+304:	00000000000000000000000000000000;	% dec 0 %
+308:	00100110011100110000000000000001;	% dec 645070849 %
+312:	10101111110100110000000000001100;	% dec 2949840908 %
+316:	10001111110101000000000000001100;	% dec 2413035532 %
+320:	00000000000000000000000000000000;	% dec 0 %
+324:	00100100000110000000000000000101;	% dec 605552645 %
+328:	00000010100110000001000000100011;	% dec 43520035 %
+332:	00000100010000001111111110111101;	% dec 71368637 %
+336:	00000000000000000000000000000000;	% dec 0 %
+340:	00100111101111010000000000011000;	% dec 666697752 %
+344:	00000000000111011111000000100001;	% dec 1962017 %
+348:	00000011111000000000000000001000;	% dec 65011720 %
+352:	00100111101111011111111111101100;	% dec 666763244 %
+356:	00000000000111011111000000100001;	% dec 1962017 %
+360:	00100100000100000000000000000100;	% dec 605028356 %
+364:	10101111110100000000000000000000;	% dec 2949644288 %
+368:	00100100000100010000000000000100;	% dec 605093892 %
+372:	10101111110100010000000000000100;	% dec 2949709828 %
+376:	00100100000100100000000000000001;	% dec 605159425 %
+380:	10101111110100100000000000001000;	% dec 2949775368 %
+384:	00001000000000000000000011010110;	% dec 134217942 %
+388:	00000000000000000000000000000000;	% dec 0 %
+392:	00100100000100110000000000000001;	% dec 605224961 %
+396:	10101111110100110000000000001100;	% dec 2949840908 %
+400:	00001000000000000000000011001100;	% dec 134217932 %
+404:	00000000000000000000000000000000;	% dec 0 %
+408:	10001111110101000000000000001000;	% dec 2413035528 %
+412:	00000000000000000000000000000000;	% dec 0 %
+416:	00100110100011011111111111111111;	% dec 646840319 %
+420:	00000000000011010111000010000000;	% dec 880768 %
+424:	00000001101011100110100000100001;	% dec 28207137 %
+428:	10001111110101010000000000001100;	% dec 2413101068 %
+432:	00000000000000000000000000000000;	% dec 0 %
+436:	00000000000101010111100000100001;	% dec 1407009 %
+440:	00000001101011110110100000100001;	% dec 28272673 %
+444:	00000000000011011100000010000000;	% dec 901248 %
+448:	00000011100110001100000000100001;	% dec 60342305 %
+452:	10001111000010000000000000000000;	% dec 2399666176 %
+456:	10001111110101000000000000001000;	% dec 2413035528 %
+460:	00000000000000000000000000000000;	% dec 0 %
+464:	00000000000101000100100000100001;	% dec 1329185 %
+468:	00000000000010010101000010000000;	% dec 610432 %
+472:	00000001001010100100100000100001;	% dec 19548193 %
+476:	10001111110101010000000000001100;	% dec 2413101068 %
+480:	00000000000000000000000000000000;	% dec 0 %
+484:	00100110101011001111111111111111;	% dec 648871935 %
+488:	00000001001011000100100000100001;	% dec 19679265 %
+492:	00000000000010010111000010000000;	% dec 618624 %
+496:	00000011100011100111000000100001;	% dec 59666465 %
+500:	10001101110101110000000000000000;	% dec 2379677696 %
+504:	00000000000000000000000000000000;	% dec 0 %
+508:	00000000000101110111100000100001;	% dec 1538081 %
+512:	00000001000011110110100000100001;	% dec 17786913 %
+516:	10001111110101000000000000001000;	% dec 2413035528 %
+520:	00000000000000000000000000000000;	% dec 0 %
+524:	00000000000101001100000000100001;	% dec 1359905 %
+528:	00000000000110000101000010000000;	% dec 1593472 %
+532:	00000011000010101100000000100001;	% dec 51036193 %
+536:	10001111110101010000000000001100;	% dec 2413101068 %
+540:	00000000000000000000000000000000;	% dec 0 %
+544:	00100110101011000000000000000001;	% dec 648806401 %
+548:	00000011000011001100000000100001;	% dec 51167265 %
+552:	00000000000110000100100010000000;	% dec 1591424 %
+556:	00000011100010010100100000100001;	% dec 59328545 %
+560:	10001101001100000000000000000000;	% dec 2368733184 %
+564:	00000000000000000000000000000000;	% dec 0 %
+568:	00000000000100000111000000100001;	% dec 1077281 %
+572:	00000001101011100100000000100001;	% dec 28196897 %
+576:	10001111110101000000000000001000;	% dec 2413035528 %
+580:	00000000000000000000000000000000;	% dec 0 %
+584:	00100110100010100000000000000001;	% dec 646578177 %
+588:	00000000000010100101100010000000;	% dec 678016 %
+592:	00000001010010110101000000100001;	% dec 21712929 %
+596:	10001111110101010000000000001100;	% dec 2413101068 %
+600:	00000000000000000000000000000000;	% dec 0 %
+604:	00000000000101010110000000100001;	% dec 1400865 %
+608:	00000001010011000101000000100001;	% dec 21778465 %
+612:	00000000000010101100000010000000;	% dec 704640 %
+616:	00000011100110001100000000100001;	% dec 60342305 %
+620:	10001111000100010000000000000000;	% dec 2400256000 %
+624:	00000000000000000000000000000000;	% dec 0 %
+628:	00000000000100010100100000100001;	% dec 1132577 %
+632:	00000001000010010110100000100001;	% dec 17393697 %
+636:	10001111110101000000000000001000;	% dec 2413035528 %
+640:	00000000000000000000000000000000;	% dec 0 %
+644:	00000000000101000111000000100001;	% dec 1339425 %
+648:	00000000000011100111100010000000;	% dec 948352 %
+652:	00000001110011110111000000100001;	% dec 30371873 %
+656:	10001111110101010000000000001100;	% dec 2413101068 %
+660:	00000000000000000000000000000000;	% dec 0 %
+664:	00000000000101010101100000100001;	% dec 1398817 %
+668:	00000001110010110111000000100001;	% dec 30109729 %
+672:	00000000000011100110000010000000;	% dec 942208 %
+676:	00000011100011000110000000100001;	% dec 59531297 %
+680:	10001101100100100000000000000000;	% dec 2375155712 %
+684:	00000000000000000000000000000000;	% dec 0 %
+688:	00000000000100100101000000100001;	% dec 1200161 %
+692:	00100100000110000000000000000100;	% dec 605552644 %
+696:	00000001010110000100000000011000;	% dec 22560792 %
+700:	00000000000000000100000000010010;	% dec 16402 %
+704:	00000001101010001001100000100011;	% dec 27826211 %
+708:	10101111110100110000000000010000;	% dec 2949840912 %
+712:	10001111110100110000000000010000;	% dec 2412970000 %
+716:	00000000000000000000000000000000;	% dec 0 %
+720:	00100100000010010000000011111111;	% dec 604569855 %
+724:	00000010011010010001000000100011;	% dec 40439843 %
+728:	00011000010000000000000000000011;	% dec 406847491 %
+732:	00000000000000000000000000000000;	% dec 0 %
+736:	00100100000101100000000011111111;	% dec 605421823 %
+740:	10101111110101100000000000010000;	% dec 2950037520 %
+744:	10001111110101110000000000001000;	% dec 2413232136 %
+748:	00000000000000000000000000000000;	% dec 0 %
+752:	00000000000101110101100000100001;	% dec 1529889 %
+756:	00000000000010110111000010000000;	% dec 749696 %
+760:	00000001011011100101100000100001;	% dec 24008737 %
+764:	10001111110100000000000000001100;	% dec 2412773388 %
+768:	00000000000000000000000000000000;	% dec 0 %
+772:	00000000000100000110000000100001;	% dec 1073185 %
+776:	00000001011011000101100000100001;	% dec 23877665 %
+780:	00000000000010110101000010000000;	% dec 741504 %
+784:	10001111110100010000000000010000;	% dec 2412838928 %
+788:	00000000000000000000000000000000;	% dec 0 %
+792:	00000011100010100101000000100001;	% dec 59396129 %
+796:	10101101010100010000000001100100;	% dec 2907766884 %
+800:	10001111110100000000000000001100;	% dec 2412773388 %
+804:	00000000000000000000000000000000;	% dec 0 %
+808:	00100110000100000000000000000001;	% dec 638582785 %
+812:	10101111110100000000000000001100;	% dec 2949644300 %
+816:	10001111110101010000000000001100;	% dec 2413101068 %
+820:	10001111110100100000000000000100;	% dec 2412904452 %
+824:	00000000000000000000000000000000;	% dec 0 %
+828:	00000010101100100001000000100011;	% dec 45223971 %
+832:	00000100010000001111111110010101;	% dec 71368597 %
+836:	00000000000000000000000000000000;	% dec 0 %
+840:	10001111110100110000000000001000;	% dec 2412969992 %
+844:	00000000000000000000000000000000;	% dec 0 %
+848:	00100110011100110000000000000001;	% dec 645070849 %
+852:	10101111110100110000000000001000;	% dec 2949840904 %
+856:	10001111110101100000000000001000;	% dec 2413166600 %
+860:	10001111110101110000000000000000;	% dec 2413232128 %
+864:	00000000000000000000000000000000;	% dec 0 %
+868:	00000010110101110001000000100011;	% dec 47648803 %
+872:	00000100010000001111111110000111;	% dec 71368583 %
+876:	00000000000000000000000000000000;	% dec 0 %
+880:	00100111101111010000000000010100;	% dec 666697748 %
+884:	00000000000111011111000000100001;	% dec 1962017 %
+888:	00000011111000000000000000001000;	% dec 65011720 %
+END;

+ 0 - 74
src/tools/mips/memory/mi2.memory

@@ -1,74 +0,0 @@
-0604241920
-0666763232
-2948464664
-2948530204
-0001962017
-2948857856
-2412773376
-0605093888
-0638713861
-0001087521
-0134217786
-0605290496
-0134217782
-0605356032
-0134217767
-0001269793
-0000811136
-0000813184
-0026042401
-0001404961
-0026107937
-0000817280
-0059734049
-2381709312
-0001490977
-0001392673
-0000540800
-0000542848
-0017383457
-0001331233
-0017448993
-0000546944
-0059463713
-2373387840
-0001533985
-0051212312
-0000028690
-0036603937
-0649396225
-0604962836
-0045027363
-0071368677
-0001263649
-0000608384
-0000610432
-0019548193
-0001327137
-0019417121
-0000612480
-0059463713
-2909867136
-0605093888
-2949709828
-0647233537
-0604897300
-0042864675
-0071368660
-0645070849
-0041029667
-0071368655
-0605421584
-2945848000
-0201326660
-2948726816
-2411593752
-2411659292
-0666697760
-4294967295
-0666763260
-0001962017
-0605028353
-0001052705
-0666697732
-0065011720

+ 85 - 0
test/MemoryJUnitTest.java

@@ -0,0 +1,85 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import tools.mips.Memory;
+
+/**
+ *
+ * @author EUGENIO CARVALHO
+ */
+public class MemoryJUnitTest {
+
+    private Memory memory;
+
+    public MemoryJUnitTest() {
+
+    }
+
+    @BeforeClass
+    public static void setUpClass() {
+
+    }
+
+    @AfterClass
+    public static void tearDownClass() {
+    }
+
+    @Before
+    public void setUp() {
+        memory = new Memory(16 * 1024);
+    }
+
+    @After
+    public void tearDown() {
+    }
+
+    @Test
+    public void WriteByte() throws Exception {
+        String bd = "00000010";
+        memory.WB(bd);
+        Assert.assertEquals(bd, memory.RB(0));
+    }
+
+    @Test
+    public void WriteByteAddressed() throws Exception {
+        String bd = "00000010";
+        Long address = 16L;
+        memory.WB(address, bd);
+        Assert.assertEquals(bd, memory.RB(address));
+    }
+
+    @Test
+    public void WriteMultByteAddressed() throws Exception {
+        Long value = 14030L;
+
+        Long address = 16L;
+        // Escreve 4 bytes a partir do endereco 16
+        memory.W(address, Long.toBinaryString(value), 4);
+
+        // Lê 4 bytes a partir do endereco 16 -> converte binario para long
+        Assert.assertEquals(value, memory.ReadLong(address, 4));
+    }
+
+    @Test
+    public void WriteInvalidAddress() throws Exception {
+        boolean result = false;
+        try {
+            String bd = "00000010";
+            Long address = 17000L;
+            memory.WB(address, bd);
+        } catch (Exception e) {
+            result = true;
+        }
+        Assert.assertTrue(result);
+    }
+
+}