-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
2971 lines (2730 loc) · 95.1 KB
/
main.cpp
File metadata and controls
2971 lines (2730 loc) · 95.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include<iostream>
#include<fstream>
#include<sstream>
#include<time.h>
#include<string>
#include<cstring>
#include<vector>
#include<map>
#include<stack>
#include<set>
#include<algorithm>
using namespace std;
#define RANDOM_UNSIGNED ((((unsigned)rand()) << 24) ^ (((unsigned)rand()) << 12) ^ ((unsigned)rand()))
#define GetBit(p, i) (((p)[(i)>>5] & (1<<((i) & 31))) > 0)
#define SetBit(p, i) ((p)[(i)>>5] |= (1<<((i) & 31)))
#define UnSetBit(p, i) ((p)[(i)>>5] ^= (1<<((i) & 31)))
// if one node's fanin have two same nodes could have error...
struct Node
{
string name;
vector<Node*> fanin;
vector<Node*> fanout;
set <Node*> piset;
set <string> piset_str;
set <Node*> faninCone;
string graphName;//Graph name :R1,R2,G1
unsigned* seeds;
int type; //0:not 1:and 2:or 3:nand 4:nor 5:xor 6:xnor 7:buf 8:assign 9:PI 10:PO
int realGate; // -1:default
int id;//for blif file
};
struct Graph
{
vector< Node* > netlist;
vector< Node* > PI;
vector< Node* > PO;
vector< Node*> Constants; //record 1'b0 1'b1
map<string, Node*> PIMAP;//use PI's name to find its pointer
string name;//Graph name -> R1,R2,G1
set<Node*> PIFanoutNode;//record all PI fanout Nodes
};
struct MatchInfo
{
map<Node*, Node*> matches; //success match pair (golden,origin)
map<Node*, bool> originState; //(in this map represent it visited , true represent still in NodeSet)
map<Node*, bool> goldenState; //(in this map represent it visited , true represent still in NodeSet)
vector<Node*> originNode; //the remains is matched node need to save
map<Node*, bool> originRemoveNode; //the content node is not match in origin and needed to remove from origin
map<Node*, bool> goldenRemoveNode; //the content node is not match in golden and needed to create into origin
vector<Node*> goldenNode; //the remains is matched
set<Node*> originSupprotSet; //record support set
set<Node*> goldenSupprotSet; //record support set
map<Node*, Node*> backMatches; //record PO to PI structure match and fanout only one
};
struct PatchInfo
{
map<Node*, Node*> matches;
map<Node*, bool> originMatch;
map<Node*, bool> netlist;
int cost;
};
struct PatchGraph
{
Graph graph;
PatchInfo info;
};
struct NodeName
{
Node* node;
string graphName;
};
struct NameCompare
{
bool operator()(const Node* lhs, const Node* rhs) {
return lhs->name == rhs->name;
}
};
void loadFile(Graph& graph, char* argv);
// Convert verilog command to graph
// Also process node which fanin number larger than two,
// and split it into multi nodes each node only have two fanin
void verilog2graph(string& verilog_command, Graph& graph, vector<Node*>& assign_name);
// Process assign command type
void assignCommandTransform(string& verilog_command);
// Record PI/PO node info
void PiPoRecord(string str, Graph& graph);
// Initialize new node
Node* initialNewnode(string name, int type, string graphName);
// Select gate type
int selectGateType(string gate);
//run topological sort
void topologicalSort(Graph& graph, int& idStart);
//topological sort recursive
void topologicalSortUtil(Graph& graph, Node* node, map<Node*, bool>& visited, stack<Node*>& Stack);
//Set every node piset and bitwise operation seed
void setNodePIsetandSeed(Graph& graph);
//Set the random seed
void setRandomSeed(Graph& R2, Graph& G1);
//return random seed
unsigned* getRandomSeed();
//BitWiseOperation
void BitWiseOperation(vector<unsigned*>& fainSeed, Node* currNode);
// Match pair by using structure compare
void structureCompareMain(Graph origin, Graph golden, MatchInfo& matchInfo);
// structure compare operation
void structureCompareOper(Node* origin, Node* golden, MatchInfo& matchInfo);
// check gate is equal
bool IsGateTypeEqual(Node* origin, Node* golden);
// check fanin is equal
bool IsFaninEqual(Node* origin, Node* golden, MatchInfo matchInfo);
// check this node fanin whether visited or not
bool IsFaninVisited(Node* ptr, map<Node*, bool> maps);
// check this node whether visited or not
bool IsVisited(Node* target, map<Node*, bool>maps);
// when a node not match, removing all fanout
void removeAllFanout(Node* node, map<Node*, bool>& states, map<Node*, bool>& removed);
//start Random Simulation
void randomSimulation(MatchInfo& matchInfo);
//create a path for SAT solver
void outputPIwithFaninCone(ofstream& outfile, Node* nextNode, vector<NodeName>& internalNode, vector<bool>& faninConst);
//check if this node's fanin is PI
bool faninIsPI(Node* nextNode);
//remove fanin node
void removeAllFanin(MatchInfo& matchInfo, Node* originalSameNode, Node* goldenSameNode);
//outputBlif
void outputBlif(ofstream& outfile, Node* originalNode, Node* goldenNode);
//transfer graph to blif file and write blif file
void graph2Blif(Node* originalNode, Node* goldenNode);
//find the node's fanout and call node2Blif
void netlist2Blif(ofstream& outfile, vector<NodeName>& netlist);
//output constant 0 or 1 in blif file
void outputConst(ofstream& outfile, vector<bool>& faninConst);
//output .names to BLIF File
void outputDotNames(ofstream& outfile, Node* currNode, string currGraphName);
//write gate type ex: and gate -> 11 1
void node2Blif(ofstream& outfile, Node* currNode, int type);
//let original POs and Golden POs connet to the XOR to make the miter
void buildMiter(ofstream& outfile, Node* PO_original, Node* PO_golden, int miterPos, string originalGraphName, string goldenGraphName);
//call abc -> "turn blif into cnf" and minisat -> "check if this two netlist is equal"
bool SATsolver();
//check if output is UNSAT
bool readSATsolverResult();
//abc tool
void abcBlif2CNF();
// From PO to PI Comapre
void backStructureComapre(Graph origin, Graph golden, MatchInfo& matchInfo);
// Check PO to PI all path gate type equal
void backCheckStructureEqual(Node* origin, Node* golden, MatchInfo& matchInfo);
// Check gate type equal
bool checkGateTypeEqual(Node* origin, Node* golden);
// generate patch verilog
PatchGraph generatePatchVerilog(MatchInfo& matchInfo, Graph& R2, Graph& G1, char* argv);
// generate verilog instruction
string generateInstruction(Node* node, vector<string> names, int eco, int& cost);
// get type string
string getTypeString(int type);
// outfile declare variable
void generateDeclare(map<Node*, string> maps, string types, ofstream& outfile, int& cost);
// patch format
string generatePatchFormat(Node* node);
// is constant
void isConstantCondition(string& name, map<string, bool>& useConstant, Node* node, int& totalCost);
// is in match
void isInMatchCondition(string& name, map<Node*, Node*> matches, Node* node, map<Node*, string>& inputDeclareMap);
// is in goldenremoveNode
void isInGoldenRemoveNode(string& name, map<Node*, string>& newGateMap, Node* node);
// is randomsimulation remove from goldenremovenode and need to declare this leaking gate
void isLeakingNode(string& name, vector<Node*>& leakingNodeVec, Node* node, map<Node*, string>& newGateMap);
// accounting
PatchGraph costAccounting(MatchInfo& matchInfo, Graph& R2, Graph& G1);
// generate patch PI/PO node and put them in graph
void generatePatchPIPO(string type, string name, Graph& graph);
// configure patch name
void configurePatch(Graph& graph);
// match name
void nodeMatch(Graph& patch, Graph& origin, PatchInfo& info);
// remove extra node
void removeExtraNode(Graph& patch, Graph& origin, PatchInfo& info);
// remove all fanin single fanout node
void removeSingleFanout(Node* node, PatchInfo& info);
// apply node
void applyNode(Graph& patch, PatchInfo& info);
// generate patchG1 graph
void generatePatchG1(Graph& origin, PatchInfo& info, Graph& patchG1);
//// Output patch
//void outFile(Graph graph, char* argv);
//// Process same node name but multi Bracket(like op[0],op[1],op[2],.....) and count name times
//void strExtractBracket(Graph graph, vector<Node>& pi_items, vector<Node>& po_items);
//// Output declare type(input/output/wire)
//void outputFront(ofstream& outfile, vector<Node> p, string str);
//// Output gate
//void gateOutput(ofstream& outfile, Graph graph);
//// Sort by type and number count
//bool typeAndNumberCompare(const Node& p1, const Node& p2);
//// Sort by node name
//bool strTitleCompare(const string& p1, const string& p2);
void patchOptimize(MatchInfo& matchInfo);
//void createRectifyPair(Graph& R2, Graph& G1);
//bool pisetIsDifferent(Node object, Node golden);
//out patch blif to optimize
void outputPatchBlif(Graph& currPatchGraph, map<Node*, bool>& isVisitedPatch);
//read optimized patch blif file
void readOptPatchBlif(Graph& currPatchGraph, map<Node*, bool>& newGoldenRemoveNode);
//read the patch blif PI
void readOptPatchPI(ifstream& infile, Graph& currPatchGraph, map<string, string>& patchPI);
//read the patch blif PO
void readOptPatchPO(ifstream& infile, Graph& currPatchGraph, map<string, string>& patchPI);
//transfer blif command to graph
void blif2Graph(ifstream& infile, string& line, Graph& currPatchGraph, map<Node*, bool>& newGoldenRemoveNode,
map<string, Node*>& checkExist, int& notGatePos, map<string, string>& patchPI, map<string, string>& patchPO);
//return blif file gate type
int selectBlifGateType(ifstream& infile);
//solve the proble of blif file (ex:10 1,01 1)
Node* connectNewNotGate(Node* faninNode, string& notGateName, int& notGatePos, map<Node*, bool>& newGoldenRemoveNode);
//find two fanin node
bool faninNodeisLegal(Node* currNode, map<Node*, bool>& newGoldenRemoveNode, int& gatePos);
//combine into XRO gate or XNOR gate
void removeRedundantNode(map<Node*, bool>& newGoldenRemoveNode);
//start rebuild new node
void startRebuildNode(Node* fanoutNode, set<Node*>& redundantFaninNode, set<Node*>& redundantNode,
map<Node*, bool>& newGoldenRemoveNode, int type, int& gatePos);
//remove fanout node's redundant fanin
void removeRedundantFanin(Node* redundantNode, Node* newNode);
//remove fanin node's redundant fanout
void removeRedundantFanout(Node* faninNode, set<Node*>& redundantNode);
//solve the problem of old node in the fanin node's fanout
void removeOldNode(Graph currPatchGraph, map<Node*, bool>& newGoldenRemoveNode, map<Node*, bool>& oldGoldenRemoveNode);
//call the abc to optimize patch
void optimizePatch();
/*start verify patch*/
//start verify with minisat
bool patchSelfVerify();
bool seedIsDifferent(Node* origin, Node* golden);
//tool function
string toString(int trans) {
stringstream ss;
ss << trans;
return ss.str();
};
//for vetor PO sort
bool PONameCompare(Node* lhs, Node* rhs) { return lhs->name > rhs->name; };
/* Function Flow
---------------------------------------------------------
loadFile -> verilog2graph -> assignCommandTransform
. -> initialNewnode
. -> selectGateType
. -> PiPoRecord
----------------------------------------------------------
|
----------------------------------
setRandomSeed -> getRandomSeed
----------------------------------
|
-----------------------------------------
topologicalSort -> topologicalSortUtil
-----------------------------------------
|
------------------------------------------
setNodePIsetandSeed -> BitWiseOperation
------------------------------------------
|
------------------------------------------------------------------------------------------
structureCompareMain -> structureCompareOper -> IsGateTypeEqual
. -> IsFaninEqual
. -> IsVisited
. -> IsFaninVisited -> IsVisited
. -> removeAllFanout -> removeAllFanout
------------------------------------------------------------------------------------------
|
-------------------------------------------------------------------------------------
randomSimulation -> outputBlif -> graph2Blif -> outputPIwithFaninCone -> node2Blif
. -> outputConst
. -> netlist2Blif -> node2Blif
. -> buildMiter
. -> SATsolver -> abcBlif2CNF
. -> readSATsolverResult
. -> removeAllFanin
-------------------------------------------------------------------------------------
|
-------------------------------------------------------------------------------------
patchVerify -> checkRemoveNodeFaninExist
. -> faninIsPI
. -> compareNetlist -> outputPatchDotNames
. -> outputConst
. -> buildMiter
. -> SATsolver
------------------------------------------------------------------------------------
|
-------------------------------------------------------------------------------------
generatePatchVerilog -> generateInstruction -> getTypeString
. -> generateDeclare
-------------------------------------------------------------------------------------
*/
int nWords = 10;
int nodeID = 1;
//for debug pointer
Node* debug;
// inpurt format
//./eco R1.v R2.v G1.v patch.v
int main(int argc, char* argv[])
{
srand(time(NULL));
//golden netlist
Graph R2;
vector<MatchInfo> eachMatchInfoVersion;
R2.name = "R2";
//optimize netlist
Graph G1;
G1.name = "G1";
//Load R2 golden netlist
//assign value is fault, need to retrieve fan_in value in next step
loadFile(R2, argv[2]);
//Load G1 optimize netlist
//assign value is fault, need to retrieve fan_in value in next step
loadFile(G1, argv[3]);
//Set random seed to PI
setRandomSeed(R2, G1);
////Start topological sort
//In order to set ID and PI
topologicalSort(R2, nodeID);
topologicalSort(G1, nodeID);
//Set all nodes Primary Input
setNodePIsetandSeed(R2);
setNodePIsetandSeed(G1);
MatchInfo matchInfo;
PatchGraph test;
int currcost;
structureCompareMain(G1, R2, matchInfo);
//cout << "structureCompareMain\n";
test = costAccounting(matchInfo, R2, G1);
currcost = test.info.cost;
int k = 0;
//record matchInfo w/ struct compare
eachMatchInfoVersion.push_back(matchInfo);
/*
map<Node*, bool>::iterator it = matchInfo.goldenRemoveNode.begin();
int pos = 0;
for (; it != matchInfo.goldenRemoveNode.end(); ++it) {
pos++;
if (it->first->name == "n_307")
cout << pos << endl;
}
*/
//check seed and do SAT solver
/*for (map<Node*, bool>::iterator it = matchInfo.goldenRemoveNode.begin(); it != matchInfo.goldenRemoveNode.end(); ++it) {
if (it->first->name == "n_505")
cout << "505---\n";
if (it->first->name == "n_264")
cout << "264---\n";
}*/
MatchInfo m1 = matchInfo;
randomSimulation(m1);
//cout << "randomSimulation\n";
test = costAccounting(m1, R2, G1);
//cout << test.info.cost << " : " << currcost << "\n";
if (test.info.cost <= currcost) {
currcost = test.info.cost;
matchInfo = m1;
eachMatchInfoVersion.push_back(m1);
}
/*for (map<Node*, bool>::iterator it = matchInfo.goldenRemoveNode.begin(); it != matchInfo.goldenRemoveNode.end(); ++it) {
if (it->first->name == "n_505")
cout << "505***\n";
if (it->first->name == "n_264")
cout << "264***\n";
}*/
//cout << "after random\n";
MatchInfo m2 = matchInfo;
/*start optimize*/
backStructureComapre(G1, R2, m2);
//cout << "backStructureComapre\n";
test = costAccounting(m2, R2, G1);
//cout << test.info.cost << " : " << currcost << "\n";
if (test.info.cost <= currcost) {
currcost = test.info.cost;
matchInfo = m2;
eachMatchInfoVersion.push_back(m2);
}
MatchInfo m3 = matchInfo;
//start optimize patch with abc tool
patchOptimize(m3);
//cout << "patchOptimize\n";
test = costAccounting(m3, R2, G1);
//cout << test.info.cost << " : " << currcost << "\n";
if (test.info.cost <= currcost) {
currcost = test.info.cost;
matchInfo = m3;
eachMatchInfoVersion.push_back(m3);
}
//cout << "eachVersionMatchInfo size : " << eachMatchInfoVersion.size() << endl;
//output the patch.v
for (int m = eachMatchInfoVersion.size() - 1; m >= 0; --m) {
PatchGraph patch;
Graph patchG1;
MatchInfo currMatchInfo = eachMatchInfoVersion[m];
patch = generatePatchVerilog(currMatchInfo, R2, G1, argv[4]);
configurePatch(patch.graph);
nodeMatch(patch.graph, G1, patch.info);
removeExtraNode(patch.graph, G1, patch.info);
applyNode(patch.graph, patch.info);
generatePatchG1(G1, patch.info, patchG1);
int i = 0;
//make sure the patch is correct
if (patchSelfVerify() || m == 0) {
//cout << "Success output patch version:" << m+1 << endl;
break;
}
}
}
void loadFile(Graph& graph, char* argv)
{
/*
ifstream infileR1("r1.v"); //replace by argv[1]
ifstream infileR2("r2.v"); //replace by argv[2]
ifstream infileG1("g1.v"); //replace by argv[3]
*/
ifstream infile(argv); //replace by argv[]
vector<Node*> assign; //optimize assign name
graph.Constants.resize(2);
string verilog_command;
//load R1.v
while (1) {
getline(infile, verilog_command, ';');
//if this command include "endmodule" then break while loop
if (verilog_command.find("endmodule") != string::npos)
break;
verilog2graph(verilog_command, graph, assign);
getline(infile, verilog_command); //dicard \n
}
}
void verilog2graph(string& verilog_command, Graph& graph, vector<Node*>& assign_name)
{
//delete front blank
while (verilog_command[0] == ' ')
verilog_command = verilog_command.substr(1, verilog_command.size() - 1);
//if this command include "module" then return
if (verilog_command.find("module") != string::npos)
return;
//if this command include "wire" then return
if (verilog_command.find("wire") != string::npos || verilog_command.find("WIRE") != string::npos)
return;
//if this command include "input" then record
if (verilog_command.find("input") != string::npos || verilog_command.find("INPUT") != string::npos) {
PiPoRecord(verilog_command, graph);
return;
}
//if this command include "output" then record
if (verilog_command.find("output") != string::npos || verilog_command.find("OUTPUT") != string::npos) {
PiPoRecord(verilog_command, graph);
return;
}
//solve "assign" type special conversion
if (verilog_command.find("assign") != string::npos || verilog_command.find("ASSIGN") != string::npos)
assignCommandTransform(verilog_command);
/*if (verilog_command.find("buf") != string::npos)
int i = 0;*/
int type, count = 1;
string split_command;
Node* currGate = NULL;
stringstream ss;
ss << verilog_command;
//return corresponding gate type id
getline(ss, split_command, ' ');
type = selectGateType(split_command);
getline(ss, split_command, '(');
while (getline(ss, split_command, ',')) {
bool isexist = false;
Node* scanNode = NULL;
while (split_command[0] == ' ' || split_command[0] == '\n') //delete front blank
split_command = split_command.substr(1, split_command.size() - 1);
if (split_command[split_command.size() - 1] == ')') //delete right parentheses
split_command = split_command.substr(0, split_command.size() - 1);
while (split_command[split_command.size() - 1] == ' ' || split_command[split_command.size() - 1] == '\n') //delete front blank
split_command = split_command.substr(0, split_command.size() - 1);
// search this whether exist
for (int i = 0; i < graph.netlist.size(); i++)
if (graph.netlist[i]->name == split_command)
{
isexist = true;
scanNode = graph.netlist[i];
if (count)
currGate = graph.netlist[i];
break;
}
if (!isexist) { // not exist
Node* req = initialNewnode(split_command, -1, graph.name);
if (split_command == "1'b0")
graph.Constants[0] = req;
else if (split_command == "1'b1")
graph.Constants[1] = req;
graph.netlist.push_back(req);
if (count) { //first node
currGate = req;
req->type = type;
count = 0;
}
else {
//fanin node
// >2 fanin split to 2 fanin gate
req->fanout.push_back(currGate);
if (currGate->fanin.size() == 2) {
Node* n1 = currGate->fanin[0];
Node* n2 = currGate->fanin[1];
int currtype = currGate->type;
if (currtype == 10)
currtype = currGate->realGate;
Node* newnode = initialNewnode(n1->name + "_" + n2->name + "_" + toString(nodeID++), currtype, graph.name);
for (int i = 0; i < n1->fanout.size(); i++)
if (n1->fanout[i]->name == currGate->name)
n1->fanout[i] = newnode;
for (int i = 0; i < n2->fanout.size(); i++)
if (n2->fanout[i]->name == currGate->name)
n2->fanout[i] = newnode;
newnode->fanin.push_back(n1);
newnode->fanin.push_back(n2);
newnode->fanout.push_back(currGate);
currGate->fanin.clear();
currGate->fanin.push_back(newnode);
graph.netlist.push_back(newnode);
}
currGate->fanin.push_back(req);
//if currGate fanin is Pi then add to PIfanoutNode
if (req->type == 9)
graph.PIFanoutNode.insert(currGate);
}
}
else { //is exist
if (count) { //first node
if (currGate->type == 9 || currGate->type == 10)
currGate->realGate = type;
else if (currGate->type == -1)
currGate->type = type;
count = 0;
}
else {
// its fanin node
// > 2 fanin split to 2 fanin gate
scanNode->fanout.push_back(currGate);
if (currGate->fanin.size() == 2) {
Node* n1 = currGate->fanin[0];
Node* n2 = currGate->fanin[1];
int currtype = currGate->type;
if (currtype == 10)
currtype = currGate->realGate;
Node* newnode = initialNewnode(n1->name + "_" + n2->name + "_" + toString(nodeID++), currtype, graph.name);
//modify
if (newnode->type == 9 || newnode->type == 10)
newnode->realGate = currGate->realGate;
for (int i = 0; i < n1->fanout.size(); i++)
if (n1->fanout[i]->name == currGate->name)
n1->fanout[i] = newnode;
for (int i = 0; i < n2->fanout.size(); i++)
if (n2->fanout[i]->name == currGate->name)
n2->fanout[i] = newnode;
newnode->fanin.push_back(n1);
newnode->fanin.push_back(n2);
newnode->fanout.push_back(currGate);
currGate->fanin.clear();
currGate->fanin.push_back(newnode);
graph.netlist.push_back(newnode);
}
currGate->fanin.push_back(scanNode);
//if currGate fanin is Pi then add to PIfanoutNode
if (scanNode->type == 9)
graph.PIFanoutNode.insert(currGate);
}
}
}
}
void assignCommandTransform(string& verilog_command) {
verilog_command.insert(7, "(");
verilog_command.insert(verilog_command.size(), ")");
if (verilog_command.find(" = ") != string::npos) {
int pos = verilog_command.find(" = ");
verilog_command.replace(pos, 3, ","); // (position,offset,replace_str)
}
}
void PiPoRecord(string str, Graph& graph)
{
string type = str.substr(0, 6);
str = str.substr(6, str.size() - 1);
stringstream ss;
string split_command;
if (str.find(':') != string::npos) { //have multi input
stringstream kk;
int max_index, min_index;
ss << str;
getline(ss, split_command, '[');
getline(ss, split_command, ':');
kk << split_command;
kk >> max_index;
getline(ss, split_command, ']');
stringstream cc;
cc << split_command;
cc >> min_index;
while (getline(ss, split_command, ',')) {
while (split_command[0] == ' ') //delete front blank
split_command = split_command.substr(1, split_command.size() - 1);
while (split_command[split_command.size() - 1] == ' ') //delete front blank
split_command = split_command.substr(0, split_command.size() - 1);
for (int i = min_index; i <= max_index; i++) {
stringstream ss;
ss << i;
Node* req = new Node();
req->name = split_command + "[" + ss.str() + "]";
req->realGate = -1;
if (type == "input ") {
graph.PIMAP[req->name] = req;
req->type = 9;
req->seeds = new unsigned[nWords];
graph.netlist.push_back(req);
graph.PI.push_back(req);
//req->piset.push_back(req);
req->piset.insert(req);
//add piset_str with string not Node*
req->piset_str.insert(req->name);
req->graphName = graph.name;
}
else if (type == "output") {
req->type = 10;
req->seeds = new unsigned[nWords];
req->graphName = graph.name;
graph.netlist.push_back(req);
graph.PO.push_back(req);
}
}
}
}
else {
ss << str;
while (getline(ss, split_command, ',')) {
while (split_command[0] == ' ') //delete front blank
split_command = split_command.substr(1, split_command.size() - 1);
while (split_command[split_command.size() - 1] == ' ') //delete front blank
split_command = split_command.substr(0, split_command.size() - 1);
Node* req = new Node();
req->name = split_command;
req->realGate = -1;
if (type == "input ") {
graph.PIMAP[req->name] = req;
req->type = 9;
req->seeds = new unsigned[nWords];
graph.netlist.push_back(req);
graph.PI.push_back(req);
//req->piset.push_back(req);
req->piset.insert(req);
//add piset_str with string not Node*
req->piset_str.insert(req->name);
req->graphName = graph.name;
}
else if (type == "output") {
req->type = 10;
req->seeds = new unsigned[nWords];
req->graphName = graph.name;
graph.netlist.push_back(req);
graph.PO.push_back(req);
}
}
}
}
int selectGateType(string gate)
{
if (gate == "NOT" || gate == "not") return 0;
else if (gate == "AND" || gate == "and") return 1;
else if (gate == "OR" || gate == "or") return 2;
else if (gate == "NAND" || gate == "nand") return 3;
else if (gate == "NOR" || gate == "nor") return 4;
else if (gate == "XOR" || gate == "xor") return 5;
else if (gate == "XNOR" || gate == "xnor") return 6;
else if (gate == "BUF" || gate == "buf") return 7;
else if (gate == "ASSIGN" || gate == "assign") return 8;
else if (gate == "input")return 9;
else if (gate == "output")return 10;
}
Node* initialNewnode(string name, int type, string graphName) {
Node* newnode = new Node();
newnode->name = name;
newnode->realGate = -1;
newnode->type = type;
newnode->seeds = new unsigned[nWords];
newnode->graphName = graphName;
return newnode;
}
void setRandomSeed(Graph& R2, Graph& G1)
{
for (int i = 0; i < R2.PI.size(); ++i) {
//get the PI name
string PIname = R2.PI[i]->name;
//get the random seed memory location
unsigned* seed = getRandomSeed();
R2.PIMAP[PIname]->seeds = seed;
G1.PIMAP[PIname]->seeds = seed;
}
}
void topologicalSort(Graph& graph, int& idStart)
{
stack<Node*> Stack;
map<Node*, bool> visited;
vector<Node*>::iterator it1 = graph.netlist.begin();
for (; it1 != graph.netlist.end(); ++it1)
visited[*it1] = false;
/*
map<Node*, bool>::iterator it2 = visited.begin();
for (; it2 != visited.end(); ++it2) {
if (!it2->second)
topologicalSortUtil(graph, it2->first, visited, Stack);
}
*/
for (int i = 0; i < graph.Constants.size(); ++i) {
if (graph.Constants[i] != NULL && !visited[graph.Constants[i]])
topologicalSortUtil(graph, graph.Constants[i], visited, Stack);
}
for (int i = 0; i < graph.PI.size(); ++i) {
if (!visited[graph.PI[i]])
topologicalSortUtil(graph, graph.PI[i], visited, Stack);
}
int pos = 0;
vector<Node*> sortNode;
sortNode.resize(Stack.size());
while (Stack.empty() == false) {
//cout << Stack.top() << " ";
//Stack.top()->id = pos + idStart;
Stack.top()->id = idStart++;
sortNode[pos++] = Stack.top();
Stack.pop();
}
graph.netlist = sortNode;
}
void topologicalSortUtil(Graph& graph, Node* node, map<Node*, bool>& visited, stack<Node*>& Stack)
{
//Mark the current node as visited
visited[node] = true;
for (int i = 0; i < node->fanout.size(); ++i) {
Node* nextNode = node->fanout[i];
if (!visited[nextNode])
topologicalSortUtil(graph, nextNode, visited, Stack);
}
if (node->name != "1'b0" && node->name != "1'b1")
Stack.push(node);
}
void setNodePIsetandSeed(Graph& graph)
{
for (int i = 0; i < graph.netlist.size(); ++i) {
Node* currNode = graph.netlist[i];
//add itself to fanincone
currNode->faninCone.insert(currNode);
if (currNode->fanin.size() > 0) {
vector<unsigned*> faninSeed;
for (int j = 0; j < currNode->fanin.size(); ++j) {
//set the PI to the PISET
Node* faninNode = currNode->fanin[j];
currNode->piset.insert(faninNode->piset.begin(), faninNode->piset.end());
//add piset_str with string not Node*
currNode->piset_str.insert(faninNode->piset_str.begin(), faninNode->piset_str.end());
//set fanin cone
currNode->faninCone.insert(faninNode->faninCone.begin(), faninNode->faninCone.end());
//record fanin seed
faninSeed.push_back(faninNode->seeds);
}
BitWiseOperation(faninSeed, currNode);
}
}
}
void BitWiseOperation(vector<unsigned*>& faninSeed, Node* currNode)
{
//0:not 1:and 2:or 3:nand 4:nor 5:xor 6:xnor 7:buf 8:assign 9:PI 10:PO
int type;
if (currNode->type == 10 || currNode->type == 9)
type = currNode->realGate;
else
type = currNode->type;
if (faninSeed.size() > 1) {
//and gate
if (type == 1)
for (int i = 0; i < nWords; ++i) currNode->seeds[i] = faninSeed[0][i] & faninSeed[1][i];
//or gate
else if (type == 2)
for (int i = 0; i < nWords; ++i) currNode->seeds[i] = faninSeed[0][i] | faninSeed[1][i];
//nand gate
else if (type == 3)
for (int i = 0; i < nWords; ++i) currNode->seeds[i] = ~(faninSeed[0][i] & faninSeed[1][i]);
//nor gate
else if (type == 4)
for (int i = 0; i < nWords; ++i) currNode->seeds[i] = ~(faninSeed[0][i] | faninSeed[1][i]);
//xor gate
else if (type == 5)
for (int i = 0; i < nWords; ++i) currNode->seeds[i] = faninSeed[0][i] ^ faninSeed[1][i];
//xnor gate
else if (type == 6)
for (int i = 0; i < nWords; ++i) currNode->seeds[i] = ~(faninSeed[0][i] ^ faninSeed[1][i]);
}
else {
//not gate
if (type == 0)
for (int i = 0; i < nWords; ++i) currNode->seeds[i] = ~faninSeed[0][i];
//buffer or assign
else if (type == 7 || type == 8)
for (int i = 0; i < nWords; ++i) currNode->seeds[i] = faninSeed[0][i];
}
}
unsigned* getRandomSeed()
{
//32bits
unsigned* bw = new unsigned[nWords];
for (int i = 0; i < nWords; i++) bw[i] = RANDOM_UNSIGNED;
/*
for (int i = 0; i < nWords; i++)
for (int k = 0; k < 32; k++)
cout << GetBit(bw, k + (i * 32));
*/
return bw;
}
void structureCompareMain(Graph origin, Graph golden, MatchInfo& matchInfo)
{
for (int i = 0; i < golden.PI.size(); i++) {
// put (golden , origin) PI in matches
matchInfo.matches[golden.PI[i]] = origin.PI[i];
matchInfo.originState[origin.PI[i]] = true;
matchInfo.goldenState[golden.PI[i]] = true;
matchInfo.originSupprotSet.insert(origin.PI[i]);
matchInfo.goldenSupprotSet.insert(golden.PI[i]);
}
for (int i = 0; i < origin.netlist.size(); i++)
matchInfo.originNode.push_back(origin.netlist[i]);
for (int i = 0; i < golden.netlist.size(); i++)
matchInfo.goldenNode.push_back(golden.netlist[i]);
int originIndex = 0, goldenIndex = 0;
while (true) {
bool ending = false;
Node* originPtr = matchInfo.originNode[originIndex];
Node* goldenPtr = matchInfo.goldenNode[goldenIndex];
/*if (goldenPtr->name == "overflow")
cout << "point";*/
while (matchInfo.originState.find(originPtr) != matchInfo.originState.end() && matchInfo.originState[originPtr] == false) {
matchInfo.originNode.erase(matchInfo.originNode.begin() + originIndex);
if (originIndex < matchInfo.originNode.size())
originPtr = matchInfo.originNode[originIndex];
else {
ending = true;
break;
}
}
while (matchInfo.goldenState.find(goldenPtr) != matchInfo.goldenState.end() && matchInfo.goldenState[goldenPtr] == false) {
matchInfo.goldenNode.erase(matchInfo.goldenNode.begin() + goldenIndex);
if (goldenIndex < matchInfo.goldenNode.size())
goldenPtr = matchInfo.goldenNode[goldenIndex];
else {
ending = true;
break;
}
}
if (!ending) {
structureCompareOper(originPtr, goldenPtr, matchInfo);
originIndex++; goldenIndex++;
}
if (originIndex >= matchInfo.originNode.size() || goldenIndex >= matchInfo.goldenNode.size()) {
int minisize = matchInfo.originNode.size();
if (matchInfo.originNode.size() > matchInfo.goldenNode.size())
minisize = matchInfo.goldenNode.size();
while (matchInfo.originNode.size() > minisize) {
Node* ptr = matchInfo.originNode[matchInfo.originNode.size() - 1];
if (matchInfo.originState.find(ptr) != matchInfo.originState.end() && matchInfo.originState[ptr] == false)
matchInfo.originNode.pop_back();
else {
matchInfo.originState[ptr] = false;
matchInfo.originRemoveNode[ptr] = true;
matchInfo.originNode.pop_back();
}
}
while (matchInfo.goldenNode.size() > minisize) {
Node* ptr = matchInfo.goldenNode[matchInfo.goldenNode.size() - 1];
if (matchInfo.goldenState.find(ptr) != matchInfo.goldenState.end() && matchInfo.goldenState[ptr] == false)
matchInfo.goldenNode.pop_back();
else {
matchInfo.goldenState[ptr] = false;
matchInfo.goldenRemoveNode[ptr] = true;
matchInfo.goldenNode.pop_back();
}
}
break;
}
}
//set<Node*>::iterator req = matchInfo.originSupprotSet.begin();
//for (set<Node*>::iterator it = matchInfo.originSupprotSet.begin(); it != matchInfo.originSupprotSet.end(); it = req) {
// ++req;
// bool updates = true;
// Node* accesses = *it;
// for (int m = 0; m < accesses->fanout.size(); m++)
// if (matchInfo.originRemoveNode.find(accesses->fanout[m]) != matchInfo.originRemoveNode.end()) {
// updates = false;
// break;
// }
// if (updates) {
// for (int m = 0; m < accesses->fanout.size(); m++)
// matchInfo.originSupprotSet.insert(accesses->fanout[m]);
// matchInfo.originSupprotSet.erase(it);
// }
//}
//req = matchInfo.goldenSupprotSet.begin();
//for (set<Node*>::iterator it = matchInfo.goldenSupprotSet.begin(); it != matchInfo.goldenSupprotSet.end(); it = req) {
// ++req;
// bool updates = true;
// Node* accesses = *it;
// for (int m = 0; m < accesses->fanout.size(); m++)
// if (matchInfo.matches.find(accesses->fanout[m]) == matchInfo.matches.end()) {
// updates = false;
// break;
// }
// if (updates) {
// for (int m = 0; m < accesses->fanout.size(); m++)
// matchInfo.goldenSupprotSet.insert(accesses->fanout[m]);
// matchInfo.goldenSupprotSet.erase(it);