Control flow analysis is used to understand the various entry and exit points within a block of code and to answer questions about reachability. If we’re analyzing a method, we might be interested in all the points at which we can
return out of the method. If we’re analyzing a for-loop, we might be interested in all the places we
We trigger control flow analysis via an extension method on the
SemanticModel. This returns an instance of
ControlFlowAnalysis to us that exposes the following properties:
EntryPoints– The set of statements inside the region that are the destination of branches outside the region.
ExitPoints– The set of statements inside a region that jump to locations outside the region.
EndPointIsReachable– Indicates whether a region completes normally. Returns true if and only if the end of the last statement is reachable or the entire region contains no statements.
StartPointIsReachable– Indicates whether a region can begin normally.
ReturnStatements– The set of returns statements within a region.
Succeeded– Returns true if and only if analysis was successful. Analysis can fail if the region does not properly span a single expression, a single statement, or a contiguous series of statements within the enclosing block.
Basic usage of the API:
Alternatively, we can specify two statements and analyze the statements between the two. The following example demonstrates this and the usage of
In the above example, we see an example of a possible entry point label L3. To the best of my knowledge, labels are the only possible entry points.
Finally, we’ll take a look at answering questions about reachability. In the following, neither the start point or the end point is reachable:
Overall, the Control Flow API seems a lot more intuitive than the Data Flow Analysis API. It requires less knowledge of the C# specification and is straightforward to work with. At Code Connect, we’ve been using it when rewriting and logging methods. Although it looks like no one has experimented much with this API, I’m really interested to see what uses others will come up with.