/
PartialLoopPurityPass.cpp
1639 lines (1514 loc) · 60.2 KB
/
PartialLoopPurityPass.cpp
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
/* Copyright (C) 2021 Magnus Lång
*
* This file is part of Nidhugg.
*
* Nidhugg is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Nidhugg is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include "PartialLoopPurityPass.h"
#include "CheckModule.h"
#include "Debug.h"
#include "Option.h"
#include "SpinAssumePass.h"
#include "vecset.h"
#include <boost/container/flat_map.hpp>
#include <llvm/ADT/SmallVector.h>
#include <llvm/Analysis/CallGraph.h>
#include <llvm/Analysis/LoopInfo.h>
#include <llvm/Analysis/LoopPass.h>
#include <llvm/Analysis/ValueTracking.h>
#if defined(HAVE_LLVM_IR_DOMINATORS_H)
#include <llvm/IR/Dominators.h>
#elif defined(HAVE_LLVM_ANALYSIS_DOMINATORS_H)
#include <llvm/Analysis/Dominators.h>
#endif
#include <llvm/Config/llvm-config.h>
#if defined(HAVE_LLVM_IR_FUNCTION_H)
#include <llvm/IR/Function.h>
#elif defined(HAVE_LLVM_FUNCTION_H)
#include <llvm/Function.h>
#endif
#include <llvm/IR/Constants.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/Verifier.h>
#if defined(HAVE_LLVM_IR_INSTRUCTIONS_H)
#include <llvm/IR/Instructions.h>
#elif defined(HAVE_LLVM_INSTRUCTIONS_H)
#include <llvm/Instructions.h>
#endif
#if defined(HAVE_LLVM_IR_LLVMCONTEXT_H)
#include <llvm/IR/LLVMContext.h>
#elif defined(HAVE_LLVM_LLVMCONTEXT_H)
#include <llvm/LLVMContext.h>
#endif
#if defined(HAVE_LLVM_IR_MODULE_H)
#include <llvm/IR/Module.h>
#elif defined(HAVE_LLVM_MODULE_H)
#include <llvm/Module.h>
#endif
#if defined(HAVE_LLVM_SUPPORT_CALLSITE_H)
#include <llvm/Support/CallSite.h>
#elif defined(HAVE_LLVM_IR_CALLSITE_H)
#include <llvm/IR/CallSite.h>
#endif
#include <llvm/Pass.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/Debug.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <algorithm>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#ifdef LLVM_HAS_TERMINATORINST
typedef llvm::TerminatorInst TerminatorInst;
#else
typedef llvm::Instruction TerminatorInst;
#endif
namespace {
llvm::cl::opt<int> cl_plp_dbgp("plp-debug");
const int MAX_CONJUNCTION_TERMS = 5;
const int MAX_DISJUNCTION_TERMS = 10;
/* Not reentrant */
static const llvm::DominatorTree *DominatorTree;
static const llvm::Loop *Loop;
static const struct RPO *LoopRPO;
static const std::unordered_map<llvm::Function *, bool> *may_inline;
static bool inlining_needed = false;
std::uint_fast8_t icmpop_to_bits(llvm::CmpInst::Predicate pred) {
using llvm::CmpInst;
assert(pred >= CmpInst::FIRST_ICMP_PREDICATE
&& pred <= CmpInst::LAST_ICMP_PREDICATE);
switch(pred) {
case CmpInst::ICMP_SGT: return 0b00010;
case CmpInst::ICMP_UGT: return 0b00001;
case CmpInst::ICMP_SGE: return 0b00110;
case CmpInst::ICMP_UGE: return 0b00101;
case CmpInst::ICMP_EQ: return 0b00100;
case CmpInst::ICMP_NE: return 0b11011;
case CmpInst::ICMP_SLE: return 0b01100;
case CmpInst::ICMP_ULE: return 0b10100;
case CmpInst::ICMP_SLT: return 0b01000;
case CmpInst::ICMP_ULT: return 0b10000;
default: abort();
}
}
llvm::CmpInst::Predicate bits_to_icmpop(std::uint_fast8_t bits, bool &ua) {
using llvm::CmpInst;
if ((bits & 0b01110) == 0b01110) return CmpInst::FCMP_TRUE; // Not expected to happen
if ((bits & 0b10101) == 0b10101) return CmpInst::FCMP_TRUE; // Not expected to happen
if ((bits & 0b01100) == 0b01100) { ua |= bits != 0b01100; return CmpInst::ICMP_SLE; }
if ((bits & 0b00110) == 0b00110) { ua |= bits != 0b00110; return CmpInst::ICMP_SGE; }
if ((bits & 0b10100) == 0b10100) { ua |= bits != 0b10100; return CmpInst::ICMP_ULE; }
if ((bits & 0b00101) == 0b00101) { ua |= bits != 0b00101; return CmpInst::ICMP_UGE; }
if ((bits & 0b01000) == 0b01000) { ua |= bits != 0b01000; return CmpInst::ICMP_SLT; }
if ((bits & 0b00010) == 0b00010) { ua |= bits != 0b00010; return CmpInst::ICMP_SGT; }
if ((bits & 0b10000) == 0b10000) { ua |= bits != 0b10000; return CmpInst::ICMP_ULT; }
if ((bits & 0b00001) == 0b00001) { ua |= bits != 0b00001; return CmpInst::ICMP_UGT; }
if ((bits & 0b01010) == 0b01010) { ua |= bits != 0b01010; return CmpInst::ICMP_NE; }
if ((bits & 0b10001) == 0b10001) { ua |= bits != 0b10001; return CmpInst::ICMP_NE; }
if ((bits & 0b00100) == 0b00100) { ua |= bits != 0b00100; return CmpInst::ICMP_EQ; }
ua |= bits != 0;
return CmpInst::FCMP_FALSE;
}
llvm::CmpInst::Predicate icmpop_invert_strictness(llvm::CmpInst::Predicate pred) {
bool underapprox = false;
llvm::CmpInst::Predicate res = bits_to_icmpop(0b00100 ^ icmpop_to_bits(pred),
underapprox);
assert(!underapprox);
return res;
}
bool check_predicate_satisfaction(const llvm::APInt &lhs,
llvm::CmpInst::Predicate pred,
const llvm::APInt &rhs) {
using llvm::CmpInst;
assert(pred >= CmpInst::FIRST_ICMP_PREDICATE
&& pred <= CmpInst::LAST_ICMP_PREDICATE);
switch(pred) {
case CmpInst::ICMP_SGT: return lhs.sgt(rhs);
case CmpInst::ICMP_UGT: return lhs.ugt(rhs);
case CmpInst::ICMP_SGE: return lhs.sge(rhs);
case CmpInst::ICMP_UGE: return lhs.uge(rhs);
case CmpInst::ICMP_EQ: return lhs.eq (rhs);
case CmpInst::ICMP_NE: return lhs.ne (rhs);
case CmpInst::ICMP_SLE: return lhs.sle(rhs);
case CmpInst::ICMP_ULE: return lhs.ule(rhs);
case CmpInst::ICMP_SLT: return lhs.slt(rhs);
case CmpInst::ICMP_ULT: return lhs.ult(rhs);
default: abort();
}
}
struct BinaryPredicate {
llvm::Value *lhs = nullptr, *rhs = nullptr;
/* FCMP_TRUE and FCMP_FALSE are used as special values indicating
* unconditional purity
*/
llvm::CmpInst::Predicate op = llvm::CmpInst::FCMP_FALSE;
BinaryPredicate() {}
BinaryPredicate(bool static_value) {
op = static_value ? llvm::CmpInst::FCMP_TRUE : llvm::CmpInst::FCMP_FALSE;
}
BinaryPredicate(llvm::CmpInst::Predicate op, llvm::Value *lhs,
llvm::Value *rhs)
: lhs(lhs), rhs(rhs), op(op) {
assert(!(is_true() || is_false()) || (lhs == nullptr && rhs == nullptr));
}
/* A BinaryPredicate must be normalised after direct modification of its members. */
void normalise() {
if (op == llvm::CmpInst::FCMP_TRUE || op == llvm::CmpInst::FCMP_FALSE) {
lhs = rhs = nullptr;
} else {
assert(lhs && rhs);
}
}
bool is_true() const {
assert(!(op == llvm::CmpInst::FCMP_TRUE && (lhs || rhs)));
return op == llvm::CmpInst::FCMP_TRUE;
}
bool is_false() const {
assert(!(op == llvm::CmpInst::FCMP_FALSE && (lhs || rhs)));
return op == llvm::CmpInst::FCMP_FALSE;
}
BinaryPredicate negate() const {
return {llvm::CmpInst::getInversePredicate(op), lhs, rhs};
}
BinaryPredicate swap() const {
return {llvm::CmpInst::getSwappedPredicate(op), rhs, lhs};
}
/* Returns the conjunction of *this and other. Assigns true to
* underapprox if the result is an underapproximation. */
BinaryPredicate meet(const BinaryPredicate &other,
bool &underapprox) const {
if (other.is_true() || *this == other) return *this;
if (is_true()) return other;
using llvm::CmpInst;
BinaryPredicate res = *this;
BinaryPredicate o(other);
if (res.rhs == o.lhs || res.rhs == o.rhs) res = swap();
if (res.lhs == o.lhs || res.lhs == o.rhs) {
if (res.lhs != o.lhs) o = o.swap();
if (res.rhs == o.rhs) {
if (llvm::CmpInst::isFPPredicate(res.op)
&& llvm::CmpInst::isFPPredicate(o.op)) {
res.op = CmpInst::Predicate(res.op & o.op);
} else if (llvm::CmpInst::isIntPredicate(res.op)
&& llvm::CmpInst::isIntPredicate(o.op)) {
res.op = bits_to_icmpop(icmpop_to_bits(res.op) & icmpop_to_bits(o.op),
underapprox);
} else {
underapprox = true;
return false; // Mixing fp and int predicates
}
res.normalise();
return res;
}
if (llvm::isa<llvm::ConstantInt>(res.rhs) && llvm::isa<llvm::ConstantInt>(o.rhs)) {
assert((llvm::cast<llvm::ConstantInt>(res.rhs)->getValue()
!= llvm::cast<llvm::ConstantInt>(o.rhs)->getValue()));
if (res.op == CmpInst::ICMP_EQ || o.op == CmpInst::ICMP_EQ) {
if (res.op != CmpInst::ICMP_EQ) std::swap(o, res);
const llvm::APInt &RR = llvm::cast<llvm::ConstantInt>(res.rhs)->getValue();
const llvm::APInt &OR = llvm::cast<llvm::ConstantInt>(o.rhs)->getValue();
if (check_predicate_satisfaction(RR, o.op, OR)) {
return res;
} else {
return false;
}
}
if (res.op == CmpInst::ICMP_NE || o.op == CmpInst::ICMP_NE) {
if (o.op != CmpInst::ICMP_NE) std::swap(o, res);
const llvm::APInt &RR = llvm::cast<llvm::ConstantInt>(res.rhs)->getValue();
const llvm::APInt &OR = llvm::cast<llvm::ConstantInt>(o.rhs)->getValue();
if (check_predicate_satisfaction(OR, res.op, RR)) {
underapprox = true;
return false; // Possible to refine: we'd have to
// exclude OR from res somehow
} else {
return res;
}
}
{
const llvm::APInt &RR = llvm::cast<llvm::ConstantInt>(res.rhs)->getValue();
const llvm::APInt &OR = llvm::cast<llvm::ConstantInt>(o.rhs)->getValue();
assert(res.op != CmpInst::ICMP_EQ && res.op != CmpInst::ICMP_NE);
if (CmpInst::isIntPredicate(res.op)
&& (o.op == res.op || o.op == icmpop_invert_strictness(res.op))) {
underapprox = true; /* Maybe not always? */
return ((check_predicate_satisfaction(RR, res.op, OR))) ? o : res;
}
}
}
}
if (!other.is_false()) underapprox = true;
return false;
}
BinaryPredicate operator&(const BinaryPredicate &other) const {
bool underapprox = false;
return meet(other, underapprox);
}
BinaryPredicate &operator&=(const BinaryPredicate &other) {
return *this = (*this & other);
}
bool operator!=(const BinaryPredicate &other) const { return !(*this == other); }
bool operator==(const BinaryPredicate &other) const {
assert(!(is_true() || is_false()) || (lhs == nullptr && rhs == nullptr));
return lhs == other.lhs && rhs == other.rhs && op == other.op;
}
bool operator<=(const BinaryPredicate &other) const {
// Special case optimisations, should not be needed
if (other.is_true() || is_false()) return true;
if (*this == other) return true;
bool underapprox = false;
BinaryPredicate m = meet(other, underapprox);
return m == *this;
}
bool operator<(const BinaryPredicate &other) const {
return *this != other && *this <= other;
}
};
struct RPO {
std::vector<llvm::BasicBlock *> blocks;
boost::container::flat_map<const llvm::BasicBlock *, std::size_t> block_indices;
bool is_backedge(const llvm::BasicBlock *From, const llvm::BasicBlock *To) const {
assert(block_indices.count(From) && block_indices.count(To));
return block_indices.at(From) >= block_indices.at(To);
}
RPO(std::size_t capacity) { blocks.reserve(capacity); }
};
/* Encodes a restriction on where an assume may be inserted. There is
* no bottom value, instead, operator& (which is the only operation
* that may return bottom) uses Option<InsertionPoint>. */
struct InsertionPoint {
/* Earliest location that can support an insertion. nullptr means
* that any location is fine. */
llvm::Instruction *earliest = nullptr;
InsertionPoint(llvm::Instruction *earliest = nullptr) : earliest(earliest) {}
/* Reset to default value (no insertion point requirement) */
void clear() { earliest = nullptr; }
operator bool() const { return earliest; }
bool is_true() const { return *this; }
bool is_false() const { return !*this; }
static bool isBefore(llvm::Instruction *I, llvm::Instruction *J) {
llvm::BasicBlock *IB = I->getParent(), *JB = J->getParent();
if (IB == JB) {
while(true) {
if (J == &*JB->begin()) return false;
J = J->getPrevNode();
if (I == J) return true;
}
} else {
std::size_t IBI = LoopRPO->block_indices.at(IB),
JBI = LoopRPO->block_indices.at(JB);
assert (IBI != JBI);
if (IBI > JBI) return false;
VecSet<std::size_t> predecessors;
while (true) {
for (llvm::BasicBlock *Pred : llvm::predecessors(JB)) {
if (Pred == IB) return true;
assert(LoopRPO->block_indices.count(Pred)); // Cannot exit loop
std::size_t PredI = LoopRPO->block_indices.at(Pred);
// if (it == LoopRPO->block_indices.end()) continue;
if (PredI >= IBI && PredI < JBI)
predecessors.insert(PredI);
}
if (predecessors.empty()) return false;
assert(predecessors.back() < JBI);
JBI = predecessors.back();
predecessors.pop_back();
assert(IBI < JBI);
JB = LoopRPO->blocks[JBI];
}
abort();
}
}
Option<InsertionPoint> operator&(InsertionPoint other) const {
InsertionPoint res;
if (!earliest) res.earliest = other.earliest;
else if (!other.earliest) res.earliest = earliest;
else if (earliest == other.earliest) res.earliest = earliest;
else if (isBefore(earliest, other.earliest)) res.earliest = other.earliest;
else if (isBefore(other.earliest, earliest)) res.earliest = earliest;
else return {};
return res;
}
/* WARNING: Dangerous semantics, should we really do this?
* Meets *this with other. If the result is bottom, returns false
* and sets *this to top (sic!)
*/
bool operator &=(InsertionPoint other) {
if (auto res = *this & other) {
*this = *res;
return true;
} else {
clear();
return false;
}
}
InsertionPoint operator|(InsertionPoint other) const {
return *this <= other ? other : *this;
}
InsertionPoint &operator|=(InsertionPoint other) {
return *this = *this | other;
}
bool operator==(InsertionPoint other) const { return earliest == other.earliest; }
bool operator!=(InsertionPoint other) const { return !(*this == other); }
bool operator<=(InsertionPoint other) const {
if (!earliest && other.earliest) return false;
if (!other.earliest) return true;
if (earliest == other.earliest) return true;
return isBefore(other.earliest, earliest);
}
bool operator<(InsertionPoint other) const {
return *this != other && *this <= other;
}
};
llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const struct ConjunctionLoc &cond);
llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const struct Disjunction &cond);
struct ConjunctionLoc {
ConjunctionLoc(bool static_pred, InsertionPoint insertion_point = nullptr)
: insertion_point(static_pred ? insertion_point : nullptr)
{ addConjunct(static_pred); }
ConjunctionLoc(BinaryPredicate pred, InsertionPoint insertion_point = nullptr)
: insertion_point(pred.is_false() ? nullptr : insertion_point)
{ addConjunct(pred); }
ConjunctionLoc(InsertionPoint insertion_point)
: insertion_point(insertion_point) {}
ConjunctionLoc operator&(const ConjunctionLoc &other) const {
ConjunctionLoc res = *this;
if (!(res.insertion_point &= other.insertion_point)) return false;
res.addConjuncts(other.conjuncts);
if (res.conjuncts.size() > MAX_CONJUNCTION_TERMS) {
Debug::warn("plp:conjunct_limit")
<< "Notice: PLP: Bounding size of conjunction " << *this <<"\n"
<< "This does not affect correctness, but might slow down verification or\n"
<< "cause it to require loop bounding to terminate.\n";
res = false; // It's unlikely we can do better
}
if (res.is_false()) res.insertion_point.clear(); // normalise
return res;
}
ConjunctionLoc &operator&=(const ConjunctionLoc &other) {
return *this = (*this & other);
}
bool implies(const ConjunctionLoc &other) const {
if (!(insertion_point <= other.insertion_point)) return false;
/* Every conjunct in other must be implied by some in this */
for (const BinaryPredicate &o : other.conjuncts) {
bool implied = false;
for (const BinaryPredicate &t : conjuncts) {
if (o <= t /* t.implies(o) */) {
implied = true;
break;
}
}
if (!implied) return false;
}
return true;
}
bool operator!=(const ConjunctionLoc &other) const { return !(*this == other); }
bool operator==(const ConjunctionLoc &other) const {
return conjuncts == other.conjuncts && insertion_point == other.insertion_point;
}
bool operator<=(const ConjunctionLoc &other) const {
return implies(other);
}
bool operator<(const ConjunctionLoc &other) const {
return *this != other && *this <= other;
}
/* A ConjunctionLoc must be normalised after direct modification of its members. */
void normalise() {
auto terms = std::move(conjuncts).get_vector();
conjuncts.clear();
for (BinaryPredicate &p : terms) p.normalise();
addConjuncts({std::move(terms)});
if (is_false()) insertion_point = nullptr;
}
bool has_conjuncts() const { return !conjuncts.empty(); }
bool is_true() const { return !has_conjuncts() && !insertion_point; }
bool is_false() const { return conjuncts.size() == 1 && conjuncts[0].is_false(); }
auto begin() const { return conjuncts.begin(); }
auto end() const { return conjuncts.end(); }
ConjunctionLoc map(std::function<BinaryPredicate(const BinaryPredicate &)> f) const {
auto vec = conjuncts.get_vector();
for (BinaryPredicate &term : vec)
term = f(term);
ConjunctionLoc res(true, insertion_point);
for (BinaryPredicate &term : vec)
res.addConjunct(std::move(term));
return res;
}
/* Earliest location that can support an insertion. */
InsertionPoint insertion_point;
private:
struct LexicalCompare {
auto tupleit(const BinaryPredicate &p) const {
return std::make_tuple(p.lhs, p.op, p.rhs);
}
bool operator()(const BinaryPredicate &a, const BinaryPredicate &b) const {
return tupleit(a) < tupleit(b);
}
};
// &=, if you will
void addConjunct(BinaryPredicate cond) {
if (cond.is_true()) return; /* Keep it normalised */
std::vector<BinaryPredicate> newset;
for (const BinaryPredicate &c : conjuncts) {
bool underapprox = false;
BinaryPredicate m = c.meet(cond, underapprox);
if (m == c) return;
if (m == cond) continue;
if (underapprox) {
newset.push_back(c); /* Have to keep both */
} else {
// Start the loop over!
#ifndef NDEBUG
/* We're going to meet c with m again, so ensure that meet
* recognizes that c implies m */
bool ua2 = false;
BinaryPredicate m2 = c.meet(m, ua2);
assert(m2 == m && !ua2);
#endif
return addConjunct(m);
}
}
conjuncts = std::move(newset);
conjuncts.insert(cond);
}
void addConjuncts(const VecSet<BinaryPredicate, LexicalCompare> &conds) {
for(const BinaryPredicate &cond : conds)
addConjunct(cond); /* Can be more efficient */
}
VecSet<BinaryPredicate, LexicalCompare> conjuncts;
friend struct Disjunction;
};
struct Disjunction {
Disjunction(InsertionPoint ip) { disjuncts.insert_gt(ip); }
Disjunction(bool b = false){ if (b) disjuncts.insert_gt(b); }
Disjunction(BinaryPredicate cond) {
if (!cond.is_false()) disjuncts.insert_gt(cond);
}
Disjunction(ConjunctionLoc cond) {
if (!cond.is_false()) disjuncts.insert_gt(cond);
}
bool is_true() const { return disjuncts.size() == 1 && disjuncts[0].is_true(); }
bool is_false() const { return disjuncts.empty(); }
auto begin() const { return disjuncts.begin(); }
auto end() const { return disjuncts.end(); }
bool operator!=(const Disjunction &othr) const { return !(*this == othr); }
bool operator==(const Disjunction &other) const {
return disjuncts == other.disjuncts;
}
bool operator<(const Disjunction &other) const {
bool found_smaller = disjuncts.size() < other.disjuncts.size();
for (const Elem &c : disjuncts) {
bool found_leq = false;
for (const Elem &r : other.disjuncts) {
if (r < c) return false;
if (c < r) {
found_smaller = found_leq = true;
break;
}
if (c == r) {
found_leq = true;
break;
}
}
if (!found_leq) return false;
}
return found_smaller;
}
bool operator<=(const Disjunction &other) const {
return *this == other || *this < other;
}
Disjunction operator|(const Disjunction &other) const {
Disjunction res = *this;
res.addConds(other.disjuncts);
res.bound();
return res;
}
Disjunction &operator|=(const Disjunction &other) {
return *this = (*this | other);
}
Disjunction operator&(const Disjunction &other) const {
/* Step one: pick out common terms */
auto lhs = disjuncts;
auto rhs = other.disjuncts;
Disjunction res(false);
assert(!res.is_true() && res.is_false());
for (unsigned l = 0; l < unsigned(lhs.size());) {
if (rhs.erase(lhs[l])) {
res.addCond(lhs[l]);
lhs.erase_at(l);
} else {
++l;
}
}
/* Step two: distribute over the remaining terms */
for (const Elem &r : rhs) {
for (const Elem &l : lhs) {
res.addCond(r & l);
}
}
res.bound();
return res;
}
Disjunction &operator&=(const Disjunction &other) {
return *this = (*this & other);
}
Disjunction map(std::function<BinaryPredicate(const BinaryPredicate &)> f) const {
auto vec = disjuncts.get_vector();
for (Elem &term : vec)
term = term.map(f);
Disjunction res(false);
for (Elem &term : vec)
res.addCond(std::move(term));
return res;
}
private:
using Elem = ConjunctionLoc;
void bound() {
if (disjuncts.size() > MAX_DISJUNCTION_TERMS) {
Debug::warn("plp:disjunct_bound")
<< "Notice: PLP: Bounding size of disjunction " << *this << "\n"
<< "This does not affect correctness, but might slow down verification or\n"
<< "cause it to require loop bounding to terminate.\n";
// Delete the terms with the largest number of conjuncts (least
// likely to be useful)
auto vec = std::move(disjuncts).get_vector();
std::sort(vec.begin(), vec.end(), [](const Elem &a, const Elem &b) {
return a.conjuncts.size() < b.conjuncts.size();
});
vec.resize(MAX_DISJUNCTION_TERMS, vec[0]);
std::sort(vec.begin(), vec.end(), LexicalCompare());
disjuncts = vec;
}
}
struct LexicalCompare {
auto tupleit(const Elem &p) const {
return std::make_tuple(p.insertion_point, p.conjuncts);
}
bool operator()(const Elem &a, const Elem &b) const {
return tupleit(a) < tupleit(b);
}
};
void addCond(const Elem &cond) {
if (cond.is_false()) return; /* Keep it normalised */
std::vector<Elem> newset;
for (const Elem &c : disjuncts) {
if (cond < c) return;
if (!(c < cond)) newset.push_back(c);
}
disjuncts = std::move(newset);
disjuncts.insert(cond);
}
void addConds(const VecSet<Elem, LexicalCompare> &conds) {
for(const Elem &cond : conds)
addCond(cond); /* Can be more efficient */
}
static bool erase_greater(VecSet<Elem, LexicalCompare> &set,
const Elem &c) {
bool erased = false;
for (unsigned i = 0; i < unsigned(set.size());) {
if (c < set[i]) {
set.erase_at(i);
erased = true;
} else {
++i;
}
}
return erased;
}
VecSet<Elem, LexicalCompare> disjuncts;
};
using PurityCondition = Disjunction;
typedef std::unordered_map<const llvm::BasicBlock*,PurityCondition> PurityConditions;
const char *getPredicateName(llvm::CmpInst::Predicate pred) {
using llvm::ICmpInst; using llvm::FCmpInst;
switch (pred) {
default: return "unknown";
case FCmpInst::FCMP_FALSE: return "false";
case FCmpInst::FCMP_OEQ: return "oeq";
case FCmpInst::FCMP_OGT: return "ogt";
case FCmpInst::FCMP_OGE: return "oge";
case FCmpInst::FCMP_OLT: return "olt";
case FCmpInst::FCMP_OLE: return "ole";
case FCmpInst::FCMP_ONE: return "one";
case FCmpInst::FCMP_ORD: return "ord";
case FCmpInst::FCMP_UNO: return "uno";
case FCmpInst::FCMP_UEQ: return "ueq";
case FCmpInst::FCMP_UGT: return "ugt";
case FCmpInst::FCMP_UGE: return "uge";
case FCmpInst::FCMP_ULT: return "ult";
case FCmpInst::FCMP_ULE: return "ule";
case FCmpInst::FCMP_UNE: return "une";
case FCmpInst::FCMP_TRUE: return "true";
case ICmpInst::ICMP_EQ: return "eq";
case ICmpInst::ICMP_NE: return "ne";
case ICmpInst::ICMP_SGT: return "sgt";
case ICmpInst::ICMP_SGE: return "sge";
case ICmpInst::ICMP_SLT: return "slt";
case ICmpInst::ICMP_SLE: return "sle";
case ICmpInst::ICMP_UGT: return "ugt";
case ICmpInst::ICMP_UGE: return "uge";
case ICmpInst::ICMP_ULT: return "ult";
case ICmpInst::ICMP_ULE: return "ule";
}
}
llvm::Instruction::OtherOps getPredicateOpcode(llvm::CmpInst::Predicate pred) {
using llvm::ICmpInst; using llvm::FCmpInst;
switch (pred) {
case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE:
case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE:
case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE:
case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_UGE:
case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
return llvm::Instruction::OtherOps::ICmp;
case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_TRUE:
assert(false && "Predicates false & true should not generate cmp insts");
case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT:
case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ONE:
case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT:
case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULT:
case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
return llvm::Instruction::OtherOps::FCmp;
case ICmpInst::BAD_ICMP_PREDICATE:
case FCmpInst::BAD_FCMP_PREDICATE:
(void)0; // fallthrough
}
llvm::dbgs() << "Predicate " << pred << " unknown!\n";
assert(false && "unknown predicate"); abort();
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const BinaryPredicate &pred) {
if (pred.is_true()) {
os << "true";
} else if (pred.is_false()) {
os << "false";
} else {
pred.lhs->printAsOperand(os);
os << " " << getPredicateName(pred.op) << " ";
pred.rhs->printAsOperand(os);
}
return os;
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &os, InsertionPoint ip) {
if (ip.earliest) {
os << " before " << *ip.earliest;
}
return os;
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const ConjunctionLoc &cond) {
if (!cond.has_conjuncts()) {
os << "true";
} else {
for (auto it = cond.begin(); it != cond.end(); ++it) {
if (it != cond.begin()) os << " && ";
os << *it;
}
}
return os << cond.insertion_point;
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const PurityCondition &cond) {
if (cond.is_false()) {
os << "false";
} else {
for (auto it = cond.begin(); it != cond.end(); ++it) {
if (it != cond.begin()) os << " || ";
os << *it;
}
}
return os;
}
llvm::Instruction *maybeFindUserLocationOrNull(llvm::User *U) {
return llvm::dyn_cast_or_null<llvm::Instruction>(U);
}
llvm::Instruction *maybeFindValueLocation(llvm::Value *V) {
return llvm::dyn_cast<llvm::Instruction>(V);
}
BinaryPredicate collapseTautologies(const BinaryPredicate &cond) {
if (cond.is_true() || cond.is_false()) return cond;
if (cond.rhs == cond.lhs) {
if (llvm::CmpInst::isFalseWhenEqual(cond.op)) return false;
if (llvm::CmpInst::isTrueWhenEqual(cond.op)) return true;
}
if (llvm::ConstantInt *LHS = llvm::dyn_cast_or_null<llvm::ConstantInt>(cond.lhs)) {
if (llvm::ConstantInt *RHS = llvm::dyn_cast_or_null<llvm::ConstantInt>(cond.rhs)) {
return check_predicate_satisfaction(LHS->getValue(), cond.op, RHS->getValue());
}
}
return cond;
}
llvm::Value *maybeGetExtractValueAggregate
(llvm::Value *I, unsigned OnlyIfIndex) {
auto *EV = llvm::dyn_cast<llvm::ExtractValueInst>(I);
if (!EV || EV->getNumIndices() != 1 || EV->getIndices()[0] != OnlyIfIndex)
return nullptr;
return EV->getAggregateOperand();
}
/* Does not check that def-use order is respected, only for global
* side effects */
bool mayReorder(const llvm::Instruction *I, const llvm::Instruction *J) {
/* Crude but hopefully safe */
if (J->mayReadOrWriteMemory()) return false;
return true;
}
bool deepPointerComparison(const llvm::Value *P1, const llvm::Value *P2) {
if (P1 == P2) return true;
/* Hail-mary */
if (auto *I1 = llvm::dyn_cast<llvm::Instruction>(P1)) {
if (I1->mayReadOrWriteMemory()) return false; /* Two identical loads, f.ex. */
auto *I2 = llvm::dyn_cast<llvm::Instruction>(P2);
return I2 && I1->isIdenticalTo(I2);
}
return false;
}
bool isPermissibleLeak(const llvm::Loop *L, const llvm::PHINode *Phi,
llvm::Instruction *LoopCarried) {
auto *CmpXchg = llvm::dyn_cast_or_null<llvm::AtomicCmpXchgInst>
(maybeGetExtractValueAggregate(LoopCarried, 0));
if (!CmpXchg) {
/* Sometimes, clang generates this odd pattern where the expected
* value is only assigned when the cmpxchg fails */
if (auto *CPhi = llvm::dyn_cast<llvm::PHINode>(LoopCarried)) {
if (CPhi->getNumIncomingValues() != 2) return false;
for (unsigned predi = 0; predi < 2; ++predi) {
CmpXchg = llvm::dyn_cast_or_null<llvm::AtomicCmpXchgInst>
(maybeGetExtractValueAggregate(CPhi->getIncomingValue(predi), 0));
if (!CmpXchg) continue;
llvm::BasicBlock *Pred = CPhi->getIncomingBlock(predi);
llvm::BasicBlock *PPred = Pred->getSinglePredecessor();
if (!PPred) return false;
auto *Term = llvm::dyn_cast<llvm::BranchInst>(PPred->getTerminator());
if (!Term || !Term->isConditional()) return false;
if (maybeGetExtractValueAggregate(Term->getCondition(), 1) != CmpXchg)
return false;
}
}
/* Do we need else if (auto *Select = ...) ? */
}
if (!CmpXchg) return false;
llvm::Value *Ptr = CmpXchg->getPointerOperand();
/* Note, we do not check the location of the cmpxchg because no more
* than one value can permissibly be carried along a backedge, and
* so we are always allowed to do the "code motion" */
for (llvm::BasicBlock *Entering : llvm::predecessors(L->getHeader())) {
if (L->contains(Entering)) continue; // Not an entering block
llvm::Value *V = Phi->getIncomingValueForBlock(Entering);
llvm::LoadInst *Ld = llvm::dyn_cast<llvm::LoadInst>(V);
if (!Ld) return false;
if (!deepPointerComparison(Ld->getPointerOperand(), Ptr)) return false;
if (Ld->getParent() != Entering) return false;
for (llvm::Instruction *I = Ld; I != Entering->getTerminator();){
I = I->getNextNode();
if (!mayReorder(Ld, I)) return false;
}
}
return true;
}
void RPOVisit(llvm::Loop* L, RPO &rpo,
std::unordered_set<llvm::BasicBlock *> &visited,
decltype(RPO::block_indices)::sequence_type &poorder,
llvm::BasicBlock *BB) {
if (!visited.insert(BB).second) return;
for (llvm::BasicBlock *Succ : llvm::successors(BB)) {
if (!L->contains(Succ)) continue;
RPOVisit(L, rpo, visited, poorder, Succ);
}
rpo.blocks.push_back(BB);
poorder.emplace_back(BB, L->getNumBlocks() - rpo.blocks.size());
}
RPO getLoopRPO(llvm::Loop *L) {
RPO ret(L->getNumBlocks());
std::unordered_set<llvm::BasicBlock *> visited(L->getNumBlocks());
decltype(RPO::block_indices)::sequence_type poorder;
poorder.reserve(L->getNumBlocks());
RPOVisit(L, ret, visited, poorder, L->getHeader());
std::reverse(ret.blocks.begin(), ret.blocks.end());
std::sort(poorder.begin(), poorder.end());
ret.block_indices.adopt_sequence
(boost::container::ordered_unique_range, std::move(poorder));
assert(ret.blocks.size() == L->getNumBlocks());
#ifndef NDEBUG
for (std::size_t i = 0; i < ret.blocks.size(); ++i) {
assert(ret.block_indices.at(ret.blocks[i]) == i);
}
#endif
return ret;
}
PurityCondition getIn(const llvm::Loop *L, PurityConditions &conds,
const RPO &rpo,
const llvm::BasicBlock *From,
const llvm::BasicBlock *To) {
if (To == L->getHeader()) {
/* Check for data leaks along the back edge */
if (cl_plp_dbgp >= 4)
llvm::dbgs() << "Checking " << From->getName() << "->" << To->getName()
<< " for escaping phis: \n";
for (const llvm::Instruction *I = &*To->begin(),
*End = To->getFirstNonPHI(); I != End; I = I->getNextNode()) {
const llvm::PHINode *Phi = llvm::cast<llvm::PHINode>(I);
/* XXX: DANGER ZONE */
if (Phi->getName().startswith("plp_inner_mon")) continue;
llvm::Value *FromOutside = nullptr;
for (llvm::BasicBlock *Entering : llvm::predecessors(L->getHeader())) {
if (L->contains(Entering)) continue;
if (!FromOutside) {
FromOutside = Phi->getIncomingValueForBlock(Entering);
assert(FromOutside);
} else if (Phi->getIncomingValueForBlock(Entering) != FromOutside) {
FromOutside = nullptr;
break;
}
}
llvm::Value *V = Phi->getIncomingValueForBlock(From);
assert(V);
if (V == FromOutside || V == Phi) continue;
if (cl_plp_dbgp >= 4) { llvm::dbgs() << " "; Phi->printAsOperand(llvm::dbgs()); }
if (cl_plp_dbgp >= 4) { llvm::dbgs() << ": "; V->printAsOperand(llvm::dbgs()); llvm::dbgs() << "\n"; }
llvm::Instruction *VI = maybeFindValueLocation(V);
if (!VI) return false;
if (!L->contains(VI) || !isPermissibleLeak(L, Phi, VI)) return false;
}
return true;
}
if (!L->contains(To)) return false;
if (rpo.is_backedge(From, To)) {
if (cl_plp_dbgp >= 3)
llvm::dbgs() << " backedge: " << From->getName() << " -> " << To->getName() << "\n";
return false;
}
if (cl_plp_dbgp >= 4) llvm::dbgs() << " in from " << To->getName() << ": " << conds[To] << "\n";
PurityCondition in = conds[To].map([](BinaryPredicate term) {
term.normalise();
return collapseTautologies(term);
});
if (cl_plp_dbgp >= 3) llvm::dbgs() << " normalised: " << in << "\n";
return in;
}
BinaryPredicate getBranchCondition(llvm::Value *cond) {
assert(cond && llvm::isa<llvm::IntegerType>(cond->getType())
&& llvm::cast<llvm::IntegerType>(cond->getType())->getBitWidth() == 1);
if (auto *cmp = llvm::dyn_cast<llvm::CmpInst>(cond)) {
return BinaryPredicate(cmp->getPredicate(), cmp->getOperand(0),
cmp->getOperand(1));
} else if (auto *bop = llvm::dyn_cast<llvm::BinaryOperator>(cond)) {
if (bop->getOpcode() == llvm::Instruction::Xor) {
llvm::Value *lhs = bop->getOperand(0), *rhs = bop->getOperand(1);
if (llvm::isa<llvm::ConstantInt>(lhs) || llvm::isa<llvm::ConstantInt>(rhs)) {