forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSCCPSolver.cpp
More file actions
2115 lines (1787 loc) · 75.3 KB
/
SCCPSolver.cpp
File metadata and controls
2115 lines (1787 loc) · 75.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
//===- SCCPSolver.cpp - SCCP Utility --------------------------- *- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// \file
// This file implements the Sparse Conditional Constant Propagation (SCCP)
// utility.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/SCCPSolver.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/ValueLattice.h"
#include "llvm/Analysis/ValueLatticeUtils.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Local.h"
#include <cassert>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "sccp"
// The maximum number of range extensions allowed for operations requiring
// widening.
static const unsigned MaxNumRangeExtensions = 10;
/// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts() {
return ValueLatticeElement::MergeOptions().setMaxWidenSteps(
MaxNumRangeExtensions);
}
static ConstantRange getConstantRange(const ValueLatticeElement &LV, Type *Ty,
bool UndefAllowed = true) {
assert(Ty->isIntOrIntVectorTy() && "Should be int or int vector");
if (LV.isConstantRange(UndefAllowed))
return LV.getConstantRange();
return ConstantRange::getFull(Ty->getScalarSizeInBits());
}
namespace llvm {
bool SCCPSolver::isConstant(const ValueLatticeElement &LV) {
return LV.isConstant() ||
(LV.isConstantRange() && LV.getConstantRange().isSingleElement());
}
bool SCCPSolver::isOverdefined(const ValueLatticeElement &LV) {
return !LV.isUnknownOrUndef() && !SCCPSolver::isConstant(LV);
}
static bool canRemoveInstruction(Instruction *I) {
if (wouldInstructionBeTriviallyDead(I))
return true;
// Some instructions can be handled but are rejected above. Catch
// those cases by falling through to here.
// TODO: Mark globals as being constant earlier, so
// TODO: wouldInstructionBeTriviallyDead() knows that atomic loads
// TODO: are safe to remove.
return isa<LoadInst>(I);
}
bool SCCPSolver::tryToReplaceWithConstant(Value *V) {
Constant *Const = getConstantOrNull(V);
if (!Const)
return false;
// Replacing `musttail` instructions with constant breaks `musttail` invariant
// unless the call itself can be removed.
// Calls with "clang.arc.attachedcall" implicitly use the return value and
// those uses cannot be updated with a constant.
CallBase *CB = dyn_cast<CallBase>(V);
if (CB && ((CB->isMustTailCall() &&
!canRemoveInstruction(CB)) ||
CB->getOperandBundle(LLVMContext::OB_clang_arc_attachedcall))) {
Function *F = CB->getCalledFunction();
// Don't zap returns of the callee
if (F)
addToMustPreserveReturnsInFunctions(F);
LLVM_DEBUG(dbgs() << " Can\'t treat the result of call " << *CB
<< " as a constant\n");
return false;
}
LLVM_DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
// Replaces all of the uses of a variable with uses of the constant.
V->replaceAllUsesWith(Const);
return true;
}
/// Try to use \p Inst's value range from \p Solver to infer the NUW flag.
static bool refineInstruction(SCCPSolver &Solver,
const SmallPtrSetImpl<Value *> &InsertedValues,
Instruction &Inst) {
bool Changed = false;
auto GetRange = [&Solver, &InsertedValues](Value *Op) {
if (auto *Const = dyn_cast<ConstantInt>(Op))
return ConstantRange(Const->getValue());
if (isa<Constant>(Op) || InsertedValues.contains(Op)) {
unsigned Bitwidth = Op->getType()->getScalarSizeInBits();
return ConstantRange::getFull(Bitwidth);
}
return getConstantRange(Solver.getLatticeValueFor(Op), Op->getType(),
/*UndefAllowed=*/false);
};
if (isa<OverflowingBinaryOperator>(Inst)) {
auto RangeA = GetRange(Inst.getOperand(0));
auto RangeB = GetRange(Inst.getOperand(1));
if (!Inst.hasNoUnsignedWrap()) {
auto NUWRange = ConstantRange::makeGuaranteedNoWrapRegion(
Instruction::BinaryOps(Inst.getOpcode()), RangeB,
OverflowingBinaryOperator::NoUnsignedWrap);
if (NUWRange.contains(RangeA)) {
Inst.setHasNoUnsignedWrap();
Changed = true;
}
}
if (!Inst.hasNoSignedWrap()) {
auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(
Instruction::BinaryOps(Inst.getOpcode()), RangeB,
OverflowingBinaryOperator::NoSignedWrap);
if (NSWRange.contains(RangeA)) {
Inst.setHasNoSignedWrap();
Changed = true;
}
}
} else if (isa<ZExtInst>(Inst) && !Inst.hasNonNeg()) {
auto Range = GetRange(Inst.getOperand(0));
if (Range.isAllNonNegative()) {
Inst.setNonNeg();
Changed = true;
}
}
return Changed;
}
/// Try to replace signed instructions with their unsigned equivalent.
static bool replaceSignedInst(SCCPSolver &Solver,
SmallPtrSetImpl<Value *> &InsertedValues,
Instruction &Inst) {
// Determine if a signed value is known to be >= 0.
auto isNonNegative = [&Solver](Value *V) {
// If this value was constant-folded, it may not have a solver entry.
// Handle integers. Otherwise, return false.
if (auto *C = dyn_cast<Constant>(V)) {
auto *CInt = dyn_cast<ConstantInt>(C);
return CInt && !CInt->isNegative();
}
const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
return IV.isConstantRange(/*UndefAllowed=*/false) &&
IV.getConstantRange().isAllNonNegative();
};
Instruction *NewInst = nullptr;
switch (Inst.getOpcode()) {
// Note: We do not fold sitofp -> uitofp here because that could be more
// expensive in codegen and may not be reversible in the backend.
case Instruction::SExt: {
// If the source value is not negative, this is a zext.
Value *Op0 = Inst.getOperand(0);
if (InsertedValues.count(Op0) || !isNonNegative(Op0))
return false;
NewInst = new ZExtInst(Op0, Inst.getType(), "", &Inst);
NewInst->setNonNeg();
break;
}
case Instruction::AShr: {
// If the shifted value is not negative, this is a logical shift right.
Value *Op0 = Inst.getOperand(0);
if (InsertedValues.count(Op0) || !isNonNegative(Op0))
return false;
NewInst = BinaryOperator::CreateLShr(Op0, Inst.getOperand(1), "", &Inst);
NewInst->setIsExact(Inst.isExact());
break;
}
case Instruction::SDiv:
case Instruction::SRem: {
// If both operands are not negative, this is the same as udiv/urem.
Value *Op0 = Inst.getOperand(0), *Op1 = Inst.getOperand(1);
if (InsertedValues.count(Op0) || InsertedValues.count(Op1) ||
!isNonNegative(Op0) || !isNonNegative(Op1))
return false;
auto NewOpcode = Inst.getOpcode() == Instruction::SDiv ? Instruction::UDiv
: Instruction::URem;
NewInst = BinaryOperator::Create(NewOpcode, Op0, Op1, "", &Inst);
if (Inst.getOpcode() == Instruction::SDiv)
NewInst->setIsExact(Inst.isExact());
break;
}
default:
return false;
}
// Wire up the new instruction and update state.
assert(NewInst && "Expected replacement instruction");
NewInst->takeName(&Inst);
InsertedValues.insert(NewInst);
Inst.replaceAllUsesWith(NewInst);
Solver.removeLatticeValueFor(&Inst);
Inst.eraseFromParent();
return true;
}
bool SCCPSolver::simplifyInstsInBlock(BasicBlock &BB,
SmallPtrSetImpl<Value *> &InsertedValues,
Statistic &InstRemovedStat,
Statistic &InstReplacedStat) {
bool MadeChanges = false;
for (Instruction &Inst : make_early_inc_range(BB)) {
if (Inst.getType()->isVoidTy())
continue;
if (tryToReplaceWithConstant(&Inst)) {
if (canRemoveInstruction(&Inst))
Inst.eraseFromParent();
MadeChanges = true;
++InstRemovedStat;
} else if (replaceSignedInst(*this, InsertedValues, Inst)) {
MadeChanges = true;
++InstReplacedStat;
} else if (refineInstruction(*this, InsertedValues, Inst)) {
MadeChanges = true;
}
}
return MadeChanges;
}
bool SCCPSolver::removeNonFeasibleEdges(BasicBlock *BB, DomTreeUpdater &DTU,
BasicBlock *&NewUnreachableBB) const {
SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors;
bool HasNonFeasibleEdges = false;
for (BasicBlock *Succ : successors(BB)) {
if (isEdgeFeasible(BB, Succ))
FeasibleSuccessors.insert(Succ);
else
HasNonFeasibleEdges = true;
}
// All edges feasible, nothing to do.
if (!HasNonFeasibleEdges)
return false;
// SCCP can only determine non-feasible edges for br, switch and indirectbr.
Instruction *TI = BB->getTerminator();
assert((isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
isa<IndirectBrInst>(TI)) &&
"Terminator must be a br, switch or indirectbr");
if (FeasibleSuccessors.size() == 0) {
// Branch on undef/poison, replace with unreachable.
SmallPtrSet<BasicBlock *, 8> SeenSuccs;
SmallVector<DominatorTree::UpdateType, 8> Updates;
for (BasicBlock *Succ : successors(BB)) {
Succ->removePredecessor(BB);
if (SeenSuccs.insert(Succ).second)
Updates.push_back({DominatorTree::Delete, BB, Succ});
}
TI->eraseFromParent();
new UnreachableInst(BB->getContext(), BB);
DTU.applyUpdatesPermissive(Updates);
} else if (FeasibleSuccessors.size() == 1) {
// Replace with an unconditional branch to the only feasible successor.
BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin();
SmallVector<DominatorTree::UpdateType, 8> Updates;
bool HaveSeenOnlyFeasibleSuccessor = false;
for (BasicBlock *Succ : successors(BB)) {
if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) {
// Don't remove the edge to the only feasible successor the first time
// we see it. We still do need to remove any multi-edges to it though.
HaveSeenOnlyFeasibleSuccessor = true;
continue;
}
Succ->removePredecessor(BB);
Updates.push_back({DominatorTree::Delete, BB, Succ});
}
BranchInst::Create(OnlyFeasibleSuccessor, BB);
TI->eraseFromParent();
DTU.applyUpdatesPermissive(Updates);
} else if (FeasibleSuccessors.size() > 1) {
SwitchInstProfUpdateWrapper SI(*cast<SwitchInst>(TI));
SmallVector<DominatorTree::UpdateType, 8> Updates;
// If the default destination is unfeasible it will never be taken. Replace
// it with a new block with a single Unreachable instruction.
BasicBlock *DefaultDest = SI->getDefaultDest();
if (!FeasibleSuccessors.contains(DefaultDest)) {
if (!NewUnreachableBB) {
NewUnreachableBB =
BasicBlock::Create(DefaultDest->getContext(), "default.unreachable",
DefaultDest->getParent(), DefaultDest);
new UnreachableInst(DefaultDest->getContext(), NewUnreachableBB);
}
DefaultDest->removePredecessor(BB);
SI->setDefaultDest(NewUnreachableBB);
Updates.push_back({DominatorTree::Delete, BB, DefaultDest});
Updates.push_back({DominatorTree::Insert, BB, NewUnreachableBB});
}
for (auto CI = SI->case_begin(); CI != SI->case_end();) {
if (FeasibleSuccessors.contains(CI->getCaseSuccessor())) {
++CI;
continue;
}
BasicBlock *Succ = CI->getCaseSuccessor();
Succ->removePredecessor(BB);
Updates.push_back({DominatorTree::Delete, BB, Succ});
SI.removeCase(CI);
// Don't increment CI, as we removed a case.
}
DTU.applyUpdatesPermissive(Updates);
} else {
llvm_unreachable("Must have at least one feasible successor");
}
return true;
}
/// Helper class for SCCPSolver. This implements the instruction visitor and
/// holds all the state.
class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> {
const DataLayout &DL;
std::function<const TargetLibraryInfo &(Function &)> GetTLI;
SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
DenseMap<Value *, ValueLatticeElement>
ValueState; // The state each value is in.
/// StructValueState - This maintains ValueState for values that have
/// StructType, for example for formal arguments, calls, insertelement, etc.
DenseMap<std::pair<Value *, unsigned>, ValueLatticeElement> StructValueState;
/// GlobalValue - If we are tracking any values for the contents of a global
/// variable, we keep a mapping from the constant accessor to the element of
/// the global, to the currently known value. If the value becomes
/// overdefined, it's entry is simply removed from this map.
DenseMap<GlobalVariable *, ValueLatticeElement> TrackedGlobals;
/// TrackedRetVals - If we are tracking arguments into and the return
/// value out of a function, it will have an entry in this map, indicating
/// what the known return value for the function is.
MapVector<Function *, ValueLatticeElement> TrackedRetVals;
/// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
/// that return multiple values.
MapVector<std::pair<Function *, unsigned>, ValueLatticeElement>
TrackedMultipleRetVals;
/// The set of values whose lattice has been invalidated.
/// Populated by resetLatticeValueFor(), cleared after resolving undefs.
DenseSet<Value *> Invalidated;
/// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
/// represented here for efficient lookup.
SmallPtrSet<Function *, 16> MRVFunctionsTracked;
/// A list of functions whose return cannot be modified.
SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions;
/// TrackingIncomingArguments - This is the set of functions for whose
/// arguments we make optimistic assumptions about and try to prove as
/// constants.
SmallPtrSet<Function *, 16> TrackingIncomingArguments;
/// The reason for two worklists is that overdefined is the lowest state
/// on the lattice, and moving things to overdefined as fast as possible
/// makes SCCP converge much faster.
///
/// By having a separate worklist, we accomplish this because everything
/// possibly overdefined will become overdefined at the soonest possible
/// point.
SmallVector<Value *, 64> OverdefinedInstWorkList;
SmallVector<Value *, 64> InstWorkList;
// The BasicBlock work list
SmallVector<BasicBlock *, 64> BBWorkList;
/// KnownFeasibleEdges - Entries in this set are edges which have already had
/// PHI nodes retriggered.
using Edge = std::pair<BasicBlock *, BasicBlock *>;
DenseSet<Edge> KnownFeasibleEdges;
DenseMap<Function *, std::unique_ptr<PredicateInfo>> FnPredicateInfo;
DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers;
LLVMContext &Ctx;
private:
ConstantInt *getConstantInt(const ValueLatticeElement &IV, Type *Ty) const {
return dyn_cast_or_null<ConstantInt>(getConstant(IV, Ty));
}
// pushToWorkList - Helper for markConstant/markOverdefined
void pushToWorkList(ValueLatticeElement &IV, Value *V);
// Helper to push \p V to the worklist, after updating it to \p IV. Also
// prints a debug message with the updated value.
void pushToWorkListMsg(ValueLatticeElement &IV, Value *V);
// markConstant - Make a value be marked as "constant". If the value
// is not already a constant, add it to the instruction work list so that
// the users of the instruction are updated later.
bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C,
bool MayIncludeUndef = false);
bool markConstant(Value *V, Constant *C) {
assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
return markConstant(ValueState[V], V, C);
}
// markOverdefined - Make a value be marked as "overdefined". If the
// value is not already overdefined, add it to the overdefined instruction
// work list so that the users of the instruction are updated later.
bool markOverdefined(ValueLatticeElement &IV, Value *V);
/// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV
/// changes.
bool mergeInValue(ValueLatticeElement &IV, Value *V,
ValueLatticeElement MergeWithV,
ValueLatticeElement::MergeOptions Opts = {
/*MayIncludeUndef=*/false, /*CheckWiden=*/false});
bool mergeInValue(Value *V, ValueLatticeElement MergeWithV,
ValueLatticeElement::MergeOptions Opts = {
/*MayIncludeUndef=*/false, /*CheckWiden=*/false}) {
assert(!V->getType()->isStructTy() &&
"non-structs should use markConstant");
return mergeInValue(ValueState[V], V, MergeWithV, Opts);
}
/// getValueState - Return the ValueLatticeElement object that corresponds to
/// the value. This function handles the case when the value hasn't been seen
/// yet by properly seeding constants etc.
ValueLatticeElement &getValueState(Value *V) {
assert(!V->getType()->isStructTy() && "Should use getStructValueState");
auto I = ValueState.insert(std::make_pair(V, ValueLatticeElement()));
ValueLatticeElement &LV = I.first->second;
if (!I.second)
return LV; // Common case, already in the map.
if (auto *C = dyn_cast<Constant>(V))
LV.markConstant(C); // Constants are constant
// All others are unknown by default.
return LV;
}
/// getStructValueState - Return the ValueLatticeElement object that
/// corresponds to the value/field pair. This function handles the case when
/// the value hasn't been seen yet by properly seeding constants etc.
ValueLatticeElement &getStructValueState(Value *V, unsigned i) {
assert(V->getType()->isStructTy() && "Should use getValueState");
assert(i < cast<StructType>(V->getType())->getNumElements() &&
"Invalid element #");
auto I = StructValueState.insert(
std::make_pair(std::make_pair(V, i), ValueLatticeElement()));
ValueLatticeElement &LV = I.first->second;
if (!I.second)
return LV; // Common case, already in the map.
if (auto *C = dyn_cast<Constant>(V)) {
Constant *Elt = C->getAggregateElement(i);
if (!Elt)
LV.markOverdefined(); // Unknown sort of constant.
else
LV.markConstant(Elt); // Constants are constant.
}
// All others are underdefined by default.
return LV;
}
/// Traverse the use-def chain of \p Call, marking itself and its users as
/// "unknown" on the way.
void invalidate(CallBase *Call) {
SmallVector<Instruction *, 64> ToInvalidate;
ToInvalidate.push_back(Call);
while (!ToInvalidate.empty()) {
Instruction *Inst = ToInvalidate.pop_back_val();
if (!Invalidated.insert(Inst).second)
continue;
if (!BBExecutable.count(Inst->getParent()))
continue;
Value *V = nullptr;
// For return instructions we need to invalidate the tracked returns map.
// Anything else has its lattice in the value map.
if (auto *RetInst = dyn_cast<ReturnInst>(Inst)) {
Function *F = RetInst->getParent()->getParent();
if (auto It = TrackedRetVals.find(F); It != TrackedRetVals.end()) {
It->second = ValueLatticeElement();
V = F;
} else if (MRVFunctionsTracked.count(F)) {
auto *STy = cast<StructType>(F->getReturnType());
for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
TrackedMultipleRetVals[{F, I}] = ValueLatticeElement();
V = F;
}
} else if (auto *STy = dyn_cast<StructType>(Inst->getType())) {
for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
if (auto It = StructValueState.find({Inst, I});
It != StructValueState.end()) {
It->second = ValueLatticeElement();
V = Inst;
}
}
} else if (auto It = ValueState.find(Inst); It != ValueState.end()) {
It->second = ValueLatticeElement();
V = Inst;
}
if (V) {
LLVM_DEBUG(dbgs() << "Invalidated lattice for " << *V << "\n");
for (User *U : V->users())
if (auto *UI = dyn_cast<Instruction>(U))
ToInvalidate.push_back(UI);
auto It = AdditionalUsers.find(V);
if (It != AdditionalUsers.end())
for (User *U : It->second)
if (auto *UI = dyn_cast<Instruction>(U))
ToInvalidate.push_back(UI);
}
}
}
/// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
/// work list if it is not already executable.
bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest);
// getFeasibleSuccessors - Return a vector of booleans to indicate which
// successors are reachable from a given terminator instruction.
void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
// OperandChangedState - This method is invoked on all of the users of an
// instruction that was just changed state somehow. Based on this
// information, we need to update the specified user of this instruction.
void operandChangedState(Instruction *I) {
if (BBExecutable.count(I->getParent())) // Inst is executable?
visit(*I);
}
// Add U as additional user of V.
void addAdditionalUser(Value *V, User *U) {
auto Iter = AdditionalUsers.insert({V, {}});
Iter.first->second.insert(U);
}
// Mark I's users as changed, including AdditionalUsers.
void markUsersAsChanged(Value *I) {
// Functions include their arguments in the use-list. Changed function
// values mean that the result of the function changed. We only need to
// update the call sites with the new function result and do not have to
// propagate the call arguments.
if (isa<Function>(I)) {
for (User *U : I->users()) {
if (auto *CB = dyn_cast<CallBase>(U))
handleCallResult(*CB);
}
} else {
for (User *U : I->users())
if (auto *UI = dyn_cast<Instruction>(U))
operandChangedState(UI);
}
auto Iter = AdditionalUsers.find(I);
if (Iter != AdditionalUsers.end()) {
// Copy additional users before notifying them of changes, because new
// users may be added, potentially invalidating the iterator.
SmallVector<Instruction *, 2> ToNotify;
for (User *U : Iter->second)
if (auto *UI = dyn_cast<Instruction>(U))
ToNotify.push_back(UI);
for (Instruction *UI : ToNotify)
operandChangedState(UI);
}
}
void handleCallOverdefined(CallBase &CB);
void handleCallResult(CallBase &CB);
void handleCallArguments(CallBase &CB);
void handleExtractOfWithOverflow(ExtractValueInst &EVI,
const WithOverflowInst *WO, unsigned Idx);
private:
friend class InstVisitor<SCCPInstVisitor>;
// visit implementations - Something changed in this instruction. Either an
// operand made a transition, or the instruction is newly executable. Change
// the value type of I to reflect these changes if appropriate.
void visitPHINode(PHINode &I);
// Terminators
void visitReturnInst(ReturnInst &I);
void visitTerminator(Instruction &TI);
void visitCastInst(CastInst &I);
void visitSelectInst(SelectInst &I);
void visitUnaryOperator(Instruction &I);
void visitFreezeInst(FreezeInst &I);
void visitBinaryOperator(Instruction &I);
void visitCmpInst(CmpInst &I);
void visitExtractValueInst(ExtractValueInst &EVI);
void visitInsertValueInst(InsertValueInst &IVI);
void visitCatchSwitchInst(CatchSwitchInst &CPI) {
markOverdefined(&CPI);
visitTerminator(CPI);
}
// Instructions that cannot be folded away.
void visitStoreInst(StoreInst &I);
void visitLoadInst(LoadInst &I);
void visitGetElementPtrInst(GetElementPtrInst &I);
void visitInvokeInst(InvokeInst &II) {
visitCallBase(II);
visitTerminator(II);
}
void visitCallBrInst(CallBrInst &CBI) {
visitCallBase(CBI);
visitTerminator(CBI);
}
void visitCallBase(CallBase &CB);
void visitResumeInst(ResumeInst &I) { /*returns void*/
}
void visitUnreachableInst(UnreachableInst &I) { /*returns void*/
}
void visitFenceInst(FenceInst &I) { /*returns void*/
}
void visitInstruction(Instruction &I);
public:
void addPredicateInfo(Function &F, DominatorTree &DT, AssumptionCache &AC) {
FnPredicateInfo.insert({&F, std::make_unique<PredicateInfo>(F, DT, AC)});
}
void visitCallInst(CallInst &I) { visitCallBase(I); }
bool markBlockExecutable(BasicBlock *BB);
const PredicateBase *getPredicateInfoFor(Instruction *I) {
auto It = FnPredicateInfo.find(I->getParent()->getParent());
if (It == FnPredicateInfo.end())
return nullptr;
return It->second->getPredicateInfoFor(I);
}
SCCPInstVisitor(const DataLayout &DL,
std::function<const TargetLibraryInfo &(Function &)> GetTLI,
LLVMContext &Ctx)
: DL(DL), GetTLI(GetTLI), Ctx(Ctx) {}
void trackValueOfGlobalVariable(GlobalVariable *GV) {
// We only track the contents of scalar globals.
if (GV->getValueType()->isSingleValueType()) {
ValueLatticeElement &IV = TrackedGlobals[GV];
IV.markConstant(GV->getInitializer());
}
}
void addTrackedFunction(Function *F) {
// Add an entry, F -> undef.
if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
MRVFunctionsTracked.insert(F);
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
TrackedMultipleRetVals.insert(
std::make_pair(std::make_pair(F, i), ValueLatticeElement()));
} else if (!F->getReturnType()->isVoidTy())
TrackedRetVals.insert(std::make_pair(F, ValueLatticeElement()));
}
void addToMustPreserveReturnsInFunctions(Function *F) {
MustPreserveReturnsInFunctions.insert(F);
}
bool mustPreserveReturn(Function *F) {
return MustPreserveReturnsInFunctions.count(F);
}
void addArgumentTrackedFunction(Function *F) {
TrackingIncomingArguments.insert(F);
}
bool isArgumentTrackedFunction(Function *F) {
return TrackingIncomingArguments.count(F);
}
void solve();
bool resolvedUndef(Instruction &I);
bool resolvedUndefsIn(Function &F);
bool isBlockExecutable(BasicBlock *BB) const {
return BBExecutable.count(BB);
}
bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const;
std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const {
std::vector<ValueLatticeElement> StructValues;
auto *STy = dyn_cast<StructType>(V->getType());
assert(STy && "getStructLatticeValueFor() can be called only on structs");
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
auto I = StructValueState.find(std::make_pair(V, i));
assert(I != StructValueState.end() && "Value not in valuemap!");
StructValues.push_back(I->second);
}
return StructValues;
}
void removeLatticeValueFor(Value *V) { ValueState.erase(V); }
/// Invalidate the Lattice Value of \p Call and its users after specializing
/// the call. Then recompute it.
void resetLatticeValueFor(CallBase *Call) {
// Calls to void returning functions do not need invalidation.
Function *F = Call->getCalledFunction();
(void)F;
assert(!F->getReturnType()->isVoidTy() &&
(TrackedRetVals.count(F) || MRVFunctionsTracked.count(F)) &&
"All non void specializations should be tracked");
invalidate(Call);
handleCallResult(*Call);
}
const ValueLatticeElement &getLatticeValueFor(Value *V) const {
assert(!V->getType()->isStructTy() &&
"Should use getStructLatticeValueFor");
DenseMap<Value *, ValueLatticeElement>::const_iterator I =
ValueState.find(V);
assert(I != ValueState.end() &&
"V not found in ValueState nor Paramstate map!");
return I->second;
}
const MapVector<Function *, ValueLatticeElement> &getTrackedRetVals() {
return TrackedRetVals;
}
const DenseMap<GlobalVariable *, ValueLatticeElement> &getTrackedGlobals() {
return TrackedGlobals;
}
const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
return MRVFunctionsTracked;
}
void markOverdefined(Value *V) {
if (auto *STy = dyn_cast<StructType>(V->getType()))
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
markOverdefined(getStructValueState(V, i), V);
else
markOverdefined(ValueState[V], V);
}
bool isStructLatticeConstant(Function *F, StructType *STy);
Constant *getConstant(const ValueLatticeElement &LV, Type *Ty) const;
Constant *getConstantOrNull(Value *V) const;
SmallPtrSetImpl<Function *> &getArgumentTrackedFunctions() {
return TrackingIncomingArguments;
}
void setLatticeValueForSpecializationArguments(Function *F,
const SmallVectorImpl<ArgInfo> &Args);
void markFunctionUnreachable(Function *F) {
for (auto &BB : *F)
BBExecutable.erase(&BB);
}
void solveWhileResolvedUndefsIn(Module &M) {
bool ResolvedUndefs = true;
while (ResolvedUndefs) {
solve();
ResolvedUndefs = false;
for (Function &F : M)
ResolvedUndefs |= resolvedUndefsIn(F);
}
}
void solveWhileResolvedUndefsIn(SmallVectorImpl<Function *> &WorkList) {
bool ResolvedUndefs = true;
while (ResolvedUndefs) {
solve();
ResolvedUndefs = false;
for (Function *F : WorkList)
ResolvedUndefs |= resolvedUndefsIn(*F);
}
}
void solveWhileResolvedUndefs() {
bool ResolvedUndefs = true;
while (ResolvedUndefs) {
solve();
ResolvedUndefs = false;
for (Value *V : Invalidated)
if (auto *I = dyn_cast<Instruction>(V))
ResolvedUndefs |= resolvedUndef(*I);
}
Invalidated.clear();
}
};
} // namespace llvm
bool SCCPInstVisitor::markBlockExecutable(BasicBlock *BB) {
if (!BBExecutable.insert(BB).second)
return false;
LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
BBWorkList.push_back(BB); // Add the block to the work list!
return true;
}
void SCCPInstVisitor::pushToWorkList(ValueLatticeElement &IV, Value *V) {
if (IV.isOverdefined()) {
if (OverdefinedInstWorkList.empty() || OverdefinedInstWorkList.back() != V)
OverdefinedInstWorkList.push_back(V);
return;
}
if (InstWorkList.empty() || InstWorkList.back() != V)
InstWorkList.push_back(V);
}
void SCCPInstVisitor::pushToWorkListMsg(ValueLatticeElement &IV, Value *V) {
LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n');
pushToWorkList(IV, V);
}
bool SCCPInstVisitor::markConstant(ValueLatticeElement &IV, Value *V,
Constant *C, bool MayIncludeUndef) {
if (!IV.markConstant(C, MayIncludeUndef))
return false;
LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
pushToWorkList(IV, V);
return true;
}
bool SCCPInstVisitor::markOverdefined(ValueLatticeElement &IV, Value *V) {
if (!IV.markOverdefined())
return false;
LLVM_DEBUG(dbgs() << "markOverdefined: ";
if (auto *F = dyn_cast<Function>(V)) dbgs()
<< "Function '" << F->getName() << "'\n";
else dbgs() << *V << '\n');
// Only instructions go on the work list
pushToWorkList(IV, V);
return true;
}
bool SCCPInstVisitor::isStructLatticeConstant(Function *F, StructType *STy) {
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
assert(It != TrackedMultipleRetVals.end());
ValueLatticeElement LV = It->second;
if (!SCCPSolver::isConstant(LV))
return false;
}
return true;
}
Constant *SCCPInstVisitor::getConstant(const ValueLatticeElement &LV,
Type *Ty) const {
if (LV.isConstant()) {
Constant *C = LV.getConstant();
assert(C->getType() == Ty && "Type mismatch");
return C;
}
if (LV.isConstantRange()) {
const auto &CR = LV.getConstantRange();
if (CR.getSingleElement())
return ConstantInt::get(Ty, *CR.getSingleElement());
}
return nullptr;
}
Constant *SCCPInstVisitor::getConstantOrNull(Value *V) const {
Constant *Const = nullptr;
if (V->getType()->isStructTy()) {
std::vector<ValueLatticeElement> LVs = getStructLatticeValueFor(V);
if (any_of(LVs, SCCPSolver::isOverdefined))
return nullptr;
std::vector<Constant *> ConstVals;
auto *ST = cast<StructType>(V->getType());
for (unsigned I = 0, E = ST->getNumElements(); I != E; ++I) {
ValueLatticeElement LV = LVs[I];
ConstVals.push_back(SCCPSolver::isConstant(LV)
? getConstant(LV, ST->getElementType(I))
: UndefValue::get(ST->getElementType(I)));
}
Const = ConstantStruct::get(ST, ConstVals);
} else {
const ValueLatticeElement &LV = getLatticeValueFor(V);
if (SCCPSolver::isOverdefined(LV))
return nullptr;
Const = SCCPSolver::isConstant(LV) ? getConstant(LV, V->getType())
: UndefValue::get(V->getType());
}
assert(Const && "Constant is nullptr here!");
return Const;
}
void SCCPInstVisitor::setLatticeValueForSpecializationArguments(Function *F,
const SmallVectorImpl<ArgInfo> &Args) {
assert(!Args.empty() && "Specialization without arguments");
assert(F->arg_size() == Args[0].Formal->getParent()->arg_size() &&
"Functions should have the same number of arguments");
auto Iter = Args.begin();
Function::arg_iterator NewArg = F->arg_begin();
Function::arg_iterator OldArg = Args[0].Formal->getParent()->arg_begin();
for (auto End = F->arg_end(); NewArg != End; ++NewArg, ++OldArg) {
LLVM_DEBUG(dbgs() << "SCCP: Marking argument "
<< NewArg->getNameOrAsOperand() << "\n");
// Mark the argument constants in the new function
// or copy the lattice state over from the old function.
if (Iter != Args.end() && Iter->Formal == &*OldArg) {
if (auto *STy = dyn_cast<StructType>(NewArg->getType())) {
for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}];
NewValue.markConstant(Iter->Actual->getAggregateElement(I));
}
} else {
ValueState[&*NewArg].markConstant(Iter->Actual);
}
++Iter;
} else {
if (auto *STy = dyn_cast<StructType>(NewArg->getType())) {
for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}];
NewValue = StructValueState[{&*OldArg, I}];
}
} else {
ValueLatticeElement &NewValue = ValueState[&*NewArg];
NewValue = ValueState[&*OldArg];
}
}
}
}
void SCCPInstVisitor::visitInstruction(Instruction &I) {
// All the instructions we don't do any special handling for just
// go to overdefined.
LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
markOverdefined(&I);
}
bool SCCPInstVisitor::mergeInValue(ValueLatticeElement &IV, Value *V,
ValueLatticeElement MergeWithV,
ValueLatticeElement::MergeOptions Opts) {
if (IV.mergeIn(MergeWithV, Opts)) {
pushToWorkList(IV, V);
LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : "
<< IV << "\n");
return true;
}
return false;
}