forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConstraintGraph.cpp
1136 lines (965 loc) · 38.4 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 "ConstraintGraph.h"
#include "ConstraintGraphScope.h"
#include "ConstraintSystem.h"
#include "swift/Basic/Statistic.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() {
assert(Changes.empty() && "Scope stack corrupted");
for (unsigned i = 0, n = TypeVariables.size(); i != n; ++i) {
auto &impl = TypeVariables[i]->getImpl();
delete impl.getGraphNode();
impl.setGraphNode(nullptr);
}
}
#pragma mark Graph accessors
std::pair<ConstraintGraphNode &, unsigned>
ConstraintGraph::lookupNode(TypeVariableType *typeVar) {
// Check whether we've already created a node for this type variable.
auto &impl = typeVar->getImpl();
if (auto nodePtr = impl.getGraphNode()) {
assert(impl.getGraphIndex() < TypeVariables.size() && "Out-of-bounds index");
assert(TypeVariables[impl.getGraphIndex()] == typeVar &&
"Type variable mismatch");
return { *nodePtr, impl.getGraphIndex() };
}
// Allocate the new node.
auto nodePtr = new ConstraintGraphNode(typeVar);
unsigned index = TypeVariables.size();
impl.setGraphNode(nodePtr);
impl.setGraphIndex(index);
// Record this type variable.
TypeVariables.push_back(typeVar);
// Record the change, if there are active scopes.
if (ActiveScope)
Changes.push_back(Change::addedTypeVariable(typeVar));
// If this type variable is not the representative of its equivalence class,
// add it to its representative's set of equivalences.
auto typeVarRep = CS.getRepresentative(typeVar);
if (typeVar != typeVarRep)
mergeNodes(typeVar, typeVarRep);
else if (auto fixed = CS.getFixedType(typeVarRep)) {
// Bind the type variable.
bindTypeVariable(typeVar, fixed);
}
return { *nodePtr, index };
}
ArrayRef<TypeVariableType *> ConstraintGraphNode::getEquivalenceClass() const{
assert(TypeVar == TypeVar->getImpl().getRepresentative(nullptr) &&
"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
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();
}
ConstraintGraphNode::Adjacency &
ConstraintGraphNode::getAdjacency(TypeVariableType *typeVar) {
assert(typeVar != TypeVar && "Cannot be adjacent to oneself");
// Look for existing adjacency information.
auto pos = AdjacencyInfo.find(typeVar);
if (pos != AdjacencyInfo.end())
return pos->second;
// If we weren't already adjacent to this type variable, add it to the
// list of adjacencies.
pos = AdjacencyInfo.insert(
{ typeVar, { static_cast<unsigned>(Adjacencies.size()), 0, 0 } })
.first;
Adjacencies.push_back(typeVar);
return pos->second;
}
void ConstraintGraphNode::modifyAdjacency(
TypeVariableType *typeVar,
llvm::function_ref<void(Adjacency& adj)> modify) {
// Find the adjacency information.
auto pos = AdjacencyInfo.find(typeVar);
assert(pos != AdjacencyInfo.end() && "Type variables not adjacent");
assert(Adjacencies[pos->second.Index] == typeVar && "Mismatched adjacency");
// Perform the modification .
modify(pos->second);
// If the adjacency is not empty, leave the information in there.
if (!pos->second.empty())
return;
// Remove this adjacency from the mapping.
unsigned index = pos->second.Index;
AdjacencyInfo.erase(pos);
// If this adjacency is last in the vector, just pop it off.
unsigned lastIndex = Adjacencies.size()-1;
if (index == lastIndex) {
Adjacencies.pop_back();
return;
}
// This adjacency is somewhere in the middle; swap it with the last
// adjacency so we can remove the adjacency from the vector in O(1) time
// rather than O(n) time.
auto lastTypeVar = Adjacencies[lastIndex];
Adjacencies[index] = lastTypeVar;
AdjacencyInfo[lastTypeVar].Index = index;
Adjacencies.pop_back();
}
void ConstraintGraphNode::addAdjacency(TypeVariableType *typeVar) {
auto &adjacency = getAdjacency(typeVar);
// Bump the degree of the adjacency.
++adjacency.NumConstraints;
}
void ConstraintGraphNode::removeAdjacency(TypeVariableType *typeVar) {
modifyAdjacency(typeVar, [](Adjacency &adj) {
assert(adj.NumConstraints > 0 && "No adjacency to remove?");
--adj.NumConstraints;
});
}
void ConstraintGraphNode::addToEquivalenceClass(
ArrayRef<TypeVariableType *> typeVars) {
assert(TypeVar == TypeVar->getImpl().getRepresentative(nullptr) &&
"Can't extend equivalence class of non-representative type var");
if (EquivalenceClass.empty())
EquivalenceClass.push_back(TypeVar);
EquivalenceClass.append(typeVars.begin(), typeVars.end());
}
void ConstraintGraphNode::addFixedBinding(TypeVariableType *typeVar) {
auto &adjacency = getAdjacency(typeVar);
assert(!adjacency.FixedBinding && "Already marked as a fixed binding?");
adjacency.FixedBinding = true;
}
void ConstraintGraphNode::removeFixedBinding(TypeVariableType *typeVar) {
modifyAdjacency(typeVar, [](Adjacency &adj) {
assert(adj.FixedBinding && "Not a fixed binding?");
adj.FixedBinding = false;
});
}
#pragma mark Graph scope management
ConstraintGraphScope::ConstraintGraphScope(ConstraintGraph &CG)
: CG(CG), ParentScope(CG.ActiveScope), NumChanges(CG.Changes.size())
{
CG.ActiveScope = this;
}
ConstraintGraphScope::~ConstraintGraphScope() {
// Pop changes off the stack until we hit the change could we had prior to
// introducing this scope.
assert(CG.Changes.size() >= NumChanges && "Scope stack corrupted");
while (CG.Changes.size() > NumChanges) {
CG.Changes.back().undo(CG);
CG.Changes.pop_back();
}
// The active scope is now the parent scope.
CG.ActiveScope = ParentScope;
}
ConstraintGraph::Change
ConstraintGraph::Change::addedTypeVariable(TypeVariableType *typeVar) {
Change result;
result.Kind = ChangeKind::AddedTypeVariable;
result.TypeVar = typeVar;
return result;
}
ConstraintGraph::Change
ConstraintGraph::Change::addedConstraint(Constraint *constraint) {
Change result;
result.Kind = ChangeKind::AddedConstraint;
result.TheConstraint = constraint;
return result;
}
ConstraintGraph::Change
ConstraintGraph::Change::removedConstraint(Constraint *constraint) {
Change result;
result.Kind = ChangeKind::RemovedConstraint;
result.TheConstraint = constraint;
return result;
}
ConstraintGraph::Change
ConstraintGraph::Change::extendedEquivalenceClass(TypeVariableType *typeVar,
unsigned prevSize) {
Change result;
result.Kind = ChangeKind::ExtendedEquivalenceClass;
result.EquivClass.TypeVar = typeVar;
result.EquivClass.PrevSize = prevSize;
return result;
}
ConstraintGraph::Change
ConstraintGraph::Change::boundTypeVariable(TypeVariableType *typeVar,
Type fixed) {
Change result;
result.Kind = ChangeKind::BoundTypeVariable;
result.Binding.TypeVar = typeVar;
result.Binding.FixedType = fixed.getPointer();
return result;
}
void ConstraintGraph::Change::undo(ConstraintGraph &cg) {
/// Temporarily change the active scope to null, so we don't record
/// any changes made while performing the undo operation.
llvm::SaveAndRestore<ConstraintGraphScope *> prevActiveScope(cg.ActiveScope,
nullptr);
switch (Kind) {
case ChangeKind::AddedTypeVariable:
cg.removeNode(TypeVar);
break;
case ChangeKind::AddedConstraint:
cg.removeConstraint(TheConstraint);
break;
case ChangeKind::RemovedConstraint:
cg.addConstraint(TheConstraint);
break;
case ChangeKind::ExtendedEquivalenceClass: {
auto &node = cg[EquivClass.TypeVar];
node.EquivalenceClass.erase(
node.EquivalenceClass.begin() + EquivClass.PrevSize,
node.EquivalenceClass.end());
break;
}
case ChangeKind::BoundTypeVariable:
cg.unbindTypeVariable(Binding.TypeVar, Binding.FixedType);
break;
}
}
#pragma mark Graph mutation
void ConstraintGraph::removeNode(TypeVariableType *typeVar) {
// Remove this node.
auto &impl = typeVar->getImpl();
unsigned index = impl.getGraphIndex();
delete impl.getGraphNode();
impl.setGraphNode(nullptr);
// Remove this type variable from the list.
unsigned lastIndex = TypeVariables.size()-1;
if (index < lastIndex)
TypeVariables[index] = TypeVariables[lastIndex];
TypeVariables.pop_back();
}
void ConstraintGraph::addConstraint(Constraint *constraint) {
// For the nodes corresponding to each type variable...
auto referencedTypeVars = constraint->getTypeVariables();
for (auto typeVar : referencedTypeVars) {
// Find the node for this type variable.
auto &node = (*this)[typeVar];
// Note the constraint within the node for that type variable.
node.addConstraint(constraint);
// Record the adjacent type variables.
// This is O(N^2) in the number of referenced type variables, because
// we're updating all of the adjacent type variables eagerly.
for (auto otherTypeVar : referencedTypeVars) {
if (typeVar == otherTypeVar)
continue;
node.addAdjacency(otherTypeVar);
}
}
// If the constraint doesn't reference any type variables, it's orphaned;
// track it as such.
if (referencedTypeVars.empty()) {
OrphanedConstraints.push_back(constraint);
}
// Record the change, if there are active scopes.
if (ActiveScope)
Changes.push_back(Change::addedConstraint(constraint));
}
void ConstraintGraph::removeConstraint(Constraint *constraint) {
// For the nodes corresponding to each type variable...
auto referencedTypeVars = constraint->getTypeVariables();
for (auto typeVar : referencedTypeVars) {
// Find the node for this type variable.
auto &node = (*this)[typeVar];
// Remove the constraint.
node.removeConstraint(constraint);
// Remove the adjacencies for all adjacent type variables.
// This is O(N^2) in the number of referenced type variables, because
// we're updating all of the adjacent type variables eagerly.
for (auto otherTypeVar : referencedTypeVars) {
if (typeVar == otherTypeVar)
continue;
node.removeAdjacency(otherTypeVar);
}
}
// If this is an orphaned constraint, remove it from the list.
if (referencedTypeVars.empty()) {
auto known = std::find(OrphanedConstraints.begin(),
OrphanedConstraints.end(),
constraint);
assert(known != OrphanedConstraints.end() && "missing orphaned constraint");
*known = OrphanedConstraints.back();
OrphanedConstraints.pop_back();
}
// Record the change, if there are active scopes.
if (ActiveScope)
Changes.push_back(Change::removedConstraint(constraint));
}
void ConstraintGraph::mergeNodes(TypeVariableType *typeVar1,
TypeVariableType *typeVar2) {
assert(CS.getRepresentative(typeVar1) == CS.getRepresentative(typeVar2) &&
"type representatives don't match");
// Retrieve the node for the representative that we're merging into.
auto typeVarRep = CS.getRepresentative(typeVar1);
auto &repNode = (*this)[typeVarRep];
// Retrieve the node for the non-representative.
assert((typeVar1 == typeVarRep || typeVar2 == typeVarRep) &&
"neither type variable is the new representative?");
auto typeVarNonRep = typeVar1 == typeVarRep? typeVar2 : typeVar1;
// Record the change, if there are active scopes.
if (ActiveScope)
Changes.push_back(Change::extendedEquivalenceClass(
typeVarRep,
repNode.getEquivalenceClass().size()));
// Merge equivalence class from the non-representative type variable.
auto &nonRepNode = (*this)[typeVarNonRep];
repNode.addToEquivalenceClass(nonRepNode.getEquivalenceClassUnsafe());
}
void ConstraintGraph::bindTypeVariable(TypeVariableType *typeVar, Type fixed) {
// If there are no type variables in the fixed type, there's nothing to do.
if (!fixed->hasTypeVariable())
return;
SmallVector<TypeVariableType *, 4> typeVars;
llvm::SmallPtrSet<TypeVariableType *, 4> knownTypeVars;
fixed->getTypeVariables(typeVars);
auto &node = (*this)[typeVar];
for (auto otherTypeVar : typeVars) {
if (knownTypeVars.insert(otherTypeVar).second) {
if (typeVar == otherTypeVar) continue;
(*this)[otherTypeVar].addFixedBinding(typeVar);
node.addFixedBinding(otherTypeVar);
}
}
// Record the change, if there are active scopes.
// Note: If we ever use this to undo the actual variable binding,
// we'll need to store the change along the early-exit path as well.
if (ActiveScope)
Changes.push_back(Change::boundTypeVariable(typeVar, fixed));
}
void ConstraintGraph::unbindTypeVariable(TypeVariableType *typeVar, Type fixed){
// If there are no type variables in the fixed type, there's nothing to do.
if (!fixed->hasTypeVariable())
return;
SmallVector<TypeVariableType *, 4> typeVars;
llvm::SmallPtrSet<TypeVariableType *, 4> knownTypeVars;
fixed->getTypeVariables(typeVars);
auto &node = (*this)[typeVar];
for (auto otherTypeVar : typeVars) {
if (knownTypeVars.insert(otherTypeVar).second) {
(*this)[otherTypeVar].removeFixedBinding(typeVar);
node.removeFixedBinding(otherTypeVar);
}
}
}
void ConstraintGraph::gatherConstraints(
TypeVariableType *typeVar, llvm::SetVector<Constraint *> &constraints,
GatheringKind kind,
llvm::function_ref<bool(Constraint *)> acceptConstraint) {
auto &reprNode = (*this)[CS.getRepresentative(typeVar)];
auto equivClass = reprNode.getEquivalenceClass();
llvm::SmallPtrSet<TypeVariableType *, 4> typeVars;
for (auto typeVar : equivClass) {
if (!typeVars.insert(typeVar).second)
continue;
for (auto constraint : (*this)[typeVar].getConstraints()) {
if (acceptConstraint(constraint))
constraints.insert(constraint);
}
auto &node = (*this)[typeVar];
// Retrieve the constraints from adjacent bindings.
for (auto adjTypeVar : node.getAdjacencies()) {
switch (kind) {
case GatheringKind::EquivalenceClass:
if (!node.getAdjacency(adjTypeVar).FixedBinding)
continue;
break;
case GatheringKind::AllMentions:
break;
}
ArrayRef<TypeVariableType *> adjTypeVarsToVisit;
switch (kind) {
case GatheringKind::EquivalenceClass:
adjTypeVarsToVisit = adjTypeVar;
break;
case GatheringKind::AllMentions:
adjTypeVarsToVisit
= (*this)[CS.getRepresentative(adjTypeVar)].getEquivalenceClass();
break;
}
for (auto adjTypeVarEquiv : adjTypeVarsToVisit) {
if (!typeVars.insert(adjTypeVarEquiv).second)
continue;
for (auto constraint : (*this)[adjTypeVarEquiv].getConstraints()) {
if (acceptConstraint(constraint))
constraints.insert(constraint);
}
}
}
}
}
#pragma mark Algorithms
/// Depth-first search for connected components
static void connectedComponentsDFS(ConstraintGraph &cg,
ConstraintGraphNode &node,
unsigned component,
SmallVectorImpl<unsigned> &components) {
// Local function that recurses on the given set of type variables.
auto visitAdjacencies = [&](ArrayRef<TypeVariableType *> typeVars) {
for (auto adj : typeVars) {
auto nodeAndIndex = cg.lookupNode(adj);
// If we've already seen this node in this component, we're done.
unsigned &curComponent = components[nodeAndIndex.second];
if (curComponent == component)
continue;
// Mark this node as part of this connected component, then recurse.
assert(curComponent == components.size() && "Already in a component?");
curComponent = component;
connectedComponentsDFS(cg, nodeAndIndex.first, component, components);
}
};
// Recurse to mark adjacent nodes as part of this connected component.
visitAdjacencies(node.getAdjacencies());
// Figure out the representative for this type variable.
auto &cs = cg.getConstraintSystem();
auto typeVarRep = cs.getRepresentative(node.getTypeVariable());
if (typeVarRep == node.getTypeVariable()) {
// This type variable is the representative of its set; visit all of the
// other type variables in the same equivalence class.
visitAdjacencies(node.getEquivalenceClass().slice(1));
} else {
// Otherwise, visit the representative of the set.
visitAdjacencies(typeVarRep);
}
}
unsigned ConstraintGraph::computeConnectedComponents(
SmallVectorImpl<TypeVariableType *> &typeVars,
SmallVectorImpl<unsigned> &components) {
// Track those type variables that the caller cares about.
llvm::SmallPtrSet<TypeVariableType *, 4> typeVarSubset(typeVars.begin(),
typeVars.end());
typeVars.clear();
// Initialize the components with component == # of type variables,
// a sentinel value indicating
unsigned numTypeVariables = TypeVariables.size();
components.assign(numTypeVariables, numTypeVariables);
// Perform a depth-first search from each type variable to identify
// what component it is in.
unsigned numComponents = 0;
for (unsigned i = 0; i != numTypeVariables; ++i) {
auto typeVar = TypeVariables[i];
// Look up the node for this type variable.
auto nodeAndIndex = lookupNode(typeVar);
// If we're already assigned a component for this node, skip it.
unsigned &curComponent = components[nodeAndIndex.second];
if (curComponent != numTypeVariables)
continue;
// Record this component.
unsigned component = numComponents++;
// Note that this node is part of this component, then visit it.
curComponent = component;
connectedComponentsDFS(*this, nodeAndIndex.first, component, components);
}
// Figure out which components have unbound type variables; these
// are the only components and type variables we want to report.
SmallVector<bool, 4> componentHasUnboundTypeVar(numComponents, false);
for (unsigned i = 0; i != numTypeVariables; ++i) {
// If this type variable has a fixed type, skip it.
if (CS.getFixedType(TypeVariables[i]))
continue;
// If this type variable isn't in the subset of type variables we care
// about, skip it.
if (typeVarSubset.count(TypeVariables[i]) == 0)
continue;
componentHasUnboundTypeVar[components[i]] = true;
}
// Renumber the old components to the new components.
SmallVector<unsigned, 4> componentRenumbering(numComponents, 0);
numComponents = 0;
for (unsigned i = 0, n = componentHasUnboundTypeVar.size(); i != n; ++i) {
// Skip components that have no unbound type variables.
if (!componentHasUnboundTypeVar[i])
continue;
componentRenumbering[i] = numComponents++;
}
// Copy over the type variables in the live components and remap
// component numbers.
unsigned outIndex = 0;
for (unsigned i = 0, n = TypeVariables.size(); i != n; ++i) {
// Skip type variables in dead components.
if (!componentHasUnboundTypeVar[components[i]])
continue;
typeVars.push_back(TypeVariables[i]);
components[outIndex] = componentRenumbering[components[i]];
++outIndex;
}
components.erase(components.begin() + outIndex, components.end());
return numComponents + getOrphanedConstraints().size();
}
/// For a given constraint kind, decide if we should attempt to eliminate its
/// edge in the graph.
static bool shouldContractEdge(ConstraintKind kind) {
switch (kind) {
case ConstraintKind::Bind:
case ConstraintKind::BindParam:
case ConstraintKind::BindToPointerType:
case ConstraintKind::Equal:
return true;
default:
return false;
}
}
bool ConstraintGraph::contractEdges() {
SmallVector<Constraint *, 16> constraints;
CS.findConstraints(constraints, [&](const Constraint &constraint) {
// Track how many constraints did contraction algorithm iterated over.
incrementConstraintsPerContractionCounter();
return shouldContractEdge(constraint.getKind());
});
bool didContractEdges = false;
for (auto *constraint : constraints) {
auto kind = constraint->getKind();
// Contract binding edges between type variables.
assert(shouldContractEdge(kind));
auto t1 = constraint->getFirstType()->getDesugaredType();
auto t2 = constraint->getSecondType()->getDesugaredType();
auto tyvar1 = t1->getAs<TypeVariableType>();
auto tyvar2 = t2->getAs<TypeVariableType>();
if (!(tyvar1 && tyvar2))
continue;
auto isParamBindingConstraint = kind == ConstraintKind::BindParam;
// If the argument is allowed to bind to `inout`, in general,
// it's invalid to contract the edge between argument and parameter,
// but if we can prove that there are no possible bindings
// which result in attempt to bind `inout` type to argument
// type variable, we should go ahead and allow (temporary)
// contraction, because that greatly helps with performance.
// Such action is valid because argument type variable can
// only get its bindings from related overload, which gives
// us enough information to decided on l-valueness.
if (isParamBindingConstraint && tyvar1->getImpl().canBindToInOut()) {
bool isNotContractable = true;
if (auto bindings = CS.getPotentialBindings(tyvar1)) {
for (auto &binding : bindings.Bindings) {
auto type = binding.BindingType;
isNotContractable = type.findIf([&](Type nestedType) -> bool {
if (auto tv = nestedType->getAs<TypeVariableType>()) {
if (!tv->getImpl().mustBeMaterializable())
return true;
}
return nestedType->is<InOutType>();
});
// If there is at least one non-contractable binding, let's
// not risk contracting this edge.
if (isNotContractable)
break;
}
}
if (isNotContractable)
continue;
}
auto rep1 = CS.getRepresentative(tyvar1);
auto rep2 = CS.getRepresentative(tyvar2);
if (((rep1->getImpl().canBindToLValue() ==
rep2->getImpl().canBindToLValue()) ||
// Allow l-value contractions when binding parameter types.
isParamBindingConstraint)) {
if (CS.TC.getLangOpts().DebugConstraintSolver) {
auto &log = CS.getASTContext().TypeCheckerDebug->getStream();
if (CS.solverState)
log.indent(CS.solverState->depth * 2);
log << "Contracting constraint ";
constraint->print(log, &CS.getASTContext().SourceMgr);
log << "\n";
}
// Merge the edges and remove the constraint.
removeEdge(constraint);
if (rep1 != rep2)
CS.mergeEquivalenceClasses(rep1, rep2, /*updateWorkList*/ false);
didContractEdges = true;
}
}
return didContractEdges;
}
void ConstraintGraph::removeEdge(Constraint *constraint) {
bool isExistingConstraint = false;
for (auto &active : CS.ActiveConstraints) {
if (&active == constraint) {
CS.ActiveConstraints.erase(constraint);
isExistingConstraint = true;
break;
}
}
for (auto &inactive : CS.InactiveConstraints) {
if (&inactive == constraint) {
CS.InactiveConstraints.erase(constraint);
isExistingConstraint = true;
break;
}
}
if (CS.solverState) {
if (isExistingConstraint)
CS.solverState->retireConstraint(constraint);
else
CS.solverState->removeGeneratedConstraint(constraint);
}
removeConstraint(constraint);
}
void ConstraintGraph::optimize() {
// Merge equivalence classes until a fixed point is reached.
while (contractEdges()) {}
}
void ConstraintGraph::incrementConstraintsPerContractionCounter() {
SWIFT_FUNC_STAT;
auto &context = CS.getASTContext();
if (context.Stats)
context.Stats->getFrontendCounters()
.NumConstraintsConsideredForEdgeContraction++;
}
#pragma mark Debugging output
void ConstraintGraphNode::print(llvm::raw_ostream &out, unsigned indent) {
out.indent(indent);
TypeVar->print(out);
out << ":\n";
// Print constraints.
if (!Constraints.empty()) {
out.indent(indent + 2);
out << "Constraints:\n";
SmallVector<Constraint *, 4> sortedConstraints(Constraints.begin(),
Constraints.end());
std::sort(sortedConstraints.begin(), sortedConstraints.end());
for (auto constraint : sortedConstraints) {
out.indent(indent + 4);
constraint->print(out, &TypeVar->getASTContext().SourceMgr);
out << "\n";
}
}
// Print adjacencies.
if (!Adjacencies.empty()) {
out.indent(indent + 2);
out << "Adjacencies:";
SmallVector<TypeVariableType *, 4> sortedAdjacencies(Adjacencies.begin(),
Adjacencies.end());
std::sort(sortedAdjacencies.begin(), sortedAdjacencies.end(),
[&](TypeVariableType *typeVar1, TypeVariableType *typeVar2) {
return typeVar1->getID() < typeVar2->getID();
});
for (auto adj : sortedAdjacencies) {
out << ' ';
adj->print(out);
auto &info = AdjacencyInfo[adj];
auto degree = info.NumConstraints;
if (degree > 1 || info.FixedBinding) {
out << " (";
if (degree > 1) {
out << degree;
if (info.FixedBinding)
out << ", fixed";
} else {
out << "fixed";
}
out << ")";
}
}
out << "\n";
}
// Print equivalence class.
if (TypeVar->getImpl().getRepresentative(nullptr) == TypeVar &&
EquivalenceClass.size() > 1) {
out.indent(indent + 2);
out << "Equivalence class:";
for (unsigned i = 1, n = EquivalenceClass.size(); i != n; ++i) {
out << ' ';
EquivalenceClass[i]->print(out);
}
out << "\n";
}
}
void ConstraintGraphNode::dump() {
llvm::SaveAndRestore<bool>
debug(TypeVar->getASTContext().LangOpts.DebugConstraintSolver, true);
print(llvm::dbgs(), 0);
}
void ConstraintGraph::print(llvm::raw_ostream &out) {
for (auto typeVar : TypeVariables) {
(*this)[typeVar].print(out, 2);
out << "\n";
}
}
void ConstraintGraph::dump() {
llvm::SaveAndRestore<bool>
debug(CS.getASTContext().LangOpts.DebugConstraintSolver, true);
print(llvm::dbgs());
}
void ConstraintGraph::printConnectedComponents(llvm::raw_ostream &out) {
SmallVector<TypeVariableType *, 16> typeVars;
typeVars.append(TypeVariables.begin(), TypeVariables.end());
SmallVector<unsigned, 16> components;
unsigned numComponents = computeConnectedComponents(typeVars, components);
for (unsigned component = 0; component != numComponents; ++component) {
out.indent(2);
out << component << ":";
for (unsigned i = 0, n = typeVars.size(); i != n; ++i) {
if (components[i] == component) {
out << ' ';
typeVars[i]->print(out);
}
}
out << '\n';
}
}
void ConstraintGraph::dumpConnectedComponents() {
printConnectedComponents(llvm::dbgs());
}
#pragma mark Verification of graph invariants
/// Require that the given condition evaluate true.
///
/// If the condition is not true, complain about the problem and abort.
///
/// \param condition The actual Boolean condition.
///
/// \param complaint A string that describes the problem.
///
/// \param cg The constraint graph that failed verification.
///
/// \param node If non-null, the graph node that failed verification.
///
/// \param extraContext If provided, a function that will be called to
/// provide extra, contextual information about the failure.
static void _require(bool condition, const Twine &complaint,
ConstraintGraph &cg,
ConstraintGraphNode *node,
const std::function<void()> &extraContext = nullptr) {
if (condition)
return;
// Complain
llvm::dbgs() << "Constraint graph verification failed: " << complaint << '\n';
if (extraContext)
extraContext();
// Print the graph.
// FIXME: Highlight the offending node/constraint/adjacency/etc.
cg.print(llvm::dbgs());
abort();
}
/// Print a type variable value.
static void printValue(llvm::raw_ostream &os, TypeVariableType *typeVar) {
typeVar->print(os);
}
/// Print a constraint value.
static void printValue(llvm::raw_ostream &os, Constraint *constraint) {
constraint->print(os, nullptr);
}
/// Print an unsigned value.
static void printValue(llvm::raw_ostream &os, unsigned value) {
os << value;
}
void ConstraintGraphNode::verify(ConstraintGraph &cg) {
#define require(condition, complaint) _require(condition, complaint, cg, this)
#define requireWithContext(condition, complaint, context) \
_require(condition, complaint, cg, this, context)
#define requireSameValue(value1, value2, complaint) \
_require(value1 == value2, complaint, cg, this, [&] { \
llvm::dbgs() << " "; \
printValue(llvm::dbgs(), value1); \
llvm::dbgs() << " != "; \
printValue(llvm::dbgs(), value2); \
llvm::dbgs() << '\n'; \
})
// Verify that the constraint map/vector haven't gotten out of sync.
requireSameValue(Constraints.size(), ConstraintIndex.size(),
"constraint vector and map have different sizes");
for (auto info : ConstraintIndex) {
require(info.second < Constraints.size(), "constraint index out-of-range");
requireSameValue(info.first, Constraints[info.second],
"constraint map provides wrong index into vector");
}
// Verify that the adjacency map/vector haven't gotten out of sync.
requireSameValue(Adjacencies.size(), AdjacencyInfo.size(),
"adjacency vector and map have different sizes");
for (auto info : AdjacencyInfo) {
require(info.second.Index < Adjacencies.size(),
"adjacency index out-of-range");
requireSameValue(info.first, Adjacencies[info.second.Index],
"adjacency map provides wrong index into vector");
require(!info.second.empty(),
"adjacency information should have been removed");
require(info.second.NumConstraints <= Constraints.size(),
"adjacency information has higher degree than # of constraints");
}
// Based on the constraints we have, build up a representation of what
// we expect the adjacencies to look like.
llvm::DenseMap<TypeVariableType *, unsigned> expectedAdjacencies;
for (auto constraint : Constraints) {
for (auto adjTypeVar : constraint->getTypeVariables()) {
if (adjTypeVar == TypeVar)
continue;
++expectedAdjacencies[adjTypeVar];
}
}
// Make sure that the adjacencies we expect are the adjacencies we have.
for (auto adj : expectedAdjacencies) {
auto knownAdj = AdjacencyInfo.find(adj.first);
requireWithContext(knownAdj != AdjacencyInfo.end(),
"missing adjacency information for type variable",
[&] {
llvm::dbgs() << " type variable=" << adj.first->getString() << 'n';
});