Skip to content

Commit 44fdcc0

Browse files
Compute only the case a compiled piecewise takes (#2438)
* Compute only the case a compiled piecewise takes, in the LINQ compiler * Compute only the case a compiled piecewise takes, in FastExpression Part of #2195. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 5c8eafa commit 44fdcc0

6 files changed

Lines changed: 280 additions & 32 deletions

File tree

‎Sources/AngouriMath/Functions/Compilation/Compile.FE.Definition.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ partial record Entity
2323
/// <remarks>
2424
/// A statement compiles to its truth value: 1 where it holds, 0 where it does not, and NaN
2525
/// where it has none, as <c>i &gt; 1</c> has none. A <c>provided</c> or a <c>piecewise</c> is NaN
26-
/// where no predicate holds. https://github.com/asc-community/AngouriMath/issues/2195
26+
/// where no predicate holds, and computes only the case it takes, as evaluation does.
27+
/// https://github.com/asc-community/AngouriMath/issues/2195
2728
/// </remarks>
2829
public FastExpression Compile(params Variable[] variables) => Compiler.Compile(this, variables);
2930

‎Sources/AngouriMath/Functions/Compilation/IntoFE/Compiler.cs‎

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//
1+
//
22
// Copyright (c) 2019-2022 Angouri.
33
// AngouriMath is licensed under MIT.
44
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
@@ -48,6 +48,7 @@ internal void InnerCompile(Compiler compiler)
4848
cacheLine = ~cacheLine;
4949
compiler.Cache[this] = cacheLine;
5050
compiler.Instructions.Add(new(InstructionType.SAVE_CACHE, cacheLine));
51+
compiler.Saved.Add(this);
5152
}
5253
}
5354
}
@@ -536,29 +537,48 @@ public partial record Providedf
536537
{
537538
private protected override bool CompilesItself => true;
538539

540+
// The value where the predicate holds, and NaN elsewhere, the value not being computed there.
539541
private protected override void CompileNode(Compiler compiler)
540542
{
543+
var start = compiler.Saved.Count;
541544
Predicate.InnerCompile(compiler);
545+
var unless = compiler.Jump(InstructionType.JUMP_UNLESS_HOLDS);
542546
Expression.InnerCompile(compiler);
543-
compiler.Instructions.Add(new(InstructionType.CALL_PROVIDED));
547+
var past = compiler.Jump(InstructionType.JUMP);
548+
compiler.Land(unless);
549+
compiler.Instructions.Add(new(InstructionType.PUSH_CONST, Value: double.NaN));
550+
compiler.Land(past);
551+
compiler.Forget(start);
544552
}
545553
}
546554

547-
// The first case whose predicate holds, and NaN where none does: from the last case up,
548-
// each is kept where its predicate holds and the cases below it are kept elsewhere.
555+
// The first case whose predicate holds, and NaN where none does. Each predicate is tried in
556+
// turn, and the first that holds has its case computed and jumps past the rest, so that a case
557+
// not taken is not computed: one may be undefined, or costly, where it is not taken.
549558
public partial record Piecewise
550559
{
551560
private protected override bool CompilesItself => true;
552561

553562
private protected override void CompileNode(Compiler compiler)
554563
{
555-
compiler.Instructions.Add(new(InstructionType.PUSH_CONST, Value: double.NaN));
556-
foreach (var @case in Cases.Reverse())
564+
var start = compiler.Saved.Count;
565+
var past = new List<int>();
566+
foreach (var @case in Cases)
557567
{
558568
@case.Predicate.InnerCompile(compiler);
569+
var unless = compiler.Jump(InstructionType.JUMP_UNLESS_HOLDS);
570+
// What the predicates computed holds for the cases after them, as reaching one
571+
// means every predicate before it was computed; what a case computed does not.
572+
var predicates = compiler.Saved.Count;
559573
@case.Expression.InnerCompile(compiler);
560-
compiler.Instructions.Add(new(InstructionType.CALL_SELECT));
574+
compiler.Forget(predicates);
575+
past.Add(compiler.Jump(InstructionType.JUMP));
576+
compiler.Land(unless);
561577
}
578+
compiler.Instructions.Add(new(InstructionType.PUSH_CONST, Value: double.NaN));
579+
foreach (var jump in past)
580+
compiler.Land(jump);
581+
compiler.Forget(start);
562582
}
563583
}
564584

@@ -1010,6 +1030,33 @@ public partial class FastExpression
10101030
internal sealed record Compiler(List<Instruction> Instructions,
10111031
IReadOnlyDictionary<Variable, int> VarNamespace, IDictionary<Entity, int> Cache)
10121032
{
1033+
/// <summary>
1034+
/// The subexpressions saved to the cache, in the order their instructions were emitted. A
1035+
/// subexpression saved where a jump may pass over it has no value in its slot after the jump,
1036+
/// so once the code that may be passed over is compiled it is <see cref="Forget"/>-ed back to
1037+
/// unsaved, and is computed again where it is next met: a slot is read only where every path
1038+
/// to the read has written it, as <see cref="FastExpression.Substitute"/> relies on.
1039+
/// </summary>
1040+
internal List<Entity> Saved { get; } = new();
1041+
1042+
/// <summary>Marks every subexpression saved since <paramref name="count"/> were as unsaved.</summary>
1043+
internal void Forget(int count)
1044+
{
1045+
for (var i = count; i < Saved.Count; i++)
1046+
Cache[Saved[i]] = ~Cache[Saved[i]];
1047+
Saved.RemoveRange(count, Saved.Count - count);
1048+
}
1049+
1050+
/// <summary>Emits a jump whose target is not yet known, and returns where it is.</summary>
1051+
internal int Jump(InstructionType type)
1052+
{
1053+
Instructions.Add(new(type));
1054+
return Instructions.Count - 1;
1055+
}
1056+
1057+
/// <summary>Makes the jump at <paramref name="jump"/> land on the next instruction emitted.</summary>
1058+
internal void Land(int jump) => Instructions[jump] = Instructions[jump] with { Reference = Instructions.Count };
1059+
10131060
/// <summary>Returns a compiled expression. Allows to boost substitution a lot</summary>
10141061
/// <param name="func">The function to be compiled</param>
10151062
/// <param name="variables">Must be equal to func's variables (ignoring constants)</param>

‎Sources/AngouriMath/Functions/Compilation/IntoFE/FastExpression.cs‎

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ internal enum InstructionType
2121
LOAD_CACHE,
2222
SAVE_CACHE,
2323

24+
// Control flow, to the instruction its Reference names: a jump, and a jump taken
25+
// unless the truth value popped holds, as a case of a piecewise is passed over unless
26+
// its predicate holds.
27+
JUMP = 20,
28+
JUMP_UNLESS_HOLDS,
29+
2430
// 1-arg functions
2531
CALL_SIN = 50,
2632
CALL_COS,
@@ -86,8 +92,6 @@ internal enum InstructionType
8692
CALL_OR,
8793
CALL_XOR,
8894
CALL_IMPLIES,
89-
// A value where its predicate holds, and NaN elsewhere.
90-
CALL_PROVIDED,
9195
CALL_BINOMIAL,
9296
CALL_FALLING_FACTORIAL,
9397
CALL_RISING_FACTORIAL,
@@ -98,10 +102,8 @@ internal enum InstructionType
98102
CALL_VALUATION,
99103
CALL_DIVIDES,
100104

101-
// 3-arg: a value where its predicate holds, and the one below it elsewhere.
102-
CALL_SELECT = 150,
103-
// Whether two numbers are congruent modulo a third.
104-
CALL_CONGRUENT,
105+
// 3-arg: whether two numbers are congruent modulo a third.
106+
CALL_CONGRUENT = 150,
105107
}
106108
internal sealed partial record Instruction(InstructionType Type, int Reference = -1, System.Numerics.Complex Value = default)
107109
{
@@ -136,7 +138,7 @@ private sealed class Scratch
136138

137139
[System.ThreadStatic] private static Scratch? scratch;
138140

139-
private readonly List<Instruction> instructions;
141+
private readonly Instruction[] instructions;
140142
private readonly int varCount;
141143
private readonly int cacheCount;
142144

@@ -147,7 +149,7 @@ private sealed class Scratch
147149
internal FastExpression(int varCount, List<Instruction> instructions, int cacheCount)
148150
{
149151
this.varCount = varCount;
150-
this.instructions = instructions;
152+
this.instructions = instructions.ToArray();
151153
this.cacheCount = cacheCount;
152154
}
153155

@@ -171,9 +173,20 @@ public System.Numerics.Complex Substitute(params System.Numerics.Complex[] value
171173
var cache = mine.Cache;
172174
if (cache.Length < cacheCount)
173175
mine.Cache = cache = new System.Numerics.Complex[cacheCount];
174-
foreach (var instruction in instructions)
176+
for (var next = 0; next < instructions.Length; next++)
177+
{
178+
var instruction = instructions[next];
175179
switch (instruction.Type)
176180
{
181+
// Every jump is forward, so a call ends. A piecewise computes the case it takes
182+
// and no other: https://github.com/asc-community/AngouriMath/issues/2195
183+
case InstructionType.JUMP:
184+
next = instruction.Reference - 1;
185+
break;
186+
case InstructionType.JUMP_UNLESS_HOLDS:
187+
if (Truth(stack.Pop()) != true)
188+
next = instruction.Reference - 1;
189+
break;
177190
case InstructionType.PUSH_VAR:
178191
stack.Push(values[instruction.Reference]);
179192
break;
@@ -364,12 +377,6 @@ public System.Numerics.Complex Substitute(params System.Numerics.Complex[] value
364377
case InstructionType.CALL_IMPLIES:
365378
stack.Push(Truth(Logic.Implies(Truth(stack.Pop()), Truth(stack.Pop()))));
366379
break;
367-
case InstructionType.CALL_PROVIDED:
368-
{
369-
var value = stack.Pop();
370-
stack.Push(Truth(stack.Pop()) == true ? value : double.NaN);
371-
break;
372-
}
373380
// The binomial coefficient, the factorial powers and the double factorial.
374381
// https://github.com/asc-community/AngouriMath/issues/2195
375382
case InstructionType.CALL_BINOMIAL:
@@ -426,15 +433,8 @@ public System.Numerics.Complex Substitute(params System.Numerics.Complex[] value
426433
case InstructionType.CALL_CONGRUENT:
427434
stack.Push(Truth(AngouriMath.Numerics.NumberStatements.Congruent(stack.Pop(), stack.Pop(), stack.Pop())));
428435
break;
429-
case InstructionType.CALL_SELECT:
430-
{
431-
var value = stack.Pop();
432-
var holds = Truth(stack.Pop()) == true;
433-
var otherwise = stack.Pop();
434-
stack.Push(holds ? value : otherwise);
435-
break;
436-
}
437436
}
437+
}
438438
if (stack.Count != 1)
439439
throw new AngouriBugException($"Unused values remain in the stack: {stack.Count} instead of 1");
440440
return stack.Pop();
@@ -447,6 +447,6 @@ public System.Numerics.Complex Substitute(params System.Numerics.Complex[] value
447447
private static bool? Truth(System.Numerics.Complex value) => value == 1 ? true : value == 0 ? false : null;
448448

449449
/// <summary>Might be useful for debug if a function works too slowly</summary>
450-
public override string ToString() => string.Join(" \n| ", instructions);
450+
public override string ToString() => string.Join<Instruction>(" \n| ", instructions);
451451
}
452452
}

‎Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,22 @@ IUnaryNode oneArg
201201
=> protocol.ConvertMembership(
202202
BuildTree(element, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType), set),
203203

204+
// The value of a case is computed only where it is taken, inside the conditional, so that a case
205+
// that is undefined, or costly, where it is not taken is not computed there. Every subexpression is
206+
// otherwise a local assigned before the expression's value is, which would compute each case.
207+
// https://github.com/asc-community/AngouriMath/issues/2195
208+
Providedf(var value, var predicate)
209+
=> protocol.ConvertBinaryNode(
210+
Conditional(value, cachedSubexpressions, protocol, constantType),
211+
BuildTree(predicate, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType),
212+
expr),
213+
214+
// The first predicate is always computed; the others only where every one before them fails.
215+
Piecewise piecewise
216+
=> protocol.ConvertOtherNode(piecewise.DirectChildren.Select((child, i) => i == 1
217+
? BuildTree(child, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType)
218+
: Conditional(child, cachedSubexpressions, protocol, constantType)).ToArray(), expr),
219+
204220
IBinaryNode twoArg
205221
=> protocol.ConvertBinaryNode(
206222
BuildTree(twoArg.NodeFirstChild, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType),
@@ -216,5 +232,23 @@ IBinaryNode twoArg
216232
newLocalVars.Add(newVar);
217233
return newVar;
218234
}
235+
236+
/// <summary>
237+
/// <paramref name="expr"/> as a block of its own, computed only where the block is: what it computes is
238+
/// cached inside the block and not outside it, where the block may not have been computed. What was
239+
/// cached before it is read as it is everywhere else.
240+
/// </summary>
241+
private static Expression Conditional(
242+
Entity expr,
243+
Dictionary<Entity, ParameterExpression> cachedSubexpressions,
244+
CompilationProtocol protocol,
245+
Type? constantType)
246+
{
247+
var cached = new Dictionary<Entity, ParameterExpression>(cachedSubexpressions);
248+
var locals = new List<ParameterExpression>();
249+
var assignments = new List<Expression>();
250+
var tree = BuildTree(expr, cached, assignments, locals, protocol, constantType);
251+
return assignments.Count == 0 ? tree : Expression.Block(locals, assignments.Append(tree));
252+
}
219253
}
220254
}

‎Sources/Tests/AotSmokeTest/Program.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,11 @@ private static void Compilation()
294294

295295
var piecewise = "piecewise(x provided x > 0, 0 provided x <= 0)".Compile<double, double>(x);
296296
Check("compiled piecewise at -3 and 3", piecewise(-3) == 0 && piecewise(3) == 3, $"{piecewise(-3)}, {piecewise(3)}");
297+
// A case computed only where it is taken is a block with locals of its own.
298+
// https://github.com/asc-community/AngouriMath/issues/2195
299+
var computedCases = "piecewise(x^2 + 1 provided x > 0, x^2 - 1) + x^2".Compile<double, double>(x);
300+
Check("compiled piecewise of computed cases at -3 and 3", computedCases(-3) == 17 && computedCases(3) == 19,
301+
$"{computedCases(-3)}, {computedCases(3)}");
297302

298303
// A comparison of numbers that are not ordered has no truth value, and the connectives
299304
// follow Kleene's tables, in the interpreter a native build compiles to.

0 commit comments

Comments
 (0)