Browse Source

add CachedDelegateInitialization block transform

pull/728/merge
Siegfried Pammer 9 years ago
parent
commit
4ac1c2d0b0
  1. 1
      ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs
  2. 1
      ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj
  3. 15
      ICSharpCode.Decompiler/IL/Instructions/PatternMatching.cs
  4. 143
      ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs
  5. 125
      ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs

1
ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs

@ -63,6 +63,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -63,6 +63,7 @@ namespace ICSharpCode.Decompiler.CSharp
new IntroduceExitPoints(),
new BlockILTransform( // per-block transforms
new ConditionDetection(),
new CachedDelegateInitialization(), // must run after ConditionDetection and before/in LoopingBlockTransform.
new ILInlining(),
new TransformAssignment(),
new CopyPropagation(),

1
ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj

@ -133,6 +133,7 @@ @@ -133,6 +133,7 @@
<Compile Include="IL\Patterns\Match.cs" />
<Compile Include="IL\SlotInfo.cs" />
<Compile Include="IL\Transforms\BlockTransform.cs" />
<Compile Include="IL\Transforms\CachedDelegateInitialization.cs" />
<Compile Include="IL\Transforms\CopyPropagation.cs" />
<Compile Include="IL\Transforms\IILTransform.cs" />
<Compile Include="IL\Transforms\ILInlining.cs" />

15
ICSharpCode.Decompiler/IL/Instructions/PatternMatching.cs

@ -191,10 +191,21 @@ namespace ICSharpCode.Decompiler.IL @@ -191,10 +191,21 @@ namespace ICSharpCode.Decompiler.IL
return false;
}
/// <summary>
/// Matches comp(left == right) or logic.not(comp(left != right)).
/// </summary>
public bool MatchCompEquals(out ILInstruction left, out ILInstruction right)
{
Comp comp = this as Comp;
if (comp != null && comp.Kind == ComparisonKind.Equality) {
ComparisonKind op;
Comp comp;
if (this is LogicNot logicNot) {
op = ComparisonKind.Inequality;
comp = logicNot.Argument as Comp;
} else {
op = ComparisonKind.Equality;
comp = this as Comp;
}
if (comp != null && comp.Kind == op) {
left = comp.Left;
right = comp.Right;
return true;

143
ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs

@ -0,0 +1,143 @@ @@ -0,0 +1,143 @@
// Copyright (c) 2011-2016 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.Decompiler.IL.Transforms
{
public class CachedDelegateInitialization : IBlockTransform
{
public void Run(Block block, BlockTransformContext context)
{
for (int i = block.Instructions.Count - 1; i >= 0; i--) {
if (block.Instructions[i] is IfInstruction inst) {
if (CachedDelegateInitializationWithField(inst)) {
block.Instructions.RemoveAt(i);
continue;
}
if (CachedDelegateInitializationWithLocal(inst, out bool hasFieldStore, out ILVariable v)) {
block.Instructions.RemoveAt(i);
if (hasFieldStore) {
block.Instructions.RemoveAt(i - 1);
}
//if (v.IsSingleDefinition && v.LoadCount == 0) {
// var store = v.Scope.Descendants.OfType<StLoc>().SingleOrDefault(stloc => stloc.Variable == v);
// if (store != null) {
// orphanedVariableInits.Add(store);
// }
//}
continue;
}
}
}
}
bool CachedDelegateInitializationWithField(IfInstruction inst)
{
// if (comp(ldsfld CachedAnonMethodDelegate == ldnull) {
// stsfld CachedAnonMethodDelegate(DelegateConstruction)
// }
// ... one usage of CachedAnonMethodDelegate ...
// =>
// ... one usage of DelegateConstruction ...
Block trueInst = inst.TrueInst as Block;
var condition = inst.Condition as Comp;
if (condition == null || trueInst == null || trueInst.Instructions.Count != 1 || !inst.FalseInst.MatchNop())
return false;
IField field, field2;
ILInstruction value;
var storeInst = trueInst.Instructions[0];
if (!condition.Left.MatchLdsFld(out field) || !condition.Right.MatchLdNull())
return false;
if (!storeInst.MatchStsFld(out value, out field2) || !field.Equals(field2) || !field.IsCompilerGeneratedOrIsInCompilerGeneratedClass())
return false;
if (!DelegateConstruction.IsDelegateConstruction(value as NewObj, true))
return false;
var nextInstruction = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex + 1);
if (nextInstruction == null)
return false;
var usages = nextInstruction.Descendants.Where(i => i.MatchLdsFld(field)).ToArray();
if (usages.Length != 1)
return false;
usages[0].ReplaceWith(value);
return true;
}
bool CachedDelegateInitializationWithLocal(IfInstruction inst, out bool hasFieldStore, out ILVariable local)
{
// [stloc v(ldsfld CachedAnonMethodDelegate)]
// if (comp(ldloc v == ldnull) {
// stloc v(DelegateConstruction)
// [stsfld CachedAnonMethodDelegate(v)]
// }
// ... one usage of v ...
// =>
// ... one usage of DelegateConstruction ...
Block trueInst = inst.TrueInst as Block;
hasFieldStore = false;
local = null;
if (trueInst == null || (trueInst.Instructions.Count < 1) || !inst.FalseInst.MatchNop())
return false;
if (!inst.Condition.MatchCompEquals(out ILInstruction left, out ILInstruction right) || !left.MatchLdLoc(out ILVariable v) || !right.MatchLdNull())
return false;
ILInstruction value, value2;
var storeInst = trueInst.Instructions.Last();
if (!storeInst.MatchStLoc(v, out value))
return false;
// the optional field store was moved into storeInst by inline assignment:
if (!(value is NewObj)) {
IField field, field2;
if (value.MatchStsFld(out value2, out field)) {
if (!(value2 is NewObj) || !field.IsCompilerGeneratedOrIsInCompilerGeneratedClass())
return false;
var storeBeforeIf = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex - 1) as StLoc;
if (storeBeforeIf == null || storeBeforeIf.Variable != v || !storeBeforeIf.Value.MatchLdsFld(out field2) || !field.Equals(field2))
return false;
value = value2;
hasFieldStore = true;
} else if (value.MatchStFld(out value2, out field)) {
if (!(value2 is NewObj) || !field.IsCompilerGeneratedOrIsInCompilerGeneratedClass())
return false;
var storeBeforeIf = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex - 1) as StLoc;
if (storeBeforeIf == null || storeBeforeIf.Variable != v || !storeBeforeIf.Value.MatchLdFld(out field2) || !field.Equals(field2))
return false;
value = value2;
hasFieldStore = true;
} else {
return false;
}
}
if (!DelegateConstruction.IsDelegateConstruction(value as NewObj, true))
return false;
var nextInstruction = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex + 1);
if (nextInstruction == null)
return false;
var usages = nextInstruction.Descendants.OfType<LdLoc>().Where(i => i.Variable == v).ToArray();
if (usages.Length != 1)
return false;
local = v;
usages[0].ReplaceWith(value);
return true;
}
}
}

125
ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs

@ -51,29 +51,6 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -51,29 +51,6 @@ namespace ICSharpCode.Decompiler.IL.Transforms
targetsToReplace.Add((IInstructionWithVariableOperand)target);
}
var inst = block.Instructions[i] as IfInstruction;
if (inst != null) {
if (CachedDelegateInitializationWithField(inst)) {
block.Instructions.RemoveAt(i);
continue;
}
bool hasFieldStore;
ILVariable v;
if (CachedDelegateInitializationWithLocal(inst, out hasFieldStore, out v)) {
block.Instructions.RemoveAt(i);
if (hasFieldStore) {
block.Instructions.RemoveAt(i - 1);
}
if (v.IsSingleDefinition && v.LoadCount == 0) {
var store = v.Scope.Descendants.OfType<StLoc>().SingleOrDefault(stloc => stloc.Variable == v);
if (store != null) {
orphanedVariableInits.Add(store);
}
}
continue;
}
}
ILVariable targetVariable;
ILInstruction value;
if (block.Instructions[i].MatchStLoc(out targetVariable, out value)) {
@ -158,12 +135,15 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -158,12 +135,15 @@ namespace ICSharpCode.Decompiler.IL.Transforms
function.RunTransforms(CSharpDecompiler.GetILTransforms().TakeWhile(t => !(t is DelegateConstruction)), context);
function.AcceptVisitor(new ReplaceDelegateTargetVisitor(target, function.Variables.SingleOrDefault(v => v.Index == -1 && v.Kind == VariableKind.Parameter)));
// handle nested lambdas
((IILTransform)new DelegateConstruction()).Run(function, new ILTransformContext { Settings = context.Settings, CancellationToken = context.CancellationToken, TypeSystem = localTypeSystem });
((IILTransform)new DelegateConstruction()).Run(function, new ILTransformContext(context) { TypeSystem = localTypeSystem });
return function;
}
return null;
}
/// <summary>
/// Replaces loads of 'this' with the target expression.
/// </summary>
class ReplaceDelegateTargetVisitor : ILVisitor
{
readonly ILVariable thisVariable;
@ -192,6 +172,13 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -192,6 +172,13 @@ namespace ICSharpCode.Decompiler.IL.Transforms
}
}
/// <summary>
/// 1. Stores to display class fields are replaced with stores to local variables (in some
/// cases existing variables are used; otherwise fresh variables are added to the
/// ILFunction-container) and all usages of those fields are replaced with the local variable.
/// (see initValues)
/// 2. Usages of the display class container (or any copy) are removed.
/// </summary>
class TransformDisplayClassUsages : ILVisitor
{
ILFunction currentFunction;
@ -308,95 +295,5 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -308,95 +295,5 @@ namespace ICSharpCode.Decompiler.IL.Transforms
}
}
#endregion
bool CachedDelegateInitializationWithField(IfInstruction inst)
{
// if (comp(ldsfld CachedAnonMethodDelegate == ldnull) {
// stsfld CachedAnonMethodDelegate(DelegateConstruction)
// }
// ... one usage of CachedAnonMethodDelegate ...
// =>
// ... one usage of DelegateConstruction ...
Block trueInst = inst.TrueInst as Block;
var condition = inst.Condition as Comp;
if (condition == null || trueInst == null || trueInst.Instructions.Count != 1 || !inst.FalseInst.MatchNop())
return false;
IField field, field2;
ILInstruction value;
var storeInst = trueInst.Instructions[0];
if (!condition.Left.MatchLdsFld(out field) || !condition.Right.MatchLdNull())
return false;
if (!storeInst.MatchStsFld(out value, out field2) || !field.Equals(field2) || !field.IsCompilerGeneratedOrIsInCompilerGeneratedClass())
return false;
if (!IsDelegateConstruction(value as NewObj, true))
return false;
var nextInstruction = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex + 1);
if (nextInstruction == null)
return false;
var usages = nextInstruction.Descendants.Where(i => i.MatchLdsFld(field)).ToArray();
if (usages.Length != 1)
return false;
usages[0].ReplaceWith(value);
return true;
}
bool CachedDelegateInitializationWithLocal(IfInstruction inst, out bool hasFieldStore, out ILVariable local)
{
// [stloc v(ldsfld CachedAnonMethodDelegate)]
// if (comp(ldloc v == ldnull) {
// stloc v(DelegateConstruction)
// [stsfld CachedAnonMethodDelegate(v)]
// }
// ... one usage of v ...
// =>
// ... one usage of DelegateConstruction ...
Block trueInst = inst.TrueInst as Block;
var condition = inst.Condition as Comp;
hasFieldStore = false;
local = null;
if (condition == null || trueInst == null || (trueInst.Instructions.Count < 1) || !inst.FalseInst.MatchNop())
return false;
ILVariable v;
ILInstruction value, value2;
var storeInst = trueInst.Instructions.Last();
if (!condition.Left.MatchLdLoc(out v) || !condition.Right.MatchLdNull())
return false;
if (!storeInst.MatchStLoc(v, out value))
return false;
// the optional field store was moved into storeInst by inline assignment:
if (!(value is NewObj)) {
IField field, field2;
if (value.MatchStsFld(out value2, out field)) {
if (!(value2 is NewObj) || !field.IsCompilerGeneratedOrIsInCompilerGeneratedClass())
return false;
var storeBeforeIf = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex - 1) as StLoc;
if (storeBeforeIf == null || storeBeforeIf.Variable != v || !storeBeforeIf.Value.MatchLdsFld(out field2) || !field.Equals(field2))
return false;
value = value2;
hasFieldStore = true;
} else if (value.MatchStFld(out value2, out field)) {
if (!(value2 is NewObj) || !field.IsCompilerGeneratedOrIsInCompilerGeneratedClass())
return false;
var storeBeforeIf = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex - 1) as StLoc;
if (storeBeforeIf == null || storeBeforeIf.Variable != v || !storeBeforeIf.Value.MatchLdFld(out field2) || !field.Equals(field2))
return false;
value = value2;
hasFieldStore = true;
} else {
return false;
}
}
if (!IsDelegateConstruction(value as NewObj, true))
return false;
var nextInstruction = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex + 1);
if (nextInstruction == null)
return false;
var usages = nextInstruction.Descendants.OfType<LdLoc>().Where(i => i.Variable == v).ToArray();
if (usages.Length != 1)
return false;
local = v;
usages[0].ReplaceWith(value);
return true;
}
}
}

Loading…
Cancel
Save