private void DeduplicateBranchSourceTargetCode()
{
for (int i = 0; i < code.Count; i++)
{
if (code[i].pseudo == CodeType.Label)
{
code[i].Label.Temp = i;
}
}
for (int i = 0; i < code.Count; i++)
{
if (code[i].opcode == OpCodes.Br && code[i].HasLabel)
{
int source = i - 1;
int target = code[i].Label.Temp - 1;
while (source >= 0 && target >= 0)
{
switch (code[source].pseudo)
{
case CodeType.LineNumber:
case CodeType.OpCode:
break;
default:
goto break_while;
}
if (!code[source].Match(code[target]))
{
break;
}
switch (code[source].opcode.FlowControl)
{
case FlowControl.Branch:
case FlowControl.Cond_Branch:
goto break_while;
}
source--;
target--;
}
break_while: ;
source++;
target++;
if (source != i && target > 0 && source != target - 1)
{
// TODO for now we only do this optimization if there happens to be an appriopriate label
if (code[target - 1].pseudo == CodeType.Label)
{
code[source] = new OpCodeWrapper(OpCodes.Br, code[target - 1].Label);
for (int j = source + 1; j <= i; j++)
{
// We can't depend on DCE for code correctness (we have to maintain all MSIL invariants at all times),
// so we patch out the unused code.
code[j] = new OpCodeWrapper(CodeType.Unreachable, null);
}
}
}
}
}
}