// Mike Maxim
// IR basic block former

package edu.cmu.cs.l3.canon;

import edu.cmu.cs.l3.tree.*;
import edu.cmu.cs.l3.temp.*;
import java.util.*;

public class BasicBlocker {

    public BasicBlocker() {

    }

    public Vector getBlocks() {
	return m_blocks;
    }

    public IRLabel getDoneLabel() {
	return m_done;
    }

    public void formBlocks(IRStatementList stms) {

	int i;
	boolean inblock = true;
	IRStatement curstm=null;
	IRLabel startlabel = new IRLabel(new Label());
	Block curblock = new Block(startlabel);

	for (i = 0; i < stms.getSize(); i++) {

	    curstm = stms.getStatement(i);

	    if (curstm.getClassName().equals("IRLabel")) {
		IRLabel label = (IRLabel)curstm;
		if (inblock) {
		    curblock.getBody().append_imp(new IRJump(label));
		    m_blocks.addElement(curblock);
		    inblock = false;
		}

		curblock = new Block(label);
		inblock = true;
	    }
	    else if (curstm.getClassName().equals("IRJump") || curstm.getClassName().equals("IRCJump")) {

		curblock.getBody().append_imp(curstm);
		m_blocks.addElement(curblock);
		inblock = false;

	    }
	    else {
		if (inblock) {
		    curblock.getBody().append_imp(curstm);
		}
		else {
		    curblock = new Block(new IRLabel(new Label()));
		    inblock = true;
		}
	    }

	}

	if (inblock) {
	    curblock.getBody().append_imp(new IRJump(m_done));
	    m_blocks.addElement(curblock);
	}

	//m_blocks.addElement(new Block(m_done));
    }

    public String toString() {
	int i;
	String str ="";

	for (i = 0; i < m_blocks.size(); i++) {
	    str += ((Block)m_blocks.elementAt(i)).toString() + "\n";
	}

	return str;
    }

    private IRLabel m_done = new IRLabel(new Label());
    private Vector m_blocks = new Vector();
}
