1 //===- GraphAuxiliary.cpp - Auxiliary functions on graph ------------------===//
3 // auxiliary function associated with graph: they all operate on graph, and help
4 // in inserting instrumentation for trace generation
6 //===----------------------------------------------------------------------===//
9 #include "llvm/Module.h"
10 #include "llvm/iTerminators.h"
11 #include "Support/Debug.h"
20 //check if 2 edges are equal (same endpoints and same weight)
21 static bool edgesEqual(Edge ed1, Edge ed2){
22 return ((ed1==ed2) && ed1.getWeight()==ed2.getWeight());
25 //Get the vector of edges that are to be instrumented in the graph
26 static void getChords(vector<Edge > &chords, Graph &g, Graph st){
27 //make sure the spanning tree is directional
28 //iterate over ALL the edges of the graph
29 vector<Node *> allNodes=g.getAllNodes();
30 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
32 Graph::nodeList node_list=g.getNodeList(*NI);
33 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
35 Edge f(*NI, NLI->element,NLI->weight, NLI->randId);
36 if(!(st.hasEdgeAndWt(f)))//addnl
42 //Given a tree t, and a "directed graph" g
43 //replace the edges in the tree t with edges that exist in graph
44 //The tree is formed from "undirectional" copy of graph
45 //So whatever edges the tree has, the undirectional graph
46 //would have too. This function corrects some of the directions in
47 //the tree so that now, all edge directions in the tree match
48 //the edge directions of corresponding edges in the directed graph
49 static void removeTreeEdges(Graph &g, Graph& t){
50 vector<Node* > allNodes=t.getAllNodes();
51 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
53 Graph::nodeList nl=t.getNodeList(*NI);
54 for(Graph::nodeList::iterator NLI=nl.begin(), NLE=nl.end(); NLI!=NLE;++NLI){
55 Edge ed(NLI->element, *NI, NLI->weight);
56 if(!g.hasEdgeAndWt(ed)) t.removeEdge(ed);//tree has only one edge
57 //between any pair of vertices, so no need to delete by edge wt
62 //Assign a value to all the edges in the graph
63 //such that if we traverse along any path from root to exit, and
64 //add up the edge values, we get a path number that uniquely
65 //refers to the path we travelled
66 int valueAssignmentToEdges(Graph& g, map<Node *, int> nodePriority,
68 vector<Node *> revtop=g.reverseTopologicalSort();
69 map<Node *,int > NumPaths;
70 for(vector<Node *>::iterator RI=revtop.begin(), RE=revtop.end();
77 // Modified Graph::nodeList &nlist=g.getNodeList(*RI);
78 Graph::nodeList &nlist=g.getSortedNodeList(*RI, be);
80 //sort nodelist by increasing order of numpaths
84 for(int i=0;i<sz-1; i++){
86 for(int j=i+1; j<sz; j++){
87 BasicBlock *bb1 = nlist[j].element->getElement();
88 BasicBlock *bb2 = nlist[min].element->getElement();
90 if(bb1 == bb2) continue;
92 if(*RI == g.getRoot()){
93 assert(nodePriority[nlist[min].element]!=
94 nodePriority[nlist[j].element]
95 && "priorities can't be same!");
97 if(nodePriority[nlist[j].element] <
98 nodePriority[nlist[min].element])
103 TerminatorInst *tti = (*RI)->getElement()->getTerminator();
105 BranchInst *ti = cast<BranchInst>(tti);
106 assert(ti && "not a branch");
107 assert(ti->getNumSuccessors()==2 && "less successors!");
109 BasicBlock *tB = ti->getSuccessor(0);
110 BasicBlock *fB = ti->getSuccessor(1);
112 if(tB == bb1 || fB == bb2)
117 graphListElement tempEl=nlist[min];
123 for(Graph::nodeList::iterator GLI=nlist.begin(), GLE=nlist.end();
125 GLI->weight=NumPaths[*RI];
126 NumPaths[*RI]+=NumPaths[GLI->element];
130 return NumPaths[g.getRoot()];
133 //This is a helper function to get the edge increments
134 //This is used in conjunction with inc_DFS
135 //to get the edge increments
136 //Edge increment implies assigning a value to all the edges in the graph
137 //such that if we traverse along any path from root to exit, and
138 //add up the edge values, we get a path number that uniquely
139 //refers to the path we travelled
140 //inc_Dir tells whether 2 edges are in same, or in different directions
141 //if same direction, return 1, else -1
142 static int inc_Dir(Edge e, Edge f){
146 //check that the edges must have at least one common endpoint
147 assert(*(e.getFirst())==*(f.getFirst()) ||
148 *(e.getFirst())==*(f.getSecond()) ||
149 *(e.getSecond())==*(f.getFirst()) ||
150 *(e.getSecond())==*(f.getSecond()));
152 if(*(e.getFirst())==*(f.getSecond()) ||
153 *(e.getSecond())==*(f.getFirst()))
160 //used for getting edge increments (read comments above in inc_Dir)
161 //inc_DFS is a modification of DFS
162 static void inc_DFS(Graph& g,Graph& t,map<Edge, int, EdgeCompare2>& Increment,
163 int events, Node *v, Edge e){
165 vector<Node *> allNodes=t.getAllNodes();
167 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
169 Graph::nodeList node_list=t.getNodeList(*NI);
170 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
172 Edge f(*NI, NLI->element,NLI->weight, NLI->randId);
173 if(!edgesEqual(f,e) && *v==*(f.getSecond())){
174 int dir_count=inc_Dir(e,f);
175 int wt=1*f.getWeight();
176 inc_DFS(g,t, Increment, dir_count*events+wt, f.getFirst(), f);
181 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
183 Graph::nodeList node_list=t.getNodeList(*NI);
184 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
186 Edge f(*NI, NLI->element,NLI->weight, NLI->randId);
187 if(!edgesEqual(f,e) && *v==*(f.getFirst())){
188 int dir_count=inc_Dir(e,f);
189 int wt=f.getWeight();
190 inc_DFS(g,t, Increment, dir_count*events+wt,
196 allNodes=g.getAllNodes();
197 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
199 Graph::nodeList node_list=g.getNodeList(*NI);
200 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
202 Edge f(*NI, NLI->element,NLI->weight, NLI->randId);
203 if(!(t.hasEdgeAndWt(f)) && (*v==*(f.getSecond()) ||
204 *v==*(f.getFirst()))){
205 int dir_count=inc_Dir(e,f);
206 Increment[f]+=dir_count*events;
212 //Now we select a subset of all edges
213 //and assign them some values such that
214 //if we consider just this subset, it still represents
215 //the path sum along any path in the graph
216 static map<Edge, int, EdgeCompare2> getEdgeIncrements(Graph& g, Graph& t,
218 //get all edges in g-t
219 map<Edge, int, EdgeCompare2> Increment;
221 vector<Node *> allNodes=g.getAllNodes();
223 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
225 Graph::nodeList node_list=g.getSortedNodeList(*NI, be);
226 //modified g.getNodeList(*NI);
227 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
229 Edge ed(*NI, NLI->element,NLI->weight,NLI->randId);
230 if(!(t.hasEdgeAndWt(ed))){
237 inc_DFS(g,t,Increment, 0, g.getRoot(), *ed);
239 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
241 Graph::nodeList node_list=g.getSortedNodeList(*NI, be);
242 //modified g.getNodeList(*NI);
243 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
245 Edge ed(*NI, NLI->element,NLI->weight, NLI->randId);
246 if(!(t.hasEdgeAndWt(ed))){
247 int wt=ed.getWeight();
257 const graphListElement *findNodeInList(const Graph::nodeList &NL,
260 graphListElement *findNodeInList(Graph::nodeList &NL, Node *N);
263 //Based on edgeIncrements (above), now obtain
264 //the kind of code to be inserted along an edge
265 //The idea here is to minimize the computation
266 //by inserting only the needed code
267 static void getCodeInsertions(Graph &g, map<Edge, getEdgeCode *, EdgeCompare2> &instr,
268 vector<Edge > &chords,
269 map<Edge,int, EdgeCompare2> &edIncrements){
271 //Register initialization code
273 ws.push_back(g.getRoot());
278 Graph::nodeList succs=g.getNodeList(v);
280 for(Graph::nodeList::iterator nl=succs.begin(), ne=succs.end();
282 int edgeWt=nl->weight;
285 Edge ed(v,w, edgeWt, nl->randId);
287 for(vector<Edge>::iterator CI=chords.begin(), CE=chords.end();
288 CI!=CE && !hasEdge;++CI){
289 if(*CI==ed && CI->getWeight()==edgeWt){//modf
294 if(hasEdge){//so its a chord edge
295 getEdgeCode *edCd=new getEdgeCode();
297 edCd->setInc(edIncrements[ed]);
300 else if(g.getNumberOfIncomingEdges(w)==1){
304 getEdgeCode *edCd=new getEdgeCode();
312 /////Memory increment code
313 ws.push_back(g.getExit());
322 vector<Node *> lllt=g.getAllNodes();
323 for(vector<Node *>::iterator EII=lllt.begin(); EII!=lllt.end() ;++EII){
325 Graph::nodeList &nl = g.getNodeList(lnode);
326 //graphListElement *N = findNodeInList(nl, w);
327 for(Graph::nodeList::const_iterator N = nl.begin(),
328 NNEN = nl.end(); N!= NNEN; ++N){
329 if (*N->element == *w){
333 Edge ed(v,w, N->weight, N->randId);
334 getEdgeCode *edCd=new getEdgeCode();
336 for(vector<Edge>::iterator CI=chords.begin(), CE=chords.end(); CI!=CE;
338 if(*CI==ed && CI->getWeight()==N->weight){
345 if(instr[ed]!=NULL && instr[ed]->getCond()==1){
346 instr[ed]->setCond(4);
350 edCd->setInc(edIncrements[ed]);
355 else if(g.getNumberOfOutgoingEdges(v)==1)
365 ///// Register increment code
366 for(vector<Edge>::iterator CI=chords.begin(), CE=chords.end(); CI!=CE; ++CI){
367 getEdgeCode *edCd=new getEdgeCode();
368 if(instr[*CI]==NULL){
370 edCd->setInc(edIncrements[*CI]);
376 //Add dummy edges corresponding to the back edges
377 //If a->b is a backedge
378 //then incoming dummy edge is root->b
379 //and outgoing dummy edge is a->exit
381 void addDummyEdges(vector<Edge > &stDummy,
382 vector<Edge > &exDummy,
383 Graph &g, vector<Edge> &be){
384 for(vector<Edge >::iterator VI=be.begin(), VE=be.end(); VI!=VE; ++VI){
386 Node *first=ed.getFirst();
387 Node *second=ed.getSecond();
390 if(!(*second==*(g.getRoot()))){
391 Edge *st=new Edge(g.getRoot(), second, ed.getWeight(), ed.getRandId());
392 stDummy.push_back(*st);
396 if(!(*first==*(g.getExit()))){
397 Edge *ex=new Edge(first, g.getExit(), ed.getWeight(), ed.getRandId());
398 exDummy.push_back(*ex);
404 //print a given edge in the form BB1Label->BB2Label
405 void printEdge(Edge ed){
406 cerr<<((ed.getFirst())->getElement())
407 ->getName()<<"->"<<((ed.getSecond())
408 ->getElement())->getName()<<
409 ":"<<ed.getWeight()<<" rndId::"<<ed.getRandId()<<"\n";
412 //Move the incoming dummy edge code and outgoing dummy
413 //edge code over to the corresponding back edge
414 static void moveDummyCode(vector<Edge> &stDummy,
415 vector<Edge> &exDummy,
417 map<Edge, getEdgeCode *, EdgeCompare2> &insertions,
419 typedef vector<Edge >::iterator vec_iter;
421 map<Edge,getEdgeCode *, EdgeCompare2> temp;
422 //iterate over edges with code
423 std::vector<Edge> toErase;
424 for(map<Edge,getEdgeCode *, EdgeCompare2>::iterator MI=insertions.begin(),
425 ME=insertions.end(); MI!=ME; ++MI){
427 getEdgeCode *edCd=MI->second;
430 //iterate over be, and check if its starts and end vertices hv code
431 for(vector<Edge>::iterator BEI=be.begin(), BEE=be.end(); BEI!=BEE; ++BEI){
432 if(ed.getRandId()==BEI->getRandId()){
435 temp[*BEI]=new getEdgeCode();
437 //so ed is either in st, or ex!
438 if(ed.getFirst()==g.getRoot()){
441 temp[*BEI]->setCdIn(edCd);
442 toErase.push_back(ed);
444 else if(ed.getSecond()==g.getExit()){
447 toErase.push_back(ed);
448 temp[*BEI]->setCdOut(edCd);
451 assert(false && "Not found in either start or end! Rand failed?");
457 for(vector<Edge >::iterator vmi=toErase.begin(), vme=toErase.end(); vmi!=vme;
459 insertions.erase(*vmi);
460 g.removeEdgeWithWt(*vmi);
463 for(map<Edge,getEdgeCode *, EdgeCompare2>::iterator MI=temp.begin(),
464 ME=temp.end(); MI!=ME; ++MI){
465 insertions[MI->first]=MI->second;
468 #ifdef DEBUG_PATH_PROFILES
469 cerr<<"size of deletions: "<<toErase.size()<<"\n";
470 cerr<<"SIZE OF INSERTIONS AFTER DEL "<<insertions.size()<<"\n";
475 //Do graph processing: to determine minimal edge increments,
476 //appropriate code insertions etc and insert the code at
477 //appropriate locations
478 void processGraph(Graph &g,
482 vector<Edge >& stDummy,
483 vector<Edge >& exDummy,
484 int numPaths, int MethNo,
487 //Given a graph: with exit->root edge, do the following in seq:
489 //2. insert dummy edges and remove back edges
490 //3. get edge assignments
491 //4. Get Max spanning tree of graph:
492 // -Make graph g2=g undirectional
493 // -Get Max spanning tree t
494 // -Make t undirectional
495 // -remove edges from t not in graph g
496 //5. Get edge increments
497 //6. Get code insertions
498 //7. move code on dummy edges over to the back edges
501 //This is used as maximum "weight" for
503 //This would hold all
504 //right as long as number of paths in the graph
506 const int Infinity=99999999;
509 //step 1-3 are already done on the graph when this function is called
510 DEBUG(printGraph(g));
512 //step 4: Get Max spanning tree of graph
514 //now insert exit to root edge
515 //if its there earlier, remove it!
516 //assign it weight Infinity
517 //so that this edge IS ALWAYS IN spanning tree
518 //Note than edges in spanning tree do not get
519 //instrumented: and we do not want the
520 //edge exit->root to get instrumented
521 //as it MAY BE a dummy edge
522 Edge ed(g.getExit(),g.getRoot(),Infinity);
523 g.addEdge(ed,Infinity);
526 //make g2 undirectional: this gives a better
527 //maximal spanning tree
528 g2.makeUnDirectional();
529 DEBUG(printGraph(g2));
531 Graph *t=g2.getMaxSpanningTree();
532 #ifdef DEBUG_PATH_PROFILES
533 std::cerr<<"Original maxspanning tree\n";
536 //now edges of tree t have weights reversed
537 //(negative) because the algorithm used
538 //to find max spanning tree is
539 //actually for finding min spanning tree
540 //so get back the original weights
543 //Ordinarily, the graph is directional
544 //lets converts the graph into an
545 //undirectional graph
546 //This is done by adding an edge
547 //v->u for all existing edges u->v
548 t->makeUnDirectional();
550 //Given a tree t, and a "directed graph" g
551 //replace the edges in the tree t with edges that exist in graph
552 //The tree is formed from "undirectional" copy of graph
553 //So whatever edges the tree has, the undirectional graph
554 //would have too. This function corrects some of the directions in
555 //the tree so that now, all edge directions in the tree match
556 //the edge directions of corresponding edges in the directed graph
557 removeTreeEdges(g, *t);
559 #ifdef DEBUG_PATH_PROFILES
560 cerr<<"Final Spanning tree---------\n";
562 cerr<<"-------end spanning tree\n";
565 //now remove the exit->root node
566 //and re-add it with weight 0
567 //since infinite weight is kinda confusing
569 Edge edNew(g.getExit(), g.getRoot(),0);
579 //step 5: Get edge increments
581 //Now we select a subset of all edges
582 //and assign them some values such that
583 //if we consider just this subset, it still represents
584 //the path sum along any path in the graph
586 map<Edge, int, EdgeCompare2> increment=getEdgeIncrements(g,*t, be);
587 #ifdef DEBUG_PATH_PROFILES
588 //print edge increments for debugging
589 std::cerr<<"Edge Increments------\n";
590 for(map<Edge, int, EdgeCompare2>::iterator MMI=increment.begin(), MME=increment.end(); MMI != MME; ++MMI){
591 printEdge(MMI->first);
592 std::cerr<<"Increment for above:"<<MMI->second<<"\n";
594 std::cerr<<"-------end of edge increments\n";
598 //step 6: Get code insertions
600 //Based on edgeIncrements (above), now obtain
601 //the kind of code to be inserted along an edge
602 //The idea here is to minimize the computation
603 //by inserting only the needed code
605 getChords(chords, g, *t);
608 map<Edge, getEdgeCode *, EdgeCompare2> codeInsertions;
609 getCodeInsertions(g, codeInsertions, chords,increment);
611 #ifdef DEBUG_PATH_PROFILES
612 //print edges with code for debugging
613 cerr<<"Code inserted in following---------------\n";
614 for(map<Edge, getEdgeCode *, EdgeCompare2>::iterator cd_i=codeInsertions.begin(),
615 cd_e=codeInsertions.end(); cd_i!=cd_e; ++cd_i){
616 printEdge(cd_i->first);
617 cerr<<cd_i->second->getCond()<<":"<<cd_i->second->getInc()<<"\n";
619 cerr<<"-----end insertions\n";
622 //step 7: move code on dummy edges over to the back edges
624 //Move the incoming dummy edge code and outgoing dummy
625 //edge code over to the corresponding back edge
627 moveDummyCode(stDummy, exDummy, be, codeInsertions, g);
629 #ifdef DEBUG_PATH_PROFILES
631 cerr<<"After moving dummy code\n";
632 for(map<Edge, getEdgeCode *>::iterator cd_i=codeInsertions.begin(),
633 cd_e=codeInsertions.end(); cd_i != cd_e; ++cd_i){
634 printEdge(cd_i->first);
635 cerr<<cd_i->second->getCond()<<":"
636 <<cd_i->second->getInc()<<"\n";
638 cerr<<"Dummy end------------\n";
642 //see what it looks like...
643 //now insert code along edges which have codes on them
644 for(map<Edge, getEdgeCode *>::iterator MI=codeInsertions.begin(),
645 ME=codeInsertions.end(); MI!=ME; ++MI){
647 insertBB(ed, MI->second, rInst, countInst, numPaths, MethNo, threshold);
651 //print the graph (for debugging)
652 void printGraph(Graph &g){
653 vector<Node *> lt=g.getAllNodes();
654 cerr<<"Graph---------------------\n";
655 for(vector<Node *>::iterator LI=lt.begin();
657 cerr<<((*LI)->getElement())->getName()<<"->";
658 Graph::nodeList nl=g.getNodeList(*LI);
659 for(Graph::nodeList::iterator NI=nl.begin();
661 cerr<<":"<<"("<<(NI->element->getElement())
662 ->getName()<<":"<<NI->element->getWeight()<<","<<NI->weight<<","
667 cerr<<"--------------------Graph\n";