I’m taking a compiler class right now and we’re at the point where we have to build a CFG in order to implement optimizations. One thing I can’t figure out is how many CFGs are there for a program? Every example I ever see seems to be the CGF of a simple code segment. So, if you have a program that has say three functions. Do you have a separate CFG for each function or is there one big CFG for the entire program?
Share
Per-function CFGs are connected by callsites. If one function calls another, e.g.:
then the control graph for
bazwill include an edge that goes to the graph forfoo. Likewise, becausefoowill eventually returns tobaz(and to wherever else it might’ve been called from), there will be an edge from the end offoo‘s graph back to the statement after the call tofooinbaz. Here, that next statement is the call tobaron line 5. At that point, there’s an edge from thebarcallsite tobar‘s CFG, and lines from exit points inbarback to the end ofbaz.Basically all you need to think about is “what code executes next”. That tells you where the edges should go in your control graph. A function call transfers control until the function returns, which implies an edge from the callsite to the function CFG and back again.
Note that not all full-program CFGs are connected graphs. If there is unreachable code in the program you’re analyzing, then that will be its own unconnected piece of the full CFG. e.g. if you took out the call to
barin the above example, thenbarwould have its own graph off to the side, whilebazandfoowould be connected by edges.