Skip to content

Commit 24e5a82

Browse files
authored
Merge pull request #76921 from slavapestov/cstrail-part-5
Sema: Finish hollowing out SolverScope
2 parents a0a77fa + e9add92 commit 24e5a82

File tree

11 files changed

+193
-293
lines changed

11 files changed

+193
-293
lines changed

include/swift/Sema/CSTrail.def

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,18 @@
3030
#define CLOSURE_CHANGE(Name) CHANGE(Name)
3131
#endif
3232

33+
#ifndef CONSTRAINT_CHANGE
34+
#define CONSTRAINT_CHANGE(Name) CHANGE(Name)
35+
#endif
36+
37+
#ifndef GRAPH_NODE_CHANGE
38+
#define GRAPH_NODE_CHANGE(Name) CHANGE(Name)
39+
#endif
40+
41+
#ifndef SCORE_CHANGE
42+
#define SCORE_CHANGE(Name) CHANGE(Name)
43+
#endif
44+
3345
#ifndef LAST_CHANGE
3446
#define LAST_CHANGE(Name)
3547
#endif
@@ -54,13 +66,22 @@ EXPR_CHANGE(RecordedExprPattern)
5466
CLOSURE_CHANGE(RecordedClosureType)
5567
CLOSURE_CHANGE(RecordedPreconcurrencyClosure)
5668

69+
CONSTRAINT_CHANGE(DisabledConstraint)
70+
CONSTRAINT_CHANGE(FavoredConstraint)
71+
CONSTRAINT_CHANGE(GeneratedConstraint)
72+
CONSTRAINT_CHANGE(RetiredConstraint)
73+
74+
GRAPH_NODE_CHANGE(AddedConstraint)
75+
GRAPH_NODE_CHANGE(RemovedConstraint)
76+
GRAPH_NODE_CHANGE(InferredBindings)
77+
GRAPH_NODE_CHANGE(RetractedBindings)
78+
79+
SCORE_CHANGE(IncreasedScore)
80+
SCORE_CHANGE(DecreasedScore)
81+
5782
CHANGE(AddedTypeVariable)
58-
CHANGE(AddedConstraint)
59-
CHANGE(RemovedConstraint)
6083
CHANGE(ExtendedEquivalenceClass)
6184
CHANGE(RelatedTypeVariables)
62-
CHANGE(InferredBindings)
63-
CHANGE(RetractedBindings)
6485
CHANGE(UpdatedTypeVariable)
6586
CHANGE(AddedConversionRestriction)
6687
CHANGE(AddedFix)
@@ -69,8 +90,6 @@ CHANGE(RecordedOpenedPackExpansionType)
6990
CHANGE(RecordedPackEnvironment)
7091
CHANGE(RecordedNodeType)
7192
CHANGE(RecordedKeyPathComponentType)
72-
CHANGE(DisabledConstraint)
73-
CHANGE(FavoredConstraint)
7493
CHANGE(RecordedResultBuilderTransform)
7594
CHANGE(RecordedContextualInfo)
7695
CHANGE(RecordedTarget)
@@ -84,5 +103,8 @@ LAST_CHANGE(RecordedKeyPath)
84103
#undef LOCATOR_CHANGE
85104
#undef EXPR_CHANGE
86105
#undef CLOSURE_CHANGE
106+
#undef CONSTRAINT_CHANGE
107+
#undef GRAPH_NODE_CHANGE
108+
#undef SCORE_CHANGE
87109
#undef LAST_CHANGE
88110
#undef CHANGE

include/swift/Sema/CSTrail.h

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -142,17 +142,15 @@ class SolverTrail {
142142
#define LOCATOR_CHANGE(Name, _) static Change Name(ConstraintLocator *locator);
143143
#define EXPR_CHANGE(Name) static Change Name(Expr *expr);
144144
#define CLOSURE_CHANGE(Name) static Change Name(ClosureExpr *closure);
145+
#define CONSTRAINT_CHANGE(Name) static Change Name(Constraint *constraint);
146+
#define SCORE_CHANGE(Name) static Change Name(ScoreKind kind, unsigned value);
147+
#define GRAPH_NODE_CHANGE(Name) static Change Name(TypeVariableType *typeVar, \
148+
Constraint *constraint);
145149
#include "swift/Sema/CSTrail.def"
146150

147151
/// Create a change that added a type variable.
148152
static Change AddedTypeVariable(TypeVariableType *typeVar);
149153

150-
/// Create a change that added a constraint.
151-
static Change AddedConstraint(TypeVariableType *typeVar, Constraint *constraint);
152-
153-
/// Create a change that removed a constraint.
154-
static Change RemovedConstraint(TypeVariableType *typeVar, Constraint *constraint);
155-
156154
/// Create a change that extended an equivalence class.
157155
static Change ExtendedEquivalenceClass(TypeVariableType *typeVar,
158156
unsigned prevSize);
@@ -162,14 +160,6 @@ class SolverTrail {
162160
static Change RelatedTypeVariables(TypeVariableType *typeVar,
163161
TypeVariableType *otherTypeVar);
164162

165-
/// Create a change that inferred bindings from a constraint.
166-
static Change InferredBindings(TypeVariableType *typeVar,
167-
Constraint *constraint);
168-
169-
/// Create a change that retracted bindings from a constraint.
170-
static Change RetractedBindings(TypeVariableType *typeVar,
171-
Constraint *constraint);
172-
173163
/// Create a change that updated a type variable.
174164
static Change UpdatedTypeVariable(
175165
TypeVariableType *typeVar,
@@ -202,12 +192,6 @@ class SolverTrail {
202192
unsigned component,
203193
Type oldType);
204194

205-
/// Create a change that disabled a constraint.
206-
static Change DisabledConstraint(Constraint *constraint);
207-
208-
/// Create a change that favored a constraint.
209-
static Change FavoredConstraint(Constraint *constraint);
210-
211195
/// Create a change that recorded a result builder transform.
212196
static Change RecordedResultBuilderTransform(AnyFunctionRef fn);
213197

include/swift/Sema/ConstraintSystem.h

Lines changed: 18 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,13 +1045,15 @@ struct Score {
10451045
friend Score operator-(const Score &x, const Score &y) {
10461046
Score result;
10471047
for (unsigned i = 0; i != NumScoreKinds; ++i) {
1048+
ASSERT(x.Data[i] >= y.Data[i]);
10481049
result.Data[i] = x.Data[i] - y.Data[i];
10491050
}
10501051
return result;
10511052
}
10521053

10531054
friend Score &operator-=(Score &x, const Score &y) {
10541055
for (unsigned i = 0; i != NumScoreKinds; ++i) {
1056+
ASSERT(x.Data[i] >= y.Data[i]);
10551057
x.Data[i] -= y.Data[i];
10561058
}
10571059
return x;
@@ -2531,98 +2533,47 @@ class ConstraintSystem {
25312533
/// The number of the solution attempts we're looking at.
25322534
unsigned SolutionAttempt;
25332535

2534-
/// Refers to the innermost partial solution scope.
2535-
SolverScope *PartialSolutionScope = nullptr;
2536+
/// The number of fixes in the innermost partial solution scope.
2537+
unsigned numPartialSolutionFixes = 0;
25362538

25372539
// Statistics
25382540
#define CS_STATISTIC(Name, Description) unsigned Name = 0;
25392541
#include "ConstraintSolverStats.def"
25402542

2541-
/// Check whether there are any retired constraints present.
2542-
bool hasRetiredConstraints() const {
2543-
return !retiredConstraints.empty();
2544-
}
2545-
25462543
/// Mark given constraint as retired along current solver path.
25472544
///
25482545
/// \param constraint The constraint to retire temporarily.
25492546
void retireConstraint(Constraint *constraint) {
2550-
retiredConstraints.push_front(constraint);
2551-
}
2552-
2553-
/// Iterate over all of the retired constraints registered with
2554-
/// current solver state.
2555-
///
2556-
/// \param processor The processor function to be applied to each of
2557-
/// the constraints retrieved.
2558-
void forEachRetired(llvm::function_ref<void(Constraint &)> processor) {
2559-
for (auto &constraint : retiredConstraints)
2560-
processor(constraint);
2547+
Trail.recordChange(SolverTrail::Change::RetiredConstraint(constraint));
25612548
}
25622549

25632550
/// Add new "generated" constraint along the current solver path.
25642551
///
25652552
/// \param constraint The newly generated constraint.
25662553
void addGeneratedConstraint(Constraint *constraint) {
2567-
assert(constraint && "Null generated constraint?");
2568-
generatedConstraints.push_back(constraint);
2554+
Trail.recordChange(SolverTrail::Change::GeneratedConstraint(constraint));
25692555
}
25702556

2571-
/// Register given scope to be tracked by the current solver state,
2572-
/// this helps to make sure that all of the retired/generated constraints
2573-
/// are dealt with correctly when the life time of the scope ends.
2557+
/// Update statistics when a scope begins.
25742558
///
25752559
/// \param scope The scope to associate with current solver state.
2576-
void registerScope(SolverScope *scope) {
2560+
void beginScope(SolverScope *scope) {
25772561
++depth;
25782562
maxDepth = std::max(maxDepth, depth);
25792563
scope->scopeNumber = NumStatesExplored++;
25802564

25812565
CS.incrementScopeCounter();
2582-
auto scopeInfo =
2583-
std::make_tuple(scope, retiredConstraints.begin(),
2584-
generatedConstraints.size());
2585-
scopes.push_back(scopeInfo);
25862566
}
25872567

2588-
/// Restore all of the retired/generated constraints to the state
2589-
/// before given scope. This is required because retired constraints have
2590-
/// to be re-introduced to the system in order of arrival (LIFO) and list
2591-
/// of the generated constraints has to be truncated back to the
2592-
/// original size.
2568+
/// Update statistics when a scope ends.
25932569
///
25942570
/// \param scope The solver scope to rollback.
2595-
void rollback(SolverScope *scope) {
2571+
void endScope(SolverScope *scope) {
25962572
--depth;
25972573

25982574
unsigned countScopesExplored = NumStatesExplored - scope->scopeNumber;
25992575
if (countScopesExplored == 1)
26002576
CS.incrementLeafScopes();
2601-
2602-
SolverScope *savedScope;
2603-
// The position of last retired constraint before given scope.
2604-
ConstraintList::iterator lastRetiredPos;
2605-
// The original number of generated constraints before given scope.
2606-
unsigned numGenerated;
2607-
2608-
std::tie(savedScope, lastRetiredPos, numGenerated) =
2609-
scopes.pop_back_val();
2610-
2611-
assert(savedScope == scope && "Scope rollback not in LIFO order!");
2612-
2613-
// Restore all of the retired constraints.
2614-
CS.InactiveConstraints.splice(CS.InactiveConstraints.end(),
2615-
retiredConstraints,
2616-
retiredConstraints.begin(), lastRetiredPos);
2617-
2618-
// And remove all of the generated constraints.
2619-
auto genStart = generatedConstraints.begin() + numGenerated,
2620-
genEnd = generatedConstraints.end();
2621-
for (auto genI = genStart; genI != genEnd; ++genI) {
2622-
CS.InactiveConstraints.erase(ConstraintList::iterator(*genI));
2623-
}
2624-
2625-
generatedConstraints.erase(genStart, genEnd);
26262577
}
26272578

26282579
/// Check whether constraint system is allowed to form solutions
@@ -2649,29 +2600,12 @@ class ConstraintSystem {
26492600
}
26502601

26512602
private:
2652-
/// The list of constraints that have been retired along the
2653-
/// current path, this list is used in LIFO fashion when
2654-
/// constraints are added back to the circulation.
2655-
ConstraintList retiredConstraints;
2603+
/// Depth of the solution stack.
2604+
unsigned depth = 0;
26562605

26572606
/// The set of constraints which were active at the time of this state
26582607
/// creating, it's used to re-activate them on destruction.
26592608
SmallVector<Constraint *, 4> activeConstraints;
2660-
2661-
/// The current set of generated constraints.
2662-
SmallVector<Constraint *, 4> generatedConstraints;
2663-
2664-
/// The collection which holds association between solver scope
2665-
/// and position of the last retired constraint and number of
2666-
/// constraints generated before registration of given scope,
2667-
/// this helps to rollback all of the constraints retired/generated
2668-
/// each of the registered scopes correct (LIFO) order.
2669-
llvm::SmallVector<
2670-
std::tuple<SolverScope *, ConstraintList::iterator, unsigned>, 4> scopes;
2671-
2672-
2673-
/// Depth of the solution stack.
2674-
unsigned depth = 0;
26752609
};
26762610

26772611
class CacheExprTypes : public ASTWalker {
@@ -2850,14 +2784,6 @@ class ConstraintSystem {
28502784
/// The length of \c Trail.
28512785
unsigned numTrailChanges;
28522786

2853-
/// The length of \c Fixes.
2854-
///
2855-
/// FIXME: Remove this.
2856-
unsigned numFixes;
2857-
2858-
/// The previous score.
2859-
Score PreviousScore;
2860-
28612787
/// The scope number of this scope. Set when the scope is registered.
28622788
unsigned scopeNumber = 0;
28632789

@@ -2903,7 +2829,8 @@ class ConstraintSystem {
29032829
/// This operation is used to take a solution computed based on some
29042830
/// subset of the constraints and then apply it back to the
29052831
/// constraint system for further exploration.
2906-
void applySolution(const Solution &solution);
2832+
void replaySolution(const Solution &solution,
2833+
bool shouldIncreaseScore=true);
29072834

29082835
// FIXME: Perhaps these belong on ConstraintSystem itself.
29092836
friend std::optional<BraceStmt *>
@@ -5531,10 +5458,13 @@ class ConstraintSystem {
55315458

55325459
public:
55335460
/// Increase the score of the given kind for the current (partial) solution
5534-
/// along the.
5461+
/// along the current solver path.
55355462
void increaseScore(ScoreKind kind, ConstraintLocatorBuilder Locator,
55365463
unsigned value = 1);
55375464

5465+
/// Primitive form of the above. Records a change in the trail.
5466+
void increaseScore(ScoreKind kind, unsigned value);
5467+
55385468
/// Determine whether this solution is guaranteed to be worse than the best
55395469
/// solution found so far.
55405470
bool worseThanBestSolution() const;

lib/Sema/BuilderTransform.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1082,7 +1082,7 @@ TypeChecker::applyResultBuilderBodyTransform(FuncDecl *func, Type builderType) {
10821082
}
10831083

10841084
// FIXME: Shouldn't need to do this.
1085-
cs.applySolution(solutions.front());
1085+
cs.replaySolution(solutions.front());
10861086

10871087
// Apply the solution to the function body.
10881088
if (auto result = cs.applySolution(solutions.front(), target)) {

lib/Sema/CSRanking.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,14 @@ static bool shouldIgnoreScoreIncreaseForCodeCompletion(
110110
return false;
111111
}
112112

113+
void ConstraintSystem::increaseScore(ScoreKind kind, unsigned value) {
114+
unsigned index = static_cast<unsigned>(kind);
115+
CurrentScore.Data[index] += value;
116+
117+
if (solverState && value > 0)
118+
recordChange(SolverTrail::Change::IncreasedScore(kind, value));
119+
}
120+
113121
void ConstraintSystem::increaseScore(ScoreKind kind,
114122
ConstraintLocatorBuilder Locator,
115123
unsigned value) {
@@ -135,8 +143,7 @@ void ConstraintSystem::increaseScore(ScoreKind kind,
135143
llvm::errs() << ")\n";
136144
}
137145

138-
unsigned index = static_cast<unsigned>(kind);
139-
CurrentScore.Data[index] += value;
146+
increaseScore(kind, value);
140147
}
141148

142149
bool ConstraintSystem::worseThanBestSolution() const {

lib/Sema/CSSimplify.cpp

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15032,9 +15032,12 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifyFixConstraint(
1503215032
SmallVector<Type, 4> unwraps2;
1503315033
type2->lookThroughAllOptionalTypes(unwraps2);
1503415034

15035-
auto impact = unwraps1.size() != unwraps2.size()
15036-
? unwraps1.size() - unwraps2.size()
15037-
: 1;
15035+
unsigned impact = 1;
15036+
if (unwraps1.size() > unwraps2.size())
15037+
impact = unwraps1.size() - unwraps2.size();
15038+
else if (unwraps2.size() > unwraps1.size())
15039+
impact = unwraps2.size() - unwraps1.size();
15040+
1503815041
return recordFix(fix, impact) ? SolutionKind::Error : SolutionKind::Solved;
1503915042
}
1504015043

0 commit comments

Comments
 (0)