forked from cseagle/blc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockaction.cc
2345 lines (2100 loc) · 75.8 KB
/
blockaction.cc
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
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "blockaction.hh"
#include "funcdata.hh"
/// Retrieve the current edge (as a \e top FlowBlock and the index of the outgoing edge).
/// If the end-points have been collapsed together, this returns NULL.
/// The top and bottom nodes of the edge are updated to FlowBlocks in the current collapsed graph.
/// \param outedge will hold the index of the edge (outgoing relative to returned FlowBlock)
/// \param graph is the containing BlockGraph
/// \return the current \e top of the edge or NULL
FlowBlock *FloatingEdge::getCurrentEdge(int4 &outedge,FlowBlock *graph)
{
while(top->getParent() != graph)
top = top->getParent(); // Move up through collapse hierarchy to current graph
while(bottom->getParent() != graph)
bottom = bottom->getParent();
outedge = top->getOutIndex(bottom);
if (outedge < 0)
return (FlowBlock *)0; // Edge does not exist (any longer)
return top;
}
/// \brief Find blocks in containing loop that aren't in \b this
///
/// Assuming \b this has all of its nodes marked, find all additional nodes that create the
/// body of the \b container loop. Mark these and put them in \b body list.
/// \param container is a loop that contains \b this
/// \param body will hold blocks in the body of the container that aren't in \b this
void LoopBody::extendToContainer(const LoopBody &container,vector<FlowBlock *> &body) const
{
int4 i = 0;
if (!container.head->isMark()) { // container head may already be in subloop, if not
container.head->setMark(); // add it to new body
body.push_back(container.head);
i = 1; // make sure we don't traverse back from it
}
for(int4 j=0;j<container.tails.size();++j) {
FlowBlock *tail = container.tails[j];
if (!tail->isMark()) { // container tail may already be in subloop, if not
tail->setMark();
body.push_back(tail); // add to body, make sure we DO traverse back from it
}
}
// -this- head is already marked, but hasn't been traversed
if (head != container.head) { // Unless the container has the same head, traverse the contained head
int4 sizein = head->sizeIn();
for(int4 k=0;k<sizein;++k) {
if (head->isGotoIn(k)) continue; // Don't trace back through irreducible edges
FlowBlock *bl = head->getIn(k);
if (bl->isMark()) continue; // Already in list
bl->setMark();
body.push_back(bl);
}
}
while(i < body.size()) {
FlowBlock *curblock = body[i++];
int4 sizein = curblock->sizeIn();
for(int4 k=0;k<sizein;++k) {
if (curblock->isGotoIn(k)) continue; // Don't trace back through irreducible edges
FlowBlock *bl = curblock->getIn(k);
if (bl->isMark()) continue; // Already in list
bl->setMark();
body.push_back(bl);
}
}
}
/// This updates the \b head and \b tail nodes to FlowBlock in the current collapsed graph.
/// This returns the first \b tail and passes back the head.
/// \param top is where \b head is passed back
/// \param graph is the containing control-flow structure
/// \return the current loop \b head
FlowBlock *LoopBody::getCurrentBounds(FlowBlock **top,FlowBlock *graph)
{
while(head->getParent() != graph)
head = head->getParent(); // Move up through collapse hierarchy to current graph
FlowBlock *bottom;
for(int4 i=0;i<tails.size();++i) {
bottom = tails[i];
while(bottom->getParent() != graph)
bottom = bottom->getParent();
tails[i] = bottom;
if (bottom != head) { // If the loop hasn't been fully collapsed yet
*top = head;
return bottom;
}
}
return (FlowBlock *)0;
}
/// Collect all FlowBlock nodes that reach a \b tail of the loop without going through \b head.
/// Put them in a list and mark them.
/// \param body will contain the body nodes
void LoopBody::findBase(vector<FlowBlock *> &body)
{
head->setMark();
body.push_back(head);
for(int4 j=0;j<tails.size();++j) {
FlowBlock *tail = tails[j];
if (!tail->isMark()) {
tail->setMark();
body.push_back(tail);
}
}
uniquecount = body.size(); // Number of nodes that either head or tail
int4 i=1;
while(i < body.size()) {
FlowBlock *curblock = body[i++];
int4 sizein = curblock->sizeIn();
for(int4 k=0;k<sizein;++k) {
if (curblock->isGotoIn(k)) continue; // Don't trace back through irreducible edges
FlowBlock *bl = curblock->getIn(k);
if (bl->isMark()) continue; // Already in list
bl->setMark();
body.push_back(bl);
}
}
}
/// Extend the \b body of this loop to every FlowBlock that can be reached
/// \b only from \b head without hitting the \b exitblock.
/// Assume \b body has been filled out by findBase() and that all these blocks have their mark set.
/// \param body contains the current loop body and will be extended
void LoopBody::extend(vector<FlowBlock *> &body) const
{
vector<FlowBlock *> trial;
int4 i=0;
while(i<body.size()) {
FlowBlock *bl = body[i++];
int4 sizeout = bl->sizeOut();
for(int4 j=0;j<sizeout;++j) {
if (bl->isGotoOut(j)) continue; // Don't extend through goto edge
FlowBlock *curbl = bl->getOut(j);
if (curbl->isMark()) continue;
if (curbl == exitblock) continue;
int4 count = curbl->getVisitCount();
if (count == 0)
trial.push_back(curbl); // New possible extension
count += 1;
curbl->setVisitCount(count);
if (count == curbl->sizeIn()) {
curbl->setMark();
body.push_back(curbl);
}
}
}
for(i=0;i<trial.size();++i)
trial[i]->setVisitCount(0); // Make sure to clear the count
}
/// A structured loop is allowed at most one exit block: pick this block.
/// First build a set of trial exits, preferring from a \b tail, then from \b head,
/// then from the middle. If there is no containing loop, just return the first such exit we find.
/// \param body is the list FlowBlock objects in the loop body, which we assume are marked.
void LoopBody::findExit(const vector<FlowBlock *> &body)
{
vector<FlowBlock *> trialexit;
FlowBlock *tail;
for(int4 j=0;j<tails.size();++j) {
tail = tails[j];
int4 sizeout = tail->sizeOut();
for(int4 i=0;i<sizeout;++i) {
if (tail->isGotoOut(i)) continue; // Don't use goto as exit edge
FlowBlock *curbl = tail->getOut(i);
if (!curbl->isMark()) {
if (immed_container == (LoopBody *)0) {
exitblock = curbl;
return;
}
trialexit.push_back(curbl);
}
}
}
for(int4 i=0;i<body.size();++i) {
FlowBlock *bl = body[i];
if ((i>0)&&(i<uniquecount)) continue; // Filter out tails (processed previously)
int4 sizeout = bl->sizeOut();
for(int4 j=0;j<sizeout;++j) {
if (bl->isGotoOut(j)) continue; // Don't use goto as exit edge
FlowBlock *curbl = bl->getOut(j);
if (!curbl->isMark()) {
if (immed_container == (LoopBody *)0) {
exitblock = curbl;
return;
}
trialexit.push_back(curbl);
}
}
}
exitblock = (FlowBlock *)0; // Default exit is null, if no block meeting condition can be found
if (trialexit.empty())
return;
// If there is a containing loop, force exitblock to be in the containing loop
if (immed_container != (LoopBody *)0) {
vector<FlowBlock *> extension;
extendToContainer(*immed_container,extension);
for(int4 i=0;i<trialexit.size();++i) {
FlowBlock *bl = trialexit[i];
if (bl->isMark()) {
exitblock = bl;
break;
}
}
clearMarks(extension);
}
}
/// The idea is if there is more than one \b tail for a loop, some tails are more "preferred" than others
/// and should have their exit edges preserved longer and be the target of the DAG path.
/// Currently we look for a single \b tail that has an outgoing edge to the \b exitblock and
/// make sure it is the first tail.
void LoopBody::orderTails(void)
{
if (tails.size() <= 1) return;
if (exitblock == (FlowBlock *)0) return;
int4 prefindex;
FlowBlock *trial;
for(prefindex=0;prefindex < tails.size(); ++prefindex) {
trial = tails[prefindex];
int4 sizeout = trial->sizeOut();
int4 j;
for(j=0;j<sizeout;++j)
if (trial->getOut(j) == exitblock) break;
if (j<sizeout) break;
}
if (prefindex >= tails.size()) return;
if (prefindex == 0) return;
tails[prefindex] = tails[0]; // Swap preferred tail into the first position
tails[0] = trial;
}
/// Label any edge that leaves the set of nodes in \b body.
/// Put the edges in priority for removal, middle exit at front, \e head exit, then \e tail exit.
/// We assume all the FlowBlock nodes in \b body have been marked.
/// \param body is list of nodes in \b this loop body
void LoopBody::labelExitEdges(const vector<FlowBlock *> &body)
{
vector<FlowBlock *> toexitblock;
for(int4 i=uniquecount;i<body.size();++i) { // For non-head/tail nodes of graph
FlowBlock *curblock = body[i];
int4 sizeout = curblock->sizeOut();
for(int4 k=0;k<sizeout;++k) {
if (curblock->isGotoOut(k)) continue; // Don't exit through goto edges
FlowBlock *bl = curblock->getOut(k);
if (bl == exitblock) {
toexitblock.push_back(curblock);
continue; // Postpone exit to exitblock
}
if (!bl->isMark())
exitedges.push_back(FloatingEdge(curblock,bl));
}
}
if (head != (FlowBlock *)0) {
int4 sizeout = head->sizeOut();
for(int4 k=0;k<sizeout;++k) {
if (head->isGotoOut(k)) continue; // Don't exit through goto edges
FlowBlock *bl = head->getOut(k);
if (bl == exitblock) {
toexitblock.push_back(head);
continue; // Postpone exit to exitblock
}
if (!bl->isMark())
exitedges.push_back(FloatingEdge(head,bl));
}
}
for(int4 i=tails.size()-1;i>=0;--i) { // Put exits from more preferred tails later
FlowBlock *curblock = tails[i];
if (curblock == head) continue;
int4 sizeout = curblock->sizeOut();
for(int4 k=0;k<sizeout;++k) {
if (curblock->isGotoOut(k)) continue; // Don't exit through goto edges
FlowBlock *bl = curblock->getOut(k);
if (bl == exitblock) {
toexitblock.push_back(curblock);
continue; // Postpone exit to exitblock
}
if (!bl->isMark())
exitedges.push_back(FloatingEdge(curblock,bl));
}
}
for(int4 i=0;i<toexitblock.size();++i) { // Now we do exits to exitblock
FlowBlock *bl = toexitblock[i];
exitedges.push_back(FloatingEdge(bl,exitblock));
}
}
/// \brief Record any loops that \b body contains.
///
/// Search for any loop contained by \b this and update is \b depth and \b immed_container field.
/// \param body is the set of FlowBlock nodes making up this loop
/// \param looporder is the list of known loops
void LoopBody::labelContainments(const vector<FlowBlock *> &body,const vector<LoopBody *> &looporder)
{
vector<LoopBody *> containlist;
for(int4 i=0;i<body.size();++i) {
FlowBlock *curblock = body[i];
if (curblock != head) {
LoopBody *subloop = LoopBody::find(curblock,looporder);
if (subloop != (LoopBody *)0) {
containlist.push_back(subloop);
subloop->depth += 1;
}
}
}
// Note the following code works even though the depth fields may shift during subsequent calls to this routine
// Once a LoopBody calls this routine
// the depth of any contained loop will permanently be bigger than this LoopBody
// because any other loop will either
// increment the depth of both this LoopBody and any loop that it contains OR
// increment neither the LoopBody nor a loop it contains OR
// NOT increment the LoopBody but DO increment a contained loop
// So when the immediate container a of loop b calls this routine
// a has a depth greater than any containing LoopBody that has already run
// => therefore b->immed_container->depth < a->depth and a claims the immed_container position
// Subsequent containers c of a and b, will have c->depth < a->depth because c contains a
for(int4 i=0;i<containlist.size();++i) { // Keep track of the most immediate container
LoopBody *lb = containlist[i];
if ((lb->immed_container == (LoopBody *)0)||(lb->immed_container->depth < depth))
lb->immed_container = this;
}
}
/// Add edges that exit from \b this loop body to the list of likely \e gotos,
/// giving them the proper priority.
/// \param likely will hold the exit edges in (reverse) priority order
/// \param graph is the containing control-flow graph
void LoopBody::emitLikelyEdges(list<FloatingEdge> &likely,FlowBlock *graph)
{
while(head->getParent() != graph)
head = head->getParent();
if (exitblock != (FlowBlock *)0) {
while(exitblock->getParent() != graph)
exitblock = exitblock->getParent();
}
for(int4 i=0;i<tails.size();++i) {
FlowBlock *tail = tails[i];
while(tail->getParent() != graph)
tail = tail->getParent();
tails[i] = tail;
if (tail == exitblock) // If the exitblock was collapsed into the tail, we no longer really have an exit
exitblock = (FlowBlock *)0;
}
list<FloatingEdge>::iterator iter,enditer;
iter = exitedges.begin();;
enditer = exitedges.end();
FlowBlock *holdin = (FlowBlock *)0;
FlowBlock *holdout = (FlowBlock *)0;
while(iter != enditer) {
int4 outedge;
FlowBlock *inbl = (*iter).getCurrentEdge(outedge,graph);
++iter;
if (inbl == (FlowBlock *)0) continue;
FlowBlock *outbl = inbl->getOut(outedge);
if (iter==enditer) {
if (outbl == exitblock) { // If this is the official exit edge
holdin = inbl; // Hold off putting the edge in list
holdout = outbl;
break;
}
}
likely.push_back(FloatingEdge(inbl,outbl));
}
for(int4 i=tails.size()-1;i>=0;--i) { // Go in reverse order, to put out less preferred back-edges first
if ((holdin!=(FlowBlock *)0)&&(i==0))
likely.push_back(FloatingEdge(holdin,holdout)); // Put in delayed exit, right before final backedge
FlowBlock *tail = tails[i];
int4 sizeout = tail->sizeOut();
for(int4 j=0;j<sizeout;++j) {
FlowBlock *bl = tail->getOut(j);
if (bl == head) // If out edge to head (back-edge for this loop)
likely.push_back(FloatingEdge(tail,head)); // emit it
}
}
}
/// Exit edges have their f_loop_exit_edge property set.
/// \param graph is the containing control-flow structure
void LoopBody::setExitMarks(FlowBlock *graph)
{
list<FloatingEdge>::iterator iter;
for(iter=exitedges.begin();iter!=exitedges.end();++iter) {
int4 outedge;
FlowBlock *inloop = (*iter).getCurrentEdge(outedge,graph);
if (inloop != (FlowBlock *)0)
inloop->setLoopExit(outedge);
}
}
/// This clears the f_loop_exit_edge on any edge exiting \b this loop.
/// \param graph is the containing control-flow structure
void LoopBody::clearExitMarks(FlowBlock *graph)
{
list<FloatingEdge>::iterator iter;
for(iter=exitedges.begin();iter!=exitedges.end();++iter) {
int4 outedge;
FlowBlock *inloop = (*iter).getCurrentEdge(outedge,graph);
if (inloop != (FlowBlock *)0)
inloop->clearLoopExit(outedge);
}
}
/// Look for LoopBody records that share a \b head. Merge each \b tail
/// from one into the other. Set the merged LoopBody \b head to NULL,
/// for later clean up.
/// \param looporder is the list of LoopBody records
void LoopBody::mergeIdenticalHeads(vector<LoopBody *> &looporder)
{
int4 i=0;
int4 j=i+1;
LoopBody *curbody = looporder[i];
while(j < looporder.size()) {
LoopBody *nextbody = looporder[j++];
if (nextbody->head == curbody->head) {
curbody->addTail( nextbody->tails[0] );
nextbody->head = (FlowBlock *)0; // Mark this LoopBody as subsumed
}
else {
i += 1;
looporder[i] = nextbody;
curbody = nextbody;
}
}
i += 1; // Total size of merged array
looporder.resize(i);
}
/// Compare two loops based on the indices of the \b head and then the \e tail.
/// \param a is the first LoopBody to compare
/// \param b is the second LoopBody to compare
/// \return \b true if the first LoopBody comes before the second
bool LoopBody::compare_ends(LoopBody *a,LoopBody *b)
{
int4 aindex = a->head->getIndex();
int4 bindex = b->head->getIndex();
if (aindex != bindex)
return (aindex < bindex);
aindex = a->tails[0]->getIndex(); // Only compare the first tail
bindex = b->tails[0]->getIndex();
return (aindex < bindex);
}
/// Compare two loops based on the indices of the \b head
/// \param a is the first LoopBody to compare
/// \param looptop is the second
/// \return -1,0, or 1 if the first is ordered before, the same, or after the second
int4 LoopBody::compare_head(LoopBody *a,FlowBlock *looptop)
{
int4 aindex = a->head->getIndex();
int4 bindex = looptop->getIndex();
if (aindex != bindex)
return (aindex < bindex) ? -1 : 1;
return 0;
}
void TraceDAG::BranchPoint::createTraces(void)
{
int4 sizeout = top->sizeOut();
for(int4 i=0;i<sizeout;++i) {
if (!top->isLoopDAGOut(i)) continue;
paths.push_back( new BlockTrace(this,paths.size(),i) );
}
}
void TraceDAG::BranchPoint::markPath(void)
{
BranchPoint *cur = this;
do {
cur->ismark = !cur->ismark;
cur = cur->parent;
} while(cur != (BranchPoint *)0);
}
/// The \e distance is the number of edges from \b this up to the common
/// ancestor plus the number of edges down to the other BranchPoint.
/// We assume that \b this has had its path up to the root marked.
/// \param op2 is the other BranchPoint
/// \return the distance
int4 TraceDAG::BranchPoint::distance(BranchPoint *op2)
{
// find the common ancestor
BranchPoint *cur = op2;
do {
if (cur->ismark) { // Found the common ancestor
return (depth - cur->depth) + (op2->depth - cur->depth);
}
cur = cur->parent;
} while(cur != (BranchPoint *)0);
return depth + op2->depth + 1;
}
/// Get the first FlowBlock along the i-th BlockTrace path.
/// \param i is the index of the path
/// \return the first FlowBlock along the path
FlowBlock *TraceDAG::BranchPoint::getPathStart(int4 i)
{
int4 res=0;
int4 sizeout = top->sizeOut();
for(int4 j=0;j<sizeout;++j) {
if (!top->isLoopDAGOut(j)) continue;
if (res == i)
return top->getOut(j);
res += 1;
}
return (FlowBlock *)0;
}
TraceDAG::BranchPoint::BranchPoint(void)
{
parent = (BranchPoint *)0;
depth = 0;
pathout = -1;
ismark = false;
top = (FlowBlock *)0;
}
TraceDAG::BranchPoint::BranchPoint(BlockTrace *parenttrace)
{
parent = parenttrace->top;
depth = parent->depth + 1;
pathout = parenttrace->pathout;
ismark = false;
top = parenttrace->destnode;
createTraces();
}
TraceDAG::BranchPoint::~BranchPoint(void)
{
for(int4 i=0;i<paths.size();++i)
delete paths[i];
}
/// \param t is the parent BranchPoint
/// \param po is the index of the formal \e path out of the BranchPoint to \b this
/// \param eo is the edge index out of the BranchPoints root FlowBlock
TraceDAG::BlockTrace::BlockTrace(BranchPoint *t,int4 po,int4 eo)
{
flags = 0;
top = t;
pathout = po;
bottom = top->top;
destnode = bottom->getOut(eo);
edgelump = 1;
derivedbp = (BranchPoint *)0;
}
/// Attach BlockTrace to a virtual root BranchPoint, where there
/// isn't an explicit FlowBlock acting as branch point.
/// \param root is the virtual BranchPoint
/// \param po is the \e path out the BranchPoint to \b this
/// \param bl is the first FlowBlock along the path
TraceDAG::BlockTrace::BlockTrace(BranchPoint *root,int4 po,FlowBlock *bl)
{
flags = 0;
top = root;
pathout = po;
bottom = (FlowBlock *)0;
destnode = bl;
edgelump = 1;
derivedbp = (BranchPoint *)0;
}
/// \param op2 is the other BadEdgeScore to compare with \b this
/// \return true if \b this is LESS likely to be the bad edge than \b op2
bool TraceDAG::BadEdgeScore::compareFinal(const BadEdgeScore &op2) const
{
if (siblingedge != op2.siblingedge)
return (op2.siblingedge < siblingedge); // A bigger sibling edge is less likely to be the bad edge
// A sibling edge is more important than a terminal edge. Terminal edges have the most effect on
// node-joined returns, which usually doesn't happen on a switch edge, whereas switch's frequently
// exit to a terminal node
if (terminal !=op2.terminal)
return (terminal < op2.terminal);
if (distance != op2.distance)
return (distance < op2.distance); // Less distance between branchpoints means less likely to be bad
return (trace->top->depth < op2.trace->top->depth); // Less depth means less likely to be bad
}
/// Comparator for grouping BlockTraces with the same exit block and parent BranchPoint
/// \param op2 is the other BadEdgeScore to compare to
/// \return \b true is \b this should be ordered before \b op2
bool TraceDAG::BadEdgeScore::operator<(const BadEdgeScore &op2) const
{
int4 thisind = exitproto->getIndex();
int4 op2ind = op2.exitproto->getIndex();
if (thisind != op2ind) // Sort on exit block being traced to
return (thisind < op2ind);
FlowBlock *tmpbl = trace->top->top;
thisind = (tmpbl != (FlowBlock *)0) ? tmpbl->getIndex() : -1;
tmpbl = op2.trace->top->top;
op2ind = (tmpbl != (FlowBlock *)0) ? tmpbl->getIndex() : -1;
if (thisind != op2ind) // Then sort on branch point being traced from
return (thisind < op2ind);
thisind = trace->pathout;
op2ind = op2.trace->pathout; // Then on the branch being taken
return (thisind < op2ind);
}
/// This adds the BlockTrace to the list of potential unstructured edges.
/// Then patch up the BranchPoint/BlockTrace/pathout hierarchy.
/// \param trace is the indicated BlockTrace to remove
void TraceDAG::removeTrace(BlockTrace *trace)
{
// Record that we should now treat this edge like goto
likelygoto.push_back(FloatingEdge(trace->bottom,trace->destnode)); // Create goto record
trace->destnode->setVisitCount( trace->destnode->getVisitCount() + trace->edgelump ); // Ignore edge(s)
BranchPoint *parentbp = trace->top;
if (trace->bottom != parentbp->top) { // If trace has moved past the root branch, we can treat trace as terminal
trace->flags |= BlockTrace::f_terminal;
trace->bottom = (FlowBlock *)0;
trace->destnode = (FlowBlock *)0;
trace->edgelump = 0;
// Do NOT remove from active list
return;
}
// Otherwise we need to actually remove the path from the BranchPoint as the root branch will be marked as a goto
removeActive(trace); // The trace will no longer be active
int4 size = parentbp->paths.size();
for(int4 i=trace->pathout+1;i<size;++i) { // Move every trace above -trace-s pathout down one slot
BlockTrace *movedtrace = parentbp->paths[i];
movedtrace->pathout -= 1; // Correct the trace's pathout
BranchPoint *derivedbp = movedtrace->derivedbp;
if (derivedbp != (BranchPoint *)0)
derivedbp->pathout -= 1; // Correct any derived BranchPoint's pathout
parentbp->paths[i-1] = movedtrace;
}
parentbp->paths.pop_back(); // Remove the vacated slot
delete trace; // Delete the record
}
/// \brief Process a set of conflicting BlockTrace objects that go to the same exit point.
///
/// For each conflicting BlockTrace, calculate the minimum distance between it and any other BlockTrace.
/// \param start is the beginning of the list of conflicting BlockTraces (annotated as BadEdgeScore)
/// \param end is the end of the list of conflicting BlockTraces
void TraceDAG::processExitConflict(list<BadEdgeScore>::iterator start,list<BadEdgeScore>::iterator end)
{
list<BadEdgeScore>::iterator iter;
BranchPoint *startbp;
while(start != end) {
iter = start;
++iter;
startbp = (*start).trace->top;
if (iter != end) {
startbp->markPath(); // Mark path to root, so we can find common ancestors easily
do {
if (startbp == (*iter).trace->top) { // Edge coming from same BranchPoint
(*start).siblingedge += 1;
(*iter).siblingedge += 1;
}
int4 dist = startbp->distance( (*iter).trace->top );
// Distance is symmetric with respect to the pair of traces,
// Update minimum for both traces
if (((*start).distance == -1)||((*start).distance > dist))
(*start).distance = dist;
if (((*iter).distance == -1)||((*iter).distance > dist))
(*iter).distance = dist;
++iter;
} while(iter != end);
startbp->markPath(); // Unmark the path
}
++start;
}
}
/// Run through the list of active BlockTrace objects, annotate them using
/// the BadEdgeScore class, then select the BlockTrace which is the most likely
/// candidate for an unstructured edge.
/// \return the BlockTrace corresponding to the unstructured edge
TraceDAG::BlockTrace *TraceDAG::selectBadEdge(void)
{
list<BadEdgeScore> badedgelist;
list<BlockTrace *>::const_iterator aiter;
for(aiter=activetrace.begin();aiter!=activetrace.end();++aiter) {
if ((*aiter)->isTerminal()) continue;
if (((*aiter)->top->top == (FlowBlock *)0)&&((*aiter)->bottom==(FlowBlock *)0))
continue; // Never remove virtual edges
badedgelist.push_back(BadEdgeScore());
BadEdgeScore &score( badedgelist.back() );
score.trace = *aiter;
score.exitproto = score.trace->destnode;
score.distance = -1;
score.siblingedge = 0;
score.terminal = (score.trace->destnode->sizeOut()==0) ? 1 : 0;
}
badedgelist.sort();
list<BadEdgeScore>::iterator iter=badedgelist.begin();
list<BadEdgeScore>::iterator startiter = iter;
FlowBlock *curbl = (*iter).exitproto;
int4 samenodecount = 1;
++iter;
while(iter != badedgelist.end()) { // Find traces to the same exitblock
BadEdgeScore &score( *iter );
if (curbl == score.exitproto) {
samenodecount += 1; // Count another trace to the same exit
++iter;
}
else { // A new exit node
if (samenodecount > 1)
processExitConflict(startiter,iter);
curbl = score.exitproto;
startiter = iter;
samenodecount = 1;
++iter;
}
}
if (samenodecount > 1) // Process possible final group of traces exiting to same block
processExitConflict(startiter,iter);
iter = badedgelist.begin();
list<BadEdgeScore>::iterator maxiter = iter;
++iter;
while(iter != badedgelist.end()) {
if ((*maxiter).compareFinal( *iter )) {
maxiter = iter;
}
++iter;
}
return (*maxiter).trace;
}
/// \param trace is the BlockTrace to mark as \e active
void TraceDAG::insertActive(BlockTrace *trace)
{
activetrace.push_back(trace);
list<BlockTrace *>::iterator iter = activetrace.end();
--iter;
trace->activeiter = iter;
trace->flags |= BlockTrace::f_active;
activecount += 1;
}
/// \param trace is the BlockTrace to be unmarked
void TraceDAG::removeActive(BlockTrace *trace)
{
activetrace.erase(trace->activeiter);
trace->flags &= ~((uint4)BlockTrace::f_active);
activecount -= 1;
}
/// Verify the given BlockTrace can push into the next FlowBlock (\b destnode).
/// A FlowBlock node can only be \e opened if all the incoming edges have been traced.
/// \param trace is the given BlockTrace to push
/// \return \b true is the new node can be opened
bool TraceDAG::checkOpen(BlockTrace *trace)
{
if (trace->isTerminal()) return false; // Already been opened
bool isroot = false;
if (trace->top->depth == 0) {
if (trace->bottom == (FlowBlock *)0)
return true; // Artificial root can always open its first level (edge is not real edge)
isroot = true;
}
FlowBlock *bl = trace->destnode;
if ((bl == finishblock)&&(!isroot))
return false; // If there is a designated exit, only the root can open it
int4 ignore = trace->edgelump + bl->getVisitCount();
int4 count = 0;
for(int4 i=0;i<bl->sizeIn();++i) {
if (bl->isLoopDAGIn(i)) {
count += 1;
if (count > ignore) return false;
}
}
return true;
}
/// Given that a BlockTrace can be opened into its next FlowBlock node,
/// create a new BranchPoint at that node, and set up new sub-traces.
/// \param parent is the given BlockTrace to split
/// \return an iterator (within the \e active list) to the new BlockTrace objects
list<TraceDAG::BlockTrace *>::iterator TraceDAG::openBranch(BlockTrace *parent)
{
BranchPoint *newbranch = new BranchPoint( parent );
parent->derivedbp = newbranch;
if (newbranch->paths.size() == 0) { // No new traces, return immediately to parent trace
delete newbranch;
parent->derivedbp = (BranchPoint *)0;
parent->flags |= BlockTrace::f_terminal; // marking it as terminal
parent->bottom = (FlowBlock *)0;
parent->destnode = (FlowBlock *)0;
parent->edgelump = 0;
return parent->activeiter;
}
removeActive(parent);
branchlist.push_back( newbranch );
for(int4 i=0;i<newbranch->paths.size();++i)
insertActive(newbranch->paths[i]);
return newbranch->paths[0]->activeiter;
}
/// For the given BlockTrace, make sure all other sibling BlockTraces from its
/// BranchPoint parent either terminate or flow to the same FlowBlock node.
/// If so, return \b true and pass back that node as the \b exitblock.
/// \param trace is the given BlockTrace
/// \param exitblock will hold the passed back exit block
/// \return \b true is the BlockTrace can be retired
bool TraceDAG::checkRetirement(BlockTrace *trace,FlowBlock *&exitblock)
{
if (trace->pathout != 0) return false; // Only check, if this is the first sibling
BranchPoint *bp = trace->top;
if (bp->depth == 0) { // Special conditions for retirement of root branch point
for(int4 i=0;i<bp->paths.size();++i) {
BlockTrace *curtrace = bp->paths[i];
if (!curtrace->isActive()) return false;
if (!curtrace->isTerminal()) return false; // All root paths must be terminal
}
return true;
}
FlowBlock *outblock = (FlowBlock *)0;
for(int4 i=0;i<bp->paths.size();++i) {
BlockTrace *curtrace = bp->paths[i];
if (!curtrace->isActive()) return false;
if (curtrace->isTerminal()) continue;
if (outblock == curtrace->destnode) continue;
if (outblock != (FlowBlock *)0) return false;
outblock = curtrace->destnode;
}
exitblock = outblock;
return true;
}
/// \brief Retire a BranchPoint, updating its parent BlockTrace
///
/// Knowing a given BranchPoint can be retired, remove all its BlockTraces
/// from the \e active list, and update the BranchPoint's parent BlockTrace
/// as having reached the BlockTrace exit point.
/// \param bp is the given BranchPoint
/// \param exitblock is unique exit FlowBlock (calculated by checkRetirement())
/// \return an iterator to the next \e active BlockTrace to examine
list<TraceDAG::BlockTrace *>::iterator TraceDAG::retireBranch(BranchPoint *bp,FlowBlock *exitblock)
{
FlowBlock *edgeout_bl = (FlowBlock *)0;
int4 edgelump_sum = 0;
for(int4 i=0;i<bp->paths.size();++i) {
BlockTrace *curtrace = bp->paths[i];
if (!curtrace->isTerminal()) {
edgelump_sum += curtrace->edgelump;
if (edgeout_bl == (FlowBlock *)0)
edgeout_bl = curtrace->bottom;
}
removeActive(curtrace); // Child traces are complete and no longer active
}
if (bp->depth == 0) // If this is the root block
return activetrace.begin(); // This is all there is to do
if (bp->parent != (BranchPoint *)0) {
BlockTrace *parenttrace = bp->parent->paths[bp->pathout];
parenttrace->derivedbp = (BranchPoint *)0; // Derived branchpoint is gone
if (edgeout_bl == (FlowBlock *)0) { // If all traces were terminal
parenttrace->flags |= BlockTrace::f_terminal;
parenttrace->bottom = (FlowBlock *)0;
parenttrace->destnode = (FlowBlock *)0;
parenttrace->edgelump = 0;
}
else {
parenttrace->bottom = edgeout_bl;
parenttrace->destnode = exitblock;
parenttrace->edgelump = edgelump_sum;
}
insertActive(parenttrace); // Parent trace gets re-activated
return parenttrace->activeiter;
}
return activetrace.begin();
}
/// The \b visitcount field is only modified in removeTrace() whenever we put an edge
/// in the \b likelygoto list.
void TraceDAG::clearVisitCount(void)
{
list<FloatingEdge>::const_iterator iter;
for(iter=likelygoto.begin();iter!=likelygoto.end();++iter)
(*iter).getBottom()->setVisitCount(0);
}
/// Prepare for a new trace using the provided storage for the likely unstructured
/// edges that will be discovered.
/// \param lg is the container for likely unstructured edges
TraceDAG::TraceDAG(list<FloatingEdge> &lg)
: likelygoto(lg)
{
activecount = 0;
finishblock = (FlowBlock *)0;
}
TraceDAG::~TraceDAG(void)
{
for(int4 i=0;i<branchlist.size();++i)
delete branchlist[i];
}
/// Given the registered root FlowBlocks, create the initial (virtual) BranchPoint
/// and an associated BlockTrace for each root FlowBlock.
void TraceDAG::initialize(void)
{
BranchPoint *rootBranch = new BranchPoint(); // Create a virtual BranchPoint for all entry points
branchlist.push_back(rootBranch);
for(uint4 i=0;i<rootlist.size();++i) { // Find the entry points
BlockTrace *newtrace = new BlockTrace(rootBranch,rootBranch->paths.size(),rootlist[i]);
rootBranch->paths.push_back(newtrace);
insertActive(newtrace);
}
}
/// From the root BranchPoint, recursively push the trace. At any point where pushing
/// is no longer possible, select an appropriate edge to remove and add it to the
/// list of likely unstructured edges. Then continue pushing the trace.
void TraceDAG::pushBranches(void)
{
FlowBlock *exitblock;
current_activeiter = activetrace.begin();
missedactivecount = 0;
while(activecount > 0) {
if (current_activeiter == activetrace.end())
current_activeiter = activetrace.begin();
BlockTrace *curtrace = *current_activeiter;
if (missedactivecount >= activecount) { // Could not push any trace further
BlockTrace *badtrace = selectBadEdge(); // So we pick an edge to be unstructured
removeTrace(badtrace); // destroy the trace
current_activeiter = activetrace.begin();
missedactivecount = 0;
}
else if (checkRetirement(curtrace,exitblock)) {
current_activeiter = retireBranch(curtrace->top,exitblock);
missedactivecount = 0;
}
else if (checkOpen(curtrace)) {
current_activeiter = openBranch(curtrace);
missedactivecount = 0;
}