-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtraverse.hpp
1733 lines (1538 loc) · 65.3 KB
/
traverse.hpp
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
#ifndef TRAVERSE_HPP
#define TRAVERSE_HPP
#include "rose.h"
// ROSE must always be included first.
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <exception>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <variant>
#include <vector>
#include "aixlog.hpp"
#include "define.hpp"
#include "is-type-rose.hpp"
#include "lcom.hpp"
#include "node-print.hpp"
#include "sageInterfaceAda.h"
namespace Traverse {
// Global sourceFile. We would like this to be set per-file, but this is a quick
// hack to make it work everywhere.
boost::filesystem::path sourceFile = boost::filesystem::path("./NoFile");
// Forward declarations.
template <typename C>
class Class;
template <typename C>
class Method;
template <typename C>
class Attribute;
template <typename C>
class CalledMethod;
namespace sagehelper
{
// replace with SageInterface::Ada::declOf
// when available
inline
SgInitializedName& declOf(const SgEnumVal& n)
{
SgEnumDeclaration& dcl = SG_DEREF(n.get_declaration());
SgInitializedNamePtrList& lst = dcl.get_enumerators();
const auto lim = lst.end();
const auto pos = std::find_if( lst.begin(), lim,
[&n](sg::NotNull<SgInitializedName> nm)->bool
{
return boost::iequals( nm->get_name().getString(),
n.get_name().getString()
);
}
);
ASSERT_require(pos != lim);
return SG_DEREF(*pos);
}
}
// Attribute type.
class AType {
public:
using T = SgInitializedName*;
private:
std::vector<T> ids;
public:
// Converts a list of generic SgExpression to the attribute type by getting
// its declaration. This is done to properly leverage the type system.
static std::vector<T> ToAttrList(const std::vector<SgExpression*>& exps) {
std::vector<T> attrs(exps.size());
std::transform(exps.cbegin(), exps.cend(), attrs.begin(),
[](SgExpression* exp) {
T d = nullptr;
if (SgVarRefExp* vre = is<SgVarRefExp*>(exp))
{
d = is<T>(vre->get_symbol()->get_declaration());
}
else if (SgEnumVal* enm = is<SgEnumVal*>(exp))
{
d = &sagehelper::declOf(*enm);
}
else
{
if (false)
{
ASSERT_require(exp);
std::cerr << exp->get_parent()->unparseToString()
<< " -> " << exp->unparseToString()
<< " : " << typeid(*exp).name()
<< std::endl;
}
LOG(FATAL) << "Conversion of " << NPrint::p(exp)
<< " to SgVarRefExp* failed" << std::endl;
}
if (!d)
LOG(FATAL) << "Declaration of " << exp->unparseToString()
<< " is null." << std::endl;
return d;
});
return attrs;
}
AType(std::vector<T> ids) : ids(ids) {
if (ids.size() == 0)
LOG(FATAL) << "Empty vector passed to AType constructor." << std::endl;
}
AType(T id) : ids({id}) {}
AType(std::vector<SgExpression*> exps) {
ids = ToAttrList(exps);
if (ids.size() == 0)
LOG(FATAL) << "Empty vector passed to AType constructor." << std::endl;
}
// Vector iterators.
auto cbegin() const { return ids.cbegin(); }
auto cend() const { return ids.cend(); }
auto crbegin() const { return ids.crbegin(); }
auto crend() const { return ids.crend(); }
friend std::ostream& operator<<(std::ostream& os, const AType& a) {
for (auto it = a.cbegin(); it != a.cend(); ++it) {
os << NPrint::p(*it);
if (std::next(it) != a.cend()) os << '-';
}
return os;
}
// NOTE: Might this be dangerous? Perhaps this could disallow finding or
// inserting keys in some maps because they will be different but evaluate to
// equal. It may be better to make this its own function and evaluate ATypes
// for this sort of equality only when checking for access overlap.
friend bool operator==(const AType& lhs, const AType& rhs) {
const auto size = std::min(lhs.ids.size(), rhs.ids.size());
for (std::size_t i = 0; i < size; i++) {
if (lhs.ids[i] != rhs.ids[i]) {
return false;
}
}
return true;
}
friend bool operator<(const AType& lhs, const AType& rhs) {
if (lhs.ids.size() < rhs.ids.size()) {
return true;
} else if (lhs.ids.size() > rhs.ids.size()) {
return false;
}
for (std::size_t i = 0; i < lhs.ids.size(); i++) {
if (lhs.ids[i] == rhs.ids[i]) {
continue;
} else if (lhs.ids[i] < rhs.ids[i]) {
return true;
} else if (lhs.ids[i] > rhs.ids[i]) {
return false;
}
}
return false;
}
T operator[](std::size_t idx) const { return ids[idx]; }
// Get the root ID.
T GetId() const { return ids[0]; }
std::vector<T> GetIds() const { return ids; }
};
// Attributes don't use an alias. Instead, they use a custom class.
// Using AType = std::vector<SgInitializedName*>;
// MType is an alias for SgFunctionDeclaration, which covers functions and
// procedures.
using MType = SgFunctionDeclaration*;
// Class don't use an alias. Instead, it is specified using templates.
// using C = SgAdaPackageSpec*;
// Compare two vectors for matching contents, even if reordered.
template <class T>
bool compareVectors(std::vector<T> a, std::vector<T> b) {
if (a.size() != b.size()) {
return false;
}
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
return (a == b);
}
// NOTE: We use a recursive call for the sake of the type system. Intermediate
// results may not be the right node type, but the final one always should be.
// TODO: Peter: Check to see if some of these special cases should be handled by
// SageInterface::Ada::logicalParentScope().
template <typename T>
static SgNode* GetScopeRecurse(SgNode* n, SgNode* orig) {
if (n == nullptr) {
LOG(TRACE) << "n was null. No scope found." << std::endl;
return nullptr;
}
// Make sure to get the first non-defining declaration.
// Otherwise, multiple instances of one method may be seen as distinct.
if (SgFunctionDeclaration* fd = is<SgFunctionDeclaration>(n)) {
if (fd != fd->get_firstNondefiningDeclaration()) {
LOG(TRACE) << "n was an SgFunctionDeclaration. Traversing up to "
<< NPrint::p(fd->get_firstNondefiningDeclaration())
<< std::endl;
return GetScopeRecurse<T>(fd->get_firstNondefiningDeclaration(), orig);
}
}
// Make sure the target isn't the same node as the original starting node.
if (n != orig) {
// Found the target type as a parent scope.
if (T t = is<T>(n)) {
LOG(TRACE) << "Found scope: " << NPrint::p(t) << std::endl;
return n;
}
}
// Reached the top. Prevent further traversal.
if (is<SgGlobal>(n)) {
LOG(TRACE) << "Found SgGlobal before finding requested scope type."
<< std::endl;
return nullptr;
}
// Always go to the declaration from the definition.
// Otherwise scope recursion risks skipping it.
// TODO: Peter: Is there a generic way to check if a node is a definition,
// then to generically get the associated declaration?
if (SgClassDefinition* cd = is<SgClassDefinition>(n)) {
LOG(TRACE) << "n was an SgClassDefinition. Traversing up to "
<< NPrint::p(cd->get_declaration()) << std::endl;
return GetScopeRecurse<T>(cd->get_declaration(), orig);
}
if (SgFunctionDefinition* fd = is<SgFunctionDefinition>(n)) {
LOG(TRACE) << "n was an SgFunctionDefinition. Traversing up to "
<< NPrint::p(fd->get_declaration()) << std::endl;
return GetScopeRecurse<T>(fd->get_declaration(), orig);
}
if (SgNamespaceDefinitionStatement* nd = is<SgNamespaceDefinitionStatement>(n)) {
LOG(TRACE) << "n was an SgNamespaceDefinitionStatement. Traversing up to "
<< NPrint::p(nd->get_namespaceDeclaration()->get_firstNondefiningDeclaration()) << std::endl;
return GetScopeRecurse<T>(nd->get_namespaceDeclaration()->get_firstNondefiningDeclaration(), orig);
}
if (SgAdaUnitRefExp* aure = is<SgAdaUnitRefExp>(n)) {
LOG(TRACE) << "n was an SgAdaUnitRefExp. Traversing up to "
<< NPrint::p(aure->get_decl()) << std::endl;
return GetScopeRecurse<T>(aure->get_decl(), orig);
}
// Follow the scope pointer.
if (SgScopeStatement* s = is<SgScopeStatement>(n)) {
// TODO: Is there a better approach here than const_cast?
auto scope = const_cast<SgScopeStatement*>(
SageInterface::Ada::logicalParentScope(s));
LOG(TRACE) << "n was an SgScopeStatement. Traversing up to "
<< NPrint::p(scope) << std::endl;
return GetScopeRecurse<T>(scope, orig);
}
// NOTE: This was found to provide inaccurate scope traversals. Disabled.
// if (SgStatement* s = is<SgStatement>(n)) {
// LOG(TRACE) << "n was an SgStatement. Traversing up to "
// << NPrint::p(s->get_scope()) << std::endl;
// return GetScopeRecurse<T>(s->get_scope(),orig);
// }
LOG(TRACE) << "No scope pointer found. Checking parent "
<< NPrint::p(n->get_parent()) << std::endl;
return GetScopeRecurse<T>(n->get_parent(), orig);
}
template <typename T>
static T GetScope(SgNode* n) {
LOG(TRACE) << "Getting " << typeid(T).name() << " scope for " << NPrint::p(n)
<< std::endl;
return is<T>(GetScopeRecurse<T>(n, n));
}
// We support vector types in case we need to get the scope of an elaborate
// dot expression. This is just a convenience function to avoid explicitly
// grabbing the first element in the vector.
template <typename T>
static T GetScope(AType n) {
LOG(TRACE) << "Getting " << typeid(T).name() << " scope for " << n
<< std::endl;
if (!n.GetId()) LOG(FATAL) << "n.GetId() was null for " << n << std::endl;
return is<T>(GetScopeRecurse<T>(n.GetId(), n.GetId()));
}
template <typename C>
std::vector<C> GetRecords(SgNode* n) {
namespace siada = SageInterface::Ada;
LOG(DEBUG) << "Finding additional records for " << NPrint::p(n) << std::endl;
std::vector<C> owningClassIds;
// functor to store all type declarations associated with some function
auto storeRecordAssociation =
[&owningClassIds,n]
(const SgDeclarationStatement* tydcl) -> void
{
ASSERT_require(tydcl);
SgDeclarationStatement* typeDeclaration = tydcl->get_firstNondefiningDeclaration();
if (C classId = is<C>(typeDeclaration)) {
LOG(DEBUG) << NPrint::p(n) << " is a method within the class, "
<< NPrint::p(classId) << std::endl;
owningClassIds.push_back(classId);
}
};
// Tagged records approach.
// Functions/procedures that are tied to a tagged record will list the tagged
// record as a parameter. This code will find the classes associated with
// those parameters.
if (SgFunctionDeclaration* fd = is<SgFunctionDeclaration>(n)) {
#if NEW_SIGNATURE_PROCESSING
siada::PrimitiveSignatureElementsDesc elements = siada::primitiveSignatureElements(fd);
if (elements.result())
storeRecordAssociation(elements.result());
for (auto& record : elements.parameters()) {
// Get the type declaration of this record.
// TODO: There seem to be some dupes. Ask Peter about it.
storeRecordAssociation(record.typeDeclaration());
}
#else /* NEW_SIGNATURE_PROCESSING */
for (auto& record : siada::primitiveParameterPositions(fd)) {
// Get the type declaration of this record.
// TODO: There seem to be some dupes. Ask Peter about it.
storeRecordAssociation(record.typeDeclaration());
}
#endif /* NEW_SIGNATURE_PROCESSING */
}
LOG(DEBUG) << "Found " << owningClassIds.size() << " additional records for "
<< NPrint::p(n) << std::endl;
return owningClassIds;
}
// Helper function to handle the conditional logic
template <typename C>
void GetClassIdsHelper(SgNode* n, std::vector<C>& owningClassIds,
std::true_type) {
std::vector<C> recordClassIds = GetRecords<C>(n);
owningClassIds.insert(owningClassIds.end(), recordClassIds.begin(),
recordClassIds.end());
}
// Overload for when C is not an SgClassDeclaration*
template <typename C>
void GetClassIdsHelper(SgNode* n, std::vector<C>& owningClassIds,
std::false_type) {
LOG(DEBUG) << "No additional records to add." << std::endl;
// Do nothing.
return;
}
// SageInterfaceAda PrimitiveParameterDesc
// Checks for a type defined at the same package level.
// Gives position and name of parameter.
// Could be one of several types. Would need to test type as record type and
// check if record type is tagged. SgInitializedName->GetType can find it is
// record type. Can check if record declaration is tagged.
// TODO: Important to disallow duplciates?
// TODO: Need to make this a part of the search for parent classes.
template <typename C>
std::vector<C> GetClassIds(SgNode* n) {
LOG(TRACE) << "Getting class IDs for " << NPrint::p(n) << std::endl;
std::vector<C> owningClassIds;
// Standard way of getting a class ID.
// Traverse up the scope until we find the class containing this node.
const C owningClassId = GetScope<C>(n);
if (owningClassId != nullptr) {
LOG(TRACE) << "Found a base class, " << NPrint::p(owningClassId)
<< std::endl;
owningClassIds.push_back(owningClassId);
}
GetClassIdsHelper(n, owningClassIds, std::is_same<C, SgClassDeclaration*>());
return owningClassIds;
}
bool IsClassOwner(SgExpression* id, const MType& mId) {
const std::vector<SgClassDeclaration*> owningClassIds =
GetRecords<SgClassDeclaration*>(mId);
// Peter: use sageinterface ada type of expression instead of get_type
// Peter: Could cast type to a SgClassType or SgNamedType, which will have a
// good get_declaration method.
SgDeclarationStatement* declPeter =
is<SgClassType>(SageInterface::Ada::typeOfExpr(id).typerep())
->get_declaration();
SgDeclarationStatement* decl = id->get_type()->getAssociatedDeclaration();
LOG(TRACE) << "declPeter=" << declPeter << "\tdecl=" << decl << "\t"
<< (decl == declPeter) << std::endl;
if (SgClassDeclaration* classRefId = is<SgClassDeclaration>(decl)) {
for (const auto& classId : owningClassIds) {
// Peter: Try pointer for first nondefining declaration instead of
// getname.
if (classId->get_firstNondefiningDeclaration() ==
classRefId->get_firstNondefiningDeclaration()) {
LOG(TRACE) << "Match found for " << NPrint::p(classRefId) << std::endl;
return true;
}
}
}
LOG(TRACE) << "No match found for " << NPrint::p(id) << std::endl;
return false;
}
// Class, Method, and Attribute objects are all Component types.
// They are distinguished by the use of node pointers as unique IDs.
template <typename T>
class Component {
public:
T id;
Component() : id(nullptr) {}
Component(T id) : id(id) {}
T GetId() const { return id; }
Component& operator=(const Component& other) {
if (this != &other) this->id = other.id;
return *this;
}
};
template <typename C>
class Class : public Component<C> {
using LCOMType = LCOM::Class<C, MType, AType>;
public:
std::map<MType, Method<C>*> methods;
const boost::filesystem::path sourceFile;
public:
Class(const Class& t)
: Component<C>(t.id), methods(t.methods), sourceFile(t.sourceFile) {}
Class(C id, boost::filesystem::path sourceFile)
: Component<C>(id), sourceFile(sourceFile) {}
// Generate the LCOMType used in all LCOM analysis.
LCOMType ToLCOMClass() const {
LCOMType classLCOM = LCOMType(this->GetId());
for (const auto& m : methods) {
const auto& mId = std::get<0>(m);
const auto& method = std::get<1>(m);
LOG(TRACE) << "Adding method " << NPrint::p(mId) << " to LCOM Class "
<< NPrint::p(this->GetId()) << std::endl;
LCOM::Method<MType, AType> methodLCOM = LCOM::Method<MType, AType>(mId);
for (const auto& a : method->attributes) {
const auto& aId = std::get<0>(a);
const auto& attribute = std::get<1>(a);
LOG(TRACE) << "Adding attribute " << attribute << " to method "
<< NPrint::p(mId) << " to LCOM Class "
<< NPrint::p(this->GetId()) << std::endl;
const auto res = methodLCOM.attributes.emplace(aId);
// It should always succeed.
if (!res.second)
LOG(FATAL) << "Failed to emplace attribute " << attribute
<< " in method " << methodLCOM << std::endl;
}
for (const auto& c : method->calledMethods) {
const auto& cmId = std::get<0>(c);
LOG(TRACE) << "Adding called method " << NPrint::p(cmId)
<< " to method " << NPrint::p(mId) << " to LCOM Class "
<< NPrint::p(this->GetId()) << std::endl;
methodLCOM.calledMethods.emplace_back(cmId);
}
if (classLCOM.methods.count(methodLCOM) > 0) {
LOG(TRACE) << methodLCOM << " is already in class " << classLCOM
<< std::endl;
continue;
}
auto res = classLCOM.methods.emplace(methodLCOM);
// It should always succeed.
if (!res.second)
LOG(FATAL) << "Failed to emplace method " << methodLCOM << " in class "
<< classLCOM << std::endl;
}
return classLCOM;
}
friend std::ostream& operator<<(std::ostream& os, const Class<C>& c) {
os << NPrint::p(c.id);
return os;
}
// Filter attributes for non-tagged type classes.
void FilterAttributes(Method<C>* method, std::false_type) {
if (!method) return;
auto& attributes = method->attributes;
for (auto j = attributes.begin(); j != attributes.end();) {
const auto& attribute = std::get<1>(*j);
// Remove foreign attributes.
if (attribute->owningClass.GetId() != this->GetId()) {
LOG(DEBUG) << "Removing " << attribute << " from " << *this
<< " because " << NPrint::p(attribute->owningClass.GetId())
<< " != " << NPrint::p(this->GetId()) << std::endl;
j = attributes.erase(j);
} else {
++j;
}
}
}
// Tagged types. Do nothing, for now.
void FilterAttributes(Method<C>* method, std::true_type) { return; }
// Filter out class data we don't want in the final analysis.
void Filter() {
LOG(DEBUG) << "Filtering out foreign data for class " << *this << std::endl;
// The class should have no references to methods or functions contained
// within other classes.
for (auto i = methods.begin(); i != methods.end();) {
const auto& method = std::get<1>(*i);
// Remove undefined methods
if (filterUndefinedMethods) {
if (method->GetId()->get_definingDeclaration() == nullptr) {
LOG(DEBUG) << "Removing " << NPrint::p(method->GetId()) << " from " << *this
<< " because it is undefined." << std::endl;
i = methods.erase(i);
continue;
}
}
// Remove constructors and destructors.
if (filterCtorsDtors) {
if (method->GetId()->get_specialFunctionModifier().isConstructor()
|| method->GetId()->get_specialFunctionModifier().isDestructor()) {
LOG(DEBUG) << "Removing " << NPrint::p(method->GetId()) << " from " << *this
<< " because it is a constructor/destructor." << std::endl;
i = methods.erase(i);
continue;
}
}
// Remove foreign methods.
if (method->owningClass.GetId() != this->GetId()) {
LOG(DEBUG) << "Removing " << method << " from " << *this << " because "
<< NPrint::p(method->owningClass.GetId())
<< " != " << NPrint::p(this->GetId()) << std::endl;
i = methods.erase(i);
continue;
} else {
++i;
}
// TODO: This is a hack. The right way to do this is to recognize that an
// attribute could be associated with multiple classes and track them all.
// For now, we will keep it disabled for tagged types analysis.
FilterAttributes(method, std::is_same<C, SgClassDeclaration*>());
auto& calledMethods = method->calledMethods;
for (auto j = calledMethods.begin(); j != calledMethods.end();) {
const auto& cmId = std::get<0>(*j);
const auto& calledMethod = std::get<1>(*j);
// Remove foreign method calls.
if (calledMethod.owningClass.GetId() != this->GetId()) {
LOG(DEBUG) << "Removing " << calledMethod << " from " << *this
<< " because "
<< NPrint::p(calledMethod.owningClass.GetId())
<< " != " << NPrint::p(this->GetId()) << std::endl;
j = calledMethods.erase(j);
} else if (calledMethod.callingMethod.GetId() != method->GetId()) {
LOG(DEBUG) << "Removing " << calledMethod << " from " << method
<< " because "
<< NPrint::p(calledMethod.callingMethod.GetId())
<< " != " << NPrint::p(method->GetId()) << std::endl;
j = calledMethods.erase(j);
} else if (!methods.count(cmId)) {
LOG(INFO) << "Filtering out called method " << NPrint::p(cmId)
<< " since it is not within the class" << std::endl;
j = calledMethods.erase(j);
} else {
++j;
}
}
}
}
};
template <typename C>
class Method : public Component<MType> {
public:
Class<C>& owningClass;
// Attributes accessed by the method.
std::map<AType, Attribute<C>*> attributes;
// Methods accessed by the method.
// NOTE: These are their own objects, not merely references. This may be
// unnecessary, but it does make for more flexible printouts.
std::map<MType, CalledMethod<C>> calledMethods;
Method(MType id, Class<C>& owningClass)
: Component<MType>(id), owningClass(owningClass) {}
friend std::ostream& operator<<(std::ostream& os, const Method<C>& m) {
os << NPrint::p(m.id);
return os;
}
std::string printCalledMethods() {
std::stringstream ss;
for (const auto& c : calledMethods) {
const auto& calledMethod = std::get<1>(c);
ss << calledMethod;
}
return ss.str();
}
};
template <typename C>
class Attribute : public Component<AType> {
public:
Class<C>& owningClass;
Attribute(AType id, Class<C>& owningClass)
: Component<AType>(id), owningClass(owningClass) {}
static bool IsLocalVar(const AType::T& a, const MType& baseOwningMethod) {
if (!a)
LOG(FATAL) << "Null attribute passed into IsLocalVar()." << std::endl;
const MType owningMethod = GetScope<MType>(a);
// If no method scope was found, then it was declared outside of a
// method.
bool isLocal = (owningMethod == baseOwningMethod);
LOG(DEBUG) << NPrint::p(a) << " is " << (isLocal ? "" : "not ") << "local."
<< std::endl;
return isLocal;
}
static bool IsLocalVar(const AType& a, const MType& baseOwningMethod) {
return IsLocalVar(a.GetId(), baseOwningMethod);
}
friend std::ostream& operator<<(std::ostream& os, const Attribute<C>& a) {
os << a.GetId();
return os;
}
};
template <typename C>
class CalledMethod : public Component<MType> {
public:
Class<C>& owningClass;
Method<C>& callingMethod;
CalledMethod(MType id, Class<C>& owningClass, Method<C>& callingMethod)
: Component<MType>(id),
owningClass(owningClass),
callingMethod(callingMethod) {}
friend std::ostream& operator<<(std::ostream& os, const CalledMethod<C>& m) {
os << NPrint::p(m.id);
return os;
}
};
// IA = Inherited Attribute
template <typename C>
class IA {
public:
// These store a mapping of underlying Class, Method, and Attribute objects.
// These can be used for lookup.
// All other locations in the code should use references to these objects,
// rather than making copies.
static std::map<C, Class<C>> classData;
static std::map<MType, Method<C>> methodData;
static std::map<AType, Attribute<C>> attributeData;
// Stores a mapping between renamings and their renamed attributes/methods.
static std::map<SgNode*, AType> attributeAliasMap;
static std::map<MType, MType> methodAliasMap;
static std::map<SgNode*, MType> cStyleMethodAliasMap;
// Specific constructors are required to create a valid inherited attribute.
IA(){};
IA(const IA& X){};
// IA(const IA& X) : class_(X.class_), Method_(X.method_){};
// Print out all currently processed class, method, and attribute data.
friend std::ostream& operator<<(std::ostream& os, const IA<C>& c) {
for (const auto& c : classData) {
const auto& classInst = std::get<1>(c);
os << "Class: " << classInst << std::endl;
for (const auto& m : classInst.methods) {
const auto& method = std::get<1>(m);
os << "\tMethod: " << *method << std::endl;
for (const auto& a : method->attributes) {
const auto& aId = std::get<0>(a);
os << "\t\tAttribute: " << aId << std::endl;
}
for (const auto& cm : method->calledMethods) {
const auto& calledMethod = std::get<1>(cm);
os << "\t\tCalled Method: " << calledMethod << std::endl;
}
}
}
return os;
}
static std::string printClassData() {
std::stringstream ss;
ss << "Contents of classData:" << std::endl;
for (const auto& c : classData) {
const auto& cId = std::get<0>(c);
const auto& classInst = std::get<1>(c);
ss << cId << ": " << classInst << std::endl;
}
return ss.str();
}
static std::string printMethodData() {
std::stringstream ss;
ss << "Contents of methodData:" << std::endl;
for (const auto& m : methodData) {
const auto& mId = std::get<0>(m);
const auto& methodInst = std::get<1>(m);
ss << mId << ": " << methodInst << std::endl;
}
return ss.str();
}
static std::string printAttributeData() {
std::stringstream ss;
ss << "Contents of attributeData:" << std::endl;
for (const auto& a : attributeData) {
const auto& aId = std::get<0>(a);
const auto& attributeInst = std::get<1>(a);
ss << aId << ": " << attributeInst << std::endl;
}
return ss.str();
}
};
// Initializers for static IA data structures.
template <typename C>
std::map<C, Class<C>> IA<C>::classData = std::map<C, Class<C>>();
template <typename C>
std::map<MType, Method<C>> IA<C>::methodData = std::map<MType, Method<C>>();
template <typename C>
std::map<AType, Attribute<C>> IA<C>::attributeData =
std::map<AType, Attribute<C>>();
template <typename C>
std::map<SgNode*, AType> IA<C>::attributeAliasMap;
template <typename C>
std::map<MType, MType> IA<C>::methodAliasMap;
template <typename C>
std::map<SgNode*, MType> IA<C>::cStyleMethodAliasMap;
// It is possible to need to go multiple layers down, alternating between
// renames, dots, pointer derefs, etc.
// NOTE: The vector stores the full resolution of record-field
// relationships.
std::vector<SgExpression*> GetRootExp(SgExpression* exp) {
if (!exp) LOG(WARNING) << " nullptr passed into GetRootExp()." << std::endl;
// Traverse down each attribute renaming.
if (SgAdaRenamingRefExp* arre = is<SgAdaRenamingRefExp>(exp)) {
LOG(TRACE) << NPrint::p(arre)
<< " is a SgAdaRenamingRefExp*. Getting what it renames."
<< std::endl;
return GetRootExp(arre->get_decl()->get_renamed());
}
// Traverse down each function renaming.
// NOTE: This situation may not actually be possible.
if (SgAdaFunctionRenamingDecl* afrd = is<SgAdaFunctionRenamingDecl>(exp)) {
LOG(TRACE) << NPrint::p(afrd)
<< " is a SgAdaFunctionRenamingDecl*. Getting what it renames."
<< std::endl;
return GetRootExp(afrd->get_renamed_function());
}
// We can potentially rename a "dot expression" to conveniently reference a
// specific field within a record. We currently consider the whole record to
// be a single attribute, so we will treat this renaming as though it points
// to the associated record instance.
if (SgDotExp* dot = is<SgDotExp>(exp)) {
if (dotBehavior == DotBehavior::LeftOnly) {
return GetRootExp(dot->get_lhs_operand());
}
if (dotBehavior == DotBehavior::Full) {
std::vector<SgExpression*> ret;
auto l = GetRootExp(dot->get_lhs_operand());
auto r = GetRootExp(dot->get_rhs_operand());
ret.reserve(l.size() + r.size());
ret.insert(ret.end(), l.begin(), l.end());
ret.insert(ret.end(), r.begin(), r.end());
return ret;
}
throw std::logic_error("Unimplemented dotBehavior specified");
}
// Traverse down pointer derefs.
if (SgPointerDerefExp* pde = is<SgPointerDerefExp>(exp)) {
LOG(TRACE) << NPrint::p(pde)
<< " is a SgPointerDerefExp*. Getting what it points to."
<< std::endl;
return GetRootExp(pde->get_operand());
}
// Traverse down array pointer derefs.
if (SgPntrArrRefExp* pare = is<SgPntrArrRefExp>(exp)) {
LOG(TRACE) << NPrint::p(pare)
<< " is a SgPntrArrRefExp*. Getting what it points to."
<< std::endl;
return GetRootExp(pare->get_lhs_operand());
}
if (SgAdaAttributeExp* attr = is<SgAdaAttributeExp>(exp)) {
return GetRootExp(attr->get_object());
}
//
if (SgCastExp* castexp = is<SgCastExp>(exp)) {
return GetRootExp(castexp->get_operand());
}
if (/*SgTypeExpression* typeex =*/ is<SgTypeExpression>(exp)) {
return {};
}
// PP: 05/13/24 not sure how to handle function calls..
// ignore them for now?
// case:
// x : Integer renames Identity(1); -- x renames result of function call
// -- similar to variable
if (/*SgFunctionCallExp* callexp =*/ is<SgFunctionCallExp>(exp)) {
return {};
}
// No further unwrapping match found.
return { exp };
}
SgExpression* GetBaseRootExp(std::vector<SgExpression*> rootExp) {
if (!rootExp.size())
{
// PP 05/13/24 return nullptr instead of failing..
LOG(WARNING) << "Empty root list found." << std::endl;
return nullptr;
}
return rootExp[0];
}
template <typename T>
T GetBaseRootExp(SgExpression* id) {
const std::vector<SgExpression*> rootExp = GetRootExp(is<SgExpression>(id));
if (!rootExp.size())
LOG(FATAL) << "Empty root list found for " << NPrint::p(id) << std::endl;
SgExpression* root = GetBaseRootExp(rootExp);
T t = is<T>(root);
if (!t) {
if (SgAdaAttributeExp* aae = is<SgAdaAttributeExp>(root)) {
LOG(DEBUG) << "Found SgAdaAttributeExp " << NPrint::p(aae)
<< ". Returning nullptr." << std::endl;
return nullptr;
}
LOG(WARNING) << "Empty root found for " << NPrint::p(id) << std::endl;
}
return t;
}
template <typename C>
Class<C>* GetOwningClass(SgNode* n) {
LOG(TRACE) << "Getting Owning Class for " << NPrint::p(n) << std::endl;
const std::vector<C> owningClassIds = GetClassIds<C>(n);
// TODO: Not a safe assumption, but we will see how much damage this causes.
if (owningClassIds.size() > 1) {
LOG(WARNING) << "owningClassIds.size() = " << owningClassIds.size()
<< ". This method is owned by multiple classes, some of which "
"will be ignored!"
<< std::endl;
} else if (owningClassIds.size() == 0)
return nullptr;
const C owningClassId = owningClassIds[0];
// The class should already be in the map.
if (!IA<C>::classData.count(owningClassId)) {
LOG(INFO) << "Class " << NPrint::p(owningClassId)
<< " missing from classData map. Inserting... "
<< IA<C>::printClassData() << std::endl;
auto e = IA<C>::classData.emplace(
owningClassId, std::move(Class<C>(owningClassId, sourceFile)));
const bool success = std::get<1>(e);
if (!success)
LOG(FATAL) << "Failed to emplace " << NPrint::p(owningClassId)
<< std::endl;
return &std::get<0>(e)->second;
}
return &IA<C>::classData.at(owningClassId);
}
template <typename C>
Method<C>* GetOwningMethod(SgNode* n) {
const MType owningMethodId = GetScope<MType>(n);
if (owningMethodId == nullptr) return nullptr;
// The calling method should already be in the map.
if (!IA<C>::methodData.count(owningMethodId)) {
LOG(INFO) << "Did not find " << NPrint::p(owningMethodId)
<< " in methodData. Perhaps the method is not within any package "
"we are analyzing."
<< std::endl;
return nullptr;
}
return &IA<C>::methodData.at(owningMethodId);
}
template <typename C>
class VisitorTraversal : public AstTopDownProcessing<IA<C>> {
// Gets the function renamed by afrd. If the renamed function is not already
// in the methodAliasMap, this function will find and add it.
static boost::optional<MType> GetRenamed(
const SgAdaFunctionRenamingDecl* afrd) {
// The first non-defining declaration serves as a standard ID for the map.
MType id = is<MType>(afrd->get_firstNondefiningDeclaration());
// If the renaming is cached in the alias map, return it.
auto it = IA<C>::methodAliasMap.find(id);
if (it != IA<C>::methodAliasMap.end()) {
return it->second;
}
SgExpression* renamed = afrd->get_renamed_function();
// If there is no renamed function associated with this renaming, then
// there is not enough information to do anything here. Skip it.
if (!renamed) {
LOG(INFO) << "Could not find the root expression associated with this "
"SgAdaFunctionRenamingDecl* "
<< NPrint::p(afrd)
<< " because the base root expression is null." << std::endl;
return boost::none;
}
// Check down as many levels of indirection as needed to find the root
// function referenced by the renaming.
const SgFunctionRefExp* fre = GetBaseRootExp<SgFunctionRefExp*>(renamed);
if (!fre) {
LOG(INFO) << NPrint::p(renamed) << " was an " << renamed->class_name()
<< " not an SgFunctionRefExp*." << std::endl;
return boost::none;
}
// Get the declaration associated with the root expression.
MType decl = is<MType>(fre->get_symbol()->get_declaration());
// Store the renamed function in the alias map.
// Use the first non-defining declaration as the key.
bool success = IA<C>::methodAliasMap.emplace(id, decl).second;
if (!success)
LOG(FATAL) << "Failed to emplace method " << NPrint::p(id)
<< " into methodAliasMap." << std::endl;
return decl;
}
static IA<C> HandleMethod(const MType& pId, IA<C>& ia) {
if (!pId)
LOG(FATAL) << "Null method passed into HandleMethod()." << std::endl;
// Only consider the first non-defining declaration.
// This ensures no duplicate IDs are found.
MType id = is<MType>(pId->get_firstNondefiningDeclaration());
if (!id)
LOG(FATAL) << "Null method found as firstNondefiningDeclaration."
<< std::endl;
Class<C>* cPtr = GetOwningClass<C>(id);
if (!cPtr) return IA<C>(ia);
Class<C>& owningClass = *cPtr;
// In some cases, the same method will be seen more than once.
// For instance, if a procedure is forward-declared.
if (owningClass.methods.count(id)) {
LOG(NOTICE) << NPrint::p(id) << " has already been seen. Nothing to do."
<< std::endl;
return IA<C>(ia);
}
// Handle SgAdaFunctionRenamingDecl types.
// NOTE: Don't use first non-defining declaration here, as it may hide the
// renamed function.
if (SgAdaFunctionRenamingDecl* afrd = is<SgAdaFunctionRenamingDecl>(pId)) {
const boost::optional<MType> result = GetRenamed(afrd);
// We cannot handle a renamed function if it doesn't have a valid renamed
// function reference.
if (!result) return IA<C>(ia);
MType m = *result;
LOG(NOTICE) << NPrint::p(afrd)
<< " is an SgAdaFunctionRenamingDecl. Associated with"
<< NPrint::p(m) << std::endl;
return IA<C>(ia);
}
// Add the method to methodData.