Repository navigation
Bound the copies of 'when' guards in compiled pattern matches #20718
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
cc2a09c
fcf4f67
0e77160
bc838ab
4551c4a
c8c0261
dd01cb0
c4f1e76
cc97109
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1080,11 +1080,76 @@ let mkThrowUsingEDICapture (infoReader: InfoReader) tcVal m resultTy exnExpr = | |
| | _ -> | ||
| mkThrow m resultTy exnExpr | ||
|
|
||
| exception private GuardCopyBudgetExceeded | ||
|
|
||
| /// Whether the input is read through an immutable byref. A struct union input read this way is tested | ||
| /// in place, not through a copy. | ||
| let private isCopyableInputExpr origInputExpr = | ||
| match origInputExpr with | ||
| | Expr.Op (TOp.LValueOp (LByrefGet, v), [], [], _) when not v.IsMutable -> true | ||
| | _ -> false | ||
|
|
||
| /// Whether the pattern tests an array element or a mutable record field, which a 'when' guard can write. | ||
| let rec private testsMutableData inpPat = | ||
| match inpPat with | ||
| | TPat_array _ -> true | ||
| | TPat_recd (tcref, _, subPats, _) -> | ||
| (tcref.TrueInstanceFieldsAsList, subPats) | ||
| ||> List.exists2 (fun field subPat -> | ||
| match subPat with | ||
| | TPat_wild _ -> false | ||
| | _ -> field.IsMutable || testsMutableData subPat) | ||
| | TPat_query (_, subPat, _) | ||
| | TPat_as (subPat, _, _) -> testsMutableData subPat | ||
|
Comment on lines
+1102
to
+1103
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The cut can still change which rule a match picks when a total active pattern reads data that a guard writes, because this arm only checks the patterns on the active pattern's result. Here is the array case from let (|Elems|) (a: int[]) = a.[0], a.[1]
let array (arr: int[]) col =
match arr with
| Elems (0, 0) when (arr.[0] <- 7; arr.[1] <- 7; false) -> 0
| Elems (_, 0) when col <= 0 -> 10
// ... the same rule for 1 to 6
| Elems (_, 7) when col <= 7 -> 17
| Elems (1, _) -> 1
// ... the same rule for 2 to 6
| Elems (7, _) -> 7
| _ -> -1With this PR's build, The obvious fix,
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for this, I took a look at it, see cc97109
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks, that covers it. Reading cc97109, a cut can no longer separate the clauses that apply |
||
| | TPat_disjs (subPats, _) | ||
| | TPat_conjs (subPats, _) | ||
| | TPat_tuple (_, subPats, _, _) | ||
| | TPat_exnconstr (_, subPats, _) | ||
| | TPat_unioncase (_, _, subPats, _) -> List.exists testsMutableData subPats | ||
| | TPat_isinst (_, _, subPatOpt, _) -> Option.exists testsMutableData subPatOpt | ||
| | TPat_const _ | ||
| | TPat_wild _ | ||
| | TPat_null _ | ||
| | TPat_error _ -> false | ||
|
|
||
| /// The stamps of the named active patterns the pattern applies. The decision tree can share one call of such a | ||
| /// pattern between clauses, so a cut must not separate clauses that apply the same one. A generic pattern, or one | ||
| /// applied to a different input, counts as shared too, which only forbids cuts that would be safe. | ||
| let rec private activePatternStamps acc inpPat = | ||
| match inpPat with | ||
| | TPat_query ((_, _, _, apatVrefOpt, _, _), subPat, _) -> | ||
| let acc = | ||
| match apatVrefOpt with | ||
| | Some (vref, _) -> Set.add vref.Stamp acc | ||
| | None -> acc | ||
| activePatternStamps acc subPat | ||
| | TPat_as (subPat, _, _) -> activePatternStamps acc subPat | ||
| | TPat_disjs (subPats, _) | ||
| | TPat_conjs (subPats, _) | ||
| | TPat_tuple (_, subPats, _, _) | ||
| | TPat_exnconstr (_, subPats, _) | ||
| | TPat_recd (_, _, subPats, _) | ||
| | TPat_unioncase (_, _, subPats, _) | ||
| | TPat_array (subPats, _, _) -> List.fold activePatternStamps acc subPats | ||
| | TPat_isinst (_, _, subPatOpt, _) -> Option.fold activePatternStamps acc subPatOpt | ||
| | TPat_const _ | ||
| | TPat_wild _ | ||
| | TPat_null _ | ||
| | TPat_error _ -> acc | ||
|
|
||
| [<Struct; NoEquality; NoComparison>] | ||
| type private CompiledMatch = | ||
| { Tree: DecisionTree | ||
| Targets: DecisionTreeTarget list | ||
| Joins: Bindings | ||
| GuardCopies: int } | ||
|
|
||
| let private CompilePatternBasic | ||
| (g: TcGlobals) denv amap tcVal infoReader mExpr mMatch | ||
| warnOnUnused | ||
| warnOnIncomplete | ||
| (joinPromotion: JoinPromotion) | ||
| (guardCopyBudget: int voption) | ||
| actionOnFailure | ||
| (origInputVal, origInputValTypars, _origInputExprOpt: Expr option) | ||
| (clauses: MatchClause list) | ||
|
|
@@ -1270,6 +1335,9 @@ let private CompilePatternBasic | |
| let idx = matchBuilder.AddTarget(TTarget(targetParams, mkApps g ((joinE, joinThunkTy), [], args, mMatch), None)) | ||
| TDSuccess(caps |> List.map (exprForVal mMatch), idx) | ||
|
|
||
| let guardEmitted = HashSet<ClauseNumber>() | ||
| let mutable guardCopies = 0 | ||
|
|
||
| let rec InvestigateFrontiers refuted frontiers = | ||
| Cancellable.CheckAndThrow() | ||
| stackGuard.Guard(fun () -> InvestigateFrontiersImpl refuted frontiers) | ||
|
|
@@ -1324,6 +1392,11 @@ let private CompilePatternBasic | |
| match GetWhenGuardOfClause i refuted with | ||
| | Some whenExpr -> | ||
| let m = whenExpr.Range | ||
| if not (guardEmitted.Add i) then | ||
| guardCopies <- guardCopies + 1 | ||
| match guardCopyBudget with | ||
| | ValueSome budget when guardCopies > budget -> raise GuardCopyBudgetExceeded | ||
| | _ -> () | ||
| let whenExprWithBindings = mkLetsFromBindings m (mkInvisibleBinds vs2 es2) whenExpr | ||
| let failureTree = investigateMemoized (RefutedWhenClause :: refuted) rest | ||
| mkBoolSwitch m whenExprWithBindings successTree failureTree | ||
|
|
@@ -1388,11 +1461,6 @@ let private CompilePatternBasic | |
| else | ||
| None) | ||
|
|
||
| and IsCopyableInputExpr origInputExpr = | ||
| match origInputExpr with | ||
| | Expr.Op (TOp.LValueOp (LByrefGet, v), [], [], _) when not v.IsMutable -> true | ||
| | _ -> false | ||
|
|
||
| and ChoosePreBinder simulSetOfEdgeDiscrims subexpr = | ||
| match simulSetOfEdgeDiscrims with | ||
| // Very simple 'isinst' tests: put the result of 'isinst' in a local variable | ||
|
|
@@ -1424,7 +1492,7 @@ let private CompilePatternBasic | |
| let argExpr = GetSubExprOfInput subexpr | ||
| let argExpr = | ||
| match argExpr, _origInputExprOpt with | ||
| | Expr.Val (v1, _, _), Some origInputExpr when valEq origInputVal v1.Deref && IsCopyableInputExpr origInputExpr -> origInputExpr | ||
| | Expr.Val (v1, _, _), Some origInputExpr when valEq origInputVal v1.Deref && isCopyableInputExpr origInputExpr -> origInputExpr | ||
| | _ -> argExpr | ||
| let vOpt, addrExp, _readonly, _writeonly = mkExprAddrOfExprAux g true false NeverMutates argExpr None mMatch | ||
| match vOpt with | ||
|
|
@@ -1823,7 +1891,7 @@ let private CompilePatternBasic | |
| if warnOnUnused then | ||
| ReportUnusedTargets clauses dtree | ||
|
|
||
| dtree, matchBuilder.CloseTargets(), List.ofSeq joinBindings | ||
| { Tree = dtree; Targets = matchBuilder.CloseTargets(); Joins = List.ofSeq joinBindings; GuardCopies = guardCopies } | ||
|
|
||
| // Three pattern constructs can cause significant code expansion in various combinations | ||
| // - Partial active patterns | ||
|
|
@@ -1887,41 +1955,85 @@ let isProblematicClause (clause: MatchClause) = | |
| let ips = investigationPoints clause.Pattern | ||
| ips.Length > 0 && Span.exists id (ips.AsSpan (0, ips.Length - 1)) | ||
|
|
||
| let rec CompilePattern g denv amap tcVal infoReader mExpr mMatch warnOnUnused actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) (clausesL: MatchClause list) inputTy resultTy = | ||
| match clausesL with | ||
| | _ when List.exists isProblematicClause clausesL -> | ||
|
|
||
| // First make sure we generate at least some of the obvious incomplete match warnings. | ||
| let warnOnUnused = false // we can't turn this on since we're pretending all partials fail in order to control the complexity of this. | ||
| let warnOnIncomplete = true | ||
| let clausesPretendAllPartialFail = clausesL |> List.collect (fun (MatchClause(p, whenOpt, tg, m)) -> [MatchClause(erasePartialPatterns p, whenOpt, tg, m)]) | ||
| let _ = CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused warnOnIncomplete JoinPromotion.Disabled actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clausesPretendAllPartialFail inputTy resultTy | ||
| let warnOnIncomplete = false | ||
| /// Extra copies of 'when' guards a decision tree may hold. A match over this budget is cut into | ||
| /// groups, each compiled with the rest of the match as a single fall-through target. | ||
| let private guardCopyBudget = 32 | ||
|
|
||
| let CompilePattern g denv amap tcVal infoReader mExpr mMatch warnOnUnused actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) (clausesL: MatchClause list) inputTy resultTy = | ||
| let compile warnOnUnused warnOnIncomplete joinPromotion budget clauses = | ||
| CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused warnOnIncomplete joinPromotion budget actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clauses inputTy resultTy | ||
|
|
||
| let restPlaceholder = MatchClause(TPat_wild mMatch, None, TTarget([], mkDefault (mMatch, resultTy), None), mMatch) | ||
|
|
||
| let fitsBudget clauses = | ||
| try | ||
| compile false false JoinPromotion.Enabled (ValueSome guardCopyBudget) (clauses @ [ restPlaceholder ]) |> ignore | ||
| true | ||
| with GuardCopyBudgetExceeded -> | ||
| false | ||
|
|
||
| // The longest prefix of the group that fits the budget, at least one clause. A cut between two clauses | ||
| // that apply the same active pattern would call it a second time, after the guards before the cut ran, | ||
| // so the cut moves back to a point where no active pattern is shared. Without one, the group stays whole. | ||
| let cutToBudget (group: MatchClause list) rest = | ||
| let rec search lo hi = | ||
| if lo >= hi then | ||
| lo | ||
| else | ||
| let mid = (lo + hi + 1) / 2 | ||
| if fitsBudget (List.take mid group) then search mid hi else search lo (mid - 1) | ||
|
|
||
| // Partial and when clauses cause major code explosion if treated naively | ||
| // Hence treat any pattern matches with any partial clauses clause-by-clause | ||
| let rec atMostOneProblematicClauseAtATime clauses = | ||
| if fitsBudget group then | ||
| group, rest | ||
| else | ||
| let stamps = group |> List.map (fun clause -> activePatternStamps Set.empty clause.Pattern) | ||
| let before = List.scan Set.union Set.empty stamps |> List.toArray | ||
| let after = List.scanBack Set.union stamps Set.empty |> List.toArray | ||
| let canCutAt k = Set.isEmpty (Set.intersect before[k] after[k]) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This catches a pattern applied on both sides of the cut. One applied only after the cut can still run where the whole match never runs it, because the rest is compiled without what the tests before the cut ruled out. With let f (t: int) (c: int) (col: int) =
match t, c with
| 0, 0 -> 0
| _, 0 when col <= 0 -> 10
// ... the same rule for 1 to 3
| _, 4 when col <= 4 -> 14
| 1, _ -> 1
// ... the same rule for 2 to 5
| 6, _ -> 6
| Parity 1, 9 -> 90
| _ -> -1
|
||
|
|
||
| let rec lastCut k = | ||
| if k < 1 then ValueNone | ||
| elif canCutAt k then ValueSome k | ||
| else lastCut (k - 1) | ||
|
|
||
| match lastCut (search 1 (group.Length - 1)) with | ||
| | ValueSome k -> List.take k group, List.skip k group @ rest | ||
| | ValueNone -> group, rest | ||
|
|
||
| // Partial patterns and 'when' clauses cause major code explosion if treated naively, as every | ||
| // path that falls through a group would get its own copy of the clauses after it. So each group | ||
| // ends at a problematic clause or at the budget, and the rest of the match is compiled once. | ||
| // The groups report no warnings: the whole-match compile already did. | ||
| let rec compileGroups cutLargeGroups clauses = | ||
| let group, rest = | ||
| match List.takeUntil isProblematicClause clauses with | ||
| | l, [] -> | ||
| CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused warnOnIncomplete JoinPromotion.Enabled actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) l inputTy resultTy | ||
| | l, h :: t -> | ||
| // Add the problematic clause. | ||
| doGroupWithAtMostOneProblematic (l @ [h]) t | ||
| | l, [] -> l, [] | ||
| | l, h :: t -> l @ [ h ], t | ||
|
|
||
| and doGroupWithAtMostOneProblematic group rest = | ||
| // Compile the remaining clauses. | ||
| let decisionTree, targets, joins = atMostOneProblematicClauseAtATime rest | ||
| let group, rest = if cutLargeGroups then cutToBudget group rest else group, rest | ||
|
|
||
| // Make the expression that represents the remaining cases of the pattern match. | ||
| let expr = mkLetsBind mMatch joins (mkAndSimplifyMatch DebugPointAtBinding.NoneAtInvisible mExpr mMatch resultTy decisionTree targets) | ||
|
|
||
| // Make the clause that represents the remaining cases of the pattern match | ||
| match rest with | ||
| | [] -> compile false false JoinPromotion.Enabled ValueNone group | ||
| | _ -> | ||
| let rest = compileGroups cutLargeGroups rest | ||
| let expr = mkLetsBind mMatch rest.Joins (mkAndSimplifyMatch DebugPointAtBinding.NoneAtInvisible mExpr mMatch resultTy rest.Tree rest.Targets) | ||
| let clauseForRestOfMatch = MatchClause(TPat_wild mMatch, None, TTarget(List.empty, expr, None), mMatch) | ||
| compile false false JoinPromotion.Enabled ValueNone (group @ [ clauseForRestOfMatch ]) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The same gap runs the other way. The prefix is compiled with the rest as a wildcard, so a type test in the rest can no longer rule out a clause before the cut: let f (t: int) (c: int) (o: obj) (col: int) =
match t, c, o with
| 0, 0, _ when col < 0 -> 0
| _, 0, _ when col <= 0 -> 10
// ... the same rule for 1 to 4
| _, 5, _ when col <= 5 -> 15
| _, _, (:? Animal) -> 20
| Q 5, _, (:? IFoo) -> 30
| 1, _, _ -> 1
// ... the same rule for 2 to 4
| 5, _, _ -> 5
| _, _, (:? string) -> 40
| _ -> -1
|
||
|
|
||
| // The rest of a cut match tests the input again, and sees what a failed guard wrote to it, where | ||
| // the whole tree would not. So only a match whose tested data no guard can write is cut by the budget. | ||
| let canRetestInput () = | ||
| not (Option.exists isCopyableInputExpr origInputExprOpt) | ||
| && not (clausesL |> List.exists (fun clause -> testsMutableData clause.Pattern)) | ||
|
|
||
| let result = | ||
| if List.exists isProblematicClause clausesL then | ||
| // Partial patterns are treated as failing here, so unused clauses can't be reported. | ||
| let clausesPretendAllPartialFail = clausesL |> List.map (fun (MatchClause(p, whenOpt, tg, m)) -> MatchClause(erasePartialPatterns p, whenOpt, tg, m)) | ||
| let whole = compile false true JoinPromotion.Disabled ValueNone clausesPretendAllPartialFail | ||
| compileGroups (whole.GuardCopies > guardCopyBudget && canRetestInput ()) clausesL | ||
| else | ||
| let whole = compile warnOnUnused true JoinPromotion.Disabled ValueNone clausesL | ||
| if whole.GuardCopies > guardCopyBudget && canRetestInput () then compileGroups true clausesL else whole | ||
|
|
||
| CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused warnOnIncomplete JoinPromotion.Enabled actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) (group @ [clauseForRestOfMatch]) inputTy resultTy | ||
|
|
||
|
|
||
| atMostOneProblematicClauseAtATime clausesL | ||
|
|
||
| | _ -> | ||
| CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused true JoinPromotion.Disabled actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clausesL inputTy resultTy | ||
| result.Tree, result.Targets, result.Joins | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A
[<CLIMutable>]record gets past this check. Its fields have public setters, butfield.IsMutableis false for them, so a match whose guard writes the record through a setter is still cut:f { T = 0 } 0returns 6 with the head and -1 with the merge base. Reflection stands in for C# code or a serializer, which is what the attribute is for.TryOptimizeRecordFieldGetalready skips these records with theCLIMutableAttributecheck, and the same check here would cover it.