-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathConstraintGraph.cpp
1673 lines (1412 loc) · 58.5 KB
/
ConstraintGraph.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
//===--- ConstraintGraph.cpp - Constraint Graph ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the \c ConstraintGraph class, which describes the
// relationships among the type variables within a constraint system.
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Defer.h"
#include "swift/Basic/Statistic.h"
#include "swift/Sema/ConstraintGraph.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/CSTrail.h"
#include "swift/Basic/Assertions.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/SaveAndRestore.h"
#include <algorithm>
#include <memory>
#include <numeric>
using namespace swift;
using namespace constraints;
#define DEBUG_TYPE "ConstraintGraph"
#pragma mark Graph construction/destruction
ConstraintGraph::ConstraintGraph(ConstraintSystem &cs) : CS(cs) { }
ConstraintGraph::~ConstraintGraph() {
#ifndef NDEBUG
for (unsigned i = 0, n = CS.TypeVariables.size(); i != n; ++i) {
auto &impl = CS.TypeVariables[i]->getImpl();
ASSERT(impl.getGraphNode() == nullptr);
}
#endif
for (auto *node : FreeList) {
delete node;
}
}
#pragma mark Graph accessors
void ConstraintGraph::addTypeVariable(TypeVariableType *typeVar) {
// Check whether we've already created a node for this type variable.
auto &impl = typeVar->getImpl();
// ComponentStep::Scope re-introduces type variables that are already
// in the graph, but not in ConstraintSystem::TypeVariables.
if (impl.getGraphNode())
return;
ASSERT(!impl.hasRepresentativeOrFixed());
// Allocate the new node.
ConstraintGraphNode *nodePtr;
if (FreeList.empty())
nodePtr = new ConstraintGraphNode(*this, typeVar);
else {
nodePtr = FreeList.back();
FreeList.pop_back();
nodePtr->initTypeVariable(typeVar);
}
impl.setGraphNode(nodePtr);
if (CS.solverState)
CS.recordChange(SolverTrail::Change::AddedTypeVariable(typeVar));
}
ConstraintGraphNode &
ConstraintGraph::operator[](TypeVariableType *typeVar) {
auto *nodePtr = typeVar->getImpl().getGraphNode();
ASSERT(nodePtr->TypeVar == typeVar && "Use-after-free");
return *nodePtr;
}
void ConstraintGraphNode::reset() {
if (CONDITIONAL_ASSERT_enabled()) {
ASSERT(TypeVar);
ASSERT(Constraints.empty());
ASSERT(ConstraintIndex.empty());
ASSERT(ReferencedBy.empty());
ASSERT(References.empty());
ASSERT(EquivalenceClass.size() <= 1);
}
TypeVar = nullptr;
EquivalenceClass.clear();
Potential.reset();
Set.reset();
}
bool ConstraintGraphNode::forRepresentativeVar() const {
auto *typeVar = getTypeVariable();
return typeVar == typeVar->getImpl().getRepresentative(nullptr);
}
ArrayRef<TypeVariableType *> ConstraintGraphNode::getEquivalenceClass() const{
assert(forRepresentativeVar() &&
"Can't request equivalence class from non-representative type var");
return getEquivalenceClassUnsafe();
}
ArrayRef<TypeVariableType *>
ConstraintGraphNode::getEquivalenceClassUnsafe() const{
if (EquivalenceClass.empty())
EquivalenceClass.push_back(TypeVar);
return EquivalenceClass;
}
#pragma mark Node mutation
static bool isUsefulForReferencedVars(Constraint *constraint) {
switch (constraint->getKind()) {
// Don't attempt to propagate information about `Bind`s and
// `BindOverload`s to referenced variables since they are
// adjacent through that binding already, and there is no
// useful information in trying to process that kind of
// constraint.
case ConstraintKind::Bind:
case ConstraintKind::BindOverload:
return false;
default:
return true;
}
}
void ConstraintGraphNode::addConstraint(Constraint *constraint) {
assert(ConstraintIndex.count(constraint) == 0 && "Constraint re-insertion");
ConstraintIndex[constraint] = Constraints.size();
Constraints.push_back(constraint);
}
void ConstraintGraphNode::removeConstraint(Constraint *constraint) {
auto pos = ConstraintIndex.find(constraint);
assert(pos != ConstraintIndex.end());
// Remove this constraint from the constraint mapping.
auto index = pos->second;
ConstraintIndex.erase(pos);
assert(Constraints[index] == constraint && "Mismatched constraint");
// If this is the last constraint, just pop it off the list and we're done.
unsigned lastIndex = Constraints.size()-1;
if (index == lastIndex) {
Constraints.pop_back();
return;
}
// This constraint is somewhere in the middle; swap it with the last
// constraint, so we can remove the constraint from the vector in O(1)
// time rather than O(n) time.
auto lastConstraint = Constraints[lastIndex];
Constraints[index] = lastConstraint;
ConstraintIndex[lastConstraint] = index;
Constraints.pop_back();
}
void ConstraintGraphNode::notifyReferencingVars(
llvm::function_ref<void(ConstraintGraphNode &,
Constraint *)> notification) const {
SmallVector<TypeVariableType *, 4> stack;
stack.push_back(TypeVar);
auto updateAdjacencies = [&](TypeVariableType *typeVar) {
for (auto *constraint : CG[typeVar].getConstraints()) {
if (constraint->getClassification() !=
ConstraintClassification::Relational)
continue;
auto lhsTy = constraint->getFirstType();
auto rhsTy = constraint->getSecondType();
Type affectedTy =
ConstraintSystem::typeVarOccursInType(typeVar, lhsTy) ? rhsTy : lhsTy;
if (auto *affectedVar = affectedTy->getAs<TypeVariableType>()) {
auto *repr =
affectedVar->getImpl().getRepresentative(/*record=*/nullptr);
if (!repr->getImpl().getFixedType(/*record=*/nullptr))
notification(CG[repr], constraint);
}
}
};
while (!stack.empty()) {
auto *typeVar = stack.pop_back_val();
// All of the relational constraints associated with this
// variable need to get re-introduced to other mentioned
// type variable to update their bindings.
//
// If variable is a representative of an equivalence class
// it means that all members have been modified together
// with their representative and their adjacencies have to
// get updated as well.
if (CG[typeVar].forRepresentativeVar()) {
for (auto *eqVar : CG[typeVar].getEquivalenceClass()) {
updateAdjacencies(eqVar);
for (auto *referrer : CG[eqVar].getReferencedBy())
stack.push_back(referrer);
}
} else {
updateAdjacencies(typeVar);
// If current type variable is referenced by some other
// type variable as part of its fixed type it means that
// all of the adjacencies of that variable have to be
// notified as well otherwise they'll miss change in type.
for (auto *referrer : CG[typeVar].getReferencedBy())
stack.push_back(referrer);
}
}
}
void ConstraintGraphNode::notifyReferencedVars(
llvm::function_ref<void(ConstraintGraphNode &)> notification) const {
for (auto *referencedVar : getReferencedVars()) {
auto *repr = referencedVar->getImpl().getRepresentative(/*record=*/nullptr);
if (!repr->getImpl().getFixedType(/*record=*/nullptr))
notification(CG[repr]);
}
}
void ConstraintGraphNode::addToEquivalenceClass(
ArrayRef<TypeVariableType *> typeVars) {
assert(forRepresentativeVar() &&
"Can't extend equivalence class of non-representative type var");
if (EquivalenceClass.empty())
EquivalenceClass.push_back(getTypeVariable());
EquivalenceClass.append(typeVars.begin(), typeVars.end());
}
void ConstraintGraphNode::truncateEquivalenceClass(unsigned prevSize) {
EquivalenceClass.erase(EquivalenceClass.begin() + prevSize,
EquivalenceClass.end());
}
void ConstraintGraphNode::addReferencedVar(TypeVariableType *typeVar) {
bool inserted = References.insert(typeVar);
if (!inserted) {
llvm::errs() << "$T" << TypeVar->getImpl().getID() << " already "
<< "references $T" << typeVar->getImpl().getID() << "\n";
abort();
}
}
void ConstraintGraphNode::addReferencedBy(TypeVariableType *typeVar) {
bool inserted = ReferencedBy.insert(typeVar);
if (!inserted) {
llvm::errs() << "$T" << TypeVar->getImpl().getID() << " already "
<< "referenced by $T" << typeVar->getImpl().getID() << "\n";
abort();
}
}
void ConstraintGraphNode::removeReference(TypeVariableType *typeVar) {
auto removed = References.remove(typeVar);
if (!removed) {
llvm::errs() << "$T" << TypeVar->getImpl().getID() << " does not "
<< "reference $T" << typeVar->getImpl().getID() << "\n";
abort();
}
}
void ConstraintGraphNode::removeReferencedBy(TypeVariableType *typeVar) {
auto removed = ReferencedBy.remove(typeVar);
if (!removed) {
llvm::errs() << "$T" << TypeVar->getImpl().getID() << " not "
<< "referenced by $T" << typeVar->getImpl().getID() << "\n";
abort();
}
}
void ConstraintGraphNode::retractFromInference() {
auto &cs = CG.getConstraintSystem();
// Notify all of the type variables that reference this one.
//
// Since this type variable is going to be replaced with a fixed type
// all of the concrete types that reference it are going to change,
// which means that all of the not-yet-attempted bindings should
// change as well.
return notifyReferencingVars(
[&cs](ConstraintGraphNode &node, Constraint *constraint) {
node.getPotentialBindings().retract(cs, node.getTypeVariable(), constraint);
});
}
void ConstraintGraphNode::introduceToInference(Type fixedType) {
auto &cs = CG.getConstraintSystem();
// Notify all of the type variables that reference this one.
//
// Since this type variable has been replaced with a fixed type
// all of the concrete types that reference it are going to change,
// which means that all of the not-yet-attempted bindings should
// change as well.
notifyReferencingVars([&cs](ConstraintGraphNode &node, Constraint *constraint) {
node.getPotentialBindings().infer(cs, node.getTypeVariable(), constraint);
});
if (!fixedType->hasTypeVariable())
return;
SmallPtrSet<TypeVariableType *, 4> referencedVars;
fixedType->getTypeVariables(referencedVars);
for (auto *referencedVar : referencedVars) {
auto *repr = referencedVar->getImpl().getRepresentative(/*record=*/nullptr);
if (repr->getImpl().getFixedType(/*record=*/nullptr))
continue;
auto &node = CG[repr];
// Newly referred vars need to re-introduce all constraints associated
// with this type variable since they are now going to be used in
// all of the constraints that reference bound type variable.
for (auto *constraint : getConstraints()) {
if (isUsefulForReferencedVars(constraint))
node.getPotentialBindings().infer(cs, node.getTypeVariable(), constraint);
}
}
}
#pragma mark Graph mutation
void ConstraintGraph::removeNode(TypeVariableType *typeVar) {
// Remove this node.
auto &impl = typeVar->getImpl();
auto *node = impl.getGraphNode();
node->reset();
FreeList.push_back(node);
impl.setGraphNode(nullptr);
}
void ConstraintGraph::addConstraint(Constraint *constraint) {
// For the nodes corresponding to each type variable...
auto referencedTypeVars = constraint->getTypeVariables();
for (auto typeVar : referencedTypeVars) {
// Record the change, if there are active scopes.
if (CS.solverState)
CS.recordChange(SolverTrail::Change::AddedConstraint(typeVar, constraint));
addConstraint(typeVar, constraint);
auto *repr = typeVar->getImpl().getRepresentative(/*record=*/nullptr);
if (!repr->getImpl().getFixedType(/*record=*/nullptr))
(*this)[repr].getPotentialBindings().infer(CS, repr, constraint);
if (isUsefulForReferencedVars(constraint)) {
(*this)[typeVar].notifyReferencedVars([&](ConstraintGraphNode &node) {
node.getPotentialBindings().infer(CS, node.getTypeVariable(), constraint);
});
}
}
// If the constraint doesn't reference any type variables, it's orphaned;
// track it as such.
if (referencedTypeVars.empty()) {
// Record the change, if there are active scopes.
if (CS.solverState)
CS.recordChange(SolverTrail::Change::AddedConstraint(nullptr, constraint));
addConstraint(nullptr, constraint);
}
}
void ConstraintGraph::addConstraint(TypeVariableType *typeVar,
Constraint *constraint) {
if (typeVar) {
(*this)[typeVar].addConstraint(constraint);
return;
}
// If the constraint doesn't reference any type variables, it's orphaned;
// track it as such.
OrphanedConstraints.push_back(constraint);
}
void ConstraintGraph::removeConstraint(Constraint *constraint) {
// For the nodes corresponding to each type variable...
auto referencedTypeVars = constraint->getTypeVariables();
for (auto typeVar : referencedTypeVars) {
auto *repr = typeVar->getImpl().getRepresentative(/*record=*/nullptr);
if (!repr->getImpl().getFixedType(/*record=*/nullptr))
(*this)[repr].getPotentialBindings().retract(CS, repr, constraint);
if (isUsefulForReferencedVars(constraint)) {
(*this)[typeVar].notifyReferencedVars([&](ConstraintGraphNode &node) {
node.getPotentialBindings().retract(CS, node.getTypeVariable(), constraint);
});
}
// Record the change, if there are active scopes.
if (CS.solverState)
CS.recordChange(SolverTrail::Change::RemovedConstraint(typeVar, constraint));
removeConstraint(typeVar, constraint);
}
// If this is an orphaned constraint, remove it from the list.
if (referencedTypeVars.empty()) {
// Record the change, if there are active scopes.
if (CS.solverState)
CS.recordChange(SolverTrail::Change::RemovedConstraint(nullptr, constraint));
removeConstraint(nullptr, constraint);
}
}
void ConstraintGraph::removeConstraint(TypeVariableType *typeVar,
Constraint *constraint) {
if (typeVar) {
(*this)[typeVar].removeConstraint(constraint);
return;
}
// If this is an orphaned constraint, remove it from the list.
auto known = std::find(OrphanedConstraints.begin(),
OrphanedConstraints.end(),
constraint);
assert(known != OrphanedConstraints.end() && "missing orphaned constraint");
*known = OrphanedConstraints.back();
OrphanedConstraints.pop_back();
}
void ConstraintGraph::mergeNodesPre(TypeVariableType *typeVar2) {
// Merge equivalence class from the non-representative type variable.
auto &nonRepNode = (*this)[typeVar2];
for (auto *newMember : nonRepNode.getEquivalenceClassUnsafe()) {
auto &node = (*this)[newMember];
node.notifyReferencingVars(
[&](ConstraintGraphNode &node, Constraint *constraint) {
node.getPotentialBindings().retract(CS, node.getTypeVariable(), constraint);
});
}
}
void ConstraintGraph::mergeNodes(TypeVariableType *typeVar1,
TypeVariableType *typeVar2) {
// Retrieve the node for the representative that we're merging into.
ASSERT(CS.getRepresentative(typeVar1) == typeVar1);
auto &repNode = (*this)[typeVar1];
// Record the change, if there are active scopes.
if (CS.solverState) {
CS.recordChange(
SolverTrail::Change::ExtendedEquivalenceClass(
typeVar1,
repNode.getEquivalenceClass().size()));
}
// Merge equivalence class from the non-representative type variable.
auto &nonRepNode = (*this)[typeVar2];
auto typeVars = nonRepNode.getEquivalenceClassUnsafe();
repNode.addToEquivalenceClass(typeVars);
for (auto *newMember : typeVars) {
auto &node = (*this)[newMember];
for (auto *constraint : node.getConstraints()) {
if (!typeVar1->getImpl().getFixedType(/*record=*/nullptr))
repNode.getPotentialBindings().infer(CS, typeVar1, constraint);
if (!isUsefulForReferencedVars(constraint))
continue;
repNode.notifyReferencedVars([&](ConstraintGraphNode &node) {
node.getPotentialBindings().infer(CS, node.getTypeVariable(), constraint);
});
}
node.notifyReferencingVars(
[&](ConstraintGraphNode &node, Constraint *constraint) {
node.getPotentialBindings().infer(CS, node.getTypeVariable(), constraint);
});
}
}
void ConstraintGraph::bindTypeVariable(TypeVariableType *typeVar, Type fixed) {
assert(!fixed->is<TypeVariableType>() &&
"Cannot bind to type variable; merge equivalence classes instead");
auto &node = (*this)[typeVar];
llvm::SmallPtrSet<TypeVariableType *, 4> referencedVars;
fixed->getTypeVariables(referencedVars);
for (auto otherTypeVar : referencedVars) {
if (typeVar == otherTypeVar)
continue;
auto &otherNode = (*this)[otherTypeVar];
otherNode.addReferencedBy(typeVar);
node.addReferencedVar(otherTypeVar);
// Record the change, if there are active scopes.
if (CS.solverState)
CS.recordChange(SolverTrail::Change::RelatedTypeVariables(typeVar, otherTypeVar));
}
}
void ConstraintGraph::retractFromInference(TypeVariableType *typeVar) {
(*this)[typeVar].retractFromInference();
}
void ConstraintGraph::introduceToInference(TypeVariableType *typeVar, Type fixed) {
(*this)[typeVar].introduceToInference(fixed);
}
void ConstraintGraph::unrelateTypeVariables(TypeVariableType *typeVar,
TypeVariableType *otherTypeVar) {
auto &node = (*this)[typeVar];
auto &otherNode = (*this)[otherTypeVar];
otherNode.removeReferencedBy(typeVar);
node.removeReference(otherTypeVar);
}
void ConstraintGraph::retractBindings(TypeVariableType *typeVar,
Constraint *constraint) {
(*this)[typeVar].getPotentialBindings().retract(CS, typeVar, constraint);
}
#pragma mark Algorithms
/// Perform a depth-first search.
///
/// \param cg The constraint graph.
/// \param typeVar The type variable we're searching from.
/// \param preVisitNode Called before traversing a node. Must return \c
/// false when the node has already been visited.
/// \param visitConstraint Called before considering a constraint. If it
/// returns \c false, that constraint will be skipped.
/// \param visitedConstraints Set of already-visited constraints, used
/// internally to avoid duplicated work.
static void depthFirstSearch(
ConstraintGraph &cg,
TypeVariableType *typeVar,
llvm::function_ref<bool(TypeVariableType *)> preVisitNode,
llvm::function_ref<bool(Constraint *)> visitConstraint,
llvm::SmallPtrSet<Constraint *, 8> &visitedConstraints) {
// If we're not looking at this type variable right now because we're
// solving a conjunction element, don't consider its adjacencies.
if (!cg.getConstraintSystem().isActiveTypeVariable(typeVar))
return;
// Visit this node. If we've already seen it, bail out.
if (!preVisitNode(typeVar))
return;
// Local function to visit adjacent type variables.
auto visitAdjacencies = [&](ArrayRef<TypeVariableType *> adjTypeVars) {
for (auto adj : adjTypeVars) {
if (adj == typeVar)
continue;
// Recurse into this node.
depthFirstSearch(cg, adj, preVisitNode, visitConstraint,
visitedConstraints);
}
};
// Walk all of the constraints associated with this node to find related
// nodes.
auto &node = cg[typeVar];
for (auto constraint : node.getConstraints()) {
// If we've already seen this constraint, skip it.
if (!visitedConstraints.insert(constraint).second)
continue;
if (visitConstraint(constraint))
visitAdjacencies(constraint->getTypeVariables());
}
// Visit all of the other nodes in the equivalence class.
auto repTypeVar = cg.getConstraintSystem().getRepresentative(typeVar);
if (typeVar == repTypeVar) {
// We are the representative, so visit all of the other type variables
// in this equivalence class.
visitAdjacencies(node.getEquivalenceClass());
} else {
// We are not the representative; visit the representative.
visitAdjacencies(repTypeVar);
}
// Walk any type variables related via fixed bindings.
visitAdjacencies(node.getReferencedBy());
visitAdjacencies(node.getReferencedVars());
}
llvm::TinyPtrVector<Constraint *> ConstraintGraph::gatherConstraints(
TypeVariableType *typeVar, GatheringKind kind,
llvm::function_ref<bool(Constraint *)> acceptConstraintFn) {
llvm::TinyPtrVector<Constraint *> constraints;
// Whether we should consider this constraint at all.
auto shouldConsiderConstraint = [&](Constraint *constraint) {
// For a one-way constraint, only consider it when the left-hand side of
// the binding is one of the type variables currently under consideration,
// as only such constraints need solving for this component. Note that we
// don't perform any other filtering, as the constraint system should be
// responsible for checking any other conditions.
if (constraint->isOneWayConstraint()) {
auto lhsTypeVar = constraint->getFirstType()->castTo<TypeVariableType>();
return CS.isActiveTypeVariable(lhsTypeVar);
}
return true;
};
auto acceptConstraint = [&](Constraint *constraint) {
return shouldConsiderConstraint(constraint) &&
acceptConstraintFn(constraint);
};
llvm::SmallPtrSet<TypeVariableType *, 4> typeVars;
llvm::SmallPtrSet<Constraint *, 8> visitedConstraints;
if (kind == GatheringKind::AllMentions) {
// If we've been asked for "all mentions" of a type variable, search for
// constraints involving both it and its fixed bindings.
depthFirstSearch(
*this, typeVar,
[&](TypeVariableType *typeVar) {
return typeVars.insert(typeVar).second;
},
[&](Constraint *constraint) {
if (acceptConstraint(constraint))
constraints.push_back(constraint);
// Don't recurse into the constraint's type variables.
return false;
},
visitedConstraints);
return constraints;
}
// Otherwise only search in the type var's equivalence class and immediate
// fixed bindings.
// Local function to add constraints.
auto addTypeVarConstraints = [&](TypeVariableType *adjTypeVar) {
if (!typeVars.insert(adjTypeVar).second)
return;
for (auto constraint : (*this)[adjTypeVar].getConstraints()) {
if (visitedConstraints.insert(constraint).second &&
acceptConstraint(constraint))
constraints.push_back(constraint);
}
};
auto &reprNode = (*this)[CS.getRepresentative(typeVar)];
auto equivClass = reprNode.getEquivalenceClass();
for (auto typeVar : equivClass) {
if (!typeVars.insert(typeVar).second)
continue;
auto &node = (*this)[typeVar];
for (auto constraint : node.getConstraints()) {
if (visitedConstraints.insert(constraint).second &&
acceptConstraint(constraint))
constraints.push_back(constraint);
}
for (auto adjTypeVar : node.getReferencedBy()) {
addTypeVarConstraints(adjTypeVar);
}
for (auto adjTypeVar : node.getReferencedVars()) {
addTypeVarConstraints(adjTypeVar);
}
}
return constraints;
}
namespace {
/// A union-find connected components algorithm used to find the connected
/// components within a constraint graph.
class ConnectedComponents {
ConstraintGraph &cg;
ArrayRef<TypeVariableType *> typeVars;
/// The number of connected components discovered so far. Decremented when
/// we merge equivalence classes.
unsigned validComponentCount = 0;
/// Describes the one-way incoming and outcoming adjacencies of
/// a component within the directed graph of one-way constraints.
struct OneWayComponent {
/// The (uniqued) set of type variable representatives to which this
/// component has an outgoing edge.
TinyPtrVector<TypeVariableType *> outAdjacencies;
/// The (uniqued) set of type variable representatives from which this
/// component has an incoming edge.
TinyPtrVector<TypeVariableType *> inAdjacencies;
};
// Adjacency list representation of the directed graph of edges for
// one-way constraints, using type variable representatives as the
// nodes.
llvm::SmallDenseMap<TypeVariableType *, OneWayComponent> oneWayDigraph;
public:
using Component = ConstraintGraph::Component;
/// Compute connected components for the given set of type variables
/// in the constraint graph.
ConnectedComponents(ConstraintGraph &cg,
ArrayRef<TypeVariableType *> typeVars)
: cg(cg), typeVars(typeVars)
{
auto oneWayConstraints = connectedComponents();
// If there were no one-way constraints, we're done.
if (oneWayConstraints.empty())
return;
// Build the directed one-way constraint graph.
buildOneWayConstraintGraph(oneWayConstraints);
}
/// Retrieve the set of components.
SmallVector<Component, 1> getComponents() const {
// The final return value.
SmallVector<Component, 1> flatComponents;
// We don't actually need to partition the graph into components if
// there are fewer than 2.
if (validComponentCount < 2 && cg.getOrphanedConstraints().empty())
return flatComponents;
// Mapping from representatives to components.
llvm::SmallDenseMap<TypeVariableType *, Component> components;
SmallVector<TypeVariableType *, 4> representativeTypeVars;
// Capture the type variables of each component.
for (auto typeVar : typeVars) {
// Find the representative. If we aren't creating a type variable
// for this component, skip it.
auto rep = typeVar->getImpl().getComponent();
if (!rep->getImpl().isValidComponent())
continue;
auto pair = components.insert({rep, Component(components.size())});
if (pair.second)
representativeTypeVars.push_back(rep);
// Record this type variable in the set of type variables for its
// component.
pair.first->second.typeVars.push_back(typeVar);
}
// Retrieve the component for the given representative type variable.
auto getComponent = [&](TypeVariableType *rep) -> Component& {
auto component = components.find(rep);
assert(component != components.end());
return component->second;
};
auto &cs = cg.getConstraintSystem();
// Assign each constraint to its appropriate component.
// Note: we use the inactive constraints so that we maintain the
// order of constraints when we re-introduce them.
for (auto &constraint : cs.getConstraints()) {
auto constraintTypeVars = constraint.getTypeVariables();
if (constraintTypeVars.empty())
continue;
TypeVariableType *typeVar;
if (constraint.isOneWayConstraint()) {
// For one-way constraints, associate the constraint with the
// left-hand type variable.
typeVar = constraint.getFirstType()->castTo<TypeVariableType>();
} else {
typeVar = constraintTypeVars.front();
}
auto rep = typeVar->getImpl().getComponent();
getComponent(rep).addConstraint(&constraint);
}
// If we have any one-way constraint information, compute the ordering
// of representative type variables needed to respect one-way
// constraints while solving.
if (!oneWayDigraph.empty()) {
// Sort the representative type variables based on the disjunction
// count, so
std::sort(representativeTypeVars.begin(), representativeTypeVars.end(),
[&](TypeVariableType *lhs, TypeVariableType *rhs) {
return getComponent(lhs).getNumDisjunctions() >
getComponent(rhs).getNumDisjunctions();
});
representativeTypeVars =
computeOneWayComponentOrdering(representativeTypeVars);
// Fill in one-way dependency information for all of the components.
for (auto typeVar : representativeTypeVars) {
auto knownOneWayComponent = oneWayDigraph.find(typeVar);
if (knownOneWayComponent == oneWayDigraph.end())
continue;
auto &oneWayComponent = knownOneWayComponent->second;
auto &component = getComponent(typeVar);
for (auto inAdj : oneWayComponent.inAdjacencies) {
if (!inAdj->getImpl().isValidComponent())
continue;
component.recordDependency(getComponent(inAdj));
}
}
}
// Flatten the set of components.
flatComponents.reserve(
representativeTypeVars.size() + cg.getOrphanedConstraints().size());
for (auto rep: representativeTypeVars) {
assert(components.count(rep) == 1);
flatComponents.push_back(std::move(getComponent(rep)));
}
// Gather orphaned constraints; each gets its own component.
for (auto orphaned : cg.getOrphanedConstraints()) {
flatComponents.push_back(Component(flatComponents.size()));
flatComponents.back().addConstraint(orphaned);
}
// Create component ordering based on the information associated
// with constraints in each step - e.g. number of disjunctions,
// since components are going to be executed in LIFO order, we'd
// want to have smaller/faster components at the back of the list.
// When there are one-way constraints, we can't reorder them, so only
// sort the orphaned constraints at the back. In the absence of
// one-way constraints, sort everything.
if (components.size() > 1) {
auto sortStart = oneWayDigraph.empty()
? flatComponents.begin()
: flatComponents.end() - cg.getOrphanedConstraints().size();
std::sort(sortStart, flatComponents.end(),
[&](const Component &lhs, const Component &rhs) {
return lhs.getNumDisjunctions() > rhs.getNumDisjunctions();
});
}
return flatComponents;
}
private:
/// Perform the union of two type variables in a union-find data structure
/// used for connected components.
///
/// \returns true if the two components were separate and have now been
/// joined, \c false if they were already in the same set.
bool unionSets(TypeVariableType *typeVar1, TypeVariableType *typeVar2) {
auto rep1 = typeVar1->getImpl().getComponent();
auto rep2 = typeVar2->getImpl().getComponent();
if (rep1 == rep2)
return false;
// Reparent the type variable with the higher ID. The actual choice doesn't
// matter, but this makes debugging easier.
if (rep1->getID() > rep2->getID())
std::swap(rep1, rep2);
if (rep2->getImpl().isValidComponent()) {
// If both are valid components, decrement the valid component counter
// by one. Otherwise, propagate the valid component flag.
if (!rep1->getImpl().markValidComponent()) {
ASSERT(validComponentCount > 0);
--validComponentCount;
}
}
rep2->getImpl().setComponent(rep1);
return true;
}
/// Perform the connected components algorithm, skipping one-way
/// constraints.
///
/// \returns the set of one-way constraints that were skipped.
TinyPtrVector<Constraint *> connectedComponents() {
TinyPtrVector<Constraint *> oneWayConstraints;
auto &cs = cg.getConstraintSystem();
for (auto typeVar : typeVars) {
auto &impl = typeVar->getImpl();
if (auto *rep = impl.getRepresentativeOrFixed().dyn_cast<TypeVariableType *>()) {
impl.setComponent(rep);
if (typeVar == rep) {
if (impl.markValidComponent())
++validComponentCount;
}
} else {
impl.setComponent(typeVar);
}
}
for (auto typeVar : typeVars) {
auto &impl = typeVar->getImpl();
if (impl.getRepresentativeOrFixed().is<TypeBase *>()) {
auto &node = cg[typeVar];
for (auto otherTypeVar : node.getReferencedVars()) {
unionSets(typeVar, otherTypeVar);
}
}
}
for (auto &constraint : cs.getConstraints()) {
if (constraint.isOneWayConstraint()) {
oneWayConstraints.push_back(&constraint);
auto *typeVar = constraint.getFirstType()->castTo<TypeVariableType>();
typeVar = typeVar->getImpl().getComponent();
if (typeVar->getImpl().markValidComponent())
++validComponentCount;
continue;
}
auto typeVars = constraint.getTypeVariables();
if (typeVars.empty())
continue;
auto *firstTypeVar = typeVars[0]->getImpl().getComponent();
if (firstTypeVar->getImpl().markValidComponent())
++validComponentCount;
for (auto *otherTypeVar : typeVars.slice(1))
unionSets(firstTypeVar, otherTypeVar);
}
return oneWayConstraints;
}
/// Insert the given type variable into the given vector if it isn't
/// already present.
static void insertIfUnique(TinyPtrVector<TypeVariableType *> &vector,
TypeVariableType *typeVar) {
if (std::find(vector.begin(), vector.end(), typeVar) == vector.end())
vector.push_back(typeVar);
}
/// Retrieve the (uniqued) set of type variable representations that occur
/// within the given type.
TinyPtrVector<TypeVariableType *>
getRepresentativesInType(Type type) const {
TinyPtrVector<TypeVariableType *> results;
SmallPtrSet<TypeVariableType *, 2> typeVars;
type->getTypeVariables(typeVars);
for (auto typeVar : typeVars) {
auto rep = typeVar->getImpl().getComponent();
insertIfUnique(results, rep);
}
return results;
}
/// Add all of the one-way constraints to the one-way digraph
void addOneWayConstraintEdges(ArrayRef<Constraint *> oneWayConstraints) {
for (auto constraint : oneWayConstraints) {
auto lhsTypeReps =
getRepresentativesInType(constraint->getFirstType());
auto rhsTypeReps =
getRepresentativesInType(constraint->getSecondType());
// Add an edge from the type representatives on the right-hand side
// of the one-way constraint to the type representatives on the
// left-hand side, because the right-hand type variables need to
// be solved before the left-hand type variables.
for (auto lhsTypeRep : lhsTypeReps) {
for (auto rhsTypeRep : rhsTypeReps) {
if (lhsTypeRep == rhsTypeRep)