Skip to content

Commit

Permalink
Merge pull request #5427 from smrg-lm/topic/optimization_identity_cases
Browse files Browse the repository at this point in the history
class library: Fix BinaryOpUGen optimization for a === b cases
  • Loading branch information
jamshark70 authored Aug 21, 2022
2 parents b106749 + 34f2140 commit 0f66e76
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
3 changes: 3 additions & 0 deletions SCClassLibrary/Common/Audio/BasicOpsUGen.sc
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ BinaryOpUGen : BasicOpUGen {
optimizeAddNeg {
var a, b, replacement;
#a, b = inputs;
if(a === b) { ^nil }; // non optimizable edge case.

if (b.isKindOf(UnaryOpUGen) and: { b.operator == 'neg' and: { b.descendants.size == 1 } }) {
// a + b.neg -> a - b
Expand Down Expand Up @@ -197,6 +198,7 @@ BinaryOpUGen : BasicOpUGen {
optimizeToMulAdd {
var a, b, replacement;
#a, b = inputs;
if(a === b) { ^nil };

if (a.isKindOf(BinaryOpUGen) and: { a.operator == '*'
and: { a.descendants.size == 1 }})
Expand Down Expand Up @@ -269,6 +271,7 @@ BinaryOpUGen : BasicOpUGen {
optimizeToSum4 {
var a, b, replacement;
#a, b = inputs;
if(a === b) { ^nil };
if(a.rate == \demand or: { b.rate == \demand }) { ^nil };

if (a.isKindOf(Sum3) and: { a.descendants.size == 1 }) {
Expand Down
26 changes: 23 additions & 3 deletions testsuite/classlibrary/TestUGenMathOptimization.sc
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ TestUGenMathOptimization : UnitTest {
var bcd = b + c + d;
(a + bcd) * (a / bcd);
} -> [SinOsc, LFNoise0, DC, Impulse, Sum3, '+', '/', '*', Out],
"a + b when a === b should not optimize",
{
var x = SinOsc.ar([100, 200, 300]).sum();
x + x
} -> [SinOsc, SinOsc, SinOsc, Sum3, '+', Out],
]);
}

Expand All @@ -81,7 +86,12 @@ TestUGenMathOptimization : UnitTest {
var ab = a * b;
// max is contrived to avoid Sum3 or other optimizations
max(ab + c, ab / c)
} -> [SinOsc, LFNoise0, '*', DC, '+', '/', 'max', Out]
} -> [SinOsc, LFNoise0, '*', DC, '+', '/', 'max', Out],
"a + b when a === b should not optimize",
{
var x = SinOsc.ar(100) * 0.1;
x + x
} -> [SinOsc, '*', '+', Out],
])
}

Expand All @@ -96,7 +106,12 @@ TestUGenMathOptimization : UnitTest {
var a = SinOsc.kr(0.1);
var b = Rand(0, 1).neg;
(a + b) * b
} -> [SinOsc, Rand, 'neg', '+', '*', Out]
} -> [SinOsc, Rand, 'neg', '+', '*', Out],
"a + b when a === b should not optimize",
{
var x = SinOsc.ar(100).neg;
x + x
} -> [SinOsc, 'neg', '+', Out],
])
}

Expand All @@ -109,7 +124,12 @@ TestUGenMathOptimization : UnitTest {
var a = SinOsc.kr(0.1);
var b = Rand(0, 1).neg;
(a - b) * b
} -> [SinOsc, Rand, 'neg', '-', '*', Out]
} -> [SinOsc, Rand, 'neg', '-', '*', Out],
"a - b when a === b results in a - a",
{
var x = SinOsc.ar(100).neg;
x - x
} -> [SinOsc, '-', Out],
])
}

Expand Down

0 comments on commit 0f66e76

Please sign in to comment.