Search code examples
c#roslynroslyn-code-analysiscontrol-flow-graph

Roslyn : get instructions from a basicblock


Control flow graph generated in roslyn contains blocks (basicblock) as nodes, each basicblock contains one or more instructions. for the basicblocks that contains more than one instruction, i try to get all the instructions and their types this is what i did :

var cfg = ControlFlowGraph.Create(method);
foreach(var block in cfg.Blocks)
{
    foreach(var operation in block.Operations)
    {
        var syntax = operation.Syntax;
        Console.WriteLine(syntax.Kind());
    }
}

for the following method :

public int method(int x, int y)
{
y = 10;
x = y;
return x + y;
}

i get the result :

ExpressionStatement
ExpressionStatement

but i wan to get the exacte instruction and it's type for example for the instruction x = y; i want to get AssignmentExpressionSyntax. Also i want to performe some opeartion on each instruction depending on it's type.


Solution

  • Since you are looking at the syntax kind, the ExpressionStatement is the correct kind for the statement. You can find the expressions's kind by looking at the kind of the expression within the ExpressionStatement.

    if (operation.Syntax is ExpressionStatement es)
    {
        var kind = es.Expression.Kind();
    }
    

    However, if you are using operations (IOperation) then you can probably get better info by skipping the syntax and using the OperationKind.