1 //===-- Graph.cpp - Implements Graph class --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements Graph for helping in trace generation This graph gets used by
11 // "ProfilePaths" class.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/iTerminators.h"
17 #include "Support/Debug.h"
22 const graphListElement *findNodeInList(const Graph::nodeList &NL,
24 for(Graph::nodeList::const_iterator NI = NL.begin(), NE=NL.end(); NI != NE;
26 if (*NI->element== *N)
31 graphListElement *findNodeInList(Graph::nodeList &NL, Node *N) {
32 for(Graph::nodeList::iterator NI = NL.begin(), NE=NL.end(); NI != NE; ++NI)
33 if (*NI->element== *N)
38 //graph constructor with root and exit specified
39 Graph::Graph(std::vector<Node*> n, std::vector<Edge> e,
43 for(vector<Node* >::iterator x=n.begin(), en=n.end(); x!=en; ++x)
44 //nodes[*x] = list<graphListElement>();
45 nodes[*x] = vector<graphListElement>();
47 for(vector<Edge >::iterator x=e.begin(), en=e.end(); x!=en; ++x){
50 //nodes[ee.getFirst()].push_front(graphListElement(ee.getSecond(),w, ee.getRandId()));
51 nodes[ee.getFirst()].push_back(graphListElement(ee.getSecond(),w, ee.getRandId()));
56 //sorting edgelist, called by backEdgeVist ONLY!!!
57 Graph::nodeList &Graph::sortNodeList(Node *par, nodeList &nl, vector<Edge> &be){
58 assert(par && "null node pointer");
59 BasicBlock *bbPar = par->getElement();
61 if(nl.size()<=1) return nl;
62 if(getExit() == par) return nl;
64 for(nodeList::iterator NLI = nl.begin(), NLE = nl.end()-1; NLI != NLE; ++NLI){
65 nodeList::iterator min = NLI;
66 for(nodeList::iterator LI = NLI+1, LE = nl.end(); LI!=LE; ++LI){
67 //if LI < min, min = LI
68 if(min->element->getElement() == LI->element->getElement() &&
69 min->element == getExit()){
71 //same successors: so might be exit???
72 //if it is exit, then see which is backedge
73 //check if LI is a left back edge!
75 TerminatorInst *tti = par->getElement()->getTerminator();
76 BranchInst *ti = cast<BranchInst>(tti);
78 assert(ti && "not a branch");
79 assert(ti->getNumSuccessors()==2 && "less successors!");
81 BasicBlock *tB = ti->getSuccessor(0);
82 BasicBlock *fB = ti->getSuccessor(1);
83 //so one of LI or min must be back edge!
84 //Algo: if succ(0)!=LI (and so !=min) then succ(0) is backedge
85 //and then see which of min or LI is backedge
86 //THEN if LI is in be, then min=LI
87 if(LI->element->getElement() != tB){//so backedge must be made min!
88 for(vector<Edge>::iterator VBEI = be.begin(), VBEE = be.end();
89 VBEI != VBEE; ++VBEI){
90 if(VBEI->getRandId() == LI->randId){
94 else if(VBEI->getRandId() == min->randId)
98 else{// if(LI->element->getElement() != fB)
99 for(vector<Edge>::iterator VBEI = be.begin(), VBEE = be.end();
100 VBEI != VBEE; ++VBEI){
101 if(VBEI->getRandId() == min->randId){
105 else if(VBEI->getRandId() == LI->randId)
111 else if (min->element->getElement() != LI->element->getElement()){
112 TerminatorInst *tti = par->getElement()->getTerminator();
113 BranchInst *ti = cast<BranchInst>(tti);
114 assert(ti && "not a branch");
116 if(ti->getNumSuccessors()<=1) continue;
118 assert(ti->getNumSuccessors()==2 && "less successors!");
120 BasicBlock *tB = ti->getSuccessor(0);
121 BasicBlock *fB = ti->getSuccessor(1);
123 if(tB == LI->element->getElement() || fB == min->element->getElement())
128 graphListElement tmpElmnt = *min;
135 //check whether graph has an edge
136 //having an edge simply means that there is an edge in the graph
137 //which has same endpoints as the given edge
138 bool Graph::hasEdge(Edge ed){
142 nodeList &nli= nodes[ed.getFirst()]; //getNodeList(ed.getFirst());
143 Node *nd2=ed.getSecond();
145 return (findNodeInList(nli,nd2)!=NULL);
150 //check whether graph has an edge, with a given wt
151 //having an edge simply means that there is an edge in the graph
152 //which has same endpoints as the given edge
153 //This function checks, moreover, that the wt of edge matches too
154 bool Graph::hasEdgeAndWt(Edge ed){
158 Node *nd2=ed.getSecond();
159 nodeList &nli = nodes[ed.getFirst()];//getNodeList(ed.getFirst());
161 for(nodeList::iterator NI=nli.begin(), NE=nli.end(); NI!=NE; ++NI)
162 if(*NI->element == *nd2 && ed.getWeight()==NI->weight)
169 void Graph::addNode(Node *nd){
170 vector<Node *> lt=getAllNodes();
172 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE;++LI){
177 nodes[nd] =vector<graphListElement>(); //list<graphListElement>();
181 //this adds an edge ONLY when
182 //the edge to be added does not already exist
183 //we "equate" two edges here only with their
185 void Graph::addEdge(Edge ed, int w){
186 nodeList &ndList = nodes[ed.getFirst()];
187 Node *nd2=ed.getSecond();
189 if(findNodeInList(nodes[ed.getFirst()], nd2))
192 //ndList.push_front(graphListElement(nd2,w, ed.getRandId()));
193 ndList.push_back(graphListElement(nd2,w, ed.getRandId()));//chng
194 //sortNodeList(ed.getFirst(), ndList);
196 //sort(ndList.begin(), ndList.end(), NodeListSort());
199 //add an edge EVEN IF such an edge already exists
200 //this may make a multi-graph
201 //which does happen when we add dummy edges
202 //to the graph, for compensating for back-edges
203 void Graph::addEdgeForce(Edge ed){
204 //nodes[ed.getFirst()].push_front(graphListElement(ed.getSecond(),
205 //ed.getWeight(), ed.getRandId()));
206 nodes[ed.getFirst()].push_back
207 (graphListElement(ed.getSecond(), ed.getWeight(), ed.getRandId()));
209 //sortNodeList(ed.getFirst(), nodes[ed.getFirst()]);
210 //sort(nodes[ed.getFirst()].begin(), nodes[ed.getFirst()].end(), NodeListSort());
214 //Note that it removes just one edge,
215 //the first edge that is encountered
216 void Graph::removeEdge(Edge ed){
217 nodeList &ndList = nodes[ed.getFirst()];
218 Node &nd2 = *ed.getSecond();
220 for(nodeList::iterator NI=ndList.begin(), NE=ndList.end(); NI!=NE ;++NI) {
221 if(*NI->element == nd2) {
228 //remove an edge with a given wt
229 //Note that it removes just one edge,
230 //the first edge that is encountered
231 void Graph::removeEdgeWithWt(Edge ed){
232 nodeList &ndList = nodes[ed.getFirst()];
233 Node &nd2 = *ed.getSecond();
235 for(nodeList::iterator NI=ndList.begin(), NE=ndList.end(); NI!=NE ;++NI) {
236 if(*NI->element == nd2 && NI->weight==ed.getWeight()) {
243 //set the weight of an edge
244 void Graph::setWeight(Edge ed){
245 graphListElement *El = findNodeInList(nodes[ed.getFirst()], ed.getSecond());
247 El->weight=ed.getWeight();
252 //get the list of successor nodes
253 vector<Node *> Graph::getSuccNodes(Node *nd){
254 nodeMapTy::const_iterator nli = nodes.find(nd);
255 assert(nli != nodes.end() && "Node must be in nodes map");
256 const nodeList &nl = getNodeList(nd);//getSortedNodeList(nd);
259 for(nodeList::const_iterator NI=nl.begin(), NE=nl.end(); NI!=NE; ++NI)
260 lt.push_back(NI->element);
265 //get the number of outgoing edges
266 int Graph::getNumberOfOutgoingEdges(Node *nd) const {
267 nodeMapTy::const_iterator nli = nodes.find(nd);
268 assert(nli != nodes.end() && "Node must be in nodes map");
269 const nodeList &nl = nli->second;
272 for(nodeList::const_iterator NI=nl.begin(), NE=nl.end(); NI!=NE; ++NI)
278 //get the list of predecessor nodes
279 vector<Node *> Graph::getPredNodes(Node *nd){
281 for(nodeMapTy::const_iterator EI=nodes.begin(), EE=nodes.end(); EI!=EE ;++EI){
282 Node *lnode=EI->first;
283 const nodeList &nl = getNodeList(lnode);
285 const graphListElement *N = findNodeInList(nl, nd);
286 if (N) lt.push_back(lnode);
291 //get the number of predecessor nodes
292 int Graph::getNumberOfIncomingEdges(Node *nd){
294 for(nodeMapTy::const_iterator EI=nodes.begin(), EE=nodes.end(); EI!=EE ;++EI){
295 Node *lnode=EI->first;
296 const nodeList &nl = getNodeList(lnode);
297 for(Graph::nodeList::const_iterator NI = nl.begin(), NE=nl.end(); NI != NE;
299 if (*NI->element== *nd)
305 //get the list of all the vertices in graph
306 vector<Node *> Graph::getAllNodes() const{
308 for(nodeMapTy::const_iterator x=nodes.begin(), en=nodes.end(); x != en; ++x)
309 lt.push_back(x->first);
314 //get the list of all the vertices in graph
315 vector<Node *> Graph::getAllNodes(){
317 for(nodeMapTy::const_iterator x=nodes.begin(), en=nodes.end(); x != en; ++x)
318 lt.push_back(x->first);
323 //class to compare two nodes in graph
324 //based on their wt: this is used in
325 //finding the maximal spanning tree
326 struct compare_nodes {
327 bool operator()(Node *n1, Node *n2){
328 return n1->getWeight() < n2->getWeight();
333 static void printNode(Node *nd){
334 std::cerr<<"Node:"<<nd->getElement()->getName()<<"\n";
337 //Get the Maximal spanning tree (also a graph)
339 Graph* Graph::getMaxSpanningTree(){
340 //assume connected graph
342 Graph *st=new Graph();//max spanning tree, undirected edges
343 int inf=9999999;//largest key
344 vector<Node *> lt = getAllNodes();
346 //initially put all vertices in vector vt
348 //wt(others)=infinity
351 //pull out u: a vertex frm vt of min wt
352 //for all vertices w in vt,
353 //if wt(w) greater than
354 //the wt(u->w), then assign
355 //wt(w) to be wt(u->w).
357 //make parent(u)=w in the spanning tree
358 //keep pulling out vertices from vt till it is empty
362 std::map<Node*, Node* > parent;
363 std::map<Node*, int > ed_weight;
365 //initialize: wt(root)=0, wt(others)=infinity
366 //parent(root)=NULL, parent(others) not defined (but not null)
367 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE; ++LI){
369 if(*thisNode == *getRoot()){
370 thisNode->setWeight(0);
371 parent[thisNode]=NULL;
372 ed_weight[thisNode]=0;
375 thisNode->setWeight(inf);
377 st->addNode(thisNode);//add all nodes to spanning tree
378 //we later need to assign edges in the tree
379 vt.push_back(thisNode); //pushed all nodes in vt
382 //keep pulling out vertex of min wt from vt
384 Node *u=*(min_element(vt.begin(), vt.end(), compare_nodes()));
385 DEBUG(std::cerr<<"popped wt"<<(u)->getWeight()<<"\n";
388 if(parent[u]!=NULL){ //so not root
389 Edge edge(parent[u],u, ed_weight[u]); //assign edge in spanning tree
390 st->addEdge(edge,ed_weight[u]);
392 DEBUG(std::cerr<<"added:\n";
399 for(vector<Node *>::iterator VI=vt.begin(), VE=vt.end(); VI!=VE; ++VI){
406 //assign wt(v) to all adjacent vertices v of u
408 Graph::nodeList &nl = getNodeList(u);
409 for(nodeList::iterator NI=nl.begin(), NE=nl.end(); NI!=NE; ++NI){
411 int weight=-NI->weight;
412 //check if v is in vt
414 for(vector<Node *>::iterator VI=vt.begin(), VE=vt.end(); VI!=VE; ++VI){
420 DEBUG(std::cerr<<"wt:v->wt"<<weight<<":"<<v->getWeight()<<"\n";
421 printNode(v);std::cerr<<"node wt:"<<(*v).weight<<"\n");
423 //so if v in in vt, change wt(v) to wt(u->v)
424 //only if wt(u->v)<wt(v)
425 if(contains && weight<v->getWeight()){
428 v->setWeight(weight);
430 DEBUG(std::cerr<<v->getWeight()<<":Set weight------\n";
432 printEdge(Edge(u,v,weight)));
439 //print the graph (for debugging)
440 void Graph::printGraph(){
441 vector<Node *> lt=getAllNodes();
442 std::cerr<<"Graph---------------------\n";
443 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE; ++LI){
444 std::cerr<<((*LI)->getElement())->getName()<<"->";
445 Graph::nodeList &nl = getNodeList(*LI);
446 for(Graph::nodeList::iterator NI=nl.begin(), NE=nl.end(); NI!=NE; ++NI){
447 std::cerr<<":"<<"("<<(NI->element->getElement())
448 ->getName()<<":"<<NI->element->getWeight()<<","<<NI->weight<<")";
450 std::cerr<<"--------\n";
455 //get a list of nodes in the graph
456 //in r-topological sorted order
457 //note that we assumed graph to be connected
458 vector<Node *> Graph::reverseTopologicalSort(){
459 vector <Node *> toReturn;
460 vector<Node *> lt=getAllNodes();
461 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE; ++LI){
462 if((*LI)->getWeight()!=GREY && (*LI)->getWeight()!=BLACK)
463 DFS_Visit(*LI, toReturn);
469 //a private method for doing DFS traversal of graph
470 //this is used in determining the reverse topological sort
472 void Graph::DFS_Visit(Node *nd, vector<Node *> &toReturn){
474 vector<Node *> lt=getSuccNodes(nd);
475 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE; ++LI){
476 if((*LI)->getWeight()!=GREY && (*LI)->getWeight()!=BLACK)
477 DFS_Visit(*LI, toReturn);
479 toReturn.push_back(nd);
482 //Ordinarily, the graph is directional
483 //this converts the graph into an
484 //undirectional graph
485 //This is done by adding an edge
486 //v->u for all existing edges u->v
487 void Graph::makeUnDirectional(){
488 vector<Node* > allNodes=getAllNodes();
489 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
491 nodeList &nl = getNodeList(*NI);
492 for(nodeList::iterator NLI=nl.begin(), NLE=nl.end(); NLI!=NLE; ++NLI){
493 Edge ed(NLI->element, *NI, NLI->weight);
494 if(!hasEdgeAndWt(ed)){
495 DEBUG(std::cerr<<"######doesn't hv\n";
503 //reverse the sign of weights on edges
504 //this way, max-spanning tree could be obtained
505 //using min-spanning tree, and vice versa
506 void Graph::reverseWts(){
507 vector<Node *> allNodes=getAllNodes();
508 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
510 nodeList &node_list = getNodeList(*NI);
511 for(nodeList::iterator NLI=nodes[*NI].begin(), NLE=nodes[*NI].end();
513 NLI->weight=-NLI->weight;
518 //getting the backedges in a graph
519 //Its a variation of DFS to get the backedges in the graph
520 //We get back edges by associating a time
521 //and a color with each vertex.
522 //The time of a vertex is the time when it was first visited
523 //The color of a vertex is initially WHITE,
524 //Changes to GREY when it is first visited,
525 //and changes to BLACK when ALL its neighbors
527 //So we have a back edge when we meet a successor of
528 //a node with smaller time, and GREY color
529 void Graph::getBackEdges(vector<Edge > &be, std::map<Node *, int> &d){
530 std::map<Node *, Color > color;
533 getBackEdgesVisit(getRoot(), be, color, d, time);
536 //helper function to get back edges: it is called by
537 //the "getBackEdges" function above
538 void Graph::getBackEdgesVisit(Node *u, vector<Edge > &be,
539 std::map<Node *, Color > &color,
540 std::map<Node *, int > &d, int &time) {
545 vector<graphListElement> &succ_list = getNodeList(u);
547 for(vector<graphListElement>::iterator vl=succ_list.begin(),
548 ve=succ_list.end(); vl!=ve; ++vl){
550 if(color[v]!=GREY && color[v]!=BLACK){
551 getBackEdgesVisit(v, be, color, d, time);
554 //now checking for d and f vals
556 //so v is ancestor of u if time of u > time of v
558 Edge *ed=new Edge(u, v,vl->weight, vl->randId);
559 if (!(*u == *getExit() && *v == *getRoot()))
560 be.push_back(*ed); // choose the forward edges
564 color[u]=BLACK;//done with visiting the node and its neighbors