view python/arm_cm3.py @ 202:f22b431f4113

Added arm add instruction
author Windel Bouwman
date Sat, 15 Jun 2013 10:02:50 +0200
parents
children ca1ea402f6a1
line wrap: on
line source

from target import Register, Instruction, Target
from asmnodes import ASymbol, ANumber
from ppci import CompilerError
import struct, types

def u16(h):
    return struct.pack('<H', h)

armtarget = Target('arm')

# Add a custom operand mapping method:
def mapOp(self, operand):
    if type(operand) is ASymbol:
        # try to map to register:
        regs = {}
        for r in self.registers:
            regs[r.name] = r
        if operand.name in regs:
            reg = regs[operand.name]
            return reg
    elif type(operand) is ANumber:
        return ArmImm(operand.number)
    raise CompilerError('Cannot map {0}'.format(operand))

armtarget.mapOperand = types.MethodType(mapOp, armtarget)

# Define:
registers = 'r0,r1,r2,r3,r4,r5'

class ArmReg(Register):
    def __init__(self, num, name):
        super().__init__(name)
        self.num = num

class ArmImm:
    def __init__(self, i):
        self.i = i

# 8 bit registers:
r4 = ArmReg(4, 'r4')
armtarget.registers.append(r4)

class ArmInstruction(Instruction):
    pass

@armtarget.instruction
class ldr_ins(ArmInstruction):
    mnemonic = 'ldr'
    opcode = 1337


@armtarget.instruction
class mov_ins(ArmInstruction):
    """ mov Rd, imm8, move immediate value into register """
    mnemonic = 'mov'
    opcode = 4 # 00100
    operands = (ArmReg, ArmImm)
    def __init__(self, r, imm):
        self.imm = imm.i
        self.r = r.num
    def encode(self):
        rd = self.r
        opcode = self.opcode
        imm8 = self.imm
        h = (opcode << 11) | (rd << 8) | imm8
        return u16(h)
        

@armtarget.instruction
class yield_ins(ArmInstruction):
    operands = ()
    mnemonic = 'yield'
    def encode(self):
        return u16(0xbf10)