-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathLLVMAliasSet.cpp
More file actions
801 lines (681 loc) · 24.5 KB
/
LLVMAliasSet.cpp
File metadata and controls
801 lines (681 loc) · 24.5 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
/******************************************************************************
* Copyright (c) 2020 Philipp Schubert.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of LICENSE.txt.
*
* Contributors:
* Philipp Schubert and others
*****************************************************************************/
#include "phasar/PhasarLLVM/Pointer/LLVMAliasSet.h"
#include "phasar/PhasarLLVM/DB/LLVMProjectIRDB.h"
#include "phasar/PhasarLLVM/Pointer/LLVMAliasInfo.h"
#include "phasar/PhasarLLVM/Pointer/LLVMPointsToUtils.h"
#include "phasar/PhasarLLVM/Utils/LLVMShorthands.h"
#include "phasar/Pointer/AliasAnalysisType.h"
#include "phasar/Utils/BoxedPointer.h"
#include "phasar/Utils/Logger.h"
#include "phasar/Utils/NlohmannLogging.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormatVariadic.h"
#include "nlohmann/json.hpp"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <iomanip>
#include <iterator>
#include <memory>
#include <type_traits>
#include <utility>
namespace psr {
template class BoxedPtr<LLVMAliasInfo::AliasSetTy>;
template class BoxedConstPtr<LLVMAliasInfo::AliasSetTy>;
template class AliasSetOwner<LLVMAliasInfo::AliasSetTy>;
LLVMAliasSet::LLVMAliasSet(LLVMProjectIRDB *IRDB, bool UseLazyEvaluation,
AliasAnalysisType PATy)
: PTA(*IRDB, UseLazyEvaluation, PATy) {
assert(IRDB != nullptr);
auto NumGlobals = IRDB->getNumGlobals();
AliasSets.reserve(NumGlobals);
Owner.reserve(NumGlobals);
PHASAR_LOG_LEVEL_CAT(
INFO, "LLVMAliasSet",
"Start constructing LLVMAliasSet "
<< std::chrono::steady_clock::now().time_since_epoch().count());
auto *M = IRDB->getModule();
// compute points-to information for all globals
for (const auto &G : M->globals()) {
computeValuesAliasSet(&G);
}
for (const auto &F : M->functions()) {
computeValuesAliasSet(&F);
}
if (!UseLazyEvaluation) {
// compute points-to information for all functions
for (auto &F : *M) {
if (!F.isDeclaration()) {
computeFunctionsAliasSet(&F);
}
}
}
PHASAR_LOG_LEVEL_CAT(
INFO, "LLVMAliasSet",
"LLVMAliasSet completed "
<< std::chrono::steady_clock::now().time_since_epoch().count());
}
LLVMAliasSet::LLVMAliasSet(LLVMProjectIRDB *IRDB,
const nlohmann::json &SerializedPTS)
: PTA(*IRDB, true) {
assert(IRDB != nullptr);
// Assume, we already have validated the json schema
PHASAR_LOG_LEVEL_CAT(DEBUG, "LLVMAliasSet",
"Load precomputed points-to info from JSON");
const auto &Sets = SerializedPTS.at("AliasSets");
assert(Sets.is_array());
const auto &Fns = SerializedPTS.at("AnalyzedFunctions");
assert(Fns.is_array());
/// Deserialize the AliasSets - an array of arrays (both are to be
/// interpreted as sets of metadata-ids)
Owner.reserve(Sets.size());
for (const auto &PtsJson : Sets) {
assert(PtsJson.is_array());
auto PTS = Owner.acquire();
for (const auto &Alias : PtsJson) {
const auto AliasStr = Alias.get<std::string>();
const auto *Inst = fromMetaDataId(*IRDB, AliasStr);
if (!Inst) {
PHASAR_LOG_LEVEL(WARNING, "Invalid Value-Id: " << AliasStr);
continue;
}
AliasSets[Inst] = PTS;
PTS->insert(Inst);
}
}
/// Deserialize the AnalyzedFunctions - an array of function-names (to be
/// interpreted as set)
AnalyzedFunctions.reserve(Fns.size());
for (const auto &F : Fns) {
if (!F.is_string()) {
PHASAR_LOG_LEVEL(WARNING, "Invalid Function Name: " << F);
continue;
}
const auto *IRFn = IRDB->getFunction(F.get<std::string>());
if (!IRFn) {
PHASAR_LOG_LEVEL(WARNING, "Function: " << F << " not in the IRDB");
continue;
}
AnalyzedFunctions.insert(IRFn);
}
}
void LLVMAliasSet::computeValuesAliasSet(const llvm::Value *V) {
if (!isInterestingPointer(V)) {
// don't need to do anything
return;
}
// Add set for the queried value if none exists, yet
addSingletonAliasSet(V);
if (const auto *G = llvm::dyn_cast<llvm::GlobalObject>(V)) {
// A global object can be a function or a global variable. We need to
// consider functions here, too, because function pointer magic may be
// used by the target program. Add a set for global object.
// A global object may be used in multiple functions.
for (const auto *User : G->users()) {
if (const auto *Inst = llvm::dyn_cast<llvm::Instruction>(User)) {
// The may be no corresponding function when the instruction is used in
// a vtable, for instance.
if (Inst->getParent()) {
computeFunctionsAliasSet(
const_cast<llvm::Function *> // NOLINT - FIXME when it is fixed in
// LLVM
(Inst->getFunction()));
if (!llvm::isa<llvm::Function>(G) && isInterestingPointer(User)) {
mergeAliasSets(User, G);
} else if (const auto *Store =
llvm::dyn_cast<llvm::StoreInst>(User)) {
if (isInterestingPointer(Store->getValueOperand())) {
// Store->getPointerOperand() doesn't require checking: it is
// always an interesting pointer
mergeAliasSets(Store->getValueOperand(),
Store->getPointerOperand());
}
}
}
}
}
} else {
const auto *VF = retrieveFunction(V);
computeFunctionsAliasSet(
const_cast<llvm::Function *> // NOLINT - FIXME when it is fixed in LLVM
(VF));
}
}
void LLVMAliasSet::addSingletonAliasSet(const llvm::Value *V) {
auto [It, Inserted] = AliasSets.try_emplace(V, nullptr);
if (!Inserted) {
assert(It->second->count(V));
return;
}
auto PTS = Owner.acquire();
PTS->insert(V);
It->second = PTS;
}
void LLVMAliasSet::mergeAliasSets(const llvm::Value *V1,
const llvm::Value *V2) {
if (V1 == V2) {
return;
}
auto SearchV1 = AliasSets.find(V1);
assert(SearchV1 != AliasSets.end());
auto SearchV2 = AliasSets.find(V2);
assert(SearchV2 != AliasSets.end());
mergeAliasSets(SearchV1->second, SearchV2->second);
}
void LLVMAliasSet::mergeAliasSets(BoxedPtr<AliasSetTy> PTS1,
BoxedPtr<AliasSetTy> PTS2) {
if (PTS1 == PTS2 || PTS1.get() == PTS2.get()) {
return;
}
assert(PTS1 && PTS1.get());
assert(PTS2 && PTS2.get());
auto [SmallerSet, LargerSet] = [&]() {
if (PTS1->size() > PTS2->size()) {
return std::make_pair(PTS2, PTS1);
}
return std::make_pair(PTS1, PTS2);
}();
// reindex the contents of the smaller set
// for (const auto *Ptr : *SmallerSet) {
// AliasSets[Ptr] = LargerSet;
// }
// add smaller set to larger one and get rid of the smaller set
LargerSet->reserve(LargerSet->size() + SmallerSet->size());
LargerSet->insert(SmallerSet->begin(), SmallerSet->end());
// *SmallerSet.value() = LargerSet.get();
auto *ToDelete = SmallerSet.get();
for (const auto *Vals : *SmallerSet) {
auto PTS = AliasSets[Vals];
if (PTS.get() == ToDelete) {
*PTS.value() = LargerSet.get();
}
}
Owner.release(ToDelete);
}
bool LLVMAliasSet::interIsReachableAllocationSiteTy(
[[maybe_unused]] const llvm::Value *V, const llvm::Value *P) const {
// consider the full inter-procedural points-to/alias information
if (llvm::isa<llvm::AllocaInst>(P)) {
return true;
}
if (const auto *CS = llvm::dyn_cast<llvm::CallBase>(P)) {
if (CS->getCalledFunction() != nullptr &&
isHeapAllocatingFunction(CS->getCalledFunction())) {
return true;
}
}
return false;
}
bool LLVMAliasSet::intraIsReachableAllocationSiteTy(
[[maybe_unused]] const llvm::Value *V, const llvm::Value *P,
const llvm::Function *VFun, const llvm::GlobalObject *VG) const {
// consider the function-local, i.e. intra-procedural, points-to/alias
// information only
// We may not be able to retrieve a function for the given value since some
// pointer values can exist outside functions, for instance, in case of
// vtables, etc.
if (const auto *Alloca = llvm::dyn_cast<llvm::AllocaInst>(P)) {
// only add function local allocation sites
if ((VFun && VFun == Alloca->getFunction())) {
return true;
}
if (VG) {
return true;
}
} else if (const auto *CS = llvm::dyn_cast<llvm::CallBase>(P)) {
if (CS->getCalledFunction() != nullptr &&
isHeapAllocatingFunction(CS->getCalledFunction())) {
if (VFun && VFun == CS->getFunction()) {
return true;
}
if (VG) {
return true;
}
}
} else if (const auto *Arg = llvm::dyn_cast<llvm::Argument>(P)) {
/// Arguments are no allocation sites, but in the inTRAprocedural case, they
/// act as such
return Arg->getParent() == VFun;
}
return false;
}
static bool mayAlias(llvm::AAResults &AA, const llvm::DataLayout &DL,
const llvm::Value *V, const llvm::Value *Rep) {
assert(V->getType()->isPointerTy());
assert(Rep->getType()->isPointerTy());
auto VSize = V->getType()->getPointerElementType()->isSized()
? DL.getTypeStoreSize(V->getType()->getPointerElementType())
: llvm::MemoryLocation::UnknownSize;
auto RepSize =
Rep->getType()->getPointerElementType()->isSized()
? DL.getTypeStoreSize(Rep->getType()->getPointerElementType())
: llvm::MemoryLocation::UnknownSize;
if (AA.alias(V, VSize, Rep, RepSize) != llvm::AliasResult::NoAlias) {
return true;
}
return false;
}
void LLVMAliasSet::addPointer(llvm::AAResults &AA, const llvm::DataLayout &DL,
const llvm::Value *V,
std::vector<const llvm::Value *> &Reps) {
llvm::SmallVector<unsigned> ToMerge;
for (unsigned It = 0, End = Reps.size(); It < End; ++It) {
if (mayAlias(AA, DL, V, Reps[It])) {
ToMerge.push_back(It);
}
}
// If we find several alias sets that may alias V, we must merge them.
// However, we cannot simply remove all respective representants (except for
// one), because for interprocedural flows, LLVM assumes all possible
// aliases and i8* is treated as void* making every pointer-type a matching
// type.
// This destroys the transitivity of the mayAlias relation partially. We can
// still remove a representant, if we have another rep of the same type
// within the same alias set.
if (ToMerge.empty()) {
Reps.push_back(V);
addSingletonAliasSet(V);
} else if (ToMerge.size() == 1) {
auto PTS = AliasSets[Reps[ToMerge[0]]];
assert(PTS && "Only added to Reps together with a "
"\"addSingletonAliasSet\" call");
if (auto VPTS = AliasSets.find(V); VPTS != AliasSets.end()) {
mergeAliasSets(PTS, VPTS->second);
} else {
AliasSets[V] = PTS;
PTS->insert(V);
}
if (V->getType() != Reps[ToMerge[0]]->getType()) {
Reps.push_back(V);
}
} else {
auto PTS = AliasSets[Reps[ToMerge[0]]];
llvm::SmallPtrSet<const llvm::Type *, 6> OccurringTypes{
Reps[ToMerge[0]]->getType()};
llvm::SmallVector<unsigned> ToRemove;
for (auto Idx : llvm::makeArrayRef(ToMerge).slice(1)) {
mergeAliasSets(PTS, AliasSets[Reps[Idx]]);
if (auto [Unused, Inserted] = OccurringTypes.insert(Reps[Idx]->getType());
!Inserted) {
ToRemove.push_back(Idx);
}
}
if (auto VPTS = AliasSets.find(V); VPTS != AliasSets.end()) {
mergeAliasSets(PTS, VPTS->second);
} else {
AliasSets[V] = PTS;
PTS->insert(V);
}
Reps.erase(remove_by_index(Reps, ToRemove.begin(), ToRemove.end()),
Reps.end());
if (auto [Unused, Inserted] = OccurringTypes.insert(V->getType());
Inserted) {
Reps.push_back(V);
}
}
}
static void addIfGlobal(llvm::DenseSet<const llvm::Value *> &UsedGlobals,
const llvm::Value *Op) {
llvm::SmallPtrSet<const llvm::Value *, 4> Seen;
llvm::SmallVector<const llvm::Value *, 4> WorkList;
WorkList.push_back(Op);
Seen.insert(Op);
while (!WorkList.empty()) {
const auto *Curr = WorkList.pop_back_val();
if (llvm::isa<llvm::GlobalObject>(Curr)) {
UsedGlobals.insert(Curr);
if (const auto *Glob = llvm::dyn_cast<llvm::GlobalVariable>(Curr);
Glob && Glob->hasInitializer() &&
Seen.insert(Glob->getInitializer()).second) {
WorkList.push_back(Glob->getInitializer());
}
} else if (llvm::isa<llvm::ConstantExpr>(Curr) ||
llvm::isa<llvm::ConstantAggregate>(Curr)) {
for (const auto &CEOp : llvm::cast<llvm::User>(Curr)->operands()) {
if (Seen.insert(CEOp).second) {
WorkList.push_back(CEOp);
}
}
}
}
}
void LLVMAliasSet::computeFunctionsAliasSet(llvm::Function *F) {
// F may be null
if (!F) {
return;
}
// check if we already analyzed the function
if (auto [Unused, Inserted] = AnalyzedFunctions.insert(F);
!Inserted || F->isDeclaration()) {
return;
}
PHASAR_LOG_LEVEL_CAT(DEBUG, "LLVMAliasSet",
"Analyzing function: " << F->getName());
llvm::AAResults &AA = *PTA.getAAResults(F);
bool EvalAAMD = true;
const llvm::DataLayout &DL = F->getParent()->getDataLayout();
auto addPointer = [this, &AA, &DL](const llvm::Value *V, // NOLINT
std::vector<const llvm::Value *> &Reps) {
return this->addPointer(AA, DL, V, Reps);
};
std::vector<const llvm::Value *> Pointers;
llvm::DenseSet<const llvm::Value *> UsedGlobals;
for (auto &Inst : llvm::instructions(F)) {
if (Inst.getType()->isPointerTy()) {
// Add all pointer instructions.
addPointer(&Inst, Pointers);
}
if (EvalAAMD && llvm::isa<llvm::StoreInst>(&Inst)) {
auto *Store = llvm::cast<llvm::StoreInst>(&Inst);
auto *SVO = Store->getValueOperand();
auto *SPO = Store->getPointerOperand();
if (SVO->getType()->isPointerTy()) {
if (llvm::isa<llvm::Function>(SVO)) {
addSingletonAliasSet(SVO);
addSingletonAliasSet(SPO);
mergeAliasSets(SVO, SPO);
}
if (auto *SVOCE = llvm::dyn_cast<llvm::ConstantExpr>(SVO)) {
if (SVOCE->isCast()) {
auto *RHS = SVOCE->getOperand(0);
addSingletonAliasSet(SPO);
if (RHS->getType()->isPointerTy()) {
addSingletonAliasSet(RHS);
mergeAliasSets(RHS, SPO);
}
addSingletonAliasSet(SVOCE);
mergeAliasSets(SVOCE, SPO);
}
}
}
}
/// The operands/arguments of instructions should already be inserted,
/// because of the SSA form
if (auto *Call = llvm::dyn_cast<llvm::CallBase>(&Inst)) {
llvm::Value *Callee = Call->getCalledOperand();
// Skip actual functions for direct function calls.
if (!llvm::isa<llvm::Function>(Callee) && isInterestingPointer(Callee) &&
!llvm::isa<llvm::Instruction>(Callee)) {
addPointer(Callee, Pointers);
}
// Consider arguments.
for (llvm::Use &DataOp : Call->data_ops()) {
addIfGlobal(UsedGlobals, DataOp);
if (!llvm::isa<llvm::Instruction>(DataOp) &&
isInterestingPointer(DataOp)) {
addPointer(DataOp, Pointers);
}
}
} else {
// Consider all operands; the instructions we have already seen
for (auto &Op : Inst.operands()) {
addIfGlobal(UsedGlobals, Op);
if (!llvm::isa<llvm::Instruction>(Op) && isInterestingPointer(Op)) {
addPointer(Op, Pointers);
}
}
}
}
for (auto &I : F->args()) {
if (I.getType()->isPointerTy()) {
// Add all pointer arguments.
addPointer(&I, Pointers);
}
}
auto NumGlobals = UsedGlobals.size();
Pointers.reserve(Pointers.size() + NumGlobals);
for (const auto *Glob : UsedGlobals) {
addPointer(Glob, Pointers);
}
// we no longer need the LLVM representation
PTA.erase(F);
}
AliasResult LLVMAliasSet::alias(const llvm::Value *V1, const llvm::Value *V2,
[[maybe_unused]] const llvm::Instruction *I) {
// if V1 or V2 is not an interesting pointer those values cannot alias
if (!isInterestingPointer(V1) || !isInterestingPointer(V2)) {
return AliasResult::NoAlias;
}
computeValuesAliasSet(V1);
computeValuesAliasSet(V2);
return AliasSets[V1]->count(V2) ? AliasResult::MayAlias
: AliasResult::NoAlias;
}
auto LLVMAliasSet::getEmptyAliasSet() -> BoxedPtr<AliasSetTy> {
static AliasSetTy EmptySet{};
static AliasSetTy *EmptySetPtr = &EmptySet;
return &EmptySetPtr;
}
auto LLVMAliasSet::getAliasSet(const llvm::Value *V,
[[maybe_unused]] const llvm::Instruction *I)
-> AliasSetPtrTy {
// if V is not a (interesting) pointer we can return an empty set
if (!isInterestingPointer(V)) {
return getEmptyAliasSet();
}
// compute V's points-to set
computeValuesAliasSet(V);
if (auto It = AliasSets.find(V); It != AliasSets.end()) {
return It->second;
}
// if we still can't find its value return an empty set
return getEmptyAliasSet();
}
auto LLVMAliasSet::getReachableAllocationSites(
const llvm::Value *V, bool IntraProcOnly,
[[maybe_unused]] const llvm::Instruction *I) -> AllocationSiteSetPtrTy {
auto AllocSites = std::make_unique<AliasSetTy>();
// if V is not a (interesting) pointer we can return an empty set
if (!isInterestingPointer(V)) {
return AllocSites;
}
computeValuesAliasSet(V);
const auto PTS = AliasSets[V];
// consider the full inter-procedural points-to/alias information
if (!IntraProcOnly) {
for (const auto *P : *PTS) {
if (interIsReachableAllocationSiteTy(V, P)) {
AllocSites->insert(P);
}
}
} else {
// consider the function-local, i.e. intra-procedural, points-to/alias
// information only
const auto *VFun = retrieveFunction(V);
const auto *VG = llvm::dyn_cast<llvm::GlobalObject>(V);
// We may not be able to retrieve a function for the given value since some
// pointer values can exist outside functions, for instance, in case of
// vtables, etc.
for (const auto *P : *PTS) {
if (intraIsReachableAllocationSiteTy(V, P, VFun, VG)) {
AllocSites->insert(P);
}
}
}
return AllocSites;
}
bool LLVMAliasSet::isInReachableAllocationSites(
const llvm::Value *V, const llvm::Value *PotentialValue, bool IntraProcOnly,
[[maybe_unused]] const llvm::Instruction *I) {
// if V is not a (interesting) pointer we can return an empty set
if (!isInterestingPointer(V)) {
return false;
}
computeValuesAliasSet(V);
bool PVIsReachableAllocationSiteType = false;
if (IntraProcOnly) {
const auto *VFun = retrieveFunction(V);
const auto *VG = llvm::dyn_cast<llvm::GlobalObject>(V);
PVIsReachableAllocationSiteType =
intraIsReachableAllocationSiteTy(V, PotentialValue, VFun, VG);
} else {
PVIsReachableAllocationSiteType =
interIsReachableAllocationSiteTy(V, PotentialValue);
}
if (PVIsReachableAllocationSiteType) {
const auto PTS = AliasSets[V];
return PTS->count(PotentialValue);
}
return false;
}
void LLVMAliasSet::mergeWith(const LLVMAliasSet &OtherPTI) {
// merge analyzed functions
AnalyzedFunctions.insert(OtherPTI.AnalyzedFunctions.begin(),
OtherPTI.AnalyzedFunctions.end());
// merge points-to sets
for (const auto &[KeyPtr, Set] : OtherPTI.AliasSets) {
bool FoundElemPtr = false;
for (const auto *ElemPtr : *Set) {
// check if a pointer of other is already present in this
if (auto Search = AliasSets.find(ElemPtr); Search != AliasSets.end()) {
// if so, copy its elements
FoundElemPtr = true;
Search->second->insert(Set->begin(), Set->end());
// and reindex its elements
for (const auto *ElemPtr : *Set) {
AliasSets.insert({ElemPtr, Search->second});
}
break;
}
}
// if none of the pointers of a set of other is known in this, we need to
// perform a copy
if (!FoundElemPtr) {
auto PTS = Owner.acquire();
*PTS = *Set;
AliasSets.try_emplace(KeyPtr, PTS);
}
}
}
void LLVMAliasSet::introduceAlias(const llvm::Value *V1, const llvm::Value *V2,
[[maybe_unused]] const llvm::Instruction *I,
[[maybe_unused]] AliasResult Kind) {
// only introduce aliases if both values are interesting pointer
if (!isInterestingPointer(V1) || !isInterestingPointer(V2)) {
return;
}
// before introducing additional aliases make sure we initially computed
// the aliases for V1 and V2
computeValuesAliasSet(V1);
computeValuesAliasSet(V2);
mergeAliasSets(V1, V2);
}
nlohmann::json LLVMAliasSet::getAsJson() const {
nlohmann::json J;
/// Serialize the AliasSets
auto &Sets = J["AliasSets"];
for (const AliasSetTy *PTS : Owner.getAllAliasSets()) {
auto PtsJson = nlohmann::json::array();
for (const auto *Alias : *PTS) {
auto Id = getMetaDataID(Alias);
if (Id != "-1") {
PtsJson.push_back(std::move(Id));
}
}
if (!PtsJson.empty()) {
Sets.push_back(std::move(PtsJson));
}
}
/// Serialize the AnalyzedFunctions
auto &Fns = J["AnalyzedFunctions"];
for (const auto *F : AnalyzedFunctions) {
Fns.push_back(F->getName());
}
return J;
}
void LLVMAliasSet::printAsJson(llvm::raw_ostream &OS) const {
OS << getAsJson();
}
void LLVMAliasSet::print(llvm::raw_ostream &OS) const {
for (const auto &[V, PTS] : AliasSets) {
OS << "V: " << llvmIRToString(V) << '\n';
for (const auto &Ptr : *PTS) {
OS << "\tpoints to -> " << llvmIRToString(Ptr) << '\n';
}
}
}
void LLVMAliasSet::peakIntoAliasSet(const AliasSetMap::value_type &ValueSetPair,
int Peak) {
llvm::outs() << "Value: ";
ValueSetPair.first->print(llvm::outs());
llvm::outs() << '\n';
int PeakCounter = 0;
llvm::outs() << "aliases with: {\n";
for (const llvm::Value *I : *ValueSetPair.second) {
I->print(llvm::outs());
llvm::outs() << '\n';
PeakCounter++;
if (PeakCounter > Peak) {
llvm::outs() << llvm::formatv("... and {0} more\n",
ValueSetPair.second->size() - Peak);
break;
}
}
llvm::outs() << "}\n";
}
void LLVMAliasSet::drawAliasSetsDistribution(int Peak) const {
std::vector<std::pair<size_t, unsigned>> SizeAmountPairs;
for (const auto &ValueSetPair : AliasSets) {
auto Search =
std::find_if(SizeAmountPairs.begin(), SizeAmountPairs.end(),
[&ValueSetPair](const auto &Entry) {
return Entry.first == ValueSetPair.second->size();
});
if (Search != SizeAmountPairs.end()) {
Search->second++;
} else {
SizeAmountPairs.emplace_back(ValueSetPair.second->size(), 1);
}
}
std::sort(SizeAmountPairs.begin(), SizeAmountPairs.end(),
[](const auto &KVPair1, const auto &KVPair2) {
return KVPair1.first < KVPair2.first;
});
int TotalValues = std::accumulate(
SizeAmountPairs.begin(), SizeAmountPairs.end(), 0,
[](int Current, const auto &KVPair) { return Current + KVPair.second; });
llvm::outs() << llvm::formatv("{0,10} {1,-=50} {2,10}\n", "PtS Size",
"Distribution", "Number of sets");
for (auto &KV : SizeAmountPairs) {
std::string PeakBar(static_cast<double>(KV.second) * 50 /
static_cast<double>(TotalValues),
'*');
llvm::outs() << llvm::formatv("{0,10} |{1,-50} {2,-10}\n", KV.first,
PeakBar, KV.second);
}
llvm::outs() << "\n";
if (Peak) {
for (const auto &ValueSetPair : AliasSets) {
if (ValueSetPair.second->size() == SizeAmountPairs.back().first) {
llvm::outs() << "Peak into one of the biggest points sets.\n";
peakIntoAliasSet(ValueSetPair, Peak);
return;
}
}
}
}
} // namespace psr