Browse Source

Merge branch 'master' of git://github.com/icsharpcode/ILSpy into Debugger

pull/191/merge
Eusebiu Marcu 16 years ago
parent
commit
45d37675db
  1. 172
      ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs
  2. 125
      ICSharpCode.Decompiler/ILAst/GotoRemoval.cs
  3. 205
      ICSharpCode.Decompiler/ILAst/ILAstOptimizer.cs
  4. 29
      ICSharpCode.Decompiler/ILAst/ILAstTypes.cs
  5. 4
      ICSharpCode.Decompiler/ILAst/ILCodes.cs
  6. 2
      ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs
  7. 12
      NRefactory/ICSharpCode.NRefactory/CSharp/OutputVisitor/OutputVisitor.cs

172
ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs

@ -84,9 +84,7 @@ namespace ICSharpCode.Decompiler.Ast
{ {
Ast.BlockStatement astBlock = new BlockStatement(); Ast.BlockStatement astBlock = new BlockStatement();
if (block != null) { if (block != null) {
if (block.EntryGoto != null) foreach(ILNode node in block.GetChildren()) {
astBlock.Add((Statement)TransformExpression(block.EntryGoto));
foreach(ILNode node in block.Body) {
astBlock.AddRange(TransformNode(node)); astBlock.AddRange(TransformNode(node));
} }
} }
@ -127,16 +125,18 @@ namespace ICSharpCode.Decompiler.Ast
}; };
} else if (node is ILSwitch) { } else if (node is ILSwitch) {
ILSwitch ilSwitch = (ILSwitch)node; ILSwitch ilSwitch = (ILSwitch)node;
SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition.Arguments[0]) }; SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) };
for (int i = 0; i < ilSwitch.CaseBlocks.Count; i++) { foreach (var caseBlock in ilSwitch.CaseBlocks) {
SwitchSection section = new SwitchSection(); SwitchSection section = new SwitchSection();
section.CaseLabels.Add(new CaseLabel() { Expression = new PrimitiveExpression(i) }); if (caseBlock.Values != null) {
section.Statements.Add(TransformBlock(ilSwitch.CaseBlocks[i])); section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, ilSwitch.Condition.InferredType) }));
} else {
section.CaseLabels.Add(new CaseLabel());
}
section.Statements.Add(TransformBlock(caseBlock));
switchStmt.SwitchSections.Add(section); switchStmt.SwitchSections.Add(section);
} }
yield return switchStmt; yield return switchStmt;
if (ilSwitch.DefaultGoto != null)
yield return (Statement)TransformExpression(ilSwitch.DefaultGoto);
} else if (node is ILTryCatchBlock) { } else if (node is ILTryCatchBlock) {
ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node); ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node);
var tryCatchStmt = new Ast.TryCatchStatement(); var tryCatchStmt = new Ast.TryCatchStatement();
@ -161,41 +161,6 @@ namespace ICSharpCode.Decompiler.Ast
} }
} }
List<Ast.Expression> TransformExpressionArguments(ILExpression expr)
{
List<Ast.Expression> args = new List<Ast.Expression>();
// Args generated by nested expressions (which must be closed)
foreach(ILExpression arg in expr.Arguments) {
args.Add((Ast.Expression)TransformExpression(arg));
}
return args;
}
static string FormatByteCodeOperand(object operand)
{
if (operand == null) {
return string.Empty;
//} else if (operand is ILExpression) {
// return string.Format("IL_{0:X2}", ((ILExpression)operand).Offset);
} else if (operand is MethodReference) {
return ((MethodReference)operand).Name + "()";
} else if (operand is Cecil.TypeReference) {
return ((Cecil.TypeReference)operand).FullName;
} else if (operand is VariableDefinition) {
return ((VariableDefinition)operand).Name;
} else if (operand is ParameterDefinition) {
return ((ParameterDefinition)operand).Name;
} else if (operand is FieldReference) {
return ((FieldReference)operand).Name;
} else if (operand is string) {
return "\"" + operand + "\"";
} else if (operand is int) {
return operand.ToString();
} else {
return operand.ToString();
}
}
AstNode TransformExpression(ILExpression expr) AstNode TransformExpression(ILExpression expr)
{ {
AstNode node = TransformByteCode(expr); AstNode node = TransformByteCode(expr);
@ -211,7 +176,10 @@ namespace ICSharpCode.Decompiler.Ast
object operand = byteCode.Operand; object operand = byteCode.Operand;
AstType operandAsTypeRef = AstBuilder.ConvertType(operand as Cecil.TypeReference); AstType operandAsTypeRef = AstBuilder.ConvertType(operand as Cecil.TypeReference);
List<Ast.Expression> args = TransformExpressionArguments(byteCode); List<Ast.Expression> args = new List<Expression>();
foreach(ILExpression arg in byteCode.Arguments) {
args.Add((Ast.Expression)TransformExpression(arg));
}
Ast.Expression arg1 = args.Count >= 1 ? args[0] : null; Ast.Expression arg1 = args.Count >= 1 ? args[0] : null;
Ast.Expression arg2 = args.Count >= 2 ? args[1] : null; Ast.Expression arg2 = args.Count >= 2 ? args[1] : null;
Ast.Expression arg3 = args.Count >= 3 ? args[2] : null; Ast.Expression arg3 = args.Count >= 3 ? args[2] : null;
@ -237,14 +205,12 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Shl: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftLeft, arg2); case ILCode.Shl: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftLeft, arg2);
case ILCode.Shr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2); case ILCode.Shr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2);
case ILCode.Shr_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2); case ILCode.Shr_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2);
case ILCode.Neg: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Minus, arg1); case ILCode.Neg: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Minus, arg1);
case ILCode.Not: return new Ast.UnaryOperatorExpression(UnaryOperatorType.BitNot, arg1); case ILCode.Not: return new Ast.UnaryOperatorExpression(UnaryOperatorType.BitNot, arg1);
#endregion #endregion
#region Arrays #region Arrays
case ILCode.Newarr: case ILCode.Newarr:
case ILCode.InitArray: case ILCode.InitArray: {
{
var ace = new Ast.ArrayCreateExpression(); var ace = new Ast.ArrayCreateExpression();
ace.Type = operandAsTypeRef; ace.Type = operandAsTypeRef;
ComposedType ct = operandAsTypeRef as ComposedType; ComposedType ct = operandAsTypeRef as ComposedType;
@ -260,8 +226,7 @@ namespace ICSharpCode.Decompiler.Ast
} }
return ace; return ace;
} }
case ILCode.Ldlen: case ILCode.Ldlen: return arg1.Member("Length");
return arg1.Member("Length");
case ILCode.Ldelem_I: case ILCode.Ldelem_I:
case ILCode.Ldelem_I1: case ILCode.Ldelem_I1:
case ILCode.Ldelem_I2: case ILCode.Ldelem_I2:
@ -275,9 +240,7 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Ldelem_Ref: case ILCode.Ldelem_Ref:
case ILCode.Ldelem_Any: case ILCode.Ldelem_Any:
return arg1.Indexer(arg2); return arg1.Indexer(arg2);
case ILCode.Ldelema: case ILCode.Ldelema: return MakeRef(arg1.Indexer(arg2));
return MakeRef(arg1.Indexer(arg2));
case ILCode.Stelem_I: case ILCode.Stelem_I:
case ILCode.Stelem_I1: case ILCode.Stelem_I1:
case ILCode.Stelem_I2: case ILCode.Stelem_I2:
@ -290,23 +253,18 @@ namespace ICSharpCode.Decompiler.Ast
return new Ast.AssignmentExpression(arg1.Indexer(arg2), arg3); return new Ast.AssignmentExpression(arg1.Indexer(arg2), arg3);
#endregion #endregion
#region Comparison #region Comparison
case ILCode.Ceq: case ILCode.Ceq: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Equality, arg2);
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Equality, arg2); case ILCode.Cgt: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2);
case ILCode.Cgt: case ILCode.Cgt_Un: {
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2);
case ILCode.Cgt_Un:
// can also mean Inequality, when used with object references // can also mean Inequality, when used with object references
{
TypeReference arg1Type = byteCode.Arguments[0].InferredType; TypeReference arg1Type = byteCode.Arguments[0].InferredType;
if (arg1Type != null && !arg1Type.IsValueType) if (arg1Type != null && !arg1Type.IsValueType)
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.InEquality, arg2); return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.InEquality, arg2);
else else
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2); return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2);
} }
case ILCode.Clt: case ILCode.Clt: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2);
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2); case ILCode.Clt_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2);
case ILCode.Clt_Un:
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2);
#endregion #endregion
#region Logical #region Logical
case ILCode.LogicNot: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Not, arg1); case ILCode.LogicNot: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Not, arg1);
@ -323,7 +281,7 @@ namespace ICSharpCode.Decompiler.Ast
new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name) new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name)
} }
}; };
case ILCode.LoopBreak: return new Ast.BreakStatement(); case ILCode.LoopOrSwitchBreak: return new Ast.BreakStatement();
case ILCode.LoopContinue: return new Ast.ContinueStatement(); case ILCode.LoopContinue: return new Ast.ContinueStatement();
#endregion #endregion
#region Conversions #region Conversions
@ -341,7 +299,6 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Conv_R4: return arg1.CastTo(typeof(float)); case ILCode.Conv_R4: return arg1.CastTo(typeof(float));
case ILCode.Conv_R8: return arg1.CastTo(typeof(double)); case ILCode.Conv_R8: return arg1.CastTo(typeof(double));
case ILCode.Conv_R_Un: return arg1.CastTo(typeof(double)); // TODO case ILCode.Conv_R_Un: return arg1.CastTo(typeof(double)); // TODO
case ILCode.Conv_Ovf_I1: case ILCode.Conv_Ovf_I1:
case ILCode.Conv_Ovf_I2: case ILCode.Conv_Ovf_I2:
case ILCode.Conv_Ovf_I4: case ILCode.Conv_Ovf_I4:
@ -363,16 +320,11 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Conv_Ovf_U: return arg1.CastTo(typeof(UIntPtr)); case ILCode.Conv_Ovf_U: return arg1.CastTo(typeof(UIntPtr));
case ILCode.Conv_Ovf_I_Un: return arg1.CastTo(typeof(IntPtr)); case ILCode.Conv_Ovf_I_Un: return arg1.CastTo(typeof(IntPtr));
case ILCode.Conv_Ovf_U_Un: return arg1.CastTo(typeof(UIntPtr)); case ILCode.Conv_Ovf_U_Un: return arg1.CastTo(typeof(UIntPtr));
case ILCode.Castclass: return arg1.CastTo(operandAsTypeRef);
case ILCode.Castclass: case ILCode.Unbox_Any: return arg1.CastTo(operandAsTypeRef);
case ILCode.Unbox_Any: case ILCode.Isinst: return arg1.CastAs(operandAsTypeRef);
return arg1.CastTo(operandAsTypeRef); case ILCode.Box: return arg1;
case ILCode.Isinst: case ILCode.Unbox: return InlineAssembly(byteCode, args);
return arg1.CastAs(operandAsTypeRef);
case ILCode.Box:
return arg1;
case ILCode.Unbox:
return InlineAssembly(byteCode, args);
#endregion #endregion
#region Indirect #region Indirect
case ILCode.Ldind_I: case ILCode.Ldind_I:
@ -391,7 +343,6 @@ namespace ICSharpCode.Decompiler.Ast
return ((DirectionExpression)args[0]).Expression.Detach(); return ((DirectionExpression)args[0]).Expression.Detach();
else else
return InlineAssembly(byteCode, args); return InlineAssembly(byteCode, args);
case ILCode.Stind_I: case ILCode.Stind_I:
case ILCode.Stind_I1: case ILCode.Stind_I1:
case ILCode.Stind_I2: case ILCode.Stind_I2:
@ -408,12 +359,9 @@ namespace ICSharpCode.Decompiler.Ast
#endregion #endregion
case ILCode.Arglist: return InlineAssembly(byteCode, args); case ILCode.Arglist: return InlineAssembly(byteCode, args);
case ILCode.Break: return InlineAssembly(byteCode, args); case ILCode.Break: return InlineAssembly(byteCode, args);
case ILCode.Call: case ILCode.Call: return TransformCall(false, operand, methodDef, args);
return TransformCall(false, operand, methodDef, args); case ILCode.Callvirt: return TransformCall(true, operand, methodDef, args);
case ILCode.Callvirt: case ILCode.Ldftn: {
return TransformCall(true, operand, methodDef, args);
case ILCode.Ldftn:
{
Cecil.MethodReference cecilMethod = ((MethodReference)operand); Cecil.MethodReference cecilMethod = ((MethodReference)operand);
var expr = new Ast.IdentifierExpression(cecilMethod.Name); var expr = new Ast.IdentifierExpression(cecilMethod.Name);
expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod)); expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod));
@ -421,8 +369,7 @@ namespace ICSharpCode.Decompiler.Ast
return new IdentifierExpression("ldftn").Invoke(expr) return new IdentifierExpression("ldftn").Invoke(expr)
.WithAnnotation(new Transforms.DelegateConstruction.Annotation(false)); .WithAnnotation(new Transforms.DelegateConstruction.Annotation(false));
} }
case ILCode.Ldvirtftn: case ILCode.Ldvirtftn: {
{
Cecil.MethodReference cecilMethod = ((MethodReference)operand); Cecil.MethodReference cecilMethod = ((MethodReference)operand);
var expr = new Ast.IdentifierExpression(cecilMethod.Name); var expr = new Ast.IdentifierExpression(cecilMethod.Name);
expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod)); expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod));
@ -430,7 +377,6 @@ namespace ICSharpCode.Decompiler.Ast
return new IdentifierExpression("ldvirtftn").Invoke(expr) return new IdentifierExpression("ldvirtftn").Invoke(expr)
.WithAnnotation(new Transforms.DelegateConstruction.Annotation(true)); .WithAnnotation(new Transforms.DelegateConstruction.Annotation(true));
} }
case ILCode.Calli: return InlineAssembly(byteCode, args); case ILCode.Calli: return InlineAssembly(byteCode, args);
case ILCode.Ckfinite: return InlineAssembly(byteCode, args); case ILCode.Ckfinite: return InlineAssembly(byteCode, args);
case ILCode.Constrained: return InlineAssembly(byteCode, args); case ILCode.Constrained: return InlineAssembly(byteCode, args);
@ -445,9 +391,8 @@ namespace ICSharpCode.Decompiler.Ast
return new AssignmentExpression(((DirectionExpression)args[0]).Expression.Detach(), new DefaultValueExpression { Type = operandAsTypeRef }); return new AssignmentExpression(((DirectionExpression)args[0]).Expression.Detach(), new DefaultValueExpression { Type = operandAsTypeRef });
else else
return InlineAssembly(byteCode, args); return InlineAssembly(byteCode, args);
case ILCode.Jmp: case ILCode.Jmp: return InlineAssembly(byteCode, args);
return InlineAssembly(byteCode, args); case ILCode.Ldarg: {
case ILCode.Ldarg:
if (methodDef.HasThis && ((ParameterDefinition)operand).Index < 0) { if (methodDef.HasThis && ((ParameterDefinition)operand).Index < 0) {
if (context.CurrentMethod.DeclaringType.IsValueType) if (context.CurrentMethod.DeclaringType.IsValueType)
return MakeRef(new Ast.ThisReferenceExpression()); return MakeRef(new Ast.ThisReferenceExpression());
@ -460,14 +405,14 @@ namespace ICSharpCode.Decompiler.Ast
else else
return expr; return expr;
} }
}
case ILCode.Ldarga: case ILCode.Ldarga:
if (methodDef.HasThis && ((ParameterDefinition)operand).Index < 0) { if (methodDef.HasThis && ((ParameterDefinition)operand).Index < 0) {
return MakeRef(new Ast.ThisReferenceExpression()); return MakeRef(new Ast.ThisReferenceExpression());
} else { } else {
return MakeRef(new Ast.IdentifierExpression(((ParameterDefinition)operand).Name).WithAnnotation(operand)); return MakeRef(new Ast.IdentifierExpression(((ParameterDefinition)operand).Name).WithAnnotation(operand));
} }
case ILCode.Ldc_I4: case ILCode.Ldc_I4: return AstBuilder.MakePrimitive((int)operand, byteCode.InferredType);
return AstBuilder.MakePrimitive((int)operand, byteCode.InferredType);
case ILCode.Ldc_I8: case ILCode.Ldc_I8:
case ILCode.Ldc_R4: case ILCode.Ldc_R4:
case ILCode.Ldc_R8: case ILCode.Ldc_R8:
@ -489,8 +434,7 @@ namespace ICSharpCode.Decompiler.Ast
AstBuilder.ConvertType(((FieldReference)operand).DeclaringType) AstBuilder.ConvertType(((FieldReference)operand).DeclaringType)
.Member(((FieldReference)operand).Name).WithAnnotation(operand), .Member(((FieldReference)operand).Name).WithAnnotation(operand),
arg1); arg1);
case ILCode.Ldflda: case ILCode.Ldflda: return MakeRef(arg1.Member(((FieldReference) operand).Name).WithAnnotation(operand));
return MakeRef(arg1.Member(((FieldReference) operand).Name).WithAnnotation(operand));
case ILCode.Ldsflda: case ILCode.Ldsflda:
return MakeRef( return MakeRef(
AstBuilder.ConvertType(((FieldReference)operand).DeclaringType) AstBuilder.ConvertType(((FieldReference)operand).DeclaringType)
@ -501,10 +445,8 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Ldloca: case ILCode.Ldloca:
localVariablesToDefine.Add((ILVariable)operand); localVariablesToDefine.Add((ILVariable)operand);
return MakeRef(new Ast.IdentifierExpression(((ILVariable)operand).Name).WithAnnotation(operand)); return MakeRef(new Ast.IdentifierExpression(((ILVariable)operand).Name).WithAnnotation(operand));
case ILCode.Ldnull: case ILCode.Ldnull: return new Ast.NullReferenceExpression();
return new Ast.NullReferenceExpression(); case ILCode.Ldstr: return new Ast.PrimitiveExpression(operand);
case ILCode.Ldstr:
return new Ast.PrimitiveExpression(operand);
case ILCode.Ldtoken: case ILCode.Ldtoken:
if (operand is Cecil.TypeReference) { if (operand is Cecil.TypeReference) {
return new Ast.TypeOfExpression { Type = operandAsTypeRef }.Member("TypeHandle"); return new Ast.TypeOfExpression { Type = operandAsTypeRef }.Member("TypeHandle");
@ -514,10 +456,8 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Leave: return new GotoStatement() { Label = ((ILLabel)operand).Name }; case ILCode.Leave: return new GotoStatement() { Label = ((ILLabel)operand).Name };
case ILCode.Localloc: return InlineAssembly(byteCode, args); case ILCode.Localloc: return InlineAssembly(byteCode, args);
case ILCode.Mkrefany: return InlineAssembly(byteCode, args); case ILCode.Mkrefany: return InlineAssembly(byteCode, args);
case ILCode.Newobj: case ILCode.Newobj: {
{
Cecil.TypeReference declaringType = ((MethodReference)operand).DeclaringType; Cecil.TypeReference declaringType = ((MethodReference)operand).DeclaringType;
if (declaringType is ArrayType) { if (declaringType is ArrayType) {
ComposedType ct = AstBuilder.ConvertType((ArrayType)declaringType) as ComposedType; ComposedType ct = AstBuilder.ConvertType((ArrayType)declaringType) as ComposedType;
if (ct != null && ct.ArraySpecifiers.Count >= 1) { if (ct != null && ct.ArraySpecifiers.Count >= 1) {
@ -540,18 +480,15 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Readonly: return InlineAssembly(byteCode, args); case ILCode.Readonly: return InlineAssembly(byteCode, args);
case ILCode.Refanytype: return InlineAssembly(byteCode, args); case ILCode.Refanytype: return InlineAssembly(byteCode, args);
case ILCode.Refanyval: return InlineAssembly(byteCode, args); case ILCode.Refanyval: return InlineAssembly(byteCode, args);
case ILCode.Ret: { case ILCode.Ret:
if (methodDef.ReturnType.FullName != "System.Void") { if (methodDef.ReturnType.FullName != "System.Void") {
return new Ast.ReturnStatement { Expression = arg1 }; return new Ast.ReturnStatement { Expression = arg1 };
} else { } else {
return new Ast.ReturnStatement(); return new Ast.ReturnStatement();
} }
}
case ILCode.Rethrow: return new Ast.ThrowStatement(); case ILCode.Rethrow: return new Ast.ThrowStatement();
case ILCode.Sizeof: case ILCode.Sizeof: return new Ast.SizeOfExpression { Type = operandAsTypeRef };
return new Ast.SizeOfExpression { Type = operandAsTypeRef }; case ILCode.Starg: return new Ast.AssignmentExpression(new Ast.IdentifierExpression(((ParameterDefinition)operand).Name).WithAnnotation(operand), arg1);
case ILCode.Starg:
return new Ast.AssignmentExpression(new Ast.IdentifierExpression(((ParameterDefinition)operand).Name).WithAnnotation(operand), arg1);
case ILCode.Stloc: { case ILCode.Stloc: {
ILVariable locVar = (ILVariable)operand; ILVariable locVar = (ILVariable)operand;
localVariablesToDefine.Add(locVar); localVariablesToDefine.Add(locVar);
@ -714,6 +651,31 @@ namespace ICSharpCode.Decompiler.Ast
return new IdentifierExpression(byteCode.Code.GetName()).Invoke(args); return new IdentifierExpression(byteCode.Code.GetName()).Invoke(args);
} }
static string FormatByteCodeOperand(object operand)
{
if (operand == null) {
return string.Empty;
//} else if (operand is ILExpression) {
// return string.Format("IL_{0:X2}", ((ILExpression)operand).Offset);
} else if (operand is MethodReference) {
return ((MethodReference)operand).Name + "()";
} else if (operand is Cecil.TypeReference) {
return ((Cecil.TypeReference)operand).FullName;
} else if (operand is VariableDefinition) {
return ((VariableDefinition)operand).Name;
} else if (operand is ParameterDefinition) {
return ((ParameterDefinition)operand).Name;
} else if (operand is FieldReference) {
return ((FieldReference)operand).Name;
} else if (operand is string) {
return "\"" + operand + "\"";
} else if (operand is int) {
return operand.ToString();
} else {
return operand.ToString();
}
}
static IEnumerable<AstType> ConvertTypeArguments(MethodReference cecilMethod) static IEnumerable<AstType> ConvertTypeArguments(MethodReference cecilMethod)
{ {
GenericInstanceMethod g = cecilMethod as GenericInstanceMethod; GenericInstanceMethod g = cecilMethod as GenericInstanceMethod;

125
ICSharpCode.Decompiler/ILAst/GotoRemoval.cs

@ -29,9 +29,13 @@ namespace ICSharpCode.Decompiler.ILAst
} }
// Simplify gotos // Simplify gotos
bool modified;
do {
modified = false;
foreach (ILExpression gotoExpr in method.GetSelfAndChildrenRecursive<ILExpression>().Where(e => e.Code == ILCode.Br || e.Code == ILCode.Leave)) { foreach (ILExpression gotoExpr in method.GetSelfAndChildrenRecursive<ILExpression>().Where(e => e.Code == ILCode.Br || e.Code == ILCode.Leave)) {
TrySimplifyGoto(gotoExpr); modified |= TrySimplifyGoto(gotoExpr);
} }
} while(modified);
RemoveRedundantCode(method); RemoveRedundantCode(method);
} }
@ -52,44 +56,79 @@ namespace ICSharpCode.Decompiler.ILAst
} }
} }
// Remove redundant break at the end of case
// Remove redundant case blocks altogether
foreach(ILSwitch ilSwitch in method.GetSelfAndChildrenRecursive<ILSwitch>()) {
foreach(ILBlock ilCase in ilSwitch.CaseBlocks) {
Debug.Assert(ilCase.EntryGoto == null);
int count = ilCase.Body.Count;
if (count >= 2) {
if (!ilCase.Body[count - 2].CanFallThough() &&
ilCase.Body[count - 1].Match(ILCode.LoopOrSwitchBreak)) {
ilCase.Body.RemoveAt(count - 1);
}
}
}
var defaultCase = ilSwitch.CaseBlocks.Where(cb => cb.Values == null).SingleOrDefault();
// If there is no default block, remove empty case blocks
if (defaultCase == null || (defaultCase.Body.Count == 1 && defaultCase.Body.Single().Match(ILCode.LoopOrSwitchBreak))) {
ilSwitch.CaseBlocks.RemoveAll(b => b.Body.Count == 1 && b.Body.Single().Match(ILCode.LoopOrSwitchBreak));
}
}
// Remove redundant return // Remove redundant return
if (method.Body.Count > 0 && method.Body.Last().Match(ILCode.Ret) && ((ILExpression)method.Body.Last()).Arguments.Count == 0) { if (method.Body.Count > 0 && method.Body.Last().Match(ILCode.Ret) && ((ILExpression)method.Body.Last()).Arguments.Count == 0) {
method.Body.RemoveAt(method.Body.Count - 1); method.Body.RemoveAt(method.Body.Count - 1);
} }
} }
IEnumerable<ILNode> GetParents(ILNode node)
{
ILNode current = node;
while(true) {
current = parent[current];
if (current == null)
yield break;
yield return current;
}
}
bool TrySimplifyGoto(ILExpression gotoExpr) bool TrySimplifyGoto(ILExpression gotoExpr)
{ {
Debug.Assert(gotoExpr.Code == ILCode.Br || gotoExpr.Code == ILCode.Leave); Debug.Assert(gotoExpr.Code == ILCode.Br || gotoExpr.Code == ILCode.Leave);
Debug.Assert(gotoExpr.Prefixes == null); Debug.Assert(gotoExpr.Prefixes == null);
Debug.Assert(gotoExpr.Operand != null); Debug.Assert(gotoExpr.Operand != null);
ILExpression target = Enter(gotoExpr, new HashSet<ILNode>()); ILNode target = Enter(gotoExpr, new HashSet<ILNode>());
if (target == null) if (target == null)
return false; return false;
// The gotoExper is marked as visited because we do not want to
// walk over node which we plan to modify
// The simulated path always has to start in the same try-block
// in other for the same finally blocks to be executed.
if (target == Exit(gotoExpr, new HashSet<ILNode>() { gotoExpr })) { if (target == Exit(gotoExpr, new HashSet<ILNode>() { gotoExpr })) {
gotoExpr.Code = ILCode.Nop; gotoExpr.Code = ILCode.Nop;
gotoExpr.Operand = null; gotoExpr.Operand = null;
target.ILRanges.AddRange(gotoExpr.ILRanges); if (target is ILExpression)
((ILExpression)target).ILRanges.AddRange(gotoExpr.ILRanges);
gotoExpr.ILRanges.Clear(); gotoExpr.ILRanges.Clear();
return true; return true;
} }
ILWhileLoop loop = null; ILNode breakBlock = GetParents(gotoExpr).Where(n => n is ILWhileLoop || n is ILSwitch).FirstOrDefault();
ILNode current = gotoExpr; if (breakBlock != null && target == Exit(breakBlock, new HashSet<ILNode>() { gotoExpr })) {
while(loop == null && current != null) { gotoExpr.Code = ILCode.LoopOrSwitchBreak;
current = parent[current];
loop = current as ILWhileLoop;
}
if (loop != null && target == Exit(loop, new HashSet<ILNode>() { gotoExpr })) {
gotoExpr.Code = ILCode.LoopBreak;
gotoExpr.Operand = null; gotoExpr.Operand = null;
return true; return true;
} }
if (loop != null && target == Enter(loop, new HashSet<ILNode>() { gotoExpr })) { ILNode continueBlock = GetParents(gotoExpr).Where(n => n is ILWhileLoop).FirstOrDefault();
if (continueBlock != null && target == Enter(continueBlock, new HashSet<ILNode>() { gotoExpr })) {
gotoExpr.Code = ILCode.LoopContinue; gotoExpr.Code = ILCode.LoopContinue;
gotoExpr.Operand = null; gotoExpr.Operand = null;
return true; return true;
@ -99,9 +138,10 @@ namespace ICSharpCode.Decompiler.ILAst
} }
/// <summary> /// <summary>
/// Get the first expression to be excecuted if the instruction pointer is at the start of the given node /// Get the first expression to be excecuted if the instruction pointer is at the start of the given node.
/// Try blocks may not be entered in any way. If possible, the try block is returned as the node to be executed.
/// </summary> /// </summary>
ILExpression Enter(ILNode node, HashSet<ILNode> visitedNodes) ILNode Enter(ILNode node, HashSet<ILNode> visitedNodes)
{ {
if (node == null) if (node == null)
throw new ArgumentNullException(); throw new ArgumentNullException();
@ -117,9 +157,43 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression expr = node as ILExpression; ILExpression expr = node as ILExpression;
if (expr != null) { if (expr != null) {
if (expr.Code == ILCode.Br || expr.Code == ILCode.Leave) { if (expr.Code == ILCode.Br || expr.Code == ILCode.Leave) {
return Enter((ILLabel)expr.Operand, visitedNodes); ILLabel target = (ILLabel)expr.Operand;
// Early exit - same try-block
if (GetParents(expr).OfType<ILTryCatchBlock>().FirstOrDefault() == GetParents(target).OfType<ILTryCatchBlock>().FirstOrDefault())
return Enter(target, visitedNodes);
// Make sure we are not entering any try-block
var srcTryBlocks = GetParents(expr).OfType<ILTryCatchBlock>().Reverse().ToList();
var dstTryBlocks = GetParents(target).OfType<ILTryCatchBlock>().Reverse().ToList();
// Skip blocks that we are already in
int i = 0;
while(i < srcTryBlocks.Count && i < dstTryBlocks.Count && srcTryBlocks[i] == dstTryBlocks[i]) i++;
if (i == dstTryBlocks.Count) {
return Enter(target, visitedNodes);
} else {
ILTryCatchBlock dstTryBlock = dstTryBlocks[i];
// Check that the goto points to the start
ILTryCatchBlock current = dstTryBlock;
while(current != null) {
foreach(ILNode n in current.TryBlock.Body) {
if (n is ILLabel) {
if (n == target)
return dstTryBlock;
} else if (!n.Match(ILCode.Nop)) {
current = n as ILTryCatchBlock;
break;
}
}
}
return null;
}
} else if (expr.Code == ILCode.Nop) { } else if (expr.Code == ILCode.Nop) {
return Exit(expr, visitedNodes); return Exit(expr, visitedNodes);
} else if (expr.Code == ILCode.LoopOrSwitchBreak) {
ILNode breakBlock = GetParents(expr).Where(n => n is ILWhileLoop || n is ILSwitch).First();
return Exit(breakBlock, new HashSet<ILNode>() { expr });
} else if (expr.Code == ILCode.LoopContinue) {
ILNode continueBlock = GetParents(expr).Where(n => n is ILWhileLoop).First();
return Enter(continueBlock, new HashSet<ILNode>() { expr });
} else { } else {
return expr; return expr;
} }
@ -152,7 +226,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILTryCatchBlock tryCatch = node as ILTryCatchBlock; ILTryCatchBlock tryCatch = node as ILTryCatchBlock;
if (tryCatch != null) { if (tryCatch != null) {
return Enter(tryCatch.TryBlock, visitedNodes); return tryCatch;
} }
ILSwitch ilSwitch = node as ILSwitch; ILSwitch ilSwitch = node as ILSwitch;
@ -166,7 +240,7 @@ namespace ICSharpCode.Decompiler.ILAst
/// <summary> /// <summary>
/// Get the first expression to be excecuted if the instruction pointer is at the end of the given node /// Get the first expression to be excecuted if the instruction pointer is at the end of the given node
/// </summary> /// </summary>
ILExpression Exit(ILNode node, HashSet<ILNode> visitedNodes) ILNode Exit(ILNode node, HashSet<ILNode> visitedNodes)
{ {
if (node == null) if (node == null)
throw new ArgumentNullException(); throw new ArgumentNullException();
@ -184,13 +258,20 @@ namespace ICSharpCode.Decompiler.ILAst
} }
} }
if (nodeParent is ILCondition || if (nodeParent is ILCondition) {
nodeParent is ILTryCatchBlock ||
nodeParent is ILSwitch)
{
return Exit(nodeParent, visitedNodes); return Exit(nodeParent, visitedNodes);
} }
if (nodeParent is ILTryCatchBlock) {
// Finally blocks are completely ignored.
// We rely on the fact that try blocks can not be entered.
return Exit(nodeParent, visitedNodes);
}
if (nodeParent is ILSwitch) {
return null; // Implicit exit from switch is not allowed
}
if (nodeParent is ILWhileLoop) { if (nodeParent is ILWhileLoop) {
return Enter(nodeParent, visitedNodes); return Enter(nodeParent, visitedNodes);
} }

205
ICSharpCode.Decompiler/ILAst/ILAstOptimizer.cs

@ -101,6 +101,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression expr = block.Body[i] as ILExpression; ILExpression expr = block.Body[i] as ILExpression;
if (expr != null && expr.Prefixes == null) { if (expr != null && expr.Prefixes == null) {
switch(expr.Code) { switch(expr.Code) {
case ILCode.Switch:
case ILCode.Brtrue: case ILCode.Brtrue:
expr.Arguments.Single().ILRanges.AddRange(expr.ILRanges); expr.Arguments.Single().ILRanges.AddRange(expr.ILRanges);
expr.ILRanges.Clear(); expr.ILRanges.Clear();
@ -235,40 +236,26 @@ namespace ICSharpCode.Decompiler.ILAst
} while(modified); } while(modified);
} }
bool IsStloc(ILBasicBlock bb, ref ILVariable locVar, ref ILExpression val, ref ILLabel fallLabel)
{
if (bb.Body.Count == 1) {
ILExpression expr;
if (bb.Body[0].Match(ILCode.Stloc, out expr)) {
locVar = (ILVariable)expr.Operand;
val = expr.Arguments[0];
fallLabel = (ILLabel)bb.FallthoughGoto.Operand;
return true;
}
}
return false;
}
// scope is modified if successful // scope is modified if successful
bool TrySimplifyTernaryOperator(List<ILNode> scope, ILBasicBlock head) bool TrySimplifyTernaryOperator(List<ILNode> scope, ILBasicBlock head)
{ {
Debug.Assert(scope.Contains(head)); Debug.Assert(scope.Contains(head));
ILExpression condExpr = null; ILExpression condExpr;
ILLabel trueLabel = null; ILLabel trueLabel;
ILLabel falseLabel = null; ILLabel falseLabel;
ILVariable trueLocVar = null; ILVariable trueLocVar;
ILExpression trueExpr = null; ILExpression trueExpr;
ILLabel trueFall = null; ILLabel trueFall;
ILVariable falseLocVar = null; ILVariable falseLocVar;
ILExpression falseExpr = null; ILExpression falseExpr;
ILLabel falseFall = null; ILLabel falseFall;
if(head.MatchBrTure(out condExpr, out trueLabel, out falseLabel) && if(head.Match(ILCode.Brtrue, out trueLabel, out condExpr, out falseLabel) &&
labelGlobalRefCount[trueLabel] == 1 && labelGlobalRefCount[trueLabel] == 1 &&
labelGlobalRefCount[falseLabel] == 1 && labelGlobalRefCount[falseLabel] == 1 &&
IsStloc(labelToBasicBlock[trueLabel], ref trueLocVar, ref trueExpr, ref trueFall) && labelToBasicBlock[trueLabel].Match(ILCode.Stloc, out trueLocVar, out trueExpr, out trueFall) &&
IsStloc(labelToBasicBlock[falseLabel], ref falseLocVar, ref falseExpr, ref falseFall) && labelToBasicBlock[falseLabel].Match(ILCode.Stloc, out falseLocVar, out falseExpr, out falseFall) &&
trueLocVar == falseLocVar && trueLocVar == falseLocVar &&
trueFall == falseFall) trueFall == falseFall)
{ {
@ -297,7 +284,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression condExpr; ILExpression condExpr;
ILLabel trueLabel; ILLabel trueLabel;
ILLabel falseLabel; ILLabel falseLabel;
if(head.MatchBrTure(out condExpr, out trueLabel, out falseLabel)) { if(head.Match(ILCode.Brtrue, out trueLabel, out condExpr, out falseLabel)) {
for (int pass = 0; pass < 2; pass++) { for (int pass = 0; pass < 2; pass++) {
// On the second pass, swap labels and negate expression of the first branch // On the second pass, swap labels and negate expression of the first branch
@ -313,7 +300,7 @@ namespace ICSharpCode.Decompiler.ILAst
if (scope.Contains(nextBasicBlock) && if (scope.Contains(nextBasicBlock) &&
nextBasicBlock != head && nextBasicBlock != head &&
labelGlobalRefCount[nextBasicBlock.EntryLabel] == 1 && labelGlobalRefCount[nextBasicBlock.EntryLabel] == 1 &&
nextBasicBlock.MatchBrTure(out nextCondExpr, out nextTrueLablel, out nextFalseLabel) && nextBasicBlock.Match(ILCode.Brtrue, out nextTrueLablel, out nextCondExpr, out nextFalseLabel) &&
(otherLablel == nextFalseLabel || otherLablel == nextTrueLablel)) (otherLablel == nextFalseLabel || otherLablel == nextTrueLablel))
{ {
// Create short cicuit branch // Create short cicuit branch
@ -354,9 +341,7 @@ namespace ICSharpCode.Decompiler.ILAst
foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>()) { foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>()) {
for (int i = 0; i < block.Body.Count; i++) { for (int i = 0; i < block.Body.Count; i++) {
ILLabel targetLabel; ILLabel targetLabel;
if (block.Body[i].Match(ILCode.Br, out targetLabel) || if (block.Body[i].Match(ILCode.Br, out targetLabel) || block.Body[i].Match(ILCode.Leave, out targetLabel)) {
block.Body[i].Match(ILCode.Leave, out targetLabel))
{
// Skip extra labels // Skip extra labels
while(nextSibling.ContainsKey(targetLabel) && nextSibling[targetLabel] is ILLabel) { while(nextSibling.ContainsKey(targetLabel) && nextSibling[targetLabel] is ILLabel) {
targetLabel = (ILLabel)nextSibling[targetLabel]; targetLabel = (ILLabel)nextSibling[targetLabel];
@ -364,20 +349,25 @@ namespace ICSharpCode.Decompiler.ILAst
// Inline return statement // Inline return statement
ILNode target; ILNode target;
ILExpression retExpr; List<ILExpression> retArgs;
if (nextSibling.TryGetValue(targetLabel, out target) && if (nextSibling.TryGetValue(targetLabel, out target)) {
target.Match(ILCode.Ret, out retExpr)) if (target.Match(ILCode.Ret, out retArgs)) {
{
ILVariable locVar; ILVariable locVar;
object constValue; object constValue;
if (retExpr.Arguments.Count == 0) { if (retArgs.Count == 0) {
block.Body[i] = new ILExpression(ILCode.Ret, null); block.Body[i] = new ILExpression(ILCode.Ret, null);
} else if (retExpr.Arguments.Single().Match(ILCode.Ldloc, out locVar)) { } else if (retArgs.Single().Match(ILCode.Ldloc, out locVar)) {
block.Body[i] = new ILExpression(ILCode.Ret, null, new ILExpression(ILCode.Ldloc, locVar)); block.Body[i] = new ILExpression(ILCode.Ret, null, new ILExpression(ILCode.Ldloc, locVar));
} else if (retExpr.Arguments.Single().Match(ILCode.Ldc_I4, out constValue)) { } else if (retArgs.Single().Match(ILCode.Ldc_I4, out constValue)) {
block.Body[i] = new ILExpression(ILCode.Ret, null, new ILExpression(ILCode.Ldc_I4, constValue)); block.Body[i] = new ILExpression(ILCode.Ret, null, new ILExpression(ILCode.Ldc_I4, constValue));
} }
} }
} else {
if (method.Body.Count > 0 && method.Body.Last() == targetLabel) {
// It exits the main method - so it is same as return;
block.Body[i] = new ILExpression(ILCode.Ret, null);
}
}
} }
} }
} }
@ -466,7 +456,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression condExpr; ILExpression condExpr;
ILLabel trueLabel; ILLabel trueLabel;
ILLabel falseLabel; ILLabel falseLabel;
if(basicBlock.MatchBrTure(out condExpr, out trueLabel, out falseLabel)) if(basicBlock.Match(ILCode.Brtrue, out trueLabel, out condExpr, out falseLabel))
{ {
ControlFlowNode trueTarget; ControlFlowNode trueTarget;
labelToCfNode.TryGetValue(trueLabel, out trueTarget); labelToCfNode.TryGetValue(trueLabel, out trueTarget);
@ -579,28 +569,32 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression condBranch = block.Body[0] as ILExpression; ILExpression condBranch = block.Body[0] as ILExpression;
// Switch // Switch
if (condBranch != null && condBranch.Operand is ILLabel[] && condBranch.Arguments.Count > 0) { ILLabel[] caseLabels;
List<ILExpression> switchArgs;
ILLabel[] caseLabels = (ILLabel[])condBranch.Operand; if (condBranch.Match(ILCode.Switch, out caseLabels, out switchArgs)) {
// The labels will not be used - kill them
condBranch.Operand = null;
ILSwitch ilSwitch = new ILSwitch() { ILSwitch ilSwitch = new ILSwitch() { Condition = switchArgs.Single() };
Condition = condBranch, ILBasicBlock newBB = new ILBasicBlock() {
DefaultGoto = block.FallthoughGoto
};
result.Add(new ILBasicBlock() {
EntryLabel = block.EntryLabel, // Keep the entry label EntryLabel = block.EntryLabel, // Keep the entry label
Body = { ilSwitch } Body = { ilSwitch },
}); FallthoughGoto = block.FallthoughGoto
};
result.Add(newBB);
// Remove the item so that it is not picked up as content // Remove the item so that it is not picked up as content
scope.RemoveOrThrow(node); scope.RemoveOrThrow(node);
// Find the switch offset
int addValue = 0;
List<ILExpression> subArgs;
if (ilSwitch.Condition.Match(ILCode.Sub, out subArgs) && subArgs[1].Match(ILCode.Ldc_I4, out addValue)) {
ilSwitch.Condition = subArgs[0];
}
// Pull in code of cases // Pull in code of cases
ILLabel fallLabel = (ILLabel)block.FallthoughGoto.Operand;
ControlFlowNode fallTarget = null; ControlFlowNode fallTarget = null;
labelToCfNode.TryGetValue((ILLabel)block.FallthoughGoto.Operand, out fallTarget); labelToCfNode.TryGetValue(fallLabel, out fallTarget);
HashSet<ControlFlowNode> frontiers = new HashSet<ControlFlowNode>(); HashSet<ControlFlowNode> frontiers = new HashSet<ControlFlowNode>();
if (fallTarget != null) if (fallTarget != null)
@ -613,19 +607,44 @@ namespace ICSharpCode.Decompiler.ILAst
frontiers.UnionWith(condTarget.DominanceFrontier); frontiers.UnionWith(condTarget.DominanceFrontier);
} }
foreach(ILLabel condLabel in caseLabels) { for (int i = 0; i < caseLabels.Length; i++) {
ControlFlowNode condTarget = null; ILLabel condLabel = caseLabels[i];
labelToCfNode.TryGetValue(condLabel, out condTarget);
ILBlock caseBlock = new ILBlock() { // Find or create new case block
ILSwitch.CaseBlock caseBlock = ilSwitch.CaseBlocks.Where(b => b.EntryGoto.Operand == condLabel).FirstOrDefault();
if (caseBlock == null) {
caseBlock = new ILSwitch.CaseBlock() {
Values = new List<int>(),
EntryGoto = new ILExpression(ILCode.Br, condLabel) EntryGoto = new ILExpression(ILCode.Br, condLabel)
}; };
ilSwitch.CaseBlocks.Add(caseBlock);
ControlFlowNode condTarget = null;
labelToCfNode.TryGetValue(condLabel, out condTarget);
if (condTarget != null && !frontiers.Contains(condTarget)) { if (condTarget != null && !frontiers.Contains(condTarget)) {
HashSet<ControlFlowNode> content = FindDominatedNodes(scope, condTarget); HashSet<ControlFlowNode> content = FindDominatedNodes(scope, condTarget);
scope.ExceptWith(content); scope.ExceptWith(content);
caseBlock.Body.AddRange(FindConditions(content, condTarget)); caseBlock.Body.AddRange(FindConditions(content, condTarget));
// Add explicit break which should not be used by default, but the goto removal might decide to use it
caseBlock.Body.Add(new ILBasicBlock() { Body = { new ILExpression(ILCode.LoopOrSwitchBreak, null) } });
}
} }
caseBlock.Values.Add(i + addValue);
}
// Heuristis to determine if we want to use fallthough as default case
if (fallTarget != null && !frontiers.Contains(fallTarget)) {
HashSet<ControlFlowNode> content = FindDominatedNodes(scope, fallTarget);
if (content.Any()) {
var caseBlock = new ILSwitch.CaseBlock() { EntryGoto = new ILExpression(ILCode.Br, fallLabel) };
ilSwitch.CaseBlocks.Add(caseBlock); ilSwitch.CaseBlocks.Add(caseBlock);
newBB.FallthoughGoto = null;
scope.ExceptWith(content);
caseBlock.Body.AddRange(FindConditions(content, fallTarget));
// Add explicit break which should not be used by default, but the goto removal might decide to use it
caseBlock.Body.Add(new ILBasicBlock() { Body = { new ILExpression(ILCode.LoopOrSwitchBreak, null) } });
}
} }
} }
@ -633,7 +652,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression condExpr; ILExpression condExpr;
ILLabel trueLabel; ILLabel trueLabel;
ILLabel falseLabel; ILLabel falseLabel;
if(block.MatchBrTure(out condExpr, out trueLabel, out falseLabel)) { if(block.Match(ILCode.Brtrue, out trueLabel, out condExpr, out falseLabel)) {
// Swap bodies since that seems to be the usual C# order // Swap bodies since that seems to be the usual C# order
ILLabel temp = trueLabel; ILLabel temp = trueLabel;
@ -782,8 +801,8 @@ namespace ICSharpCode.Decompiler.ILAst
for (int i = 0; i < block.Body.Count; i++) { for (int i = 0; i < block.Body.Count; i++) {
ILCondition cond = block.Body[i] as ILCondition; ILCondition cond = block.Body[i] as ILCondition;
if (cond != null) { if (cond != null) {
bool trueExits = cond.TrueBlock.Body.Count > 0 && !cond.TrueBlock.Body.Last().CanFallthough(); bool trueExits = cond.TrueBlock.Body.Count > 0 && !cond.TrueBlock.Body.Last().CanFallThough();
bool falseExits = cond.FalseBlock.Body.Count > 0 && !cond.FalseBlock.Body.Last().CanFallthough(); bool falseExits = cond.FalseBlock.Body.Count > 0 && !cond.FalseBlock.Body.Last().CanFallThough();
if (trueExits) { if (trueExits) {
// Move the false block after the condition // Move the false block after the condition
@ -823,51 +842,73 @@ namespace ICSharpCode.Decompiler.ILAst
return expr != null && expr.Prefixes == null && expr.Code == code; return expr != null && expr.Prefixes == null && expr.Code == code;
} }
public static bool Match(this ILNode node, ILCode code, out ILExpression expr) public static bool Match<T>(this ILNode node, ILCode code, out T operand)
{ {
expr = node as ILExpression; ILExpression expr = node as ILExpression;
return expr != null && expr.Prefixes == null && expr.Code == code; if (expr != null && expr.Prefixes == null && expr.Code == code) {
operand = (T)expr.Operand;
Debug.Assert(expr.Arguments.Count == 0);
return true;
}
operand = default(T);
return false;
} }
public static bool Match<T>(this ILNode node, ILCode code, out T operand) public static bool Match(this ILNode node, ILCode code, out List<ILExpression> args)
{
ILExpression expr = node as ILExpression;
if (expr != null && expr.Prefixes == null && expr.Code == code) {
Debug.Assert(expr.Operand == null);
args = expr.Arguments;
return true;
}
args = null;
return false;
}
public static bool Match<T>(this ILNode node, ILCode code, out T operand, out List<ILExpression> args)
{ {
ILExpression expr = node as ILExpression; ILExpression expr = node as ILExpression;
if (expr != null && expr.Prefixes == null && expr.Code == code) { if (expr != null && expr.Prefixes == null && expr.Code == code) {
operand = (T)expr.Operand; operand = (T)expr.Operand;
args = expr.Arguments;
return true; return true;
} }
operand = default(T); operand = default(T);
args = null;
return false; return false;
} }
public static bool MatchBrTure(this ILBasicBlock bb, out ILExpression condition, out ILLabel trueLabel, out ILLabel falseLabel) public static bool Match<T>(this ILNode node, ILCode code, out T operand, out ILExpression arg)
{
List<ILExpression> args;
if (node.Match(code, out operand, out args)) {
arg = args.Single();
return true;
}
arg = null;
return false;
}
public static bool Match<T>(this ILBasicBlock bb, ILCode code, out T operand, out ILExpression arg, out ILLabel fallLabel)
{ {
if (bb.Body.Count == 1) { if (bb.Body.Count == 1) {
if (bb.Body[0].Match(ILCode.Brtrue, out trueLabel)) { if (bb.Body[0].Match(code, out operand, out arg)) {
condition = ((ILExpression)bb.Body[0]).Arguments.Single(); fallLabel = (ILLabel)bb.FallthoughGoto.Operand;
falseLabel = (ILLabel)((ILExpression)bb.FallthoughGoto).Operand;
return true; return true;
} }
} }
condition = null; operand = default(T);
trueLabel = null; arg = null;
falseLabel = null; fallLabel = null;
return false; return false;
} }
public static bool CanFallthough(this ILNode node) public static bool CanFallThough(this ILNode node)
{ {
ILExpression expr = node as ILExpression; ILExpression expr = node as ILExpression;
if (expr != null) { if (expr != null) {
switch(expr.Code) { return expr.Code.CanFallThough();
case ILCode.Br:
case ILCode.Ret:
case ILCode.Throw:
case ILCode.Rethrow:
case ILCode.LoopContinue:
case ILCode.LoopBreak:
return false;
}
} }
return true; return true;
} }

29
ICSharpCode.Decompiler/ILAst/ILAstTypes.cs

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -441,9 +442,24 @@ namespace ICSharpCode.Decompiler.ILAst
public class ILSwitch: ILNode public class ILSwitch: ILNode
{ {
public class CaseBlock: ILBlock
{
public List<int> Values; // null for the default case
public override void WriteTo(ITextOutput output)
{
Debug.Assert(Values.Count > 0);
foreach (int i in this.Values) {
output.WriteLine("case {0}:", i);
}
output.Indent();
base.WriteTo(output);
output.Unindent();
}
}
public ILExpression Condition; public ILExpression Condition;
public List<ILBlock> CaseBlocks = new List<ILBlock>(); public List<CaseBlock> CaseBlocks = new List<CaseBlock>();
public ILExpression DefaultGoto;
public override IEnumerable<ILNode> GetChildren() public override IEnumerable<ILNode> GetChildren()
{ {
@ -452,8 +468,6 @@ namespace ICSharpCode.Decompiler.ILAst
foreach (ILBlock caseBlock in this.CaseBlocks) { foreach (ILBlock caseBlock in this.CaseBlocks) {
yield return caseBlock; yield return caseBlock;
} }
if (this.DefaultGoto != null)
yield return this.DefaultGoto;
} }
public override void WriteTo(ITextOutput output) public override void WriteTo(ITextOutput output)
@ -462,11 +476,8 @@ namespace ICSharpCode.Decompiler.ILAst
Condition.WriteTo(output); Condition.WriteTo(output);
output.WriteLine(") {"); output.WriteLine(") {");
output.Indent(); output.Indent();
for (int i = 0; i < CaseBlocks.Count; i++) { foreach (CaseBlock caseBlock in this.CaseBlocks) {
output.WriteLine("case {0}:", i); caseBlock.WriteTo(output);
output.Indent();
CaseBlocks[i].WriteTo(output);
output.Unindent();
} }
output.Unindent(); output.Unindent();
output.WriteLine("}"); output.WriteLine("}");

4
ICSharpCode.Decompiler/ILAst/ILCodes.cs

@ -260,7 +260,7 @@ namespace ICSharpCode.Decompiler.ILAst
LogicOr, LogicOr,
InitArray, // Array Initializer InitArray, // Array Initializer
TernaryOp, // ?: TernaryOp, // ?:
LoopBreak, LoopOrSwitchBreak,
LoopContinue, LoopContinue,
Ldc_Decimal, Ldc_Decimal,
@ -286,6 +286,8 @@ namespace ICSharpCode.Decompiler.ILAst
case ILCode.Endfinally: case ILCode.Endfinally:
case ILCode.Throw: case ILCode.Throw:
case ILCode.Rethrow: case ILCode.Rethrow:
case ILCode.LoopContinue:
case ILCode.LoopOrSwitchBreak:
return false; return false;
default: default:
return true; return true;

2
ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs

@ -456,6 +456,8 @@ namespace ICSharpCode.Decompiler.ILAst
case ILCode.Switch: case ILCode.Switch:
case ILCode.Throw: case ILCode.Throw:
case ILCode.Rethrow: case ILCode.Rethrow:
case ILCode.LoopOrSwitchBreak:
case ILCode.LoopContinue:
return null; return null;
case ILCode.Ret: case ILCode.Ret:
if (forceInferChildren && expr.Arguments.Count == 1) if (forceInferChildren && expr.Arguments.Count == 1)

12
NRefactory/ICSharpCode.NRefactory/CSharp/OutputVisitor/OutputVisitor.cs

@ -1529,8 +1529,13 @@ namespace ICSharpCode.NRefactory.CSharp
public object VisitSwitchSection(SwitchSection switchSection, object data) public object VisitSwitchSection(SwitchSection switchSection, object data)
{ {
StartNode(switchSection); StartNode(switchSection);
foreach (var label in switchSection.CaseLabels) bool first = true;
foreach (var label in switchSection.CaseLabels) {
if (!first)
NewLine();
label.AcceptVisitor(this, data); label.AcceptVisitor(this, data);
first = false;
}
foreach (var statement in switchSection.Statements) foreach (var statement in switchSection.Statements)
statement.AcceptVisitor(this, data); statement.AcceptVisitor(this, data);
return EndNode(switchSection); return EndNode(switchSection);
@ -1539,11 +1544,14 @@ namespace ICSharpCode.NRefactory.CSharp
public object VisitCaseLabel(CaseLabel caseLabel, object data) public object VisitCaseLabel(CaseLabel caseLabel, object data)
{ {
StartNode(caseLabel); StartNode(caseLabel);
if (caseLabel.Expression.IsNull) {
WriteKeyword("default");
} else {
WriteKeyword("case"); WriteKeyword("case");
Space(); Space();
caseLabel.Expression.AcceptVisitor(this, data); caseLabel.Expression.AcceptVisitor(this, data);
}
WriteToken(":", CaseLabel.Roles.Colon); WriteToken(":", CaseLabel.Roles.Colon);
NewLine();
return EndNode(caseLabel); return EndNode(caseLabel);
} }

Loading…
Cancel
Save