/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package targets.mips;

import common.Code;
import common.Instruction;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.ListIterator;
import API.MiddlewareInterface;

/**
 *
 * @author EUGENIO CARVALHO
 */
public class MipsOtimizationMiddleware implements MiddlewareInterface {

    public MipsOtimizationMiddleware() {
    }

    @Override
    public void Exec(Code c, LinkedHashMap<String, MiddlewareInterface> cp) throws Exception {
        Instruction last = new Instruction();
//        ArrayList<Instruction> remove = new ArrayList<>();
        ListIterator<Instruction> instructions = c.Block().Instructions().listIterator();

        for (Iterator<Instruction> it = instructions; it.hasNext();) {
            Instruction current = it.next();
            switch (current.Get("inst")) {
                // Realiza a copia direta quando a instrucao anterior for um load e a atual for a copia
                case "addu":
                    if (current.eq("rs", "zero") && last.eq("inst", "lw")) {
                        last.Set("rt", current.Get("rd"));
//                        remove.add(current);
                        it.remove();
                    }
                    break;
            }

            last = current;
        }
//        for (Instruction current : ) {
//
//            switch (current.Get("inst")) {
//                // Realiza a copia direta quando a instrucao anterior for um load e a atual for a copia
//                case "addu":
//                    if (current.eq("rs", "zero") && last.eq("inst", "lw")) {
//                        last.Set("rt", current.Get("rd"));
//                        remove.add(current);
//                    }
//                    break;
//            }
//
//            last = current;
//        }

//        for (Instruction instruction : remove) {
//            System.out.println("Remover MipsOtimizationMiddleware:" + instruction);
//            instructions.remove(instruction);
//        }
    }

}
