llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[clang][dataflow] Diagnose branch conditions using the data-flow framework

Open Discookie opened this issue 1 year ago • 3 comments

I'm currently working on a prototype dead-code check using the data-flow framework: https://github.com/llvm/llvm-project/pull/139068 The check works by finding loop conditions that are always true or always false, and emitting an error there. However, the dataflow framework's Diagnoser entity doesn't have the ability to diagnose specifically loop conditions. It only has the ability to diagnose expressions. (The workaround for this is to tag the loop conditions separately, but it's most definitely not a sound workaround, since the tags are also visible in unexpected places.)

There needs to be a way to diagnose specifically loop conditions, in a way that is known to the Diagnoser. Ideally this diagnosis would be done in a way where both the normal Expr diagnoser, and the condition diagnoser are part of the same function.

Currently I'm thinking to add another overload to operator() in the Diagnoser class, into the DiagnosisCallback here: https://github.com/llvm/llvm-project/blob/904d0c293e4de2c63ef473bbd2b1d3f56f113402/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h#L199-L202 But at that point it might be better to move the branch-diagnoser into a named function inside the same class.

Discookie avatar May 27 '25 13:05 Discookie

What do you think @martinboehme @Xazax-hun @jvoung ?

Discookie avatar May 27 '25 13:05 Discookie

This sounds good to me! (sorry for the long-delayed response). I agree with your latter point that better to use named functions than another overload. I assume that the new function will examine a CFGTerminator? Also, another means of finding dead code is to check that the current flow condition is unsatisfiable. That can be done at any CFGElement, but your approach (of checking the terminator specifically) should be more efficient, since it will require fewer SAT calls.

ymand avatar Jul 01 '25 12:07 ymand

another means of finding dead code is to check that the current flow condition is unsatisfiable. That can be done at any CFGElement

Well, kind of. The framework currently skips checking a lot of branches that are unreachable, where the flow condition can't be satisfied. I'm not sure what the exact condition is, but I've had better success checking the terminators.

I assume that the new function will examine a CFGTerminator?

That's what I'm thinking, yeah. Add another DiagnosisCallback specifically for CFGTerminators of branches, pass the CFGTerminator and the branch condition's Value, and that should be the same information that's also present to transferBranch(). I'm going to implement this callback, then.

Discookie avatar Aug 07 '25 13:08 Discookie