def STORE_ARRAY(i):
    (x, y, z) = (data.block[i].out, data.block[i].in1, data.block[i].in2)
    try:
        int(z)
        pass
    except:
        register_allocator.getz(z)
    if data.zprime == None:
        data.zprime = z
    data.out.append("movl " + register_allocator.transform(data.zprime) + ", %edi")

    try:
        int(x)
        data.out.append("movl $" + x + ", " + y + "(, %edi, 4)")
        return
    except:
        pass
    # debug(adesc = data.adesc[x])
    register_allocator.getreg(x, y, i)
    debug(Lp=data.L)
    if data.rdesc[data.L] == None:
        data.out.append("movl " + register_allocator.transform(x) + ", " + register_allocator.transform(data.L))
    data.out.append("movl " + register_allocator.transform(data.L) + ", " + y + "(, %edi, 4)")
    data.adesc[x] = data.L
    data.rdesc[data.L] = x
def update(x):
    if data.L in data.rset:
        data.adesc[x] = data.L
        debug(x = x, L = data.L)
        data.rdesc[data.L] = x
    else:
        data.adesc[x] = None
    for v in data.vset :
        if data.adesc[v] == data.L and v != x:
            data.adesc[v] = None
    for k in data.rset:
        if data.L != k and data.rdesc[k] == x:
            data.rdesc[k] = None
def PRINT(i):
    x = data.block[i].out
    debug(x=x)
    try:
        debug(adesc=data.adesc[x])
        data.adesc[x]
        data.out.append("pushl %" + data.adesc[x])
    except:
        data.out.append("pushl " + register_allocator.transform(x))
    data.out.append("pushl $printFormat")
    register_allocator.save_to_memory()
    data.out.append("call printf")
    data.out.append("addl $8, %esp")
def PRINT(i):
    x = data.block[i].out
    debug(x = x)
    try :
        debug(adesc = data.adesc[x])
        data.adesc[x]
        data.out.append('pushl %' + data.adesc[x])
    except :
        data.out.append('pushl ' + x)
    data.out.append('pushl $printFormat')
    register_allocator.save_to_memory()
    data.out.append('call printf')
    data.out.append('addl $8, %esp')
def assembly_generator() :
    '''Entry point for assembly generation after parse_il()'''
    def block_assembly_generator() :
        '''Generates assembly code for current block. '''
        data.numins = len(data.block)
        debug(numins = data.numins)
        register_allocator.initblock()
        data.print_symbol_table()
        for i in range(0, len(data.block) - 1):
            register_allocator.ini()
            OP_MAP[data.block[i].type](i)
        i = len(data.block) - 1
        if i == -1: return
        if data.block[i].type in {'call', 'ret', 'goto', 'jg', 'je', 'jle', 'jge', 'je', 'jne'}:
            register_allocator.save_to_memory()
            register_allocator.ini()
            OP_MAP[data.block[i].type](i)
        else :
            register_allocator.ini()
            OP_MAP[data.block[i].type](i)
            register_allocator.save_to_memory()
        for line in data.out :
            print ("\t" + line)

    boilerplate()
    breakpoints = set()
    breakpoints.add(0)
    for i in range(0,len(data.raw)) :
        if data.raw[i].type == 'label' :
            breakpoints.add(i)
        if data.raw[i].type in ['call', 'ret', 'goto', 'jg', 'je', 'jle', 'jge', 'je', 'jne']:
            breakpoints.add(i+1)
    breakpoints.add(len(data.raw))
    breakpoints = sorted(breakpoints)
    for i in range(0,len(breakpoints)-1) :
        data.out.clear()
        if data.raw[breakpoints[i]].type == 'cmp' :
            debug(data.raw[breakpoints[i]])
        if data.raw[breakpoints[i]].type == 'label' :
            print("\n{}:".format(data.raw[breakpoints[i]].out))
        if i==0:
           data.block = data.raw[breakpoints[i]:breakpoints[i+1]]
        else:
            if data.raw[breakpoints[i]].type == 'label':
                data.block = data.raw[breakpoints[i] + 1:breakpoints[i+1]]
            else:
                data.block = data.raw[breakpoints[i]:breakpoints[i+1]]
        block_assembly_generator()
def transform(st):
    try :
        int(st)
        return '$'+str(st)
    except :
        if st in data.rset :
            return '%'+st
        else:
            if data.curr_scope != "" and st in data.memmap[data.curr_scope].keys() :
                return data.memmap[data.curr_scope][st]
            for k in data.memmap.keys() :
                if st in data.memmap[k].keys() :
                    return data.memmap[k][st]
            else :
                debug(frormtransform = st)
                return str(st)
Example #7
0
def parse_il(file_object) :
    flag = 0
    argcount = 8
    localcount = -4
    scope_func = 0
    index = 0
    for line in file_object.readlines():
        index+=1
        list_temp = line.split(',')
        list_i = [index]+[None]*4
        list_i[1:len(list_temp)+1] = list_temp
        list_i[len(list_temp)] = list_i[len(list_temp)].replace('\n', '')
        if not check_branching(list_i[1]) and not check_array(list_i[1]):
            for i in range(2,len(list_temp)+1) :
                if check_variable(list_i[i]) :
                    if(flag == 1):
                        if(list_i[i] not in data.memmap[scope_func].keys()):
                            debug(name = list_i[1])
                            if list_i[1] == 'arg':
                                debug('Hnishya')
                                data.memmap[scope_func][list_i[2]] = str(argcount) + "(%ebp)"
                                argcount += 4
                            elif(list_i[i] not in data.globmap):
                                data.memmap[scope_func][list_i[i]] = str(localcount) + "(%ebp)"
                                localcount -= 4
                    else:
                        data.globmap.add(list_i[i])
                    data.vset.add(list_i[i])
        if list_i[1] == 'label' and list_i[2].startswith('func'):
            flag = 1
            scope_func = list_i[2]
            data.memmap[scope_func] = {}
        if(list_i[1] == 'ret'):
            flag = 0
            data.num_var[scope_func] = -localcount
            data.num_arg[scope_func] = argcount
            argcount = 8
            localcount = -4
            scope_func = 0
        if list_i[1] == 'array':
            data.arrayset[list_i[2]] = list_i[3]
        if list_i[1] == 'printstr' :
            data.stringMap['str'+str(list_i[0])] = list_i[2]
        if list_i[1] == "cmp" :
            data.raw.append(data.instruction3ac(int(list_i[0]),list_i[1],list_i[2],list_i[3],None))
            continue
        data.raw.append(data.instruction3ac(int(list_i[0]),list_i[1],list_i[3],list_i[4],list_i[2]))
Example #8
0
def parse_il(file_object) :
        for line in file_object.readlines():
            if ',' not in line : continue
            list_temp = line.split(',')
            list_i = [None]*5
            list_i[:len(list_temp)] = list_temp
            list_i[len(list_temp)-1] = list_i[len(list_temp)-1].replace('\n', '')
            if not check_branching(list_i[1]) and not check_array(list_i[1]):
                for i in range(2,len(list_temp)) :
                    if check_variable(list_i[i]) :
                        data.vset.add(list_i[i])
            if list_i[1] == 'array':
                data.arrayset[list_i[2]] = list_i[3]
            if list_i[1] == 'printstr' :
                data.stringMap['str'+list_i[0]] = list_i[2]
            debug(list_i[0])
            if list_i[1] == "cmp" :
                data.raw.append(data.instruction3ac(int(list_i[0]),list_i[1],list_i[2],list_i[3],None))
                continue
            data.raw.append(data.instruction3ac(int(list_i[0]),list_i[1],list_i[3],list_i[4],list_i[2]))
 def block_assembly_generator() :
     '''Generates assembly code for current block. '''
     data.numins = len(data.block)
     debug(numins = data.numins)
     register_allocator.initblock()
     data.print_symbol_table()
     for i in range(0, len(data.block) - 1):
         register_allocator.ini()
         OP_MAP[data.block[i].type](i)
     i = len(data.block) - 1
     if i == -1: return
     if data.block[i].type in {'call', 'ret', 'goto', 'jg', 'je', 'jle', 'jge', 'je', 'jne'}:
         register_allocator.save_to_memory()
         register_allocator.ini()
         OP_MAP[data.block[i].type](i)
     else :
         register_allocator.ini()
         OP_MAP[data.block[i].type](i)
         register_allocator.save_to_memory()
     for line in data.out :
         print ("\t" + line)
 def block_assembly_generator():
     """Generates assembly code for current block. """
     data.numins = len(data.block)
     debug(numins=data.numins)
     register_allocator.initblock()
     data.print_symbol_table()
     for i in range(0, len(data.block) - 1):
         register_allocator.ini()
         OP_MAP[data.block[i].type](i)
     i = len(data.block) - 1
     if i == -1:
         return
     if data.block[i].type in {"call", "ret", "goto", "jg", "je", "jle", "jge", "je", "jne"}:
         register_allocator.save_to_memory()
         register_allocator.ini()
         OP_MAP[data.block[i].type](i)
     else:
         register_allocator.ini()
         OP_MAP[data.block[i].type](i)
         register_allocator.save_to_memory()
     for line in data.out:
         print("\t" + line)
def assembly_generator():
    """Entry point for assembly generation after parse_il()"""
    debug(memmap=data.memmap)
    debug(globmap=data.globmap)

    def block_assembly_generator():
        """Generates assembly code for current block. """
        data.numins = len(data.block)
        debug(numins=data.numins)
        register_allocator.initblock()
        data.print_symbol_table()
        for i in range(0, len(data.block) - 1):
            register_allocator.ini()
            OP_MAP[data.block[i].type](i)
        i = len(data.block) - 1
        if i == -1:
            return
        if data.block[i].type in {"call", "ret", "goto", "jg", "je", "jle", "jge", "je", "jne"}:
            register_allocator.save_to_memory()
            register_allocator.ini()
            OP_MAP[data.block[i].type](i)
        else:
            register_allocator.ini()
            OP_MAP[data.block[i].type](i)
            register_allocator.save_to_memory()
        for line in data.out:
            print("\t" + line)

    boilerplate()
    breakpoints = set()
    breakpoints.add(0)
    for i in range(0, len(data.raw)):
        if data.raw[i].type == "label":
            breakpoints.add(i)
        if data.raw[i].type in ["call", "ret", "goto", "jg", "je", "jle", "jge", "je", "jne"]:
            breakpoints.add(i + 1)
    breakpoints.add(len(data.raw))
    breakpoints = sorted(breakpoints)
    for i in range(0, len(breakpoints) - 1):
        data.out.clear()
        if data.raw[breakpoints[i]].type == "cmp":
            debug(data.raw[breakpoints[i]])
        if data.raw[breakpoints[i]].type == "label":
            print("\n{}:".format(data.raw[breakpoints[i]].out))
            if data.raw[breakpoints[i]].out.startswith("func"):
                data.curr_scope = data.raw[breakpoints[i]].out
                print("\t" + "pushl %ebp")
                print("\t" + "movl %esp, %ebp")
                print("\t" + "subl ${}, %esp".format(data.num_var[data.raw[breakpoints[i]].out] - 4))
        if i == 0:
            data.block = data.raw[breakpoints[i] : breakpoints[i + 1]]
        else:
            if data.raw[breakpoints[i]].type == "label":
                data.block = data.raw[breakpoints[i] + 1 : breakpoints[i + 1]]
            else:
                data.block = data.raw[breakpoints[i] : breakpoints[i + 1]]
        block_assembly_generator()
Example #12
0
#!/usr/bin/env python3
import data
import il_parser
import register_allocator
import assembly_generator

from data import debug

if __name__ == "__main__" :

    import argparse
    parser = argparse.ArgumentParser(description='Generate Assembly Code from 3-instruction code')
    parser.add_argument('file', metavar='file_name', type=argparse.FileType('r'),
                        help='file containing 3-instruction code.')
    parser.add_argument('-d','--debug', dest='debug', action='store_const',
                        const=1, default=0,
                        help='Turn on Debugging.')
    args = parser.parse_args()
    from sys import stderr
    data.debug_flag = args.debug
    debug("Debugging Mode On")
    il_parser.parse_il(args.file)
    assembly_generator.assembly_generator()

def generate_assembly(list_3AC) :
    il_parser.parse_il_from_list(list_3AC)
    assembly_generator.assembly_generator()
def freereg(var, ino):
    if var in data.vset :
        if data.symtable[ino][var] == 1000000007 and data.adesc[var] != None:
            data.rdesc[data.adesc[var]] = None
            debug('reset', var = var, )
            data.adesc[var] = None