How to get a graph of IR nodes compiled by p4c and work on it from another program?

Hi all,

As far as I know, p4c compiles a P4 program into a graph of IR nodes with provided arguments, like back-end target. So assume I want to write my own program that can process or traverse a graph of IR nodes after invoking p4c, like collecting information to analyze path selection, how should I do this?

I asked ChatGPT for an answer that it recommends that I first extract the graph from p4c to generate a JSON IR or a DOT graph, and then write a C++ program to parse those files to get the graph and do the processing.

I wonder if this is the correct way to do it? Is there way that p4c has an API that can return the graph of IR nodes, and my program can retrieve from memory and do my work?

regards,

I would recommend two things:

  1. Create a new issue here with your question, since p4c developers are far more likely to read it there than here: Issues · p4lang/p4c
  2. Create a link to the issue in a reply comment on this web forum, so that people finding this question later can click on that link to see the discussion (and hopefully answers) on that issue.

Dear @fengkeyleaf ,

The standard way to dump the IR for custom processing is to add and additional parameter (--toJSON my_prog_IR.json) to the compiler command line.

You can then consume the JSON and easily build any graph you’d like depending on what kind of relationship you are interested in graphing.

Happy hacking,
Vladimir

Thanks, I will follow you suggestions!

Thank you! And I will follow Andy’s suggestion to find if there is any better solutions!

Opened a new issue in p4lang/p4c: How to get a graph of IR nodes compiled by p4c and work on it from another program? · Issue #5137 · p4lang/p4c · GitHub

Hi Vladimir,

After adding the parameter, p4c complains that there is such parameter supported.

p4c --target bmv2 --arch v1model --toJSON my_prog_IR.json ./example.p4
p4c: error: unrecognized arguments: --toJSON

Is there something wrong?

regards,

It definitely works with Tofino backend (p4c-barefoot), but try --toJson

I believe --toJSON is implemented by the individual back-end specific p4c binaries, but not supported by the p4c Python program that chooses a back-end specific compiler to run, unfortunately.

Try

p4c-bm2-ss --toJSON my_prog_IR.json ./example.p4

It worked with p4c-bm2-ss, thanks.

Thanks, it seems that I should use p4c-bm2-ss, instead of p4c, but thanks for the information of Tofino!