code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
o1, o2 = _int_ops(op1, op2)
if int(o2) == 0: # A + 0 = 0 + A = A => Do Nothing
output = _32bit_oper(o1)
output.append('push de')
output.append('push hl')
return output
if op1[0] == '_' and op2[0] != '_':
op1, op2 = op2, op1 # swap them
if op2[0] == '_':
output = _32bit_oper(op1)
output.append('ld bc, (%s)' % op2)
output.append('add hl, bc')
output.append('ex de, hl')
output.append('ld bc, (%s + 2)' % op2)
output.append('adc hl, bc')
output.append('push hl')
output.append('push de')
return output
output = _32bit_oper(op1, op2)
output.append('pop bc')
output.append('add hl, bc')
output.append('ex de, hl')
output.append('pop bc')
output.append('adc hl, bc')
output.append('push hl') # High and low parts are reversed
output.append('push de')
return output
|
def _add32(ins)
|
Pops last 2 bytes from the stack and adds them.
Then push the result onto the stack.
Optimizations:
* If any of the operands is ZERO,
then do NOTHING: A + 0 = 0 + A = A
| 3.146626 | 3.134705 | 1.003803 |
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
if int(op2) == 0: # A - 0 = A => Do Nothing
output = _32bit_oper(op1)
output.append('push de')
output.append('push hl')
return output
rev = op1[0] != 't' and not is_int(op1) and op2[0] == 't'
output = _32bit_oper(op1, op2, rev)
output.append('call __SUB32')
output.append('push de')
output.append('push hl')
REQUIRES.add('sub32.asm')
return output
|
def _sub32(ins)
|
Pops last 2 dwords from the stack and subtract them.
Then push the result onto the stack.
NOTE: The operation is TOP[0] = TOP[-1] - TOP[0]
If TOP[0] is 0, nothing is done
| 5.840409 | 6.047465 | 0.965762 |
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2):
op1, op2 = _int_ops(op1, op2)
output = _32bit_oper(op1)
if op2 == 1:
output.append('push de')
output.append('push hl')
return output # A * 1 = Nothing
if op2 == 0:
output.append('ld hl, 0')
output.append('push hl')
output.append('push hl')
return output
output = _32bit_oper(op1, op2)
output.append('call __MUL32') # Inmmediate
output.append('push de')
output.append('push hl')
REQUIRES.add('mul32.asm')
return output
|
def _mul32(ins)
|
Multiplies two last 32bit values on top of the stack and
and returns the value on top of the stack
Optimizations done:
* If any operand is 1, do nothing
* If any operand is 0, push 0
| 5.124603 | 5.175492 | 0.990167 |
op1, op2 = tuple(ins.quad[2:])
rev = op1[0] != 't' and not is_int(op1) and op2[0] == 't'
output = _32bit_oper(op1, op2, rev)
output.append('call __SUB32')
output.append('sbc a, a')
output.append('push af')
REQUIRES.add('sub32.asm')
return output
|
def _ltu32(ins)
|
Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
32 bit unsigned version
| 8.516293 | 8.937057 | 0.952919 |
op1, op2 = tuple(ins.quad[2:])
rev = op1[0] != 't' and not is_int(op1) and op2[0] == 't'
output = _32bit_oper(op1, op2, rev)
output.append('pop bc')
output.append('or a')
output.append('sbc hl, bc')
output.append('ex de, hl')
output.append('pop de')
output.append('sbc hl, de')
output.append('sbc a, a')
output.append('push af')
return output
|
def _gtu32(ins)
|
Compares & pops top 2 operands out of the stack, and checks
if the 1st operand > 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
32 bit unsigned version
| 5.147669 | 5.491734 | 0.937349 |
op1, op2 = tuple(ins.quad[2:])
output = _32bit_oper(op1, op2)
output.append('call __EQ32')
output.append('push af')
REQUIRES.add('eq32.asm')
return output
|
def _eq32(ins)
|
Compares & pops top 2 operands out of the stack, and checks
if the 1st operand == 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
32 bit un/signed version
| 12.506129 | 13.569289 | 0.92165 |
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2):
op1, op2 = _int_ops(op1, op2)
if op2 == 0: # X and False = False
if str(op1)[0] == 't': # a temporary term (stack)
output = _32bit_oper(op1) # Remove op1 from the stack
else:
output = []
output.append('xor a')
output.append('push af')
return output
# For X and TRUE = X we do nothing as we have to convert it to boolean
# which is a rather expensive instruction
output = _32bit_oper(op1, op2)
output.append('call __AND32')
output.append('push af')
REQUIRES.add('and32.asm')
return output
|
def _and32(ins)
|
Compares & pops top 2 operands out of the stack, and checks
if the 1st operand AND (Logical) 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
32 bit un/signed version
| 8.937932 | 9.363237 | 0.954577 |
output = _32bit_oper(ins.quad[2])
output.append('call __NOT32')
output.append('push af')
REQUIRES.add('not32.asm')
return output
|
def _not32(ins)
|
Negates top (Logical NOT) of the stack (32 bits in DEHL)
| 19.496674 | 18.301563 | 1.065301 |
output = _32bit_oper(ins.quad[2])
output.append('call __BNOT32')
output.append('push de')
output.append('push hl')
REQUIRES.add('bnot32.asm')
return output
|
def _bnot32(ins)
|
Negates top (Bitwise NOT) of the stack (32 bits in DEHL)
| 13.319017 | 11.749772 | 1.133555 |
output = _32bit_oper(ins.quad[2])
output.append('call __NEG32')
output.append('push de')
output.append('push hl')
REQUIRES.add('neg32.asm')
return output
|
def _neg32(ins)
|
Negates top of the stack (32 bits in DEHL)
| 15.19089 | 13.32807 | 1.139767 |
output = _32bit_oper(ins.quad[2])
output.append('call __ABS32')
output.append('push de')
output.append('push hl')
REQUIRES.add('abs32.asm')
return output
|
def _abs32(ins)
|
Absolute value of top of the stack (32 bits in DEHL)
| 14.085396 | 13.325296 | 1.057042 |
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
output = _32bit_oper(op1)
if int(op2) == 0:
output.append('push de')
output.append('push hl')
return output
if int(op2) > 1:
label = tmp_label()
output.append('ld b, %s' % op2)
output.append('%s:' % label)
output.append('call __SHL32')
output.append('djnz %s' % label)
else:
output.append('call __SHL32')
output.append('push de')
output.append('push hl')
REQUIRES.add('shl32.asm')
return output
output = _8bit_oper(op2)
output.append('ld b, a')
output.extend(_32bit_oper(op1))
label = tmp_label()
output.append('%s:' % label)
output.append('call __SHL32')
output.append('djnz %s' % label)
output.append('push de')
output.append('push hl')
REQUIRES.add('shl32.asm')
return output
|
def _shl32(ins)
|
Logical Left shift 32bit unsigned integers.
The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 0, do nothing
| 3.005469 | 3.190614 | 0.941972 |
''' Adds 2 float values. The result is pushed onto the stack.
'''
op1, op2 = tuple(ins.quad[2:])
if _f_ops(op1, op2) is not None:
opa, opb = _f_ops(op1, op2)
if opb == 0: # A + 0 => A
output = _float_oper(opa)
output.extend(_fpush())
return output
output = _float_oper(op1, op2)
output.append('call __ADDF')
output.extend(_fpush())
REQUIRES.add('addf.asm')
return output
|
def _addf(ins)
|
Adds 2 float values. The result is pushed onto the stack.
| 6.965955 | 6.125072 | 1.137285 |
''' Divides 2 float values. The result is pushed onto the stack.
'''
op1, op2 = tuple(ins.quad[2:])
if is_float(op2) and float(op2) == 1: # Nothing to do. A / 1 = A
output = _float_oper(op1)
output.extend(_fpush())
return output
output = _float_oper(op1, op2)
output.append('call __DIVF')
output.extend(_fpush())
REQUIRES.add('divf.asm')
return output
|
def _divf(ins)
|
Divides 2 float values. The result is pushed onto the stack.
| 8.630908 | 7.313658 | 1.180108 |
''' Reminder of div. 2 float values. The result is pushed onto the stack.
'''
op1, op2 = tuple(ins.quad[2:])
output = _float_oper(op1, op2)
output.append('call __MODF')
output.extend(_fpush())
REQUIRES.add('modf.asm')
return output
|
def _modf(ins)
|
Reminder of div. 2 float values. The result is pushed onto the stack.
| 19.210651 | 10.205955 | 1.882298 |
''' Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
Floating Point version
'''
op1, op2 = tuple(ins.quad[2:])
output = _float_oper(op1, op2)
output.append('call __LTF')
output.append('push af')
REQUIRES.add('ltf.asm')
return output
|
def _ltf(ins)
|
Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
Floating Point version
| 13.337155 | 5.546747 | 2.404501 |
''' Negates top of the stack (48 bits)
'''
output = _float_oper(ins.quad[2])
output.append('call __NOTF')
output.append('push af')
REQUIRES.add('notf.asm')
return output
|
def _notf(ins)
|
Negates top of the stack (48 bits)
| 26.402483 | 18.939087 | 1.394074 |
''' Changes sign of top of the stack (48 bits)
'''
output = _float_oper(ins.quad[2])
output.append('call __NEGF')
output.extend(_fpush())
REQUIRES.add('negf.asm')
return output
|
def _negf(ins)
|
Changes sign of top of the stack (48 bits)
| 30.956348 | 20.192635 | 1.533051 |
''' Absolute value of top of the stack (48 bits)
'''
output = _float_oper(ins.quad[2])
output.append('res 7, e') # Just resets the sign bit!
output.extend(_fpush())
return output
|
def _absf(ins)
|
Absolute value of top of the stack (48 bits)
| 30.548748 | 22.652031 | 1.34861 |
result = []
for i in l:
if i not in result:
result.append(i)
return result
|
def get_uniques(l)
|
Returns a list with no repeated elements.
| 2.748488 | 2.385092 | 1.152362 |
r"'.'" # A single char
t.value = ord(t.value[1])
t.type = 'INTEGER'
return t
|
def t_CHAR(self, t)
|
r"'.
| 8.677275 | 7.483259 | 1.159558 |
r'(%[01]+)|([01]+[bB])' # A Binary integer
# Note 00B is a 0 binary, but
# 00Bh is a 12 in hex. So this pattern must come
# after HEXA
if t.value[0] == '%':
t.value = t.value[1:] # Remove initial %
else:
t.value = t.value[:-1] # Remove last 'b'
t.value = int(t.value, 2) # Convert to decimal
t.type = 'INTEGER'
return t
|
def t_BIN(self, t)
|
r'(%[01]+)|([01]+[bB])
| 6.613023 | 5.564745 | 1.188378 |
r'[._a-zA-Z][._a-zA-Z0-9]*([ \t]*[:])?' # Any identifier
tmp = t.value # Saves original value
if tmp[-1] == ':':
t.type = 'LABEL'
t.value = tmp[:-1].strip()
return t
t.value = tmp.upper() # Convert it to uppercase, since our internal tables uses uppercase
id_ = tmp.lower()
t.type = reserved_instructions.get(id_)
if t.type is not None:
return t
t.type = pseudo.get(id_)
if t.type is not None:
return t
t.type = regs8.get(id_)
if t.type is not None:
return t
t.type = flags.get(id_)
if t.type is not None:
return t
t.type = regs16.get(id_, 'ID')
if t.type == 'ID':
t.value = tmp # Restores original value
return t
|
def t_INITIAL_ID(self, t)
|
r'[._a-zA-Z][._a-zA-Z0-9]*([ \t]*[:])?
| 3.838338 | 3.360429 | 1.142217 |
r'[_a-zA-Z][_a-zA-Z0-9]*' # preprocessor directives
t.type = preprocessor.get(t.value.lower(), 'ID')
return t
|
def t_preproc_ID(self, t)
|
r'[_a-zA-Z][_a-zA-Z0-9]*
| 4.272569 | 3.840376 | 1.112539 |
r'[[(]'
if t.value != '[' and OPTIONS.bracket.value:
t.type = 'LPP'
return t
|
def t_LP(self, t)
|
r'[[(]
| 24.01075 | 13.927016 | 1.724041 |
r'[])]'
if t.value != ']' and OPTIONS.bracket.value:
t.type = 'RPP'
return t
|
def t_RP(self, t)
|
r'[])]
| 24.714563 | 14.095568 | 1.753357 |
r'\r?\n'
t.lexer.lineno += 1
t.lexer.begin('INITIAL')
return t
|
def t_INITIAL_preproc_NEWLINE(self, t)
|
r'\r?\n
| 5.305372 | 3.972871 | 1.3354 |
r'\#'
if self.find_column(t) == 1:
t.lexer.begin('preproc')
else:
self.t_INITIAL_preproc_error(t)
|
def t_INITIAL_SHARP(self, t)
|
r'\#
| 9.692094 | 8.354156 | 1.160152 |
self.input_data = str
self.lex = lex.lex(object=self)
self.lex.input(self.input_data)
|
def input(self, str)
|
Defines input string, removing current lexer.
| 4.184246 | 3.334642 | 1.254781 |
self.value = SymbolTYPECAST.make_node(type_, self.value, self.lineno)
return self.value is not None
|
def typecast(self, type_)
|
Test type casting to the argument expression.
On success changes the node value to the new typecast, and returns
True. On failure, returns False, and the node value is set to None.
| 13.037165 | 9.00621 | 1.447575 |
''' Generic array address parameter loading.
Emmits output code for setting IX at the right location.
bytes = Number of bytes to load:
1 => 8 bit value
2 => 16 bit value / string
4 => 32 bit value / f16 value
5 => 40 bit value
'''
output = []
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4 # Return Address + "push IX"
output.append('push ix')
output.append('pop hl')
output.append('ld de, %i' % I)
output.append('add hl, de')
if indirect:
output.append('ld c, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, c')
output.append('call __ARRAY')
REQUIRES.add('array.asm')
return output
|
def _paddr(offset)
|
Generic array address parameter loading.
Emmits output code for setting IX at the right location.
bytes = Number of bytes to load:
1 => 8 bit value
2 => 16 bit value / string
4 => 32 bit value / f16 value
5 => 40 bit value
| 8.174552 | 3.818395 | 2.140834 |
''' Loads an 8 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
'''
output = _paddr(ins.quad[2])
output.append('ld a, (hl)')
output.append('push af')
return output
|
def _paload8(ins)
|
Loads an 8 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
| 18.116974 | 6.062953 | 2.988144 |
''' Loads a 16 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
'''
output = _paddr(ins.quad[2])
output.append('ld e, (hl)')
output.append('inc hl')
output.append('ld d, (hl)')
output.append('ex de, hl')
output.append('push hl')
return output
|
def _paload16(ins)
|
Loads a 16 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
| 10.491938 | 5.035477 | 2.083603 |
''' Load a 32 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
'''
output = _paddr(ins.quad[2])
output.append('call __ILOAD32')
output.append('push de')
output.append('push hl')
REQUIRES.add('iload32.asm')
return output
|
def _paload32(ins)
|
Load a 32 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
| 16.756567 | 7.689537 | 2.179139 |
''' Loads a floating point value from a memory address.
If 2nd arg. start with '*', it is always treated as
an indirect value.
'''
output = _paddr(ins.quad[2])
output.append('call __ILOADF')
output.extend(_fpush())
REQUIRES.add('iloadf.asm')
return output
|
def _paloadf(ins)
|
Loads a floating point value from a memory address.
If 2nd arg. start with '*', it is always treated as
an indirect value.
| 24.137251 | 9.625903 | 2.507531 |
''' Loads a string value from a memory address.
'''
output = _paddr(ins.quad[2])
output.append('call __ILOADSTR')
output.append('push hl')
REQUIRES.add('loadstr.asm')
return output
|
def _paloadstr(ins)
|
Loads a string value from a memory address.
| 17.87672 | 17.428381 | 1.025725 |
''' Stores 2º operand content into address of 1st operand.
1st operand is an array element. Dimensions are pushed into the
stack.
Use '*' for indirect store on 1st operand (A pointer to an array)
'''
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
value = int(ins.quad[2]) & 0xFFFF
if indirect:
output.append('ld a, (%i)' % value)
output.append('ld (hl), a')
else:
value &= 0xFF
output.append('ld (hl), %i' % value)
except ValueError:
output.append('pop af')
output.append('ld (hl), a')
return output
|
def _pastore8(ins)
|
Stores 2º operand content into address of 1st operand.
1st operand is an array element. Dimensions are pushed into the
stack.
Use '*' for indirect store on 1st operand (A pointer to an array)
| 6.903531 | 3.259717 | 2.117831 |
''' Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
Use '*' for indirect store on 1st operand.
'''
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
value = int(ins.quad[2]) & 0xFFFF
output.append('ld de, %i' % value)
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
except ValueError:
output.append('pop de')
output.append('ld (hl), e')
output.append('inc hl')
output.append('ld (hl), d')
return output
|
def _pastore16(ins)
|
Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
Use '*' for indirect store on 1st operand.
| 8.885287 | 4.584237 | 1.938226 |
''' Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
'''
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
value = int(ins.quad[2]) & 0xFFFFFFFF # Immediate?
if indirect:
output.append('push hl')
output.append('ld hl, %i' % (value & 0xFFFF))
output.append('call __ILOAD32')
output.append('ld b, h')
output.append('ld c, l') # BC = Lower 16 bits
output.append('pop hl')
REQUIRES.add('iload32.asm')
else:
output.append('ld de, %i' % (value >> 16))
output.append('ld bc, %i' % (value & 0xFFFF))
except ValueError:
output.append('pop bc')
output.append('pop de')
output.append('call __STORE32')
REQUIRES.add('store32.asm')
return output
|
def _pastore32(ins)
|
Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
| 5.650909 | 4.11157 | 1.374392 |
''' Stores 2º operand content into address of 1st operand.
storef16 a, x => *(&a) = x
'''
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
if indirect:
value = int(ins.quad[2])
output.append('push hl')
output.append('ld hl, %i' % (value & 0xFFFF))
output.append('call __ILOAD32')
output.append('ld b, h')
output.append('ld c, l') # BC = Lower 16 bits
output.append('pop hl')
REQUIRES.add('iload32.asm')
else:
de, hl = f16(value)
output.append('ld de, %i' % de)
output.append('ld bc, %i' % hl)
except ValueError:
output.append('pop bc')
output.append('pop de')
output.append('call __STORE32')
REQUIRES.add('store32.asm')
return output
|
def _pastoref16(ins)
|
Stores 2º operand content into address of 1st operand.
storef16 a, x => *(&a) = x
| 6.016507 | 4.277802 | 1.406448 |
''' Stores a floating point value into a memory address.
'''
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
if indirect:
value = int(value) & 0xFFFF # Inmediate?
output.append('push hl')
output.append('ld hl, %i' % value)
output.append('call __ILOADF')
output.append('ld a, c')
output.append('ld b, h')
output.append('ld c, l') # BC = Lower 16 bits, A = Exp
output.append('pop hl') # Recovers pointer
REQUIRES.add('iloadf.asm')
else:
value = float(value) # Inmediate?
C, DE, HL = fp.immediate_float(value) # noqa TODO: it will fail
output.append('ld a, %s' % C)
output.append('ld de, %s' % DE)
output.append('ld bc, %s' % HL)
except ValueError:
output.append('pop bc')
output.append('pop de')
output.append('ex (sp), hl') # Preserve HL for STOREF
output.append('ld a, l')
output.append('pop hl')
output.append('call __STOREF')
REQUIRES.add('storef.asm')
return output
|
def _pastoref(ins)
|
Stores a floating point value into a memory address.
| 6.160501 | 5.923311 | 1.040044 |
''' Stores a string value into a memory address.
It copies content of 2nd operand (string), into 1st, reallocating
dynamic memory for the 1st str. These instruction DOES ALLOW
inmediate strings for the 2nd parameter, starting with '#'.
'''
output = _paddr(ins.quad[1])
temporal = False
value = ins.quad[2]
indirect = value[0] == '*'
if indirect:
value = value[1:]
immediate = value[0]
if immediate:
value = value[1:]
if value[0] == '_':
if indirect:
if immediate:
output.append('ld de, (%s)' % value)
else:
output.append('ld de, (%s)' % value)
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
else:
if immediate:
output.append('ld de, %s' % value)
else:
output.append('ld de, (%s)' % value)
else:
output.append('pop de')
temporal = True
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm')
if not temporal:
output.append('call __STORE_STR')
REQUIRES.add('storestr.asm')
else: # A value already on dynamic memory
output.append('call __STORE_STR2')
REQUIRES.add('storestr2.asm')
return output
|
def _pastorestr(ins)
|
Stores a string value into a memory address.
It copies content of 2nd operand (string), into 1st, reallocating
dynamic memory for the 1st str. These instruction DOES ALLOW
inmediate strings for the 2nd parameter, starting with '#'.
| 5.356786 | 3.093563 | 1.731591 |
if not isinstance(x, int): # If it is another "thing", just return ZEROs
return tuple([0] * bytes)
x = x & ((2 << (bytes * 8)) - 1) # mask the initial value
result = ()
for i in range(bytes):
result += (x & 0xFF,)
x >>= 8
return result
|
def num2bytes(x, bytes)
|
Returns x converted to a little-endian t-uple of bytes.
E.g. num2bytes(255, 4) = (255, 0, 0, 0)
| 5.843789 | 5.308459 | 1.100845 |
if self.arg is None or any(x is None for x in self.arg):
return None
for x in self.arg:
if not isinstance(x, int):
raise InvalidArgError(self.arg)
return self.arg
|
def argval(self)
|
Returns the value of the arg (if any) or None.
If the arg. is not an integer, an error be triggered.
| 3.688131 | 3.014473 | 1.223474 |
result = []
op = self.opcode.split(' ')
argi = 0
while op:
q = op.pop(0)
if q == 'XX':
for k in range(self.argbytes[argi] - 1):
op.pop(0)
result.extend(num2bytes(self.argval()[argi], self.argbytes[argi]))
argi += 1
else:
result.append(int(q, 16)) # Add opcode
if len(result) != self.size:
raise InternalMismatchSizeError(len(result), self)
return result
|
def bytes(self)
|
Returns a t-uple with instruction bytes (integers)
| 5.654054 | 5.028136 | 1.124483 |
if global_.has_errors > OPTIONS.max_syntax_errors.value:
msg = 'Too many errors. Giving up!'
msg = "%s:%i: %s" % (global_.FILENAME, lineno, msg)
msg_output(msg)
if global_.has_errors > OPTIONS.max_syntax_errors.value:
sys.exit(1)
global_.has_errors += 1
|
def syntax_error(lineno, msg)
|
Generic syntax error routine
| 5.094424 | 5.25844 | 0.968809 |
msg = "%s:%i: warning: %s" % (global_.FILENAME, lineno, msg)
msg_output(msg)
global_.has_warnings += 1
|
def warning(lineno, msg)
|
Generic warning error routine
| 7.53441 | 7.390619 | 1.019456 |
if OPTIONS.strict.value:
syntax_error_undeclared_type(lineno, id_)
return
if type_ is None:
type_ = global_.DEFAULT_TYPE
warning(lineno, "Using default implicit type '%s' for '%s'" % (type_, id_))
|
def warning_implicit_type(lineno, id_, type_=None)
|
Warning: Using default implicit type 'x'
| 6.206096 | 5.212928 | 1.19052 |
i = inst.strip(' \t\n').split(' ')
I = i[0].lower() # Instruction
i = ''.join(i[1:])
op = i.split(',')
if I in {'call', 'jp', 'jr'} and len(op) > 1:
op = op[1:] + ['f']
elif I == 'djnz':
op.append('b')
elif I in {'push', 'pop', 'call'}:
op.append('sp') # Sp is also affected by push, pop and call
elif I in {'or', 'and', 'xor', 'neg', 'cpl', 'rrca', 'rlca'}:
op.append('a')
elif I in {'rra', 'rla'}:
op.extend(['a', 'f'])
elif I in ('rr', 'rl'):
op.append('f')
elif I in {'adc', 'sbc'}:
if len(op) == 1:
op = ['a', 'f'] + op
elif I in {'add', 'sub'}:
if len(op) == 1:
op = ['a'] + op
elif I in {'ldd', 'ldi', 'lddr', 'ldir'}:
op = ['hl', 'de', 'bc']
elif I in {'cpd', 'cpi', 'cpdr', 'cpir'}:
op = ['a', 'hl', 'bc']
elif I == 'exx':
op = ['*', 'bc', 'de', 'hl', 'b', 'c', 'd', 'e', 'h', 'l']
elif I in {'ret', 'reti', 'retn'}:
op += ['sp']
elif I == 'out':
if len(op) and RE_OUTC.match(op[0]):
op[0] = 'c'
else:
op.pop(0)
elif I == 'in':
if len(op) > 1 and RE_OUTC.match(op[1]):
op[1] = 'c'
else:
op.pop(1)
for i in range(len(op)):
tmp = RE_INDIR16.match(op[i])
if tmp is not None:
op[i] = '(' + op[i].strip()[1:-1].strip().lower() + ')' # ' ( dE ) ' => '(de)'
return op
|
def oper(inst)
|
Returns operands of an ASM instruction.
Even "indirect" operands, like SP if RET or CALL is used.
| 3.37819 | 3.26834 | 1.03361 |
I = inst(i)
if I not in {'call', 'jp', 'jr', 'ret'}:
return None # This instruction always execute
if I == 'ret':
i = [x.lower() for x in i.split(' ') if x != '']
return i[1] if len(i) > 1 else None
i = [x.strip() for x in i.split(',')]
i = [x.lower() for x in i[0].split(' ') if x != '']
if len(i) > 1 and i[1] in {'c', 'nc', 'z', 'nz', 'po', 'pe', 'p', 'm'}:
return i[1]
return None
|
def condition(i)
|
Returns the flag this instruction uses
or None. E.g. 'c' for Carry, 'nz' for not-zero, etc.
That is the condition required for this instruction
to execute. For example: ADC A, 0 does NOT have a
condition flag (it always execute) whilst RETC does.
| 3.750346 | 3.16276 | 1.185783 |
result = set()
if isinstance(op, str):
op = [op]
for x in op:
if is_8bit_register(x):
result = result.union([x])
elif x == 'sp':
result.add(x)
elif x == 'af':
result = result.union(['a', 'f'])
elif x == "af'":
result = result.union(["a'", "f'"])
elif is_16bit_register(x): # Must be a 16bit reg or we have an internal error!
result = result.union([LO16(x), HI16(x)])
return list(result)
|
def single_registers(op)
|
Given a list of registers like ['a', 'bc', 'h', 'hl'] returns
a set of single registers: ['a', 'b', 'c', 'h', 'l'].
Non register parameters, like numbers will be ignored.
| 3.845639 | 3.637783 | 1.057138 |
ins = inst(i)
op = oper(i)
if ins in ('or', 'and') and op == ['a']:
return ['f']
if ins in {'xor', 'or', 'and', 'neg', 'cpl', 'daa', 'rld', 'rrd', 'rra', 'rla', 'rrca', 'rlca'}:
return ['a', 'f']
if ins in {'bit', 'cp', 'scf', 'ccf'}:
return ['f']
if ins in {'sub', 'add', 'sbc', 'adc'}:
if len(op) == 1:
return ['a', 'f']
else:
return single_registers(op[0]) + ['f']
if ins == 'djnz':
return ['b', 'f']
if ins in {'ldir', 'ldi', 'lddr', 'ldd'}:
return ['f', 'b', 'c', 'd', 'e', 'h', 'l']
if ins in {'cpi', 'cpir', 'cpd', 'cpdr'}:
return ['f', 'b', 'c', 'h', 'l']
if ins in ('pop', 'ld'):
return single_registers(op[0])
if ins in {'inc', 'dec', 'sbc', 'rr', 'rl', 'rrc', 'rlc'}:
return ['f'] + single_registers(op[0])
if ins in ('set', 'res'):
return single_registers(op[1])
return []
|
def result(i)
|
Returns which 8-bit registers are used by an asm
instruction to return a result.
| 3.529623 | 3.507653 | 1.006264 |
i += 1
new_block = BasicBlock(block.asm[i:])
block.mem = block.mem[:i]
block.asm = block.asm[:i]
block.update_labels()
new_block.update_labels()
new_block.goes_to = block.goes_to
block.goes_to = IdentitySet()
new_block.label_goes = block.label_goes
block.label_goes = []
new_block.next = new_block.original_next = block.original_next
new_block.prev = block
new_block.add_comes_from(block)
if new_block.next is not None:
new_block.next.prev = new_block
new_block.next.add_comes_from(new_block)
new_block.next.delete_from(block)
block.next = block.original_next = new_block
block.update_next_block()
block.add_goes_to(new_block)
return block, new_block
|
def block_partition(block, i)
|
Returns two blocks, as a result of partitioning the given one at
i-th instruction.
| 3.101665 | 3.025857 | 1.025053 |
result = [block]
if not block.is_partitionable:
return result
EDP = END_PROGRAM_LABEL + ':'
for i in range(len(block) - 1):
if i and block.asm[i] == EDP: # END_PROGRAM label always starts a basic block
block, new_block = block_partition(block, i - 1)
LABELS[END_PROGRAM_LABEL].basic_block = new_block
result.extend(partition_block(new_block))
return result
if block.mem[i].is_ender:
block, new_block = block_partition(block, i)
result.extend(partition_block(new_block))
op = block.mem[i].opers
for l in op:
if l in LABELS.keys():
JUMP_LABELS.add(l)
block.label_goes += [l]
return result
if block.asm[i] in arch.zx48k.backend.ASMS:
if i > 0:
block, new_block = block_partition(block, i - 1)
result.extend(partition_block(new_block))
return result
block, new_block = block_partition(block, i)
result.extend(partition_block(new_block))
return result
for label in JUMP_LABELS:
must_partition = False
if LABELS[label].basic_block is block:
for i in range(len(block)):
cell = block.mem[i]
if cell.inst == label:
break
if cell.is_label:
continue
if cell.is_ender:
continue
must_partition = True
if must_partition:
block, new_block = block_partition(block, i - 1)
LABELS[label].basic_block = new_block
result.extend(partition_block(new_block))
return result
return result
|
def partition_block(block)
|
If a block is not partitionable, returns a list with the same block.
Otherwise, returns a list with the resulting blocks, recursively.
| 3.436292 | 3.38122 | 1.016288 |
for cell in MEMORY:
if cell.is_label:
label = cell.inst
LABELS[label] = LabelInfo(label, cell.addr, basic_block)
|
def get_labels(MEMORY, basic_block)
|
Traverses memory, to annotate all the labels in the global
LABELS table
| 6.119374 | 5.833504 | 1.049005 |
global MEMORY
MEMORY = basic_block.mem
get_labels(MEMORY, basic_block)
basic_block.mem = MEMORY
|
def initialize_memory(basic_block)
|
Initializes global memory array with the given one
| 7.619335 | 7.466715 | 1.02044 |
i = 0
while i < len(initial_memory):
tmp = initial_memory[i]
match = RE_LABEL.match(tmp)
if not match:
i += 1
continue
if tmp.rstrip() == match.group():
i += 1
continue
initial_memory[i] = tmp[match.end():]
initial_memory.insert(i, match.group())
i += 1
|
def cleanupmem(initial_memory)
|
Cleans up initial memory. Each label must be
ALONE. Each instruction must have an space, etc...
| 2.923039 | 2.810408 | 1.040076 |
global PROC_COUNTER
stack = [[]]
hashes = [{}]
stackprc = [PROC_COUNTER]
used = [{}] # List of hashes of unresolved labels per scope
MEMORY = block.mem
for cell in MEMORY:
if cell.inst.upper() == 'PROC':
stack += [[]]
hashes += [{}]
stackprc += [PROC_COUNTER]
used += [{}]
PROC_COUNTER += 1
continue
if cell.inst.upper() == 'ENDP':
if len(stack) > 1: # There might be unbalanced stack due to syntax errors
for label in used[-1].keys():
if label in stack[-1]:
newlabel = hashes[-1][label]
for cell in used[-1][label]:
cell.replace_label(label, newlabel)
stack.pop()
hashes.pop()
stackprc.pop()
used.pop()
continue
tmp = cell.asm.strip()
if tmp.upper()[:5] == 'LOCAL':
tmp = tmp[5:].split(',')
for lbl in tmp:
lbl = lbl.strip()
if lbl in stack[-1]:
continue
stack[-1] += [lbl]
hashes[-1][lbl] = 'PROC%i.' % stackprc[-1] + lbl
if used[-1].get(lbl, None) is None:
used[-1][lbl] = []
cell.asm = ';' + cell.asm # Remove it
continue
if cell.is_label:
label = cell.inst
for i in range(len(stack) - 1, -1, -1):
if label in stack[i]:
label = hashes[i][label]
cell.asm = label + ':'
break
continue
for label in cell.used_labels:
labelUsed = False
for i in range(len(stack) - 1, -1, -1):
if label in stack[i]:
newlabel = hashes[i][label]
cell.replace_label(label, newlabel)
labelUsed = True
break
if not labelUsed:
if used[-1].get(label, None) is None:
used[-1][label] = []
used[-1][label] += [cell]
for i in range(len(MEMORY) - 1, -1, -1):
if MEMORY[i].asm[0] == ';':
MEMORY.pop(i)
block.mem = MEMORY
block.asm = [x.asm for x in MEMORY if len(x.asm.strip())]
|
def cleanup_local_labels(block)
|
Traverses memory, to make any local label a unique
global one. At this point there's only a single code
block
| 3.077873 | 3.012586 | 1.021671 |
global BLOCKS
global PROC_COUNTER
LABELS.clear()
JUMP_LABELS.clear()
del MEMORY[:]
PROC_COUNTER = 0
cleanupmem(initial_memory)
if OPTIONS.optimization.value <= 2:
return '\n'.join(x for x in initial_memory if not RE_PRAGMA.match(x))
optimize_init()
bb = BasicBlock(initial_memory)
cleanup_local_labels(bb)
initialize_memory(bb)
BLOCKS = basic_blocks = get_basic_blocks(bb) # 1st partition the Basic Blocks
for x in basic_blocks:
x.clean_up_comes_from()
x.clean_up_goes_to()
for x in basic_blocks:
x.update_goes_and_comes()
LABELS['*START*'].basic_block.add_goes_to(basic_blocks[0])
LABELS['*START*'].basic_block.next = basic_blocks[0]
basic_blocks[0].prev = LABELS['*START*'].basic_block
LABELS[END_PROGRAM_LABEL].basic_block.add_goes_to(LABELS['*__END_PROGRAM*'].basic_block)
for x in basic_blocks:
x.optimize()
for x in basic_blocks:
if x.comes_from == [] and len([y for y in JUMP_LABELS if x is LABELS[y].basic_block]):
x.ignored = True
return '\n'.join([y for y in flatten_list([x.asm for x in basic_blocks if not x.ignored])
if not RE_PRAGMA.match(y)])
|
def optimize(initial_memory)
|
This will remove useless instructions
| 4.980037 | 4.803319 | 1.036791 |
self.regs = {}
self.stack = []
self.mem = defaultdict(new_tmp_val) # Dict of label -> value in memory
for i in 'abcdefhl':
self.regs[i] = new_tmp_val() # Initial unknown state
self.regs["%s'" % i] = new_tmp_val()
self.regs['ixh'] = new_tmp_val()
self.regs['ixl'] = new_tmp_val()
self.regs['iyh'] = new_tmp_val()
self.regs['iyl'] = new_tmp_val()
self.regs['sp'] = new_tmp_val()
self.regs['r'] = new_tmp_val()
self.regs['i'] = new_tmp_val()
self.regs['af'] = new_tmp_val()
self.regs['bc'] = new_tmp_val()
self.regs['de'] = new_tmp_val()
self.regs['hl'] = new_tmp_val()
self.regs['ix'] = new_tmp_val()
self.regs['iy'] = new_tmp_val()
self.regs["af'"] = new_tmp_val()
self.regs["bc'"] = new_tmp_val()
self.regs["de'"] = new_tmp_val()
self.regs["hl'"] = new_tmp_val()
self._16bit = {'b': 'bc', 'c': 'bc', 'd': 'de', 'e': 'de', 'h': 'hl', 'l': 'hl',
"b'": "bc'", "c'": "bc'", "d'": "de'", "e'": "de'", "h'": "hl'", "l'": "hl'",
'ixy': 'ix', 'ixl': 'ix', 'iyh': 'iy', 'iyl': 'iy', 'a': 'af', "a'": "af'",
'f': 'af', "f'": "af'"}
self.reset_flags()
|
def reset(self)
|
Initial state
| 2.127698 | 2.096322 | 1.014967 |
self.C = None
self.Z = None
self.P = None
self.S = None
|
def reset_flags(self)
|
Resets flags to an "unknown state"
| 5.710014 | 5.073197 | 1.125526 |
if r is None:
return None
if r.lower() == '(sp)' and self.stack:
return self.stack[-1]
if r[:1] == '(':
return self.mem[r[1:-1]]
r = r.lower()
if is_number(r):
return str(valnum(r))
if not is_register(r):
return None
return self.regs[r]
|
def get(self, r)
|
Returns precomputed value of the given expression
| 5.170874 | 5.14268 | 1.005482 |
v = self.get(r)
if not is_unknown(v):
try:
v = int(v)
except ValueError:
v = None
else:
v = None
return v
|
def getv(self, r)
|
Like the above, but returns the <int> value.
| 3.519539 | 2.939759 | 1.19722 |
if not is_register(r1) or not is_register(r2):
return False
if self.regs[r1] is None or self.regs[r2] is None: # HINT: This's been never USED??
return False
return self.regs[r1] == self.regs[r2]
|
def eq(self, r1, r2)
|
True if values of r1 and r2 registers are equal
| 4.862788 | 4.553177 | 1.067999 |
self.set_flag(None)
if not is_register(r):
if r[0] == '(': # a memory position, basically: inc(hl)
r_ = r[1:-1].strip()
v_ = self.getv(self.mem.get(r_, None))
if v_ is not None:
v_ = (v_ + 1) & 0xFF
self.mem[r_] = str(v_)
self.Z = int(v_ == 0) # HINT: This might be improved
else:
self.mem[r_] = new_tmp_val()
return
if self.getv(r) is not None:
self.set(r, self.getv(r) + 1)
else:
self.set(r, None)
|
def inc(self, r)
|
Does inc on the register and precomputes flags
| 4.939744 | 4.717633 | 1.047081 |
if not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
v_ = self.getv(self.regs[r]) & 0xFF
self.regs[r] = str((v_ >> 1) | ((v_ & 1) << 7))
|
def rrc(self, r)
|
Does a ROTATION to the RIGHT |>>
| 5.501492 | 5.276896 | 1.042562 |
if self.C is None or not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
self.rrc(r)
tmp = self.C
v_ = self.getv(self.regs[r])
self.C = v_ >> 7
self.regs[r] = str((v_ & 0x7F) | (tmp << 7))
|
def rr(self, r)
|
Like the above, bus uses carry
| 5.50003 | 5.268851 | 1.043877 |
if not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
v_ = self.getv(self.regs[r]) & 0xFF
self.set(r, ((v_ << 1) & 0xFF) | (v_ >> 7))
|
def rlc(self, r)
|
Does a ROTATION to the LEFT <<|
| 5.141462 | 4.941193 | 1.040531 |
if self.C is None or not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
self.rlc(r)
tmp = self.C
v_ = self.getv(self.regs[r])
self.C = v_ & 1
self.regs[r] = str((v_ & 0xFE) | tmp)
|
def rl(self, r)
|
Like the above, bus uses carry
| 6.182892 | 5.911375 | 1.045931 |
if not is_register(r) or val is None:
return False
r = r.lower()
if is_register(val):
return self.eq(r, val)
if is_number(val):
val = str(valnum(val))
else:
val = str(val)
if val[0] == '(':
val = self.mem[val[1:-1]]
return self.regs[r] == val
|
def _is(self, r, val)
|
True if value of r is val.
| 4.10555 | 4.081696 | 1.005844 |
i = [x for x in self.asm.strip(' \t\n').split(' ') if x != '']
if len(i) == 1:
return []
i = ''.join(i[1:]).split(',')
if self.condition_flag is not None:
i = i[1:]
else:
i = i[0:]
op = [x.lower() if is_register(x) else x for x in i]
return op
|
def opers(self)
|
Returns a list of operators this mnemonic uses
| 4.820405 | 4.190307 | 1.15037 |
if self.asm in arch.zx48k.backend.ASMS:
return ALL_REGS
res = set([])
i = self.inst
o = self.opers
if i in {'push', 'ret', 'call', 'rst', 'reti', 'retn'}:
return ['sp']
if i == 'pop':
res.update('sp', single_registers(o[:1]))
elif i in {'ldi', 'ldir', 'ldd', 'lddr'}:
res.update('a', 'b', 'c', 'd', 'e', 'f')
elif i in {'otir', 'otdr', 'oti', 'otd', 'inir', 'indr', 'ini', 'ind'}:
res.update('h', 'l', 'b')
elif i in {'cpir', 'cpi', 'cpdr', 'cpd'}:
res.update('h', 'l', 'b', 'c', 'f')
elif i in ('ld', 'in'):
res.update(single_registers(o[:1]))
elif i in ('inc', 'dec'):
res.update('f', single_registers(o[:1]))
elif i == 'exx':
res.update('b', 'c', 'd', 'e', 'h', 'l')
elif i == 'ex':
res.update(single_registers(o[0]))
res.update(single_registers(o[1]))
elif i in {'ccf', 'scf', 'bit', 'cp'}:
res.add('f')
elif i in {'or', 'and', 'xor', 'add', 'adc', 'sub', 'sbc'}:
if len(o) > 1:
res.update(single_registers(o[0]))
else:
res.add('a')
res.add('f')
elif i in {'neg', 'cpl', 'daa', 'rra', 'rla', 'rrca', 'rlca', 'rrd', 'rld'}:
res.update('a', 'f')
elif i == 'djnz':
res.update('b', 'f')
elif i in {'rr', 'rl', 'rrc', 'rlc', 'srl', 'sra', 'sll', 'sla'}:
res.update(single_registers(o[0]))
res.add('f')
elif i in ('set', 'res'):
res.update(single_registers(o[1]))
return list(res)
|
def destroys(self)
|
Returns which single registers (including f, flag)
this instruction changes.
Registers are: a, b, c, d, e, i, h, l, ixh, ixl, iyh, iyl, r
LD a, X => Destroys a
LD a, a => Destroys nothing
INC a => Destroys a, f
POP af => Destroys a, f, sp
PUSH af => Destroys sp
ret => Destroys SP
| 3.34712 | 3.263764 | 1.02554 |
if isinstance(reglist, str):
reglist = [reglist]
reglist = single_registers(reglist)
return len([x for x in self.destroys if x in reglist]) > 0
|
def affects(self, reglist)
|
Returns if this instruction affects any of the registers
in reglist.
| 4.936899 | 4.130776 | 1.19515 |
if isinstance(reglist, str):
reglist = [reglist]
reglist = single_registers(reglist)
return len([x for x in self.requires if x in reglist]) > 0
|
def needs(self, reglist)
|
Returns if this instruction need any of the registers
in reglist.
| 4.407534 | 3.862385 | 1.141143 |
result = []
tmp = self.asm.strip(' \n\r\t')
if not len(tmp) or tmp[0] in ('#', ';'):
return result
try:
tmpLexer = asmlex.lex.lex(object=asmlex.Lexer(), lextab='zxbasmlextab')
tmpLexer.input(tmp)
while True:
token = tmpLexer.token()
if not token:
break
if token.type == 'ID':
result += [token.value]
except:
pass
return result
|
def used_labels(self)
|
Returns a list of required labels for this instruction
| 5.30063 | 4.746476 | 1.116751 |
if oldLabel == newLabel:
return
tmp = re.compile(r'\b' + oldLabel + r'\b')
last = 0
l = len(newLabel)
while True:
match = tmp.search(self.asm[last:])
if not match:
break
txt = self.asm
self.asm = txt[:last + match.start()] + newLabel + txt[last + match.end():]
last += match.start() + l
|
def replace_label(self, oldLabel, newLabel)
|
Replaces old label with a new one
| 2.97405 | 2.945366 | 1.009739 |
if len(self.mem) < 2:
return False # An atomic block
if any(x.is_ender or x.asm in arch.zx48k.backend.ASMS for x in self.mem):
return True
for label in JUMP_LABELS:
if LABELS[label].basic_block == self and (not self.mem[0].is_label or self.mem[0].inst != label):
return True
return False
|
def is_partitionable(self)
|
Returns if this block can be partitiones in 2 or more blocks,
because if contains enders.
| 11.115698 | 10.073615 | 1.103447 |
if basic_block is None:
return
if self.lock:
return
self.lock = True
if self.prev is basic_block:
if self.prev.next is self:
self.prev.next = None
self.prev = None
for i in range(len(self.comes_from)):
if self.comes_from[i] is basic_block:
self.comes_from.pop(i)
break
self.lock = False
|
def delete_from(self, basic_block)
|
Removes the basic_block ptr from the list for "comes_from"
if it exists. It also sets self.prev to None if it is basic_block.
| 2.64848 | 2.157217 | 1.22773 |
if basic_block is None:
return
if self.lock:
return
# Return if already added
if basic_block in self.comes_from:
return
self.lock = True
self.comes_from.add(basic_block)
basic_block.add_goes_to(self)
self.lock = False
|
def add_comes_from(self, basic_block)
|
This simulates a set. Adds the basic_block to the comes_from
list if not done already.
| 2.79692 | 2.689686 | 1.039869 |
last = self.mem[-1]
if last.inst not in ('ret', 'jp', 'jr') or last.condition_flag is not None:
return
if last.inst == 'ret':
if self.next is not None:
self.next.delete_from(self)
self.delete_goes(self.next)
return
if last.opers[0] not in LABELS.keys():
__DEBUG__("INFO: %s is not defined. No optimization is done." % last.opers[0], 2)
LABELS[last.opers[0]] = LabelInfo(last.opers[0], 0, DummyBasicBlock(ALL_REGS, ALL_REGS))
n_block = LABELS[last.opers[0]].basic_block
if self.next is n_block:
return
if self.next.prev == self:
# The next basic block is not this one since it ends with a jump
self.next.delete_from(self)
self.delete_goes(self.next)
self.next = n_block
self.next.add_comes_from(self)
self.add_goes_to(self.next)
|
def update_next_block(self)
|
If the last instruction of this block is a JP, JR or RET (with no
conditions) then the next and goes_to sets just contains a
single block
| 4.963905 | 4.592459 | 1.080882 |
# Remove any block from the comes_from and goes_to list except the PREVIOUS and NEXT
if not len(self):
return
if self.mem[-1].inst == 'ret':
return # subroutine returns are updated from CALLer blocks
self.update_used_by_list()
if not self.mem[-1].is_ender:
return
last = self.mem[-1]
inst = last.inst
oper = last.opers
cond = last.condition_flag
if oper and oper[0] not in LABELS.keys():
__DEBUG__("INFO: %s is not defined. No optimization is done." % oper[0], 1)
LABELS[oper[0]] = LabelInfo(oper[0], 0, DummyBasicBlock(ALL_REGS, ALL_REGS))
if inst == 'djnz' or inst in ('jp', 'jr') and cond is not None:
if oper[0] in LABELS.keys():
self.add_goes_to(LABELS[oper[0]].basic_block)
elif inst in ('jp', 'jr') and cond is None:
if oper[0] in LABELS.keys():
self.delete_goes(self.next)
self.next = LABELS[oper[0]].basic_block
self.add_goes_to(self.next)
elif inst == 'call':
LABELS[oper[0]].basic_block.add_comes_from(self)
stack = [LABELS[oper[0]].basic_block]
bbset = IdentitySet()
while stack:
bb = stack.pop(0)
while bb is not None:
if bb in bbset:
break
bbset.add(bb)
if len(bb):
bb1 = bb[-1]
if bb1.inst == 'ret':
bb.add_goes_to(self.next)
if bb1.condition_flag is None: # 'ret'
break
if bb1.inst in ('jp', 'jr') and bb1.condition_flag is not None: # jp/jr nc/nz/.. LABEL
if bb1.opers[0] in LABELS: # some labels does not exist (e.g. immediate numeric addresses)
stack += [LABELS[bb1.opers[0]].basic_block]
bb = bb.next # next contiguous block
if cond is None:
self.calls.add(LABELS[oper[0]].basic_block)
|
def update_goes_and_comes(self)
|
Once the block is a Basic one, check the last instruction and updates
goes_to and comes_from set of the receivers.
Note: jp, jr and ret are already done in update_next_block()
| 5.079144 | 4.683015 | 1.084588 |
if i < 0:
i = 0
if self.lock:
return True
regs = list(regs) # make a copy
if top is None:
top = len(self)
else:
top -= 1
for ii in range(i, top):
for r in self.mem[ii].requires:
if r in regs:
return True
for r in self.mem[ii].destroys:
if r in regs:
regs.remove(r)
if not regs:
return False
self.lock = True
result = self.goes_requires(regs)
self.lock = False
return result
|
def is_used(self, regs, i, top=None)
|
Checks whether any of the given regs are required from the given point
to the end or not.
| 3.606932 | 3.285441 | 1.097853 |
if is_register(regs):
regs = set(single_registers(regs))
else:
regs = set(single_registers(x) for x in regs)
return not regs.intersection(self.requires(i, end_))
|
def safe_to_write(self, regs, i=0, end_=0)
|
Given a list of registers (8 or 16 bits) returns a list of them
that are safe to modify from the given index until the position given
which, if omitted, defaults to the end of the block.
:param regs: register or iterable of registers (8 or 16 bit one)
:param i: initial position of the block to examine
:param end_: final position to examine
:returns: registers safe to write
| 5.216303 | 6.661487 | 0.783054 |
if i < 0:
i = 0
end_ = len(self) if end_ is None or end_ > len(self) else end_
regs = {'a', 'b', 'c', 'd', 'e', 'f', 'h', 'l', 'i', 'ixh', 'ixl', 'iyh', 'iyl', 'sp'}
result = []
for ii in range(i, end_):
for r in self.mem[ii].requires:
r = r.lower()
if r in regs:
result.append(r)
regs.remove(r)
for r in self.mem[ii].destroys:
r = r.lower()
if r in regs:
regs.remove(r)
if not regs:
break
return result
|
def requires(self, i=0, end_=None)
|
Returns a list of registers and variables this block requires.
By default checks from the beginning (i = 0).
:param i: initial position of the block to examine
:param end_: final position to examine
:returns: registers safe to write
| 2.813717 | 2.758572 | 1.019991 |
regs = {'a', 'b', 'c', 'd', 'e', 'f', 'h', 'l', 'i', 'ixh', 'ixl', 'iyh', 'iyl', 'sp'}
top = len(self)
result = []
for ii in range(i, top):
for r in self.mem[ii].destroys:
if r in regs:
result.append(r)
regs.remove(r)
if not regs:
break
return result
|
def destroys(self, i=0)
|
Returns a list of registers this block destroys
By default checks from the beginning (i = 0).
| 3.837655 | 3.24285 | 1.183421 |
self.mem[a], self.mem[b] = self.mem[b], self.mem[a]
self.asm[a], self.asm[b] = self.asm[b], self.asm[a]
|
def swap(self, a, b)
|
Swaps mem positions a and b
| 2.272859 | 1.95182 | 1.164482 |
if len(self) and self.mem[-1].inst == 'call' and self.mem[-1].condition_flag is None:
for block in self.calls:
if block.is_used(regs, 0):
return True
d = block.destroys()
if not len([x for x in regs if x not in d]):
return False # If all registers are destroyed then they're not used
for block in self.goes_to:
if block.is_used(regs, 0):
return True
return False
|
def goes_requires(self, regs)
|
Returns whether any of the goes_to block requires any of
the given registers.
| 6.209329 | 5.864368 | 1.058823 |
for i in range(len(self)):
if self.mem[i].is_label and self.mem[i].inst == label:
return i
return None
|
def get_label_idx(self, label)
|
Returns the index of a label.
Returns None if not found.
| 5.950801 | 5.039374 | 1.180861 |
for i in range(len(self)):
if not self.mem[i].is_label:
return self.mem[i]
return None
|
def get_first_non_label_instruction(self)
|
Returns the memcell of the given block, which is
not a LABEL.
| 3.799964 | 3.2131 | 1.182647 |
''' Returns pop sequence for 16 bits operands
1st operand in HL, 2nd operand in DE
You can swap operators extraction order
by setting reversed to True.
If no_exaf = True => No bits flags in A' will be used.
This saves two bytes.
'''
output = []
if op2 is not None and reversed:
op1, op2 = op2, op1
tmp2 = False
if op2 is not None:
val = op2
if val[0] == '*':
indirect = True
val = val[1:]
else:
indirect = False
if val[0] == '_': # Direct
output.append('ld de, (%s)' % val)
elif val[0] == '#': # Direct
output.append('ld de, %s' % val[1:])
elif val[0] == '$': # Direct in the stack
output.append('pop de')
else:
output.append('pop de')
tmp2 = True
if indirect:
output.append('call __LOAD_DE_DE')
REQUIRES.add('lddede.asm') # TODO: This is never used??
if reversed:
tmp = output
output = []
val = op1
tmp1 = False
if val[0] == '*':
indirect = True
val = val[1:]
else:
indirect = False
if val[0] == '_': # Direct
output.append('ld hl, (%s)' % val)
elif val[0] == '#': # Inmmediate
output.append('ld hl, %s' % val[1:])
elif val[0] == '$': # Direct in the stack
output.append('pop hl')
else:
output.append('pop hl')
tmp1 = True
if indirect:
output.append('ld hl, %s' % val[1:])
output.append('ld c, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, c')
if reversed:
output.extend(tmp)
if not no_exaf:
if tmp1 and tmp2:
output.append('ld a, 3') # Marks both strings to be freed
elif tmp1:
output.append('ld a, 1') # Marks str1 to be freed
elif tmp2:
output.append('ld a, 2') # Marks str2 to be freed
else:
output.append('xor a') # Marks no string to be freed
if op2 is not None:
return (tmp1, tmp2, output)
return (tmp1, output)
|
def _str_oper(op1, op2=None, reversed=False, no_exaf=False)
|
Returns pop sequence for 16 bits operands
1st operand in HL, 2nd operand in DE
You can swap operators extraction order
by setting reversed to True.
If no_exaf = True => No bits flags in A' will be used.
This saves two bytes.
| 3.515963 | 2.515747 | 1.397582 |
''' Outputs a FREEMEM sequence for 1 or 2 ops
'''
if not tmp1 and not tmp2:
return []
output = []
if tmp1 and tmp2:
output.append('pop de')
output.append('ex (sp), hl')
output.append('push de')
output.append('call __MEM_FREE')
output.append('pop hl')
output.append('call __MEM_FREE')
else:
output.append('ex (sp), hl')
output.append('call __MEM_FREE')
output.append('pop hl')
REQUIRES.add('alloc.asm')
return output
|
def _free_sequence(tmp1, tmp2=False)
|
Outputs a FREEMEM sequence for 1 or 2 ops
| 5.933164 | 4.710539 | 1.259551 |
''' Compares & pops top 2 strings out of the stack.
Temporal values are freed from memory. (a$ != b$)
'''
(tmp1, tmp2, output) = _str_oper(ins.quad[2], ins.quad[3])
output.append('call __STRNE')
output.append('push af')
REQUIRES.add('string.asm')
return output
|
def _nestr(ins)
|
Compares & pops top 2 strings out of the stack.
Temporal values are freed from memory. (a$ != b$)
| 25.52783 | 8.443302 | 3.023441 |
''' Returns string length
'''
(tmp1, output) = _str_oper(ins.quad[2], no_exaf=True)
if tmp1:
output.append('push hl')
output.append('call __STRLEN')
output.extend(_free_sequence(tmp1))
output.append('push hl')
REQUIRES.add('strlen.asm')
return output
|
def _lenstr(ins)
|
Returns string length
| 17.794804 | 17.96718 | 0.990406 |
if func is not None and len(operands) == 1: # Try constant-folding
if is_number(operands[0]) or is_string(operands[0]): # e.g. ABS(-5)
return SymbolNUMBER(func(operands[0].value), type_=type_, lineno=lineno)
return cls(lineno, fname, type_, *operands)
|
def make_node(cls, lineno, fname, func=None, type_=None, *operands)
|
Creates a node for a unary operation. E.g. -x or LEN(a$)
Parameters:
-func: function used on constant folding when possible
-type_: the resulting type (by default, the same as the argument).
For example, for LEN (str$), result type is 'u16'
and arg type is 'string'
| 5.767578 | 5.164939 | 1.116679 |
output = []
if op2 is not None and reversed_:
tmp = op1
op1 = op2
op2 = tmp
op = op1
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
if is_int(op):
op = int(op)
if indirect:
output.append('ld a, (%i)' % op)
else:
if op == 0:
output.append('xor a')
else:
output.append('ld a, %i' % int8(op))
else:
if immediate:
if indirect:
output.append('ld a, (%s)' % op)
else:
output.append('ld a, %s' % op)
elif op[0] == '_':
if indirect:
idx = 'bc' if reversed_ else 'hl'
output.append('ld %s, (%s)' % (idx, op)) # can't use HL
output.append('ld a, (%s)' % idx)
else:
output.append('ld a, (%s)' % op)
else:
if immediate:
output.append('ld a, %s' % op)
elif indirect:
idx = 'bc' if reversed_ else 'hl'
output.append('pop %s' % idx)
output.append('ld a, (%s)' % idx)
else:
output.append('pop af')
if op2 is None:
return output
if not reversed_:
tmp = output
output = []
op = op2
indirect = (op[0] == '*')
if indirect:
op = op[1:]
immediate = (op[0] == '#')
if immediate:
op = op[1:]
if is_int(op):
op = int(op)
if indirect:
output.append('ld hl, (%i - 1)' % op)
else:
output.append('ld h, %i' % int8(op))
else:
if immediate:
if indirect:
output.append('ld hl, %s' % op)
output.append('ld h, (hl)')
else:
output.append('ld h, %s' % op)
elif op[0] == '_':
if indirect:
output.append('ld hl, (%s)' % op)
output.append('ld h, (hl)' % op)
else:
output.append('ld hl, (%s - 1)' % op)
else:
output.append('pop hl')
if indirect:
output.append('ld h, (hl)')
if not reversed_:
output.extend(tmp)
return output
|
def _8bit_oper(op1, op2=None, reversed_=False)
|
Returns pop sequence for 8 bits operands
1st operand in H, 2nd operand in A (accumulator)
For some operations (like comparisons), you can swap
operands extraction by setting reversed = True
| 2.029652 | 2.036244 | 0.996762 |
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1)
if op2 == 0: # Nothing to add: A + 0 = A
output.append('push af')
return output
op2 = int8(op2)
if op2 == 1: # Adding 1 is just an inc
output.append('inc a')
output.append('push af')
return output
if op2 == 0xFF: # Adding 255 is just a dec
output.append('dec a')
output.append('push af')
return output
output.append('add a, %i' % int8(op2))
output.append('push af')
return output
if op2[0] == '_': # stack optimization
op1, op2 = op2, op1
output = _8bit_oper(op1, op2)
output.append('add a, h')
output.append('push af')
return output
|
def _add8(ins)
|
Pops last 2 bytes from the stack and adds them.
Then push the result onto the stack.
Optimizations:
* If any of the operands is ZERO,
then do NOTHING: A + 0 = 0 + A = A
* If any of the operands is 1, then
INC is used
* If any of the operands is -1 (255), then
DEC is used
| 3.496855 | 3.333503 | 1.049003 |
op1, op2 = tuple(ins.quad[2:])
if is_int(op2): # 2nd operand
op2 = int8(op2)
output = _8bit_oper(op1)
if op2 == 0:
output.append('push af')
return output # A - 0 = A
op2 = int8(op2)
if op2 == 1: # A - 1 == DEC A
output.append('dec a')
output.append('push af')
return output
if op2 == 0xFF: # A - (-1) == INC A
output.append('inc a')
output.append('push af')
return output
output.append('sub %i' % op2)
output.append('push af')
return output
if is_int(op1): # 1st operand is numeric?
if int8(op1) == 0: # 0 - A = -A ==> NEG A
output = _8bit_oper(op2)
output.append('neg')
output.append('push af')
return output
# At this point, even if 1st operand is numeric, proceed
# normally
if op2[0] == '_': # Optimization when 2nd operand is an id
rev = True
op1, op2 = op2, op1
else:
rev = False
output = _8bit_oper(op1, op2, rev)
output.append('sub h')
output.append('push af')
return output
|
def _sub8(ins)
|
Pops last 2 bytes from the stack and subtract them.
Then push the result onto the stack. Top-1 of the stack is
subtracted Top
_sub8 t1, a, b === t1 <-- a - b
Optimizations:
* If 2nd op is ZERO,
then do NOTHING: A - 0 = A
* If 1st operand is 0, then
just do a NEG
* If any of the operands is 1, then
DEC is used
* If any of the operands is -1 (255), then
INC is used
| 3.825367 | 3.444964 | 1.110423 |
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _8bit_oper(op1)
if op2 == 1: # A * 1 = 1 * A = A
output.append('push af')
return output
if op2 == 0:
output.append('xor a')
output.append('push af')
return output
if op2 == 2: # A * 2 == A SLA 1
output.append('add a, a')
output.append('push af')
return output
if op2 == 4: # A * 4 == A SLA 2
output.append('add a, a')
output.append('add a, a')
output.append('push af')
return output
output.append('ld h, %i' % int8(op2))
else:
if op2[0] == '_': # stack optimization
op1, op2 = op2, op1
output = _8bit_oper(op1, op2)
output.append('call __MUL8_FAST') # Inmmediate
output.append('push af')
REQUIRES.add('mul8.asm')
return output
|
def _mul8(ins)
|
Multiplies 2 las values from the stack.
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A
| 4.149419 | 3.879815 | 1.069489 |
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int8(op2)
output = _8bit_oper(op1)
if op2 == 1:
output.append('push af')
return output
if op2 == 2:
output.append('srl a')
output.append('push af')
return output
output.append('ld h, %i' % int8(op2))
else:
if op2[0] == '_': # Optimization when 2nd operand is an id
if is_int(op1) and int(op1) == 0:
output = list() # Optimization: Discard previous op if not from the stack
output.append('xor a')
output.append('push af')
return output
rev = True
op1, op2 = op2, op1
else:
rev = False
output = _8bit_oper(op1, op2, rev)
output.append('call __DIVU8_FAST')
output.append('push af')
REQUIRES.add('div8.asm')
return output
|
def _divu8(ins)
|
Divides 2 8bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd op is 1 then
do nothing
* If 2nd op is 2 then
Shift Right Logical
| 5.693489 | 5.536014 | 1.028446 |
output = _8bit_oper(ins.quad[2], ins.quad[3])
output.append('cp h')
output.append('sbc a, a')
output.append('push af')
return output
|
def _ltu8(ins)
|
Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version
| 13.348668 | 16.156973 | 0.826186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.