123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340(*
Copyright (c) 2001-2003,
George C. Necula <necula@cs.berkeley.edu>
Scott McPeak <smcpeak@cs.berkeley.edu>
Wes Weimer <weimer@cs.berkeley.edu>
Simon Goldsmith <sfg@cs.berkeley.edu>
S.P Rahul, Aman Bhargava
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)(* Authors: Aman Bhargava, S. P. Rahul *)(* sfg: this stuff was stolen from optim.ml - the code to print the cfg as
a dot graph is mine *)openPrettyopenCilmoduleE=Errormsg(* entry points: cfgFun, printCfgChannel, printCfgFilename *)(* known issues:
-sucessors of if somehow end up with two edges each
*)(*------------------------------------------------------------*)(* Notes regarding CFG computation:
1) Initially only succs and preds are computed. sid's are filled in
later, in whatever order is suitable (e.g. for forward problems, reverse
depth-first postorder).
2) If a stmt (return, break or continue) has no successors, then
function return must follow.
No predecessors means it is the start of the function
3) We use the fact that initially all the succs and preds are assigned []
*)(* Fill in the CFG info for the stmts in a block
next = succ of the last stmt in this block
break = succ of any Break in this block
cont = succ of any Continue in this block
None means the succ is the function return. It does not mean the break/cont
is invalid. We assume the validity has already been checked.
rlabels = list of potential successors of computed gotos (ie. every labelled
statement whose address is retained)
*)letstart_id=ref0(* for unique ids across many functions *)classcaseLabeledStmtFinderslr=object(self)inheritnopCilVisitormethod!vstmts=ifList.exists(funl->matchlwith|Case_|CaseRange_|Default_->true|_->false)s.labelsthenbeginslr:=s::(!slr);matchs.skindwith|Switch(_,_,_,_,_)->SkipChildren|_->DoChildrenendelsematchs.skindwith|Switch(_,_,_,_,_)->SkipChildren|_->DoChildrenendletfindCaseLabeledStmts(b:block):stmtlist=letslr=ref[]inletvis=newcaseLabeledStmtFinderslrinignore(visitCilBlockvisb);!slrclassaddrOfLabelFinderslr=object(self)inheritnopCilVisitormethod!vexpre=matchewith|AddrOfLabelsref->slr:=!sref::(!slr);SkipChildren|_->DoChildrenendletfindAddrOfLabelStmts(b:block):stmtlist=letslr=ref[]inletvis=newaddrOfLabelFinderslrinignore(visitCilBlockvisb);!slr(* entry point *)(** Compute a control flow graph for fd. Stmts in fd have preds and succs
filled in *)letreccfgFun(fd:fundec):int=beginletinitial_id=!start_idinletnodeList=ref[]inletrlabels=findAddrOfLabelStmtsfd.sbodyincfgBlockfd.sbodyNoneNoneNonenodeListrlabels;fd.smaxstmtid<-Some(!start_id);fd.sallstmts<-List.rev!nodeList;!start_id-initial_idendandcfgStmts(ss:stmtlist)(next:stmtoption)(break:stmtoption)(cont:stmtoption)(nodeList:stmtlistref)(rlabels:stmtlist)=matchsswith[]->();|[s]->cfgStmtsnextbreakcontnodeListrlabels|hd::tl->cfgStmthd(Some(List.hdtl))breakcontnodeListrlabels;cfgStmtstlnextbreakcontnodeListrlabelsandcfgBlock(blk:block)(next:stmtoption)(break:stmtoption)(cont:stmtoption)(nodeList:stmtlistref)(rlabels:stmtlist)=cfgStmtsblk.bstmtsnextbreakcontnodeListrlabels(* Fill in the CFG info for a stmt
Meaning of next, break, cont should be clear from earlier comment
*)andcfgStmt(s:stmt)(next:stmtoption)(break:stmtoption)(cont:stmtoption)(nodeList:stmtlistref)(rlabels:stmtlist)=incrstart_id;s.sid<-!start_id;nodeList:=s::!nodeList;(* Future traversals can be made in linear time. e.g. *)ifs.succs<>[]thenbegin(*E.s*)ignore(bug"CFG must be cleared before being computed!");raise(Failure"CFG bug")end;letaddSucc(n:stmt)=ifnot(List.memqns.succs)thens.succs<-n::s.succs;ifnot(List.memqsn.preds)thenn.preds<-s::n.predsinletaddOptionSucc(n:stmtoption)=matchnwithNone->()|Somen'->addSuccn'inletaddBlockSucc(b:block)(n:stmtoption)=(* Add the first statement in b as a successor to the current stmt.
Or, if b is empty, add n as a successor *)matchb.bstmtswith[]->addOptionSuccn|hd::_->addSucchdinletinstrFallsThrough(i:instr):bool=matchiwithCall(_,Lval(Varvf,NoOffset),_,_,_)->(* See if this has the noreturn attribute *)not(hasAttribute"noreturn"vf.vattr)|Call(_,f,_,_,_)->not(hasAttribute"noreturn"(typeAttrs(typeOff)))|_->trueinmatchs.skindwithInstril->ifList.for_allinstrFallsThroughilthenaddOptionSuccnextelse()|Return_->()|Goto(p,_)->addSucc!p|ComputedGoto(e,_)->List.iteraddSuccrlabels|Break_->addOptionSuccbreak|Continue_->addOptionSucccont|If(_,blk1,blk2,_,_)->(* The succs of If is [true branch;false branch] *)addBlockSuccblk2next;addBlockSuccblk1next;cfgBlockblk1nextbreakcontnodeListrlabels;cfgBlockblk2nextbreakcontnodeListrlabels|Blockb->addBlockSuccbnext;cfgBlockbnextbreakcontnodeListrlabels|Switch(_,blk,l,_,_)->letbl=findCaseLabeledStmtsblkinList.iteraddSucc(List.revbl(*l*));(* Add successors in order *)(* sfg: if there's no default, need to connect s->next *)ifnot(List.exists(funstmt->List.exists(functionDefault_->true|_->false)stmt.labels)bl)thenaddOptionSuccnext;cfgBlockblknextnextcontnodeListrlabels|Loop(blk,loc,eloc,s1,s2)->s.skind<-Loop(blk,loc,eloc,(Somes),next);addBlockSuccblk(Somes);cfgBlockblk(Somes)next(Somes)nodeListrlabels(* Since all loops have terminating condition true, we don't put
any direct successor to stmt following the loop *)(*------------------------------------------------------------*)(**************************************************************)(* do something for all stmts in a fundec *)letrecforallStmts(todo)(fd:fundec)=beginfasBlocktodofd.sbody;endandfasBlock(todo)(b:block)=List.iter(fasStmttodo)b.bstmtsandfasStmt(todo)(s:stmt)=beginignore(todos);matchs.skindwith|Blockb->fasBlocktodob|If(_,tb,fb,_,_)->(fasBlocktodotb;fasBlocktodofb)|Switch(_,b,_,_,_)->fasBlocktodob|Loop(b,_,_,_,_)->fasBlocktodob|(Return_|Break_|Continue_|Goto_|ComputedGoto_|Instr_)->()end;;(**************************************************************)(* printing the control flow graph - you have to compute it first *)letd_cfgnodename()(s:stmt)=dprintf"%d"s.sidletd_cfgnodelabel()(s:stmt)=letlabel=beginmatchs.skindwith|If(e,_,_,_,_)->"if"(*sprint ~width:999 (dprintf "if %a" d_exp e)*)|Loop_->"loop"|Break_->"break"|Continue_->"continue"|Goto_|ComputedGoto_->"goto"|Instr_->"instr"|Switch_->"switch"|Block_->"block"|Return_->"return"endindprintf"%d: %s"s.sidlabelletd_cfgedge(src)()(dest)=dprintf"%a -> %a"d_cfgnodenamesrcd_cfgnodenamedestletd_cfgnode()(s:stmt)=dprintf"%a [label=\"%a\"]\n\t%a"d_cfgnodenamesd_cfgnodelabels(d_list"\n\t"(d_cfgedges))s.succs(**********************************************************************)(* entry points *)(** print control flow graph (in dot form) for fundec to channel *)letprintCfgChannel(chan:out_channel)(fd:fundec)=letpnode(s:stmt)=fprintfchan"%a\n"d_cfgnodesinbeginignore(fprintfchan"digraph CFG_%s {\n"fd.svar.vname);forallStmtspnodefd;ignore(fprintfchan"}\n");end(** Print control flow graph (in dot form) for fundec to file *)letprintCfgFilename(filename:string)(fd:fundec)=letchan=open_outfilenameinbeginprintCfgChannelchanfd;close_outchan;end;;(**********************************************************************)letclearCFGinfo(fd:fundec)=letclears=s.sid<--1;s.succs<-[];s.preds<-[];inforallStmtsclearfdletclearFileCFG(f:file)=start_id:=0;iterGlobalsf(fung->matchgwithGFun(fd,_)->clearCFGinfofd|_->())letcomputeFileCFG(f:file)=iterGlobalsf(fung->matchgwithGFun(fd,_)->ignore(cfgFunfd)|_->())letallStmts(f:file):stmtlist=foldGlobalsf(funaccug->matchgwith|GFun(f,l)->f.sallstmts@accu|_->accu)[]