forked from rose-compiler/rose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
moveDeclarationToInnermostScope.C
2678 lines (2420 loc) · 117 KB
/
moveDeclarationToInnermostScope.C
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
/*
* By Chunhua "Leo" Liao, 9/3/2014
*
* A tool to move declarations into innermost scopes when applicable.
* On the request from Jeff Keasler, we provide this transformation:
* For a declaration, find the innermost scope we can move it into, without breaking the code's original semantics
* For a single use place, move to the innermost scope.
* For the case of multiple uses, we may need to duplicate the declarations and move to two scopes if there is no variable reuse in between,
* otherwise, we move the declaration into the innermost common scope of the multiple uses.
* **********************************************************************************************
* User instructions:
*
* The translator accepts the following options:
*
* -rose:merge_decl_assign will merge the moved declaration with an immediately followed assignment.
*
* -rose:aggressive : turn on the aggressive mode, which will move declarations with initializers, and across loop boundaries.
* A warning message will be sent out if the move crosses a loop boundary. Without this option, the tool only moves a declaration
* without an initializer to be safe.
*
*
* -rose:debug, which is turned on by default in the testing.
* Some dot graph files will be generated for scope trees of variables for debugging purpose.
*
* -rose:keep_going will ignore assertions as much as possible (currently on skip the assertion on complex for loop initialization statement list).
* Without this option, the tool will stop on assertion failures.
*
* -rose:identity will turn off any transformations and act like an identity translator. Useful for debugging purposes.
*
* -rose:trans-tracking will turn on the transformation tracking mode, showing the source statements of a move/merged declaration
*
* **********************************************************************************************
* Internals: (For people who are interested in how this tool works internally)
*
* Data structure: we maintain a scope tree, in which each node is
* a scope 1) defining or 2) use the variable, or 3) is live in between .
* Several implementation choices for storing the tree
* 1) The scope tree reuses the AST. AST attribute is used to store extra information
* 2) A dedicated scope tree independent from AST.
* 3) Storing individual scope chains (paths) in the tree
* hard to maintain consistency if we trim paths, hard to debug.
*
* For efficiency, we save only a single scope node if there are multiple uses in the same scope.
* Also for two use scopes with enclosing relationship, we only store the outer scope in the scope tree and trim the rest.
*
* Algorithm V1 :
* Save the scope of the declaration int DS (declaration statement)
*
* Step 1: create a scope tree first, with trimming
* Pre-order traversal to find all variable references to the declaration
* For each reference place
* {
* back track all its scopes until we reach DS
* if DS == US, nothing can be done to move the declaration, stop.
* all scopes tracked are formed into a scope chain (a vector: US .. DS).
*
* create a scope node of use type, called US.
* For all scopes in between, create nodes named intermediate scope or IS.
* Add Ds-IS1-IS2..-US (reverse order of the scope chain) into the scope tree, consider consolidating overlapped scope chains;
* 1) if an intermediate scope is equal to a use scope of another scope chain; stop add the rest of this chain.
* 2) if we are adding a use scope into the scope tree, but the same scope is already added by a intermediate scope from anther chain
* we mark the existing scope node as a use scope, and remove its children from the scope tree.
* }
*
* Step 2: find the scopes to move the declaration into
* find the innermost scope containing all paths to leaves: inner_scope: single parent, multiple children
* count the number of children of inner_scope:
* if this is only one leaf: move the declaration to the innermost scope
* if there are two scopes:
* not liveout for the variable in question? Duplicate the declaration and move to each scope chain.
* if yes liveout in between two scopes. No duplication, move the declaration to inner_scope
*
* Iterative moving process:
*
* For duplicated declarations inserted into inner scopes, we have to consider if they can be moved further.
* So we use a worklist to store all variable declarations to be considered.
* The worklist is initialized with original declarations in the code.
* New declarations are added into the worklist during the duplication/insertion process.
* The entire process terminate when the worklist becomes empty.
*
* Algorithm V2: further optimization on top of v1
* for analysis-move, we find all bottom scopes at once and only do move once after that
* the scope trees are the new worklist now.
* This eliminates the intermediate moving of declarations and is much more efficient.
* Details for how to do the iterative analysis can be found at comments for findFinalTargetScopes ()
*
* //TODO optimize efficiency for multiple declarations
* //TODO move to a separated source file or even namespace
*/
#include "rose.h"
#include <CommandLine.h>
#include "wholeAST_API.h"
#include "transformationTracking.h"
#include <iostream>
#include <queue> // used for a worklist of declarations to be moved
#include <stack> // used for a worklist of declarations to be moved , first found, last processing
#include <boost/foreach.hpp>
#include <map> // used to store special var reference's scope
#include <Sawyer/CommandLine.h>
// another level of control over transformation tracking code
#define ENABLE_TRANS_TRACKING 1
static const char *purpose = "This tool moves variable declarations to their innermost possible scopes";
static const char *description =
"This tool is designed to help parallelizing code by moving variable declarations "
"into their innermost possible scopes (essentially making many of them private)."
"As a result, less variables need to be shared.";
using namespace std;
using namespace Rose;
using namespace SageInterface;
class Scope_Node;
//--- a set of internal flags ----------------------
//! Enable debugging mode or not
bool debug = false;
//! Acting as an identity translator or not
bool isIdentity = false;
//! We now use improved algorithm v2, not exposed to users now
bool useAlgorithmV2 = true;
//! If we keep track of transformation, mapping nodes back to original input nodes
bool transTracking = false;
//! Users want to see the tool working by default
//! By default ASSERT should block the execution to find issues.
//! But some users want to keep the tool going even when some assertion fails.
//!This is only supported by moveDeclarationToInnermostScope() and associated functions for now
bool tool_keep_going = false;
//! Users want to see conservative and aggressive moving
// Like any other compiler-based tools. We do things conservatively by default.
// Declarations with initializers will not be moved
// if it is set to false. Declaration with initializers will be moved,
// sends out warning if it crosses a loop boundaries in between.
bool decl_mover_conservative = true;
//! If we further merge a naked variable declaration (without initialization) with a followed variable assignment within the same scope
bool merge_decl_assign = false;
//! This function creates a description of command-line switches that are recognized by the too.
Sawyer::CommandLine::SwitchGroup commandLineSwitches();
//--------------end of internal flags ----------------
// a global variable storing inserted declaration per input file processed
static std::vector <SgVariableDeclaration* > inserted_decls;
//! Move a declaration to a scope which is the closest to the declaration's use places. It may generate new declarations to be considered later on so worklist is used.
bool moveDeclarationToInnermostScope_v1(SgVariableDeclaration* decl, std::stack<SgVariableDeclaration *> &worklist, bool debug/*= false */);
//! An alternative algorithm: separating analysis from transformation into two phases. The move is final.
// Improved 2-step algorithm:
// Step 1: iterative subalgorithm to find the real bottom scopes
// Step 2: copy & move source declaration to all the bottom scopes.
// return the final scopes accepting the moved declarations.
//std::vector <SgVariableDeclaration*>
void moveDeclarationToInnermostScope_v2(SgVariableDeclaration* decl, std::vector <SgVariableDeclaration*>& my_inserted_decls, bool debug/*= false */);
// store scope of var ref used in array types. There is no easy way to find it by AST traversal.
// e.g. double *buffer = new double[numItems] ; // numItems is referenced. But cannot get its scope. We store SgConstructorInitialzer for it to establish its scope info.
// TODO: report this issue to Dan.
static std::map <SgVarRefExp *, SgExpression*> specialVarRefScopeExp;
// Keep track which scope tree has been considered as a new root for further possible decl moves.
// This is used to avoid considering the same one multiple times, causing infinite looping.
static std::map <Scope_Node*, bool> scopeTreeConsideredMap;
//! Check if a statement is an assignment to a variable
//TODO : move to SageInterface ?
static bool isAssignmentStmtOf(SgStatement * stmt, SgInitializedName* init_name)
{
bool rt = false;
ROSE_ASSERT (stmt != NULL);
ROSE_ASSERT (init_name != NULL);
if (SgExprStatement* exp_stmt = isSgExprStatement(stmt))
{
if (SgAssignOp * assign_op = isSgAssignOp (exp_stmt->get_expression()))
{
if (SgVarRefExp* var_exp = isSgVarRefExp (assign_op->get_lhs_operand()) )
{
if (var_exp->get_symbol()->get_declaration() == init_name)
rt = true;
}
}
}
return rt;
}
#if 0
/*
We cannot simply merge a declaration at a location A with an assignment at a location B.
This is essentially moving one statement across some code region so liveness or side effect analysis info. is needed for safety.
If the assignment's right hand operand uses any variable declared or written somewhere between A and B,
we cannot move it up and merge it with the declaration.
int i=0
int tmp =10;
i = myarray[tmp]; // this cannot be moved up
Consider only right hand is not enough, the variable declared on left side must be in the set by default.
int j;
{
// initially built into scope tree, later trimmed.
j = 0;
}
//this should trigger trimming the previous path
j = 2; // this cannot be moved up ??
The best solution is liveness analysis (or side effect analysis).
An approximation being used now is to not move when there is any references to variables used by the assignment (either lhs or rhs).
Pre-order iteration of decls is needed to check if it is mergeable: move assign up to merge with the declaration.
Example: if use reverse order: double abc will be checked first, the last assignment cannot be moved up since rhs uses aa, which is defined in between.
Using pre-order : double aa is considered first, aa=a[i] is moved up. Then double abc; abc= aa* aa; can be merged also.
double aa;
double abc; //
aa = a[i];
abc = aa * aa; //
*/
static bool isUpwardMergeable (SgVariableDeclaration* decl, SgExprStatement* assign_stmt)
{
bool rt = false;
ROSE_ASSERT (decl != NULL);
ROSE_ASSERT (assign_stmt != NULL);
std::vector <SgStatement* > stmts_in_middle ;
SgStatement* next_stmt = SageInterface::getNextStatement (decl);
while (next_stmt != assign_stmt && next_stmt != NULL)
{
stmts_in_middle.push_back(next_stmt);
next_stmt = SageInterface::getNextStatement (next_stmt);
}
if (next_stmt == NULL)
{
cout<<"Error in isMergeable (decl, assign_stmt): assign_stmt is not one of next statements for decl!"<<endl;
ROSE_ASSERT (false);
}
// collect all variables used in between
// We must use SgInitializedName instead of SgVarRefExp since a declaration in between has only SgInitializedName.
std::set<SgVariableSymbol* > usedSymbolsInBetween;
std::vector <SgVarRefExp* > usedVarRefsInRhs;
std::set<SgVariableSymbol* > usedSymbolsInAssignment;
std::set<SgVariableSymbol* > intersectSymbols;
// 1. Collect symbols used in between
// TODO wrap into a SageInterface function: query both SgVarRefExp (including these used in types) and SgInitializedName
for (size_t i=0; i< stmts_in_middle.size(); i++)
{
std::vector<SgVarRefExp*> varRefsInBetween;
// collect variable references first
SageInterface::collectVarRefs (stmts_in_middle[i], varRefsInBetween);
// convert varRef to SgInitializedName
for (size_t j = 0; j< varRefsInBetween.size(); j++)
{
if (transTracking)
{
cout<<"found referenced/used symbol in between "<< varRefsInBetween[j]->get_symbol()->get_name() <<endl;
}
usedSymbolsInBetween.insert (varRefsInBetween[j]->get_symbol());
}
// collect initialized name also for declarations
if (SgVariableDeclaration* mid_decl = isSgVariableDeclaration (stmts_in_middle[i]))
{
if (transTracking)
cout<<"found declared /used symbol in between "<< SageInterface::getFirstVarSym(mid_decl)->get_name() <<endl;
usedSymbolsInBetween.insert(SageInterface::getFirstVarSym(mid_decl));
}
}
// 2. collect symbols used by assign_op's rhs and lhs (must consider both sides!)
SageInterface::collectVarRefs ( isSgAssignOp(assign_stmt->get_expression())->get_rhs_operand(), usedVarRefsInRhs);
for (size_t k=0; k< usedVarRefsInRhs.size(); k++)
{
if (transTracking)
cout<< "found used in assignment rhs" << usedVarRefsInRhs[k]->get_symbol()-> get_name()<<endl;
usedSymbolsInAssignment.insert (usedVarRefsInRhs[k]->get_symbol());
}
if (transTracking)
cout<< "found used in assignment lhs" << SageInterface::getFirstVarSym (decl)-> get_name()<<endl;
usedSymbolsInAssignment.insert (SageInterface::getFirstVarSym (decl));
// intersection is not NULL, cannot merge or move across the area using the variable
set_intersection(usedSymbolsInBetween.begin(), usedSymbolsInBetween.end(), usedSymbolsInAssignment.begin(), usedSymbolsInAssignment.end(),
inserter (intersectSymbols, intersectSymbols.begin()));
if (intersectSymbols.size() == 0 )
rt = true;
if (transTracking)
{
cout<< "isUpwardMergeable () returns "<< rt<< "----------------" <<endl;
}
return rt;
}
#endif
// Check if a decl can be moved downwards to an assignment
/*
current algorithm: scan statements in between, if declared variable is not referenced, we can do the downwards merge
double dx2; // decl
double dy1 = yy[i2] - y[i2];
double dy2;
double a1;
double a2;
dx2 = x[i1] - x[i2]; // assignment
*/
static bool isDownwardMergeable (SgVariableDeclaration* decl, SgExprStatement* assign_stmt)
{
bool rt = false;
ROSE_ASSERT (decl != NULL);
ROSE_ASSERT (assign_stmt != NULL);
std::vector <SgStatement* > stmts_in_middle ;
SgStatement* next_stmt = SageInterface::getNextStatement (decl);
while (next_stmt != assign_stmt && next_stmt != NULL)
{
stmts_in_middle.push_back(next_stmt);
next_stmt = SageInterface::getNextStatement (next_stmt);
}
if (next_stmt == NULL)
{
cout<<"Error in isDownwardMergeable (decl, assign_stmt): assign_stmt is not one of next statements for decl!"<<endl;
ROSE_ASSERT (false);
}
// collect all variables used in between
// We must use SgInitializedName instead of SgVarRefExp since a declaration in between has only SgInitializedName.
std::set<SgVariableSymbol* > usedSymbolsInBetween;
// 1. Collect symbols used in between
// TODO wrap into a SageInterface function: query both SgVarRefExp (including these used in types) and SgInitializedName
for (size_t i=0; i< stmts_in_middle.size(); i++)
{
std::vector<SgVarRefExp*> varRefsInBetween;
// collect variable references first
SageInterface::collectVarRefs (stmts_in_middle[i], varRefsInBetween);
// convert varRef to SgInitializedName
for (size_t j = 0; j< varRefsInBetween.size(); j++)
{
if (transTracking)
{
cout<<"found referenced/used symbol in between "<< varRefsInBetween[j]->get_symbol()->get_name() <<endl;
}
usedSymbolsInBetween.insert (varRefsInBetween[j]->get_symbol());
}
// collect initialized name also for declarations
if (SgVariableDeclaration* mid_decl = isSgVariableDeclaration (stmts_in_middle[i]))
{
if (transTracking)
cout<<"found declared /used symbol in between "<< SageInterface::getFirstVarSym(mid_decl)->get_name() <<endl;
usedSymbolsInBetween.insert(SageInterface::getFirstVarSym(mid_decl));
}
}
SgVariableSymbol * declared_sym = SageInterface::getFirstVarSym (decl);
if (usedSymbolsInBetween.find(declared_sym) ==usedSymbolsInBetween.end()) // not found? We can safely do downwards merge then
rt = true;
if (transTracking)
{
cout<< "isDownwardMergeable () returns "<< rt<< "----------------" <<endl;
}
return rt;
}
// for each decl in the declaration vector,
// if it has no initialization, we find the first followed assignment within the same scope and merge the assignment into the decl as an initializer
static void collectiveMergeDeclarationAndAssignment (std::vector <SgVariableDeclaration*> decls)
{
// declarations which are not UpwardMergeable with its assignment
// std::vector <SgVariableDeclaration*> remaining_decls;
// Must not separate analysis and transformation sine the success of next stmt relies on previous merge
// pre-order iteration to check if it is mergeable: move assign up to merge with the declaration.
#if 0
//for (size_t i = 0; i< decls.size(); i++)
// The top level traversal is reverse-order of preorder
// However, to support the isUpwardMergeable()'s move-up analysis (move assign up to the decl)
// we must scan candidate decls using pre-order, or multiple decls case will not work properly!
for (int i = decls.size()-1; i>=0; i--) // -- case will cause overflow for size_t type, must not use size_t!!
{
SgVariableDeclaration* current_decl = decls[i];
ROSE_ASSERT (current_decl != NULL);
SgInitializedName* init_name = SageInterface::getFirstInitializedName (current_decl);
ROSE_ASSERT (init_name!= NULL);
SgInitializer * initor = init_name->get_initptr();
if (initor == NULL)
{
SgStatement* next_stmt = SageInterface::getNextStatement(current_decl);
while (next_stmt)
{
if (isAssignmentStmtOf (next_stmt, init_name) )
{
if (isUpwardMergeable (current_decl, isSgExprStatement (next_stmt)))
{
//SageInterface::mergeDeclarationAndAssignment (current_decl, isSgExprStatement (next_stmt));
SageInterface::mergeAssignmentWithDeclaration (isSgExprStatement (next_stmt), current_decl);
#if ENABLE_TRANS_TRACKING
if (transTracking)
{
// No need to patch up IDs for a merge transformation
// directly record input node
TransformationTracking::addInputNode (current_decl, next_stmt);
}
#endif
} // end if Mergeable
else
{
// remaining_decls.push_back(current_decl);
}
// mergeable or , we stop going to next stmt
next_stmt = NULL; // We stop when the first match is found, we also stop if the first matching assign is not mergeable
}
else
next_stmt = SageInterface::getNextStatement(next_stmt);
}
} // end if null initializer
} // end for
#endif
//
// Consider downward merge for the remaining declarations
// Does the order matter??
for (int i = decls.size()-1; i>=0; i--) // i-- will cause overflow for size_t type, must not use size_t!!
{
SgVariableDeclaration* current_decl = decls[i];
ROSE_ASSERT (current_decl != NULL);
SgInitializedName* init_name = SageInterface::getFirstInitializedName (current_decl);
ROSE_ASSERT (init_name!= NULL);
SgInitializer * initor = init_name->get_initptr();
if (initor == NULL)
{
SgStatement* next_stmt = SageInterface::getNextStatement(current_decl);
while (next_stmt)
{
if (isAssignmentStmtOf (next_stmt, init_name) )
{
if (isDownwardMergeable(current_decl, isSgExprStatement (next_stmt)))
{
SageInterface::mergeDeclarationWithAssignment(current_decl, isSgExprStatement (next_stmt));
#if ENABLE_TRANS_TRACKING
if (transTracking)
{
// No need to patch up IDs for a merge transformation
// directly record input node
TransformationTracking::addInputNode (current_decl, next_stmt);
}
#endif
} // end if Mergeable
// mergeable or not , we stop going to next stmt
next_stmt = NULL; // We stop when the first match is found, we also stop if the first matching assign is not mergeable
}
else
next_stmt = SageInterface::getNextStatement(next_stmt);
}
} // end if null initializer
} // end for
}
class visitorTraversal : public AstSimpleProcessing
{
protected:
void virtual visit (SgNode* n)
{
#if 0
printf ("In visitorTraversal::visit(): n = %p = %s \n",n,n->class_name().c_str());
#endif
// if (isSgFunctionDeclaration(n)!=NULL)
// This will match SgTemplateInstantiationFunctionDecl, which is not wanted.
if (n->variantT() == V_SgFunctionDeclaration || n->variantT() == V_SgMemberFunctionDeclaration)
{
ROSE_ASSERT (n->variantT() != V_SgTemplateInstantiationFunctionDecl);
SgFunctionDeclaration* func = isSgFunctionDeclaration(n);
ROSE_ASSERT(func != NULL);
if (func->get_definition() == NULL) return;
// TODO: skip things from headers.
// skip compiler generated codes, mostly from template headers
if (func->get_file_info()->isCompilerGenerated())
{
return;
}
SgBasicBlock* body = func->get_definition()->get_body();
if (body == NULL) return;
// Prepare the function body: ensure body basic block for while, for, if, etc.
SageInterface::changeAllBodiesToBlocks (body, false);
Rose_STL_Container<SgNode*> var_decls= NodeQuery::querySubTree(body,V_SgVariableDeclaration);
if (debug )
cout<<"Number of declarations to be considered = "<<var_decls.size()<<endl;
// std::queue<SgVariableDeclaration* > worklist;
std::stack<SgVariableDeclaration* > worklist;
for (size_t i=0; i< var_decls.size(); i++)
//Liao 2015/11/2
//reverse the order for better result: int i; int j; order will be preserved after moving both of them to the new location
//for (size_t i=var_decls.size()-1; i>=0; i--)
{
SgVariableDeclaration* decl = isSgVariableDeclaration(var_decls[i]);
ROSE_ASSERT(decl!= NULL);
// skip compiler generated (frontend) declarations
if (decl->get_file_info()->isCompilerGenerated())
continue;
worklist.push(decl);
}
// using a worklist instead of a fixed vector, since we will iteratively consider declarations added in the process.
// e.g. we insert a declaration into the true/false bodies of if statement if a target scope is a if statement.
// These two inserted declarations will be further considered.
while (!worklist.empty())
{
SgVariableDeclaration* decl = isSgVariableDeclaration(worklist.top());
ROSE_ASSERT(decl!= NULL);
worklist.pop();
//bool result=false;
if (SageInterface::isStatic(decl))
{
if (debug)
cout<<"skipping a static variable declaration .."<<endl;
}
else
{
bool null_initializer = false;
SgInitializedName* init_name = SageInterface::getFirstInitializedName (decl);
ROSE_ASSERT (init_name!= NULL);
SgInitializer * initor = init_name->get_initptr();
if (initor == NULL)
null_initializer = true;
#if 0
else
{
SgAssignInitializer* assign_initor = isSgAssignInitializer (initor);
if (assign_initor != NULL)
{
if (isSgValueExp(assign_initor->get_operand()))
null_or_literal_initializer = true;
}
}
#endif
// conservative mode: Only move declarations with no initializer
if (decl_mover_conservative)
{
if (debug)
cout<<"Consiering conservative moving for decl: "<<decl->get_file_info()->get_line() <<endl;
if (null_initializer)
{
#if 0
printf ("In visitorTraversal::visit(): n = %p = %s (conservative moving: useAlgorithmV2 = %s) \n",n,n->class_name().c_str(),useAlgorithmV2 ? "true" : "false");
#endif
if (useAlgorithmV2)
moveDeclarationToInnermostScope_v2(decl, inserted_decls, debug);
else
moveDeclarationToInnermostScope_v1(decl, worklist, debug);
#if 0
printf ("DONE: In visitorTraversal::visit(): n = %p = %s (conservative moving: useAlgorithmV2 = %s) \n",n,n->class_name().c_str(),useAlgorithmV2 ? "true" : "false");
#endif
}
else
{
if (debug)
cout<<"Skipping a declaration since it has initializer .."<<endl;
}
}
else // aggressive move
{
if (debug)
cout<<"Using aggressive moving for decl .."<<endl;
if (useAlgorithmV2)
moveDeclarationToInnermostScope_v2(decl, inserted_decls, debug);
else
moveDeclarationToInnermostScope_v1(decl, worklist, debug);
}
} // end if non-static
} // end while (worklist)
} // end if function
} // end visit()
};
// TOO1 (2014/12/05): Temporarily added this to support keep-going in rose-sh.
std::vector<std::string>
GetSourceFilenamesFromCommandline(const std::vector<std::string>& argv)
{
std::vector<std::string> filenames =
CommandlineProcessing::generateSourceFilenames(argv, false);
return filenames;
}
//! Initialize the switch group and its switches.
Sawyer::CommandLine::SwitchGroup commandLineSwitches() {
using namespace Sawyer::CommandLine;
SwitchGroup switches("The move tool switches");
switches.doc("These switches control the move tool. ");
switches.name("rose"); // be backwards compatible with -rose:optionX
switches.insert(Switch("debug")
.intrinsicValue(true, debug)
.doc("Enable the debugging mode."));
switches.insert(Switch("identity")
.intrinsicValue(true, isIdentity)
.doc("Enable acting like an identity translator, not doing any transformation at all."));
switches.insert(Switch("trans-tracking")
.intrinsicValue(true, transTracking)
.doc("Enable tracking of transformation steps."));
switches.insert(Switch("keep_going") //TODO: how to keep this option to be used by later phases?
.intrinsicValue(true, tool_keep_going)
.doc("Allow the tool to proceed without being stopped by assertions."));
switches.insert(Switch("aggressive")
.intrinsicValue(true, decl_mover_conservative)
.doc("Enable aggressive mode: declarations with initializers will be moved."));
switches.insert(Switch("merge_decl_assign")
.intrinsicValue(true, merge_decl_assign)
.doc("After the move, further merge the moved naked variable declaration (without initialization) with a followed variable assignment."));
return switches;
}
//! Command line processing
static std::vector<std::string> parseCommandLine(std::vector< std::string > & argvList) // this will cause trouble, not sure why.
//static std::vector<std::string> parseCommandLine(int argc, char* argv[])
{
using namespace Sawyer::CommandLine;
Parser p = Rose::CommandLine::createEmptyParserStage(purpose, description);
p.doc("Synopsis", "@prop{programName} @v{switches} @v{files}...");
p.longPrefix("-");
// initialize generic Sawyer switches: assertion, logging, threads, etc.
p.with(Rose::CommandLine::genericSwitches());
// initialize tool switches
p.with(commandLineSwitches());
// switches to be passed to ROSE, somehow not working yet. TODO
SwitchGroup tool("ROSE's built-in switches");
// We want the "--rose:help" switch to appear in the Sawyer documentation but we have to pass it to the next stage also. We
// could do this two different ways.
// 1. The older way (that still works) is to have Sawyer process the switch and then we
// prepend it into the returned vector for processing by later stages.
#if 0
// 2. The newer way is to set the switch's "skipping"
// property that causes Sawyer to treat it as a skipped (unrecognized) switch. We'll use SKIP_STRONG, but SKIP_WEAK is
// sort of a cross between Sawyer recognizing it and not recognizing it.
tool.insert(Switch("rose:help")
.skipping(SKIP_STRONG) // appears in documentation and is parsed, but treated as skipped
.doc("Show the ROSE switch documentation.")
.action(showHelpAndExit(0)) );
#else
bool showRoseHelp = false;
tool.insert(Switch("rose:help")
.longPrefix("-")
.intrinsicValue(true, showRoseHelp)
.doc("Show the old-style ROSE help."));
#endif
// Copy this tool's switches into the parser.
p.with(tool);
// Parse the command-line, stopping at the first "--" or positional argument. Return the unparsed stuff so it can be passed
// to the next stage. ROSE's frontend expects arg[0] to be the name of the command, which Sawyer has already processed, so
// we need to add it back again.
// std::vector<std::string> remainingArgs = p.parse(argc, argv).apply().unparsedArgs(true);
// remainingArgs.insert(remainingArgs.begin(), argv[0]);
std::vector<std::string> remainingArgs = p.parse(argvList).apply().unparsedArgs(true);
// remainingArgs.insert(remainingArgs.begin(), argvList[0]); // somehow this is not needed if I use the vector argument version of parse()
if (showRoseHelp)
SgFile::usage(0);
#if 0 // DEBUGGING [Robb P Matzke 2016-09-27]
std::cerr <<"These are the arguments after parsing with Sawyer:\n";
BOOST_FOREACH (const std::string &s, remainingArgs)
std::cerr <<" \"" <<s <<"\"\n";
#endif
return remainingArgs;
}
int main(int argc, char * argv[])
{
ROSE_INITIALIZE;
//! Command line process begin --------------------------
vector <string> argvList (argv, argv+argc) ;
//argvList = parseCommandLine (argc, argv);
argvList = parseCommandLine (argvList);
// TOO1 (2014/12/05): Temporarily added this to support keep-going in rose-sh.
if (CommandlineProcessing::isOption (argvList,"--list-filenames","",true))
{
std::vector<std::string> filenames =
GetSourceFilenamesFromCommandline(
std::vector<std::string>(argv, argv + argc));
BOOST_FOREACH(std::string filename, filenames)
{
std::cout << filename << std::endl;
}
return 0;
}
// -------------end of command line processing -------------------
SgProject *project = frontend (argvList);
// DQ (11/20/2015): AST consistency tests (optional for users, but this enforces more of our tests).
// I have added this to detect a SgTemplateClassDefinition that is being visited twice.
AstTests::runAllTests(project);
#if ENABLE_TRANS_TRACKING
// assign unique ID's for all nodes
if (transTracking)
TransformationTracking::registerAstSubtreeIds (project);
#endif
// DQ (12/11/2014): Added output of graph after transformations.
if (SgProject::get_verbose() > 0)
{
#if 0
printf ("Generating a DOT graph of the AST \n");
generateDOTforMultipleFile(*project);
#endif
}
#if 0
// DQ (10/13/2015): debugging the token-based unparsing (setting SgForStatement as modified.
printf ("NOTE: Setting verbose to value 3 to trigger debugging after the AST is built \n");
SgProject::set_verbose(3);
#endif
#if 1
// DQ (10/6/2015): Remove transformation for debugging token-unparsing.
if (!isIdentity)
{
SgFilePtrList file_ptr_list = project->get_fileList();
visitorTraversal exampleTraversal;
for (size_t i = 0; i<file_ptr_list.size(); i++)
{
SgFile* cur_file = file_ptr_list[i];
SgSourceFile* s_file = isSgSourceFile(cur_file);
if (s_file != NULL)
{
inserted_decls.clear(); // For each file, reset this.
// exampleTraversal.traverseInputFiles(project,preorder);
exampleTraversal.traverseWithinFile(s_file, preorder);
if (inserted_decls.size()>0 && merge_decl_assign)
{
if (transTracking)
cout<<"Begin merging declarations # "<<inserted_decls.size()<<endl;
collectiveMergeDeclarationAndAssignment (inserted_decls);
}
}
}
string filename= SageInterface::generateProjectName(project);
#if 0
// DQ (1/14/2015): This is a problem since it causes us to run out of disk space on large projects.
generateDOTforMultipleFile(*project);
#endif
}
#endif
// string filename= SageInterface::generateProjectName(project);
// generateDOTforMultipleFile(*project);
if (SgProject::get_verbose() > 0)
{
#if 1
printf ("Generating a WHOLE AST DOT graph \n");
generateDOTforMultipleFile(*project);
#endif
// Output an optional graph of the AST (the whole graph, of bounded complexity, when active)
const int MAX_NUMBER_OF_IR_NODES_TO_GRAPH_FOR_WHOLE_GRAPH = 10000;
generateAstGraph(project,MAX_NUMBER_OF_IR_NODES_TO_GRAPH_FOR_WHOLE_GRAPH,"");
}
#if 0
// DQ (10/6/2015): Remove transformation for debugging token-unparsing.
printf ("Calling cleanupNontransformedBasicBlockNode() \n");
#endif
#if 1
// DQ (1/18/2015): Denormalize some specific normalized bodies as a test.
SageInterface::cleanupNontransformedBasicBlockNode();
// printf ("DONE: Calling cleanupNontransformedBasicBlockNode() \n");
#endif
#if ENABLE_TRANS_TRACKING
if (transTracking)
{
std::map<AST_NODE_ID, std::set<AST_NODE_ID> >::iterator iter;
for (iter = TransformationTracking::inputIDs.begin(); iter != TransformationTracking::inputIDs.end(); iter++)
{
std::set<AST_NODE_ID> ids = (*iter).second;
if (ids.size()>0)
{
string src_comment = "Transformation generated based on ";
cout<<"Found a node with IR mapping info"<<endl;
SgNode* affected_node = TransformationTracking::getNode((*iter).first);
#if 0
// DQ (11/2/2015): Save and set to high value to trigger the verbose level to control tracking of isModified flag.
int verbose_level = SgProject::get_verbose();
SgProject::set_verbose(3);
#endif
cout<<isSgLocatedNode(affected_node)->unparseToString()<<endl;
cout<<"-- with input nodes ----------"<<endl;
std::set<AST_NODE_ID>::iterator iditer;
for(iditer = ids.begin(); iditer != ids.end(); iditer ++)
{
SgNode* input_node = TransformationTracking::getNode((*iditer));
SgLocatedNode* lnode = isSgLocatedNode(input_node);
cout<<lnode->unparseToString()<<endl; //TODO this function has unexpected side effects impacting token-based unparsing
cout<<"//Transformation generated based on line #"<< lnode->get_file_info()->get_line() <<endl;
src_comment += " line # " + StringUtility::numberToString(lnode->get_file_info()->get_line());
}
#if 0
// DQ (11/2/2015): Reset the verbose level to trigger tracking of isModified flag.
SgProject::set_verbose(verbose_level);
#endif
src_comment +="\n";
// SgStatement* enclosing_stmt = getEnclosingStatement(affected_node);
cout<<src_comment<<endl;
//TODO: turn this on and update the reference results
// attachComment (enclosing_stmt, src_comment);
} // end if ids.size() >0
} // end for inputIDs
} // end if transTracking
#endif
#if 0
// DQ (10/13/2015): debugging the token-based unparsing (setting SgForStatement as modified.
printf ("NOTE: Setting verbose to value 3 to trigger debugging after the AST is built and before running AstTests::runAllTests() \n");
SgProject::set_verbose(3);
#endif
// run all tests
AstTests::runAllTests(project);
#if 0
// DQ (10/13/2015): debugging the token-based unparsing (setting SgForStatement as modified.
printf ("NOTE: Setting verbose to value 3 to trigger debugging before unparsing of AST \n");
SgProject::set_verbose(3);
#endif
return backend(project);
}
//==================================================================================
// Three types of scope for a variable access
// 1. Variable is being declared.
// 2. Variable is being used: read or written
// 3. Not either of the above cases, just a scope in between them.
enum ScopeType {s_decl, s_intermediate, s_use};
class Scope_Node {
public:
Scope_Node (SgScopeStatement* s, ScopeType t):scope(s), s_type(t) {};
//TODO: protect members behind access functions
// scope information
SgScopeStatement* scope;
ScopeType s_type;
int depth; // the depth in the tree (path or chain) starting from 0
// for tree information
Scope_Node* parent; // point to the parent scope in the chain
std::vector < Scope_Node* > children ; // point to children scopes
//print the subtree rooted at this node to a dot file named as filename.dot
void printToDot(std::string filename);
std::string prettyPrint();
//! Depth-first traverse to get all nodes within the current subtree
void traverse_node(std::vector<Scope_Node* >& allnodes);
//! Delete all children, grandchildren, etc.
void deep_delete_children();
//! Starting from the root, find the first node which has more than one children.
// This is useful to identify the innermost common scope of all leaf scopes.
Scope_Node * findFirstBranchNode();
//~Scope_Node () { deep_delete_children(); }
private:
//! Recursive traverse the current subtree and write dot file information
void traverse_write (Scope_Node* n, std::ofstream & dotfile);
std::string getLineNumberStr(){ int lineno = scope->get_file_info()->get_line(); return StringUtility::numberToString(lineno); } ;
// Dot graph Node Id: unique memory address, prepend with "n_".
std::string getDotNodeId() { return "n_"+StringUtility::numberToString(scope); };
std::string getScopeTypeStr()
{ string rt;
if (s_type == s_decl) rt = "s_decl";
else if (s_type == s_intermediate) rt = "s_intermediate";
else if (s_type == s_use) rt = "s_use";
else ROSE_ASSERT (false);
return rt; }
};
// Topdown traverse a tree to find the first node with multiple children
// Intuitively, the innermost common scope for a variable.
// ----------- No adjustment any more ---------------
// However, we have to adjust a few special cases:
// For example: if-stmt case
// A variable is used in both true and false body.
// Naive analysis will find if-stmt is the inner-most common scope.
// But we cannot really move a declaration to the if-stmt scope (condition)
Scope_Node* Scope_Node::findFirstBranchNode()
{
Scope_Node* first_branch_node = this;
// three cases: 0 children, 1 children, >1 children
while (first_branch_node->children.size()==1)
first_branch_node = first_branch_node->children[0];
#if 0 // this adjustment should not be done until we figure out if the variable can be
// moved downward into the two branch scopes or not.
// We only adjust if we cannot move downward further,but trying to move var decl to if-stmt.
// With this consideration, we do this adjust later after considering liveness between mutliple scopes.
//
// Adjust for if-stmt: special adjustment
// switch stmt needs not to be adjusted since there is a middle scope as the innermost scope
// if a variable is used in multiple case: scopes.
if (isSgIfStmt (first_branch_node->scope))
first_branch_node = first_branch_node->parent;
#endif
// now the node must has either 0 or >1 children.
return first_branch_node;
}
//TODO make this a member of Scope_Node.
std::map <SgScopeStatement* , Scope_Node*> ScopeTreeMap; // quick query if a scope is in the scope tree, temp variable shared by all trees.
void Scope_Node::deep_delete_children()
{
std::vector <Scope_Node*> allnodes;
// TODO better way is to use width-first traversal and delete from the bottom to the top
this->traverse_node (allnodes);
// allnodes[0] is the root node itself, we keep it.
// reverse order of preorder to delete things?
//for (size_t i =1; i<allnodes.size(); i++)
for (size_t i =allnodes.size()-1 ; i>0; i--)
{
Scope_Node* child = allnodes[i];
// mark the associated scope as not in the scope tree
ScopeTreeMap[child->scope] = NULL;
// TODO: currently a workaround for multiple delete due to recursive call issue.
if (child != NULL)
{
delete child;
allnodes[i] = NULL;
}
}
// no children for the current node
children.clear();
}
void Scope_Node::traverse_node(std::vector<Scope_Node* >& allnodes)
{
// action on current node, save to the vector
ROSE_ASSERT (this != NULL); // we should not push NULL pointers
allnodes.push_back(this);
std::vector < Scope_Node* > children = this->children;
for (size_t i=0; i<children.size(); i++)
{
Scope_Node* child = children[i];
if (child != NULL) // we may delete child nodes and have NULL pointers
child->traverse_node(allnodes);
}
}
std::string Scope_Node::prettyPrint()
{
int lineno = scope->get_file_info()->get_line();
return StringUtility::numberToString(scope)+"@"+StringUtility::numberToString(lineno);