view python/instructionselector.py @ 274:ea93e0a7a31e

Move docs
author Windel Bouwman
date Wed, 04 Sep 2013 17:35:06 +0200
parents 5f8c04a8d26b
children 6f2423df0675
line wrap: on
line source


import ir
import irmach

def genTemps():
    n = 900
    while True:
        yield 't{}'.format(n)
        n = n + 1

class InstructionSelector:
    """
        Base instruction selector. This class must be overridden by
        backends.
    """
    def newTmp(self):
        return self.temps.__next__()

    def getTempReg(self, tmp):
        if tmp not in self.tempMap:
            self.tempMap[tmp] = self.newTmp()
        return self.tempMap[tmp]

    def munchProgram(self, p):
        # Entry point for instruction selection
        self.temps = genTemps()
        assert isinstance(p, ir.Module)
        self.frames = []
        self.targets = {}
        self.tempMap = {} # Mapping from temporaries to infinite register
        for f in p.Functions:
            # Enter a frame per function:
            self.frame = self.newFrame(f.name)
            self.frames.append(self.frame)
            # First define labels:
            for bb in f.Blocks:
                itgt = self.makeIns('{}:'.format(bb.name))
                self.targets[bb] = itgt
            for bb in f.Blocks:
                self.emit2(self.targets[bb])
                for i in bb.Instructions:
                    self.munchStm(i)
                #bb.machIns = self.result
        return self.frames

    def makeIns(self, *args, **kwargs):
        return irmach.AbstractInstruction(*args, **kwargs)

    def emit(self, *args, **kwargs):
        """ Abstract instruction emitter """
        i = self.makeIns(*args, **kwargs)
        return self.emit2(i)

    def emit2(self, i):
        self.frame.instructions.append(i)
        return i

    def newFrame(self, name):
        raise NotImplementedError()

    def munchStm(self, s):
        """ Implement this in the target specific back-end """
        raise NotImplementedError()

    def munchExpr(self, e):
        """ Implement this in the target specific back-end """
        raise NotImplementedError()