-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlowAware.cpp
More file actions
executable file
·2320 lines (2055 loc) · 79.3 KB
/
FlowAware.cpp
File metadata and controls
executable file
·2320 lines (2055 loc) · 79.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "FlowAware.h"
#include "VectorSolver.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Type.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Analysis/BranchProbabilityInfo.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/Dominators.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Passes/PassPlugin.h"
#include "llvm/InitializePasses.h"
// #include "llvm/Support/BranchProbability.h"
#include "llvm/Analysis/DependenceAnalysis.h"
#include "llvm/InitializePasses.h"
#include "llvm/ADT/MapVector.h"
#include <algorithm> // for transform
#include <functional>
#include <regex>
#include <iostream>
using namespace llvm;
using namespace std;
using namespace IR2Vec;
BranchProbabilityInfo *IR2Vec_FA::getBPI(Function *F, FunctionAnalysisManager &FAM) {
auto It = bpiMap.find(F);
if (It != bpiMap.end())
{
return It->second;
}
// BranchProbabilityInfo &BPI = getAnalysis<BranchProbabilityInfoWrapperPass>(*F).getBPI();
// BranchProbabilityInfo &BPI = &FAM.getResult<BranchProbabilityInfoWrapperPass>(F).getBPI();
// bpiMap[F] = &FAM.getResult<BranchProbabilityInfoWrapperPass>(*F).getBPI();
// Get new BPI analysis result
BranchProbabilityInfo *BPI = &FAM.getResult<BranchProbabilityAnalysis>(*F);
bpiMap[F] = BPI;
return bpiMap[F];
}
// Scales a vector by multiplying each element by a factor
void IR2Vec_FA::scaleVector(SmallVector<double, DIM> &vec, float factor) {
for (unsigned i = 0; i < vec.size(); i++) {
vec[i] = vec[i] * factor;
}
}
void IR2Vec_FA::killAndUpdate(Instruction *I, SmallVector<double, DIM> val) {
// LLVM_DEBUG(dbgs() << "kill and update: \n");
// LLVM_DEBUG(I->dump());
if (I == nullptr)
return;
auto It1 = instVecMap.find(I);
assert(It1 != instVecMap.end() && "Instruction should be defined in map");
It1->second = val;
auto It2 = livelinessMap.find(I);
assert(It2 != livelinessMap.end() &&
"Instruction should be in livelinessMap");
It2->second = false;
transitiveKillAndUpdate(I, val, false);
}
// Ensures that the vector updates propagate through all related memory operations.
void IR2Vec_FA::transitiveKillAndUpdate(Instruction *I,
SmallVector<double, DIM> val,
bool avg) {
assert(I != nullptr);
// LLVM_DEBUG(dbgs() << "I: ");
// LLVM_DEBUG(I->dump());
unsigned operandNum;
bool isMemAccess = isMemOp(I->getOpcodeName(), operandNum, memAccessOps);
if (!isMemAccess)
return;
auto parentI = dyn_cast<Instruction>(I->getOperand(operandNum));
if (parentI == nullptr)
return;
// assert(parentI != nullptr);
// LLVM_DEBUG(dbgs() << "\n parentI: ");
// LLVM_DEBUG(parentI->dump());
if (strcmp(parentI->getOpcodeName(), "getelementptr") == 0)
avg = true;
// LLVM_DEBUG(dbgs() << "\nVal : "; for (auto i : val) { dbgs() << i << " "; });
auto It1 = instVecMap.find(parentI);
assert(It1 != instVecMap.end() && "Instruction should be defined in map");
// LLVM_DEBUG(dbgs() << "\nIt.second = : ";
// for (auto i
// : It1->second) { dbgs() << i << " "; });
if (avg) {
std::transform(It1->second.begin(), It1->second.end(), val.begin(),
It1->second.begin(), std::plus<double>());
scaleVector(It1->second, WT);
} else {
It1->second = val;
}
// LLVM_DEBUG(dbgs() << "\nafter transforming : ";
// for (auto i
// : It1->second) { dbgs() << i << " "; });
auto It2 = livelinessMap.find(parentI);
assert(It2 != livelinessMap.end() &&
"Instruction should be in livelinessMap");
It2->second = false;
transitiveKillAndUpdate(parentI, val, avg);
}
// void IR2Vec_FA::collectData() {
// static bool wasExecuted = false;
// if (!wasExecuted) {
// errs() << "Reading from " + fname + "\n";
// std::ifstream i(fname);
// std::string delimiter = ":";
// for (std::string line; getline(i, line);) {
// std::string token = line.substr(0, line.find(delimiter));
// SmallVector<double, DIM> rep;
// std::string vec = line.substr(line.find(delimiter) + 1, line.length());
// std::string val = vec.substr(vec.find("[") + 1, vec.find(", ") - 1);
// rep.push_back(stod(val));
// int pos = vec.find(", ");
// vec = vec.substr(pos + 1);
// for (int i = 1; i < DIM - 1; i++) {
// val = vec.substr(1, vec.find(", ") - 1);
// rep.push_back(stod(val));
// pos = vec.find(", ");
// vec = vec.substr(pos + 1);
// }
// val = vec.substr(1, vec.find("]") - 1);
// rep.push_back(stod(val));
// opcMap[token] = rep;
// }
// wasExecuted = true;
// }
// }
// Performs recursive analysis of how instructions are used
// Recursively analyzes transitive uses of memory operations
void IR2Vec_FA::getTransitiveUse(
const Instruction *root, const Instruction *def,
SmallVector<const Instruction *, 100> &visitedList,
SmallVector<const Instruction *, 10> toAppend) {
unsigned operandNum = 0;
visitedList.push_back(def);
for (auto U : def->users()) {
if (auto use = dyn_cast<Instruction>(U)) {
if (std::find(visitedList.begin(), visitedList.end(), use) ==
visitedList.end()) {
IR2VEC_DEBUG(outs() << "\nDef " << /* def << */ " ";
def->print(outs(), true); outs() << "\n";);
IR2VEC_DEBUG(outs() << "Use " << /* use << */ " ";
use->print(outs(), true); outs() << "\n";);
if (isMemOp(use->getOpcodeName(), operandNum, memWriteOps) &&
use->getOperand(operandNum) == def) {
writeDefsMap[root].push_back(use);
}
// If it's a memory access operation, continue the transitive analysis
else if (isMemOp(use->getOpcodeName(), operandNum, memAccessOps) &&
use->getOperand(operandNum) == def) {
getTransitiveUse(root, use, visitedList, toAppend);
}
}
}
}
return;
}
// Connects root instructions to their dependent write operations
void IR2Vec_FA::collectWriteDefsMap(Module &M) {
SmallVector<const Instruction *, 100> visitedList;
for (auto &F : M) {
if (!F.isDeclaration()) {
EliminateUnreachableBlocks(F);
for (auto &BB : F) {
for (auto &I : BB) {
unsigned operandNum = 0;
if ((isMemOp(I.getOpcodeName(), operandNum, memAccessOps) ||
isMemOp(I.getOpcodeName(), operandNum, memWriteOps) ||
strcmp(I.getOpcodeName(), "alloca") == 0) &&
std::find(visitedList.begin(), visitedList.end(), &I) ==
visitedList.end()) {
if (I.getNumOperands() > 0) {
// IR2VEC_DEBUG(I.print(outs()); outs() << "\n");
// IR2VEC_DEBUG(outs() << "operandnum = " << operandNum << "\n");
if (auto parent =
dyn_cast<Instruction>(I.getOperand(operandNum))) {
if (std::find(visitedList.begin(), visitedList.end(), parent) ==
visitedList.end()) {
visitedList.push_back(parent);
getTransitiveUse(parent, parent, visitedList);
}
}
}
}
}
}
}
}
}
Vector IR2Vec_FA::getValue(std::string key) {
// printf("entering get value");
Vector vec;
if (opcMap.find(key) == opcMap.end()) {
IR2VEC_DEBUG(errs() << "cannot find key in map : " << key << "\n");
dataMissCounter++;
} else
vec = opcMap[key];
// for(auto x: opcMap){
// cout<< "x.first : "<<x.first<<"\n";
// }
return vec;
}
// Function to update funcVecMap of function with vectors of it's callee list
void IR2Vec_FA::updateFuncVecMapWithCallee(const llvm::Function *function) {
if (funcCallMap.find(function) != funcCallMap.end()) {
auto calleelist = funcCallMap[function];
Vector calleeVector(DIM, 0);
for (auto funcs : calleelist) {
auto tmp = funcVecMap[funcs];
std::transform(tmp.begin(), tmp.end(), calleeVector.begin(),
calleeVector.begin(), std::plus<double>());
}
scaleVector(calleeVector, WA);
auto tmpParent = funcVecMap[function];
std::transform(calleeVector.begin(), calleeVector.end(), tmpParent.begin(),
tmpParent.begin(), std::plus<double>());
funcVecMap[function] = tmpParent;
}
}
void IR2Vec_FA::generateFlowAwareEncodings(std::ostream *o,
std::ostream *missCount,
std::ostream *cyclicCount) {
// collectWriteDefsMap(M);
cout<<"it reaches generateFlow encodings right?"<<"\n";
int noOfFunc = 0;
llvm::FunctionAnalysisManager FAM;
// FAM.add(new BranchProbabilityAnalysis());
// FAM.addPass(BranchProbabilityAnalysis());
llvm::PassBuilder PB;
PB.registerFunctionAnalyses(FAM);
// FAM.registerPass([] { return llvm::BranchProbabilityAnalysis(); });
// better to run bpi for all the functions at the start itself i guess, then no issues here and there
for (auto &f : M) {
if (!f.isDeclaration()) {
getBPI(&f,FAM);
}
}
for (auto &f : M) {
if (!f.isDeclaration()) {
// BranchProbabilityInfo *BPI = &FAM.getResult<BranchProbabilityAnalysis>(f);
SmallVector<Function *, 15> funcStack;
// auto x = getBPI(&f, BPI);
// if(x != nullptr){
// cout<<"atleast stuff is not empty" << "\n";
// }
// for(auto entry : bpiMap){
// Function *func = entry.first;
// BranchProbabilityInfo *bpi = entry.second;
// outs() << func->getName() << "\n";
// }
cout<<"tmp gets filled here and func2Vec gets called here, right?"<<"\n";
auto tmp = func2Vec (f, funcStack, getBPI(&f, FAM));
// auto tmp = func2Vec(f, funcStack, BPI);
funcVecMap[&f] = tmp;
}
}
// printing the bpiMap over here, should contain the entire list of functions and their bpi
cout<<"printing the contents of bpiMap over here :"<<"\n";
for (auto &entry : bpiMap) {
llvm::Function *func = entry.first;
llvm::BranchProbabilityInfo *bpi = entry.second;
// Print the addresses of the Function and BranchProbabilityInfo pointers
std::cout << "Function pointer: " << func << "\n";
std::cout << "BranchProbabilityInfo pointer: " << bpi << "\n";
std::cout << "-------------------------\n";
}
// for (auto funcit : funcVecMap) {
// updateFuncVecMapWithCallee(funcit.first);
// }
for (auto &f : M) {
if (!f.isDeclaration()) {
Vector tmp;
SmallVector<Function *, 15> funcStack;
tmp = funcVecMap[&f];
if (level == 'f') {
res += updatedRes(tmp, &f, &M);
res += "\n";
noOfFunc++;
}
// else if (level == 'p') {
std::transform(pgmVector.begin(), pgmVector.end(), tmp.begin(),
pgmVector.begin(), std::plus<double>());
// }
}
}
if (level == 'p') {
if (cls != -1)
res += std::to_string(cls) + "\t";
for (auto i : pgmVector) {
if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) {
i = 0;
}
res += std::to_string(i) + "\t";
}
res += "\n";
}
if (o)
*o << res;
if (missCount) {
std::string missEntry =
(M.getSourceFileName() + "\t" + std::to_string(dataMissCounter) + "\n");
*missCount << missEntry;
}
if (cyclicCount)
*cyclicCount << (M.getSourceFileName() + "\t" +
std::to_string(cyclicCounter) + "\n");
}
// This function will update funcVecMap by doing DFS starting from parent
// function
void IR2Vec_FA::updateFuncVecMap(
llvm::Function *function,
llvm::SmallSet<const llvm::Function *, 16> &visitedFunctions) {
visitedFunctions.insert(function);
SmallVector<Function *, 15> funcStack;
funcStack.clear();
auto tmpParent = func2Vec(*function, funcStack, bpiMap[function]);
// funcVecMap is updated with vectors returned by func2Vec
funcVecMap[function] = tmpParent;
auto calledFunctions = funcCallMap[function];
for (auto &calledFunction : calledFunctions) {
if (calledFunction && !calledFunction->isDeclaration() &&
visitedFunctions.count(calledFunction) == 0) {
// doing casting since calledFunctions is of type of const
// llvm::Function* and we need llvm::Function* as argument
auto *callee = const_cast<Function *>(calledFunction);
// This function is called recursively to update funcVecMap
updateFuncVecMap(callee, visitedFunctions);
}
}
}
void IR2Vec_FA::generateFlowAwareEncodingsForFunction(
std::ostream *o, std::string name, std::ostream *missCount,
std::ostream *cyclicCount) {
int noOfFunc = 0;
for (auto &f : M) {
auto Result = getActualName(&f);
if (!f.isDeclaration() && Result == name) {
// If funcName is matched with one of the functions in module, we
// will update funcVecMap of it and it's child functions recursively
llvm::SmallSet<const Function *, 16> visitedFunctions;
updateFuncVecMap(&f, visitedFunctions);
}
}
// iterating over all functions in module instead of funcVecMap to preserve
// order
for (auto &f : M) {
if (funcVecMap.find(&f) != funcVecMap.end()) {
auto *function = const_cast<const Function *>(&f);
updateFuncVecMapWithCallee(function);
}
}
for (auto &f : M) {
auto Result = getActualName(&f);
if (!f.isDeclaration() && Result == name) {
Vector tmp;
SmallVector<Function *, 15> funcStack;
tmp = funcVecMap[&f];
if (level == 'f') {
res += updatedRes(tmp, &f, &M);
res += "\n";
noOfFunc++;
}
}
}
if (o)
*o << res;
if (missCount) {
std::string missEntry =
(M.getSourceFileName() + "\t" + std::to_string(dataMissCounter) + "\n");
*missCount << missEntry;
}
if (cyclicCount)
*cyclicCount << (M.getSourceFileName() + "\t" +
std::to_string(cyclicCounter) + "\n");
}
void IR2Vec_FA::topoDFS(int vertex, std::vector<bool> &Visited,
std::vector<int> &visitStack) {
Visited[vertex] = true;
auto list = SCCAdjList[vertex];
for (auto nodes : list) {
if (Visited[nodes] == false)
topoDFS(nodes, Visited, visitStack);
}
visitStack.push_back(vertex);
}
std::vector<int> IR2Vec_FA::topoOrder(int size) {
std::vector<bool> Visited(size, false);
std::vector<int> visitStack;
for (auto &nodes : SCCAdjList) {
if (Visited[nodes.first] == false) {
topoDFS(nodes.first, Visited, visitStack);
}
}
return visitStack;
}
void IR2Vec_FA::TransitiveReads(SmallVector<Instruction *, 16> &Killlist,
Instruction *Inst, BasicBlock *ParentBB) {
assert(Inst != nullptr);
unsigned operandNum;
bool isMemAccess = isMemOp(Inst->getOpcodeName(), operandNum, memAccessOps);
if (!isMemAccess)
return;
auto parentI = dyn_cast<Instruction>(Inst->getOperand(operandNum));
if (parentI == nullptr)
return;
if (ParentBB == parentI->getParent())
Killlist.push_back(parentI);
TransitiveReads(Killlist, parentI, ParentBB);
}
SmallVector<Instruction *, 16>
IR2Vec_FA::createKilllist(Instruction *Arg, Instruction *writeInst) {
SmallVector<Instruction *, 16> KillList;
SmallVector<Instruction *, 16> tempList;
BasicBlock *ParentBB = writeInst->getParent();
unsigned opnum;
for (User *U : Arg->users()) {
if (Instruction *UseInst = dyn_cast<Instruction>(U)) {
if (isMemOp(UseInst->getOpcodeName(), opnum, memWriteOps)) {
Instruction *OpInst = dyn_cast<Instruction>(UseInst->getOperand(opnum));
if (OpInst && OpInst == Arg)
tempList.push_back(UseInst);
}
}
}
for (auto I = tempList.rbegin(); I != tempList.rend(); I++) {
if (*I == writeInst)
break;
if (ParentBB == (*I)->getParent())
KillList.push_back(*I);
}
return KillList;
}
// Vector IR2Vec_FA::func2Vec(Function &F, SmallVector<Function *, 15> &funcStack, BranchProbabilityInfo *bpi){
Vector IR2Vec_FA::func2Vec(Function &F,
SmallVector<Function *, 15> &funcStack,
BranchProbabilityInfo *bpi) {
auto It = funcVecMap.find(&F);
if (It != funcVecMap.end()) {
return It->second;
}
funcStack.push_back(&F);
// instReachingDefsMap.clear();
// allSCCs.clear();
// reverseReachingDefsMap.clear();
// SCCAdjList.clear();
Vector funcVector(DIM, 0); // Initialize zero vector
MapVector<const BasicBlock *, MapVector<BasicBlock *, double>> succMap;
MapVector<const BasicBlock *, double> cumulativeScore;
if(bpi) {
// MapVector<const BasicBlock *, MapVector<BasicBlock *, double>> succMap;
// MapVector<const BasicBlock *, double> cumulativeScore;
for (auto &b : F) {
MapVector<BasicBlock *, double> succs;
for (auto it = succ_begin(&b), et = succ_end(&b); it != et; ++it) {
BasicBlock *t = *it;
auto bp = bpi->getEdgeProbability(&b, t);
double prob = double(bp.getNumerator()) / double(bp.getDenominator());
std::cout << "Probability : " << prob << "\n";
succs[*it] = prob;
}
succMap[&b] = succs;
cumulativeScore[&b] = 0;
}
}
ReversePostOrderTraversal<Function *> RPOT(&F);
bool isHeader = true;
if(bpi){
for (auto *b : RPOT) {
if (isHeader)
cumulativeScore[b] = 1;
if (succMap.find(b) != succMap.end()) {
for (auto element : succMap[b]) {
auto currentPtr = cumulativeScore[b];
cumulativeScore[element.first] =
(currentPtr * element.second) + cumulativeScore[element.first];
}
}
isHeader = false;
}
// cout<< "cumulative score here : " << "\n";
// for(auto x : cumulativeScore){
// cout<<"x.first : " << x.first<< "\n";
// cout<<"x.second : "<< x.second<< "\n";
// }
}
// for (auto *b : RPOT) {
// unsigned opnum;
// SmallVector<Instruction *, 16> lists;
// for (auto &I : *b) {
// lists.clear();
// if (isMemOp(I.getOpcodeName(), opnum, memWriteOps) &&
// dyn_cast<Instruction>(I.getOperand(opnum))) {
// Instruction *argI = cast<Instruction>(I.getOperand(opnum));
// lists = createKilllist(argI, &I);
// TransitiveReads(lists, argI, I.getParent());
// if (argI->getParent() == I.getParent())
// lists.push_back(argI);
// killMap[&I] = lists;
// }
// }
// }
// for (auto *b : RPOT) {
// for (auto &I : *b) {
// for (int i = 0; i < I.getNumOperands(); i++) {
// if (isa<Instruction>(I.getOperand(i))) {
// auto RD = getReachingDefs(&I, i);
// if (instReachingDefsMap.find(&I) == instReachingDefsMap.end()) {
// instReachingDefsMap[&I] = RD;
// } else {
// auto RDList = instReachingDefsMap[&I];
// RDList.insert(RDList.end(), RD.begin(), RD.end());
// instReachingDefsMap[&I] = RDList;
// }
// }
// }
// }
// }
// IR2VEC_DEBUG(for (auto &Inst
// : instReachingDefsMap) {
// auto RD = Inst.second;
// outs() << "(" << Inst.first << ")";
// Inst.first->print(outs());
// outs() << "\n RD : ";
// for (auto defs : RD) {
// defs->print(outs());
// outs() << "(" << defs << ") ";
// }
// outs() << "\n";
// });
// // one time Reversing instReachingDefsMap to be used to calculate SCCs
// for (auto &I : instReachingDefsMap) {
// auto RD = I.second;
// for (auto defs : RD) {
// if (reverseReachingDefsMap.find(defs) == reverseReachingDefsMap.end()) {
// llvm::SmallVector<const llvm::Instruction *, 10> revDefs;
// revDefs.push_back(I.first);
// reverseReachingDefsMap[defs] = revDefs;
// } else {
// auto defVector = reverseReachingDefsMap[defs];
// defVector.push_back(I.first);
// reverseReachingDefsMap[defs] = defVector;
// }
// }
// }
// getAllSCC();
// std::sort(allSCCs.begin(), allSCCs.end(),
// [](llvm::SmallVector<const llvm::Instruction *, 10> &a,
// llvm::SmallVector<const llvm::Instruction *, 10> &b) {
// return a.size() < b.size();
// });
// IR2VEC_DEBUG(int i = 0; for (auto &sets
// : allSCCs) {
// outs() << "set: " << i << "\n";
// for (auto insts : sets) {
// insts->print(outs());
// outs() << " " << insts << " ";
// }
// outs() << "\n";
// i++;
// });
// for (int i = 0; i < allSCCs.size(); i++) {
// auto set = allSCCs[i];
// for (int j = 0; j < set.size(); j++) {
// auto RD = instReachingDefsMap[set[j]];
// if (!RD.empty()) {
// for (auto defs : RD) {
// for (int k = 0; k < allSCCs.size(); k++) {
// if (k == i)
// continue;
// auto sccSet = allSCCs[k];
// if (std::find(sccSet.begin(), sccSet.end(), defs) != sccSet.end()) {
// // outs() << i << " depends on " << k << "\n";
// if (SCCAdjList.find(k) == SCCAdjList.end()) {
// std::vector<int> temp;
// temp.push_back(i);
// SCCAdjList[k] = temp;
// } else {
// auto temp = SCCAdjList[k];
// if (std::find(temp.begin(), temp.end(), i) == temp.end())
// temp.push_back(i);
// SCCAdjList[k] = temp;
// }
// }
// }
// }
// }
// }
// }
// IR2VEC_DEBUG(outs() << "\nAdjList:\n"; for (auto &nodes
// : SCCAdjList) {
// outs() << "Adjlist for: " << nodes.first << "\n";
// for (auto components : nodes.second) {
// outs() << components << " ";
// }
// outs() << "\n";
// });
// std::vector<int> stack;
// stack = topoOrder(allSCCs.size());
// for (int i = 0; i < allSCCs.size(); i++) {
// if (std::find(stack.begin(), stack.end(), i) == stack.end()) {
// stack.insert(stack.begin(), i);
// }
// }
// IR2VEC_DEBUG(outs() << "New topo order: \n"; for (auto sets
// : stack) {
// outs() << sets << " ";
// } outs() << "\n";);
// SmallVector<double, DIM> prevVec;
// Instruction *argToKill = nullptr;
// while (stack.size() != 0) {
// int idx = stack.back();
// stack.pop_back();
// auto component = allSCCs[idx];
// SmallMapVector<const Instruction *, Vector, 16> partialInstValMap;
// if (component.size() == 1) {
// auto defs = component[0];
// partialInstValMap[defs] = {};
// getPartialVec(*defs, partialInstValMap);
// solveSingleComponent(*defs, partialInstValMap, funcStack);
// partialInstValMap.erase(defs);
// } else {
// cyclicCounter++; // for components with length more than 1 will
// // represent cycles
// for (auto defs : component) {
// partialInstValMap[defs] = {};
// getPartialVec(*defs, partialInstValMap);
// }
// if (!partialInstValMap.empty())
// solveInsts(partialInstValMap, funcStack);
// }
// }
for (auto *b : RPOT) {
bb2Vec(*b, funcStack);
Vector bbVector(DIM, 0);
// IR2VEC_DEBUG(outs() << "-------------------------------------------\n");
for (auto &I : *b) {
auto It1 = livelinessMap.find(&I);
if (It1->second == true) {
// IR2VEC_DEBUG(I.print(outs()); outs() << "\n");
auto vec = instVecMap.find(&I)->second;
// IR2VEC_DEBUG(outs() << vec[0] << "\n\n");
std::transform(bbVector.begin(), bbVector.end(), vec.begin(),
bbVector.begin(), std::plus<double>());
}
}
// IR2VEC_DEBUG(outs() << "-------------------------------------------\n");
for (auto i : bbVector) {
if ((i <= 0.0001 && i > 0) || (i < 0 && i >= -0.0001)) {
i = 0;
}
}
if(bpi){
auto prob = cumulativeScore[b];
Vector weightedBBVector;
// main thing changes here
for(auto p : bbVector){
// cout<< "value of p here : " << p<< "\n";
weightedBBVector.push_back(prob * p);
}
// cout << "weightedBBVector here : " << "\n";
// for(auto x : weightedBBVector){
// cout<<x<<",";
// }
// cout<<endl;
// cout << "size of bbVector : " << bbVector.size() <<"\n";
// cout << "size of funcVector : " << funcVector.size() <<"\n";
// cout << "size of weightedBBVector : " << weightedBBVector.size() << "\n";
std::transform(funcVector.begin(), funcVector.end(),
weightedBBVector.begin(), funcVector.begin(),
std::plus<double>());
}
else{
std::transform(funcVector.begin(), funcVector.end(), bbVector.begin(),
funcVector.begin(), std::plus<double>());
}
}
// cout<< "funcVector here : "<<endl;
// for(auto x : funcVector){
// cout<<x<<",";
// }
// cout<<endl;
funcStack.pop_back();
funcVecMap[&F] = funcVector;
return funcVector;
}
// LoopInfo contains a mapping from basic block to the innermost loop. Find
// the outermost loop in the loop nest that contains BB.
static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
const Loop *L = LI->getLoopFor(BB);
if (L) {
while (const Loop *Parent = L->getParentLoop())
L = Parent;
}
return L;
}
double IR2Vec_FA::getRDProb(const Instruction *src, const Instruction *tgt,
llvm::SmallVector<const Instruction *, 10> writeSet) {
// if(bprob == 0)
// return 1;
// assert(instVecMap.find(src)!=instVecMap.end() && "Vector of the instruction
// should be available at this point");
// if (bprob == 0)
// return 1;
// LLVM_DEBUG(errs() << "YOLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLOOO\n");
// LLVM_DEBUG(src->dump());
// LLVM_DEBUG(tgt->dump());
// LLVM_DEBUG(errs() << "yooooooodoooaaaaaaaaaaaaaaawwwwwwwwwwwggg\n");
auto srcParent = src->getParent();
auto tgtParent = tgt->getParent();
SmallPtrSet<const BasicBlock *, 20> writingBB;
for (auto I : writeSet)
{
writingBB.insert(I->getParent());
llvm::errs() << "Writing Basic Block: " << I->getParent()->getName() << "\n";
}
if (srcParent == tgtParent) {
// auto It1 = instVecMap.find(src);
// assert (It1 != instVecMap.end() && "Instruction should be defined in
// map"); return It1->second;
llvm::errs() << "Source and Target are in the same BasicBlock\n";
return 1;
}
SmallVector<const BasicBlock *, 20> stack;
// SmallDenseMap<const BasicBlock *, bool> visited;
// SmallDenseMap<const Instruction *, unsigned> last_seen;
SmallMapVector<const BasicBlock *, bool, 16> visited;
SmallMapVector<const Instruction *, unsigned, 16> last_seen;
auto curNode = srcParent;
auto curNodeTerminatorInst = curNode->getTerminator();
bool flag = false;
double prob = 1;
llvm::errs() << "Starting traversal from: " << srcParent->getName() << "\n";
do {
visited[curNode] = true;
if (flag) {
stack.pop_back();
if (stack.empty())
break;
curNode = stack.back();
curNodeTerminatorInst = curNode->getTerminator();
} else {
stack.push_back(curNode);
}
flag = true;
if (!last_seen[curNodeTerminatorInst]) {
last_seen[curNodeTerminatorInst] = 0;
}
for (unsigned i = last_seen[curNodeTerminatorInst];
i < curNodeTerminatorInst->getNumSuccessors(); i++) {
last_seen[curNodeTerminatorInst]++;
auto succ = curNodeTerminatorInst->getSuccessor(i);
if (succ == tgtParent) {
// issues can happen here ?
// auto bpi = bpiMap[(const_cast<BasicBlock *>(stack.front())->getParent())];
// MAKING CHANGES HERE:
Function* parent = (const_cast<BasicBlock*>(stack.front())->getParent());
auto it = bpiMap.find(parent);
cout<<"parent here : "<<parent<<"\n";
llvm::errs() << "Found path to target BasicBlock: " << tgtParent->getName() << "\n";
// auto bpi;
BranchProbabilityInfo *bpi;
if(it!=bpiMap.end()){
cout<<"MEANS IT IS NOT EMPTY HERE"<<"\n";
bpi = bpiMap[parent];
}
else{
cout<<"HOW IS IT COMING AS EMPTY ?"<< "\n";
llvm::FunctionAnalysisManager FAM;
// FAM.add(new BranchProbabilityAnalysis());
// FAM.addPass(BranchProbabilityAnalysis());
llvm::PassBuilder PB;
PB.registerFunctionAnalyses(FAM);
bpiMap[parent]=getBPI(parent, FAM);
bpi = bpiMap[parent];
}
cout<<"value of bpi :"<<bpi<<"\n";
// LLVM_DEBUG(errs() << "wasuuuuuuuuuuuuuuuuupppppppppppppppp\n");
bool init = true;
const BasicBlock *prev;
for (auto BB : stack) {
if (init) {
init = false;
prev = BB;
continue;
}
auto bp = bpi->getEdgeProbability(prev, BB);
cout<<"is bp coming correctly :"<<&bp<<"\n";
llvm::errs() << "Edge Probability " << prev->getName() << " -> " << BB->getName() << " : " << double(bp.getNumerator()) / bp.getDenominator() << "\n";
prob = prob * double(bp.getNumerator()) / double(bp.getDenominator());
prev = BB;
// LLVM_DEBUG(BB->dump());
}
auto bp = bpi->getEdgeProbability(prev, succ);
llvm::errs() << "Final Edge Probability " << prev->getName() << " -> " << succ->getName() << " : " << double(bp.getNumerator()) / bp.getDenominator() << "\n";
prob = prob * double(bp.getNumerator()) / double(bp.getDenominator());
// LLVM_DEBUG(succ->dump());
// LLVM_DEBUG(errs() << "alllllllllgoooooooooooooooodddddddddd\n");
curNode = succ;
curNodeTerminatorInst = curNode->getTerminator();
flag = false;
break;
} else if (!visited[succ] && writingBB.find(succ) == writingBB.end()) {
llvm::errs() << "Traversing to successor BasicBlock: " << succ->getName() << "\n";
curNode = succ;
curNodeTerminatorInst = curNode->getTerminator();
flag = false;
break;
}
}
} while (!stack.empty());
// LLVM_DEBUG(dbgs() << "Returning from RD Value\n");
llvm::errs() << "Computed Probability: " << prob << "\n";
cout<<"value of prob here , going out successfully :" << prob <<"\n";
return prob;
}
bool isPotentiallyReachableFromMany(
SmallVectorImpl<BasicBlock *> &Worklist, BasicBlock *StopBB,
const SmallPtrSetImpl<const BasicBlock *> *ExclusionSet,
const DominatorTree *DT, const LoopInfo *LI) {
// When the stop block is unreachable, it's dominated from everywhere,
// regardless of whether there's a path between the two blocks.
if (DT && !DT->isReachableFromEntry(StopBB))
DT = nullptr;
// We can't skip directly from a block that dominates the stop block if the
// exclusion block is potentially in between.
if (ExclusionSet && !ExclusionSet->empty())
DT = nullptr;
// Normally any block in a loop is reachable from any other block in a loop,
// however excluded blocks might partition the body of a loop to make that
// untrue.
SmallPtrSet<const Loop *, 8> LoopsWithHoles;
if (LI && ExclusionSet) {
for (auto BB : *ExclusionSet) {
if (const Loop *L = getOutermostLoop(LI, BB))
LoopsWithHoles.insert(L);
}
}
const Loop *StopLoop = LI ? getOutermostLoop(LI, StopBB) : nullptr;
// Limit the number of blocks we visit. The goal is to avoid run-away
// compile times on large CFGs without hampering sensible code. Arbitrarily
// chosen.
unsigned Limit = 32;
SmallPtrSet<const BasicBlock *, 32> Visited;
do {
BasicBlock *BB = Worklist.pop_back_val();
if (!Visited.insert(BB).second)
continue;
if (BB == StopBB)
return true;
if (ExclusionSet && ExclusionSet->count(BB))
continue;
if (DT && DT->dominates(BB, StopBB))
return true;
const Loop *Outer = nullptr;
if (LI) {
Outer = getOutermostLoop(LI, BB);
// If we're in a loop with a hole, not all blocks in the loop are
// reachable from all other blocks. That implies we can't simply
// jump to the loop's exit blocks, as that exit might need to pass
// through an excluded block. Clear Outer so we process BB's
// successors.
if (LoopsWithHoles.count(Outer))
Outer = nullptr;