have to now add LD/ST-update instructions to list of explicit-allowed
[openpower-isa.git] / src / openpower / decoder / isa / caller.py
index bb3737036eb8ed3852d69b8e2da7939214d2583f..5d8498857e7ee95b1f621f25cbc8f05d14694236 100644 (file)
@@ -13,47 +13,39 @@ related bugs:
 * https://bugs.libre-soc.org/show_bug.cgi?id=424
 """
 
-import re
-from nmigen.sim import Settle, Delay
+from collections import namedtuple
+from copy import deepcopy
 from functools import wraps
-from copy import copy, deepcopy
-from openpower.decoder.orderedset import OrderedSet
-from openpower.decoder.selectable_int import (
-    FieldSelectableInt,
-    SelectableInt,
-    selectconcat,
-)
-from openpower.decoder.power_insn import SVP64Instruction
-from openpower.decoder.power_enums import (spr_dict, spr_byname, XER_bits,
-                                           insns, MicrOp,
-                                           In1Sel, In2Sel, In3Sel,
-                                           OutSel, CRInSel, CROutSel, LDSTMode,
-                                           SVMode,
-                                           SVP64RMMode, SVP64PredMode,
-                                           SVP64PredInt, SVP64PredCR,
-                                           SVP64LDSTmode, FPTRANS_INSNS)
-
-from openpower.decoder.power_enums import SVPtype
-
-from openpower.decoder.helpers import (exts, gtu, ltu, undefined,
-                                       ISACallerHelper, ISAFPHelpers)
-from openpower.consts import PIb, MSRb  # big-endian (PowerISA versions)
-from openpower.consts import (SVP64MODE, SVP64MODEb,
-                              SVP64CROffs,
-                              )
-from openpower.decoder.power_svp64 import SVP64RM, decode_extra
 
+from nmigen.sim import Settle
+from openpower.consts import (MSRb, PIb,  # big-endian (PowerISA versions)
+                              SVP64CROffs, SVP64MODEb)
+from openpower.decoder.helpers import (ISACallerHelper, ISAFPHelpers, exts,
+                                       gtu, undefined)
+from openpower.decoder.isa.mem import Mem, MemException
 from openpower.decoder.isa.radixmmu import RADIX
-from openpower.decoder.isa.mem import Mem, swap_order, MemException
 from openpower.decoder.isa.svshape import SVSHAPE
 from openpower.decoder.isa.svstate import SVP64State
-
-
+from openpower.decoder.orderedset import OrderedSet
+from openpower.decoder.power_enums import (FPTRANS_INSNS, CRInSel, CROutSel,
+                                           In1Sel, In2Sel, In3Sel, LDSTMode,
+                                           MicrOp, OutSel, SVMode,
+                                           SVP64LDSTmode, SVP64PredCR,
+                                           SVP64PredInt, SVP64PredMode,
+                                           SVP64RMMode, SVPType, XER_bits,
+                                           insns, spr_byname, spr_dict,
+                                           BFP_FLAG_NAMES)
+from openpower.decoder.power_insn import SVP64Instruction
+from openpower.decoder.power_svp64 import SVP64RM, decode_extra
+from openpower.decoder.selectable_int import (FieldSelectableInt,
+                                              SelectableInt, selectconcat,
+                                              EFFECTIVELY_UNLIMITED)
+from openpower.fpscr import FPSCRState
+from openpower.xer import XERState
 from openpower.util import LogKind, log
 
-from collections import namedtuple
-import math
-import sys
+LDST_UPDATE_INSNS = ['ldu', 'lwzu', 'lbzu', 'lhzu', 'lhau', 'lfsu', 'lfdu',
+                    ]
 
 instruction_info = namedtuple('instruction_info',
                               'func read_regs uninit_regs write_regs ' +
@@ -89,6 +81,7 @@ REG_SORT_ORDER = {
     "CTR": 0,
     "TAR": 0,
     "MSR": 0,
+    "FPSCR": 0,
     "SVSTATE": 0,
     "SVSHAPE0": 0,
     "SVSHAPE1": 0,
@@ -105,6 +98,37 @@ REG_SORT_ORDER = {
 fregs = ['FRA', 'FRB', 'FRC', 'FRS', 'FRT']
 
 
+def get_masked_reg(regs, base, offs, ew_bits):
+    # rrrright.  start by breaking down into row/col, based on elwidth
+    gpr_offs = offs // (64 // ew_bits)
+    gpr_col = offs % (64 // ew_bits)
+    # compute the mask based on ew_bits
+    mask = (1 << ew_bits) - 1
+    # now select the 64-bit register, but get its value (easier)
+    val = regs[base + gpr_offs]
+    # shift down so element we want is at LSB
+    val >>= gpr_col * ew_bits
+    # mask so we only return the LSB element
+    return val & mask
+
+
+def set_masked_reg(regs, base, offs, ew_bits, value):
+    # rrrright.  start by breaking down into row/col, based on elwidth
+    gpr_offs = offs // (64//ew_bits)
+    gpr_col = offs % (64//ew_bits)
+    # compute the mask based on ew_bits
+    mask = (1 << ew_bits)-1
+    # now select the 64-bit register, but get its value (easier)
+    val = regs[base+gpr_offs]
+    # now mask out the bit we don't want
+    val = val & ~(mask << (gpr_col*ew_bits))
+    # then wipe the bit we don't want from the value
+    value = value & mask
+    # OR the new value in, shifted up
+    val |= value << (gpr_col*ew_bits)
+    regs[base+gpr_offs] = val
+
+
 def create_args(reglist, extra=None):
     retval = list(OrderedSet(reglist))
     retval.sort(key=lambda reg: REG_SORT_ORDER.get(reg, 0))
@@ -133,10 +157,10 @@ class GPR(dict):
         # now select the 64-bit register, but get its value (easier)
         val = self[ridx+gpr_offs].value
         # now shift down and mask out
-        val = val >> (gpr_col*elwidth) & ((1<<elwidth)-1)
+        val = val >> (gpr_col*elwidth) & ((1 << elwidth)-1)
         # finally, return a SelectableInt at the required elwidth
         log("GPR call", ridx, "isvec", is_vec, "offs", offs,
-             "elwid", elwidth, "offs/col", gpr_offs, gpr_col, "val", hex(val))
+            "elwid", elwidth, "offs/col", gpr_offs, gpr_col, "val", hex(val))
         return SelectableInt(val, elwidth)
 
     def set_form(self, form):
@@ -157,7 +181,7 @@ class GPR(dict):
         gpr_offs = offs // (64//elwidth)
         gpr_col = offs % (64//elwidth)
         # compute the mask based on elwidth
-        mask = (1<<elwidth)-1
+        mask = (1 << elwidth)-1
         # now select the 64-bit register, but get its value (easier)
         val = self[base+gpr_offs].value
         # now mask out the bit we don't want
@@ -168,8 +192,8 @@ class GPR(dict):
         val |= value << (gpr_col*elwidth)
         # finally put the damn value into the regfile
         log("GPR write", base, "isvec", is_vec, "offs", offs,
-             "elwid", elwidth, "offs/col", gpr_offs, gpr_col, "val", hex(val),
-             "@", base+gpr_offs)
+            "elwid", elwidth, "offs/col", gpr_offs, gpr_col, "val", hex(val),
+            "@", base+gpr_offs)
         dict.__setitem__(self, base+gpr_offs, SelectableInt(val, 64))
 
     def __setitem__(self, rnum, value):
@@ -248,7 +272,7 @@ class SPR(dict):
                 info = spr_dict[key]
             else:
                 info = spr_byname[key]
-            dict.__setitem__(self, key, SelectableInt(0, info.length))
+            self[key] = SelectableInt(0, info.length)
             res = dict.__getitem__(self, key)
         log("spr returning", key, res)
         return res
@@ -264,6 +288,8 @@ class SPR(dict):
             self.__setitem__('SRR0', value)
         if key == 'HSRR1':  # HACK!
             self.__setitem__('SRR1', value)
+        if key == 1:
+            value = XERState(value)
         log("setting spr", key, value)
         dict.__setitem__(self, key, value)
 
@@ -405,7 +431,6 @@ def get_idx_map(dec2, name):
     elif name == 'RC':
         if in3_sel == In3Sel.RC.value:
             return 3
-        assert False, "RC does not exist yet"
     elif name in ['EA', 'RS']:
         if in1_sel == In1Sel.RS.value:
             return 1
@@ -416,6 +441,8 @@ def get_idx_map(dec2, name):
     elif name == 'FRA':
         if in1_sel == In1Sel.FRA.value:
             return 1
+        if in3_sel == In3Sel.FRA.value:
+            return 3
     elif name == 'FRB':
         if in2_sel == In2Sel.FRB.value:
             return 2
@@ -427,6 +454,12 @@ def get_idx_map(dec2, name):
             return 1
         if in3_sel == In3Sel.FRS.value:
             return 3
+    elif name == 'FRT':
+        if in1_sel == In1Sel.FRT.value:
+            return 1
+    elif name == 'RT':
+        if in1_sel == In1Sel.RT.value:
+            return 1
     return None
 
 
@@ -446,10 +479,10 @@ def get_idx_in(dec2, name, ewmode=False):
     if ewmode:
         in1_base = yield dec2.e.read_reg1.base
         in2_base = yield dec2.e.read_reg2.base
-        in3_base  = yield dec2.e.read_reg3.base
+        in3_base = yield dec2.e.read_reg3.base
         in1_offs = yield dec2.e.read_reg1.offs
         in2_offs = yield dec2.e.read_reg2.offs
-        in3_offs  = yield dec2.e.read_reg3.offs
+        in3_offs = yield dec2.e.read_reg3.offs
         in1 = (in1, in1_base, in1_offs)
         in2 = (in2, in2_base, in2_offs)
         in3 = (in3, in3_base, in3_offs)
@@ -528,92 +561,118 @@ def get_cr_out(dec2, name):
     if name == 'CR1':  # these are not actually calculated correctly
         if out_sel == CROutSel.CR1.value:
             return out, o_isvec
+    # check RC1 set? if so return implicit vector, this is a REAL bad hack
+    RC1 = yield dec2.rm_dec.RC1
+    if RC1:
+        log("get_cr_out RC1 mode")
+        if name == 'CR0':
+            return 0, True # XXX TODO: offset CR0 from SVSTATE SPR
+        if name == 'CR1':
+            return 1, True # XXX TODO: offset CR1 from SVSTATE SPR
+    # nope - not found.
     log("get_cr_out not found", name)
     return None, False
 
 
 # TODO, really should just be using PowerDecoder2
-def get_idx_out(dec2, name, ewmode=False):
+def get_out_map(dec2, name):
     op = dec2.dec.op
     out_sel = yield op.out_sel
     # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
     out = yield dec2.e.write_reg.data
-    o_isvec = yield dec2.o_isvec
-    if ewmode:
-        offs = yield dec2.e.write_reg.offs
-        base = yield dec2.e.write_reg.base
-        out = (out, base, offs)
     # identify which regnames map to out / o2
-    if name == 'BF':
-        log("get_idx_out", out_sel, out, o_isvec)
     if name == 'RA':
-        log("get_idx_out", out_sel, OutSel.RA.value, out, o_isvec)
         if out_sel == OutSel.RA.value:
-            return out, o_isvec
+            return True
     elif name == 'RT':
-        log("get_idx_out", out_sel, OutSel.RT.value,
-            OutSel.RT_OR_ZERO.value, out, o_isvec,
-            dec2.dec.RT)
         if out_sel == OutSel.RT.value:
-            return out, o_isvec
+            return True
         if out_sel == OutSel.RT_OR_ZERO.value and out != 0:
-            return out, o_isvec
+            return True
     elif name == 'RT_OR_ZERO':
-        log("get_idx_out", out_sel, OutSel.RT.value,
-            OutSel.RT_OR_ZERO.value, out, o_isvec,
-            dec2.dec.RT)
         if out_sel == OutSel.RT_OR_ZERO.value:
-            return out, o_isvec
+            return True
     elif name == 'FRA':
-        log("get_idx_out", out_sel, OutSel.FRA.value, out, o_isvec)
         if out_sel == OutSel.FRA.value:
-            return out, o_isvec
+            return True
+    elif name == 'FRS':
+        if out_sel == OutSel.FRS.value:
+            return True
     elif name == 'FRT':
-        log("get_idx_out", out_sel, OutSel.FRT.value,
-            OutSel.FRT.value, out, o_isvec)
         if out_sel == OutSel.FRT.value:
-            return out, o_isvec
+            return True
+    return False
+
+
+# TODO, really should just be using PowerDecoder2
+def get_idx_out(dec2, name, ewmode=False):
+    op = dec2.dec.op
+    out_sel = yield op.out_sel
+    # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
+    out = yield dec2.e.write_reg.data
+    o_isvec = yield dec2.o_isvec
+    if ewmode:
+        offs = yield dec2.e.write_reg.offs
+        base = yield dec2.e.write_reg.base
+        out = (out, base, offs)
+    # identify which regnames map to out / o2
+    ismap = yield from get_out_map(dec2, name)
+    if ismap:
+        log("get_idx_out", name, out_sel, out, o_isvec)
+        return out, o_isvec
     log("get_idx_out not found", name, out_sel, out, o_isvec)
     return None, False
 
 
 # TODO, really should just be using PowerDecoder2
-def get_idx_out2(dec2, name, ewmode=False):
+def get_out2_map(dec2, name):
     # check first if register is activated for write
     op = dec2.dec.op
     out_sel = yield op.out_sel
     out = yield dec2.e.write_ea.data
-    if ewmode:
-        offs = yield dec2.e.write_ea.offs
-        base = yield dec2.e.write_ea.base
-        out = (out, base, offs)
-    o_isvec = yield dec2.o2_isvec
     out_ok = yield dec2.e.write_ea.ok
-    log("get_idx_out2", name, out_sel, out, out_ok, o_isvec)
     if not out_ok:
-        return None, False
+        return False
 
-    if name == 'RA':
+    if name in ['EA', 'RA']:
         if hasattr(op, "upd"):
             # update mode LD/ST uses read-reg A also as an output
             upd = yield op.upd
             log("get_idx_out2", upd, LDSTMode.update.value,
                 out_sel, OutSel.RA.value,
-                out, o_isvec)
+                out)
             if upd == LDSTMode.update.value:
-                return out, o_isvec
+                return True
     if name == 'RS':
         fft_en = yield dec2.implicit_rs
         if fft_en:
             log("get_idx_out2", out_sel, OutSel.RS.value,
-                out, o_isvec)
-            return out, o_isvec
+                out)
+            return True
     if name == 'FRS':
         fft_en = yield dec2.implicit_rs
         if fft_en:
             log("get_idx_out2", out_sel, OutSel.FRS.value,
-                out, o_isvec)
-            return out, o_isvec
+                out)
+            return True
+    return False
+
+
+# TODO, really should just be using PowerDecoder2
+def get_idx_out2(dec2, name, ewmode=False):
+    # check first if register is activated for write
+    op = dec2.dec.op
+    out_sel = yield op.out_sel
+    out = yield dec2.e.write_ea.data
+    if ewmode:
+        offs = yield dec2.e.write_ea.offs
+        base = yield dec2.e.write_ea.base
+        out = (out, base, offs)
+    o_isvec = yield dec2.o2_isvec
+    ismap = yield from get_out2_map(dec2, name)
+    if ismap:
+        log("get_idx_out2", name, out_sel, out, o_isvec)
+        return out, o_isvec
     return None, False
 
 
@@ -669,7 +728,7 @@ class StepLoop:
                         if self.svstate.ssubstep == subvl:  # end-point
                             log("    advance pack stop")
                             return
-                        break # exit inner loop
+                        break  # exit inner loop
                     self.svstate.srcstep += SelectableInt(1, 7)  # advance ss
                 subvl = self.subvl
                 if self.svstate.ssubstep == subvl:  # end-point
@@ -698,7 +757,7 @@ class StepLoop:
                         yield (self.svstate.ssubstep, srcstep)
                     if self.svstate.ssubstep == subvl:  # end-point
                         self.svstate.ssubstep = SelectableInt(0, 2)  # reset
-                        break # exit inner loop
+                        break  # exit inner loop
                     self.svstate.ssubstep += SelectableInt(1, 2)
                 vl = self.svstate.vl
                 if srcstep == vl-1:  # end-point
@@ -835,7 +894,7 @@ class StepLoop:
 
         self.svstate.srcstep = SelectableInt(srcstep, 7)
         log("    advance src", self.svstate.srcstep, self.svstate.ssubstep,
-                               self.loopend)
+            self.loopend)
 
     def dst_iterate(self):
         """dest step iterator
@@ -898,7 +957,7 @@ class StepLoop:
 
         self.svstate.dststep = SelectableInt(dststep, 7)
         log("    advance dst", self.svstate.dststep, self.svstate.dsubstep,
-                               self.loopend)
+            self.loopend)
 
     def at_loopend(self):
         """tells if this is the last possible element.  uses the cached values
@@ -921,7 +980,7 @@ class StepLoop:
         TODO when Pack/Unpack is set, substep becomes the *outer* loop
         """
         self.subvl = yield self.dec2.rm_dec.rm_in.subvl
-        if self.loopend: # huhn??
+        if self.loopend:  # huhn??
             return
         self.src_iterate()
         self.dst_iterate()
@@ -944,11 +1003,11 @@ class StepLoop:
         pred_sz = yield self.dec2.rm_dec.pred_sz
         if pmode == SVP64PredMode.INT.value:
             srcmask = dstmask = get_predint(self.gpr, dstpred)
-            if sv_ptype == SVPtype.P2.value:
+            if sv_ptype == SVPType.P2.value:
                 srcmask = get_predint(self.gpr, srcpred)
         elif pmode == SVP64PredMode.CR.value:
             srcmask = dstmask = get_predcr(self.crl, dstpred, vl)
-            if sv_ptype == SVPtype.P2.value:
+            if sv_ptype == SVPType.P2.value:
                 srcmask = get_predcr(self.crl, srcpred, vl)
         # work out if the ssubsteps are completed
         ssubstart = ssubstep == 0
@@ -1084,7 +1143,8 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
                  initial_pc=0,
                  bigendian=False,
                  mmu=False,
-                 icachemmu=False):
+                 icachemmu=False,
+                 initial_fpscr=0):
 
         self.bigendian = bigendian
         self.halted = False
@@ -1144,7 +1204,7 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         self.last_op_svshape = False
 
         # "raw" memory
-        self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
+        self.mem = Mem(row_bytes=8, initial_mem=initial_mem, misaligned_ok=True)
         self.mem.log_fancy(kind=LogKind.InstrInOuts)
         self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
         # MMU mode, redirect underlying Mem through RADIX
@@ -1157,6 +1217,8 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         # FPR (same as GPR except for FP nums)
         # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
         #            note that mffs, mcrfs, mtfsf "manage" this FPSCR
+        self.fpscr = FPSCRState(initial_fpscr)
+
         # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
         #         note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
         #         -- Done
@@ -1169,10 +1231,10 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         # create CR then allow portions of it to be "selectable" (below)
         self.cr_fields = CRFields(initial_cr)
         self.cr = self.cr_fields.cr
-        self.cr_backup = 0 # sigh, dreadful hack: for fail-first (VLi)
+        self.cr_backup = 0  # sigh, dreadful hack: for fail-first (VLi)
 
         # "undefined", just set to variable-bit-width int (use exts "max")
-        # self.undefined = SelectableInt(0, 256)  # TODO, not hard-code 256!
+        # self.undefined = SelectableInt(0, EFFECTIVELY_UNLIMITED)
 
         self.namespace = {}
         self.namespace.update(self.spr)
@@ -1190,12 +1252,16 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
                                'SVSHAPE3': self.spr['SVSHAPE3'],
                                'CR': self.cr,
                                'MSR': self.msr,
+                               'FPSCR': self.fpscr,
                                'undefined': undefined,
                                'mode_is_64bit': True,
                                'SO': XER_bits['SO'],
                                'XLEN': 64  # elwidth overrides
                                })
 
+        for name in BFP_FLAG_NAMES:
+            setattr(self, name, 0)
+
         # update pc to requested start point
         self.set_pc(initial_pc)
 
@@ -1207,12 +1273,16 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         self.decoder = decoder2.dec
         self.dec2 = decoder2
 
-        super().__init__(XLEN=self.namespace["XLEN"])
+        super().__init__(XLEN=self.namespace["XLEN"], FPSCR=self.fpscr)
 
     @property
     def XLEN(self):
         return self.namespace["XLEN"]
 
+    @property
+    def FPSCR(self):
+        return self.fpscr
+
     def call_trap(self, trap_addr, trap_bit):
         """calls TRAP and sets up NIA to the new execution location.
         next instruction will begin at trap_addr.
@@ -1304,6 +1374,8 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         self.namespace['XER'] = self.spr['XER']
         self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
         self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
+        self.namespace['OV'] = self.spr['XER'][XER_bits['OV']].value
+        self.namespace['OV32'] = self.spr['XER'][XER_bits['OV32']].value
         self.namespace['XLEN'] = xlen
 
         # add some SVSTATE convenience variables
@@ -1320,7 +1392,8 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         if self.is_svp64_mode and insn_name.startswith("sv.bc"):
             # blegh grab bits manually
             mode = yield self.dec2.rm_dec.rm_in.mode
-            mode = SelectableInt(mode, 5) # convert to SelectableInt before test
+            # convert to SelectableInt before test
+            mode = SelectableInt(mode, 5)
             bc_vlset = mode[SVP64MODEb.BC_VLSET] != 0
             bc_vli = mode[SVP64MODEb.BC_VLI] != 0
             bc_snz = mode[SVP64MODEb.BC_SNZ] != 0
@@ -1337,7 +1410,112 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
             self.namespace['sz'] = SelectableInt(sz, 1)
             self.namespace['SNZ'] = SelectableInt(bc_snz, 1)
 
-    def handle_carry_(self, inputs, output, ca, ca32):
+    def get_kludged_op_add_ca_ov(self, inputs, inp_ca_ov):
+        """ this was not at all necessary to do.  this function massively
+        duplicates - in a laborious and complex fashion - the contents of
+        the CSV files that were extracted two years ago from microwatt's
+        source code.  A-inversion is the "inv A" column, output inversion
+        is the "inv out" column, carry-in equal to 0 or 1 or CA is the
+        "cry in" column
+
+        all of that information is available in
+            self.instrs[ins_name].op_fields
+        where info is usually assigned to self.instrs[ins_name]
+
+        https://git.libre-soc.org/?p=openpower-isa.git;a=blob;f=openpower/isatables/minor_31.csv;hb=HEAD
+
+        the immediate constants are *also* decoded correctly and placed
+        usually by DecodeIn2Imm into operand2, as part of power_decoder2.py
+        """
+        def ca(a, b, ca_in, width):
+            mask = (1 << width) - 1
+            y = (a & mask) + (b & mask) + ca_in
+            return y >> width
+
+        asmcode = yield self.dec2.dec.op.asmcode
+        insn = insns.get(asmcode)
+        SI = yield self.dec2.dec.SI
+        SI &= 0xFFFF
+        CA, OV = inp_ca_ov
+        inputs = [i.value for i in inputs]
+        if SI & 0x8000:
+            SI -= 0x10000
+        if insn in ("add", "addo", "addc", "addco"):
+            a = inputs[0]
+            b = inputs[1]
+            ca_in = 0
+        elif insn == "addic" or insn == "addic.":
+            a = inputs[0]
+            b = SI
+            ca_in = 0
+        elif insn in ("subf", "subfo", "subfc", "subfco"):
+            a = ~inputs[0]
+            b = inputs[1]
+            ca_in = 1
+        elif insn == "subfic":
+            a = ~inputs[0]
+            b = SI
+            ca_in = 1
+        elif insn == "adde" or insn == "addeo":
+            a = inputs[0]
+            b = inputs[1]
+            ca_in = CA
+        elif insn == "subfe" or insn == "subfeo":
+            a = ~inputs[0]
+            b = inputs[1]
+            ca_in = CA
+        elif insn == "addme" or insn == "addmeo":
+            a = inputs[0]
+            b = ~0
+            ca_in = CA
+        elif insn == "addze" or insn == "addzeo":
+            a = inputs[0]
+            b = 0
+            ca_in = CA
+        elif insn == "subfme" or insn == "subfmeo":
+            a = ~inputs[0]
+            b = ~0
+            ca_in = CA
+        elif insn == "subfze" or insn == "subfzeo":
+            a = ~inputs[0]
+            b = 0
+            ca_in = CA
+        elif insn == "addex":
+            # CA[32] aren't actually written, just generate so we have
+            # something to return
+            ca64 = ov64 = ca(inputs[0], inputs[1], OV, 64)
+            ca32 = ov32 = ca(inputs[0], inputs[1], OV, 32)
+            return ca64, ca32, ov64, ov32
+        elif insn == "neg" or insn == "nego":
+            a = ~inputs[0]
+            b = 0
+            ca_in = 1
+        else:
+            raise NotImplementedError(
+                "op_add kludge unimplemented instruction: ", asmcode, insn)
+
+        ca64 = ca(a, b, ca_in, 64)
+        ca32 = ca(a, b, ca_in, 32)
+        ov64 = ca64 != ca(a, b, ca_in, 63)
+        ov32 = ca32 != ca(a, b, ca_in, 31)
+        return ca64, ca32, ov64, ov32
+
+    def handle_carry_(self, inputs, output, ca, ca32, inp_ca_ov):
+        op = yield self.dec2.e.do.insn_type
+        if op == MicrOp.OP_ADD.value and ca is None and ca32 is None:
+            retval = yield from self.get_kludged_op_add_ca_ov(
+                inputs, inp_ca_ov)
+            ca, ca32, ov, ov32 = retval
+            asmcode = yield self.dec2.dec.op.asmcode
+            if insns.get(asmcode) == 'addex':
+                # TODO: if 32-bit mode, set ov to ov32
+                self.spr['XER'][XER_bits['OV']] = ov
+                self.spr['XER'][XER_bits['OV32']] = ov32
+            else:
+                # TODO: if 32-bit mode, set ca to ca32
+                self.spr['XER'][XER_bits['CA']] = ca
+                self.spr['XER'][XER_bits['CA32']] = ca32
+            return
         inv_a = yield self.dec2.e.do.invert_in
         if inv_a:
             inputs[0] = ~inputs[0]
@@ -1354,7 +1532,7 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         log(gts)
         cy = 1 if any(gts) else 0
         log("CA", cy, gts)
-        if ca is None: # already written
+        if ca is None:  # already written
             self.spr['XER'][XER_bits['CA']] = cy
 
         # 32 bit carry
@@ -1379,10 +1557,20 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
                 gts.append(gt)
             cy32 = 1 if any(gts) else 0
             log("CA32", cy32, gts)
-        if ca32 is None: # already written
+        if ca32 is None:  # already written
             self.spr['XER'][XER_bits['CA32']] = cy32
 
-    def handle_overflow(self, inputs, output, div_overflow):
+    def handle_overflow(self, inputs, output, div_overflow, inp_ca_ov):
+        op = yield self.dec2.e.do.insn_type
+        if op == MicrOp.OP_ADD.value:
+            retval = yield from self.get_kludged_op_add_ca_ov(
+                inputs, inp_ca_ov)
+            ca, ca32, ov, ov32 = retval
+            # TODO: if 32-bit mode, set ov to ov32
+            self.spr['XER'][XER_bits['OV']] = ov
+            self.spr['XER'][XER_bits['OV32']] = ov32
+            self.spr['XER'][XER_bits['SO']] |= ov
+            return
         if hasattr(self.dec2.e.do, "invert_in"):
             inv_a = yield self.dec2.e.do.invert_in
             if inv_a:
@@ -1442,7 +1630,11 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
             SO = SelectableInt(1, 0)
         else:
             SO = self.spr['XER'][XER_bits['SO']]
-        log("handle_comparison SO overflow", SO, overflow)
+        log("handle_comparison SO", SO.value,
+                    "overflow", overflow,
+                    "zero", zero.value,
+                    "+ve", positive.value,
+                     "-ve", negative.value)
         # alternative overflow checking (setvl mainly at the moment)
         if overflow is not None and overflow == 1:
             SO = SelectableInt(1, 1)
@@ -1493,8 +1685,8 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         opcode = yield self.dec2.dec.opcode_in
         opcode = SelectableInt(value=opcode, bits=32)
         pfx = SVP64Instruction.Prefix(opcode)
-        log("prefix test: opcode:", pfx.po, bin(pfx.po), pfx.id)
-        self.is_svp64_mode = bool((pfx.po == 0b000001) and (pfx.id == 0b11))
+        log("prefix test: opcode:", pfx.PO, bin(pfx.PO), pfx.id)
+        self.is_svp64_mode = bool((pfx.PO == 0b000001) and (pfx.id == 0b11))
         self.pc.update_nia(self.is_svp64_mode)
         # set SVP64 decode
         yield self.dec2.is_svp64_mode.eq(self.is_svp64_mode)
@@ -1516,27 +1708,29 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
     def execute_one(self):
         """execute one instruction
         """
+        self.insnlog = [] # log the instruction
         # get the disassembly code for this instruction
         if not self.disassembly:
             code = yield from self.get_assembly_name()
         else:
             offs, dbg = 0, ""
             if self.is_svp64_mode:
-               offs, dbg = 4, "svp64 "
+                offs, dbg = 4, "svp64 "
             code = self.disassembly[self._pc+offs]
             log("    %s sim-execute" % dbg, hex(self._pc), code)
+            self.insnlog.append(code)
         opname = code.split(' ')[0]
         try:
             yield from self.call(opname)         # execute the instruction
         except MemException as e:                # check for memory errors
             if e.args[0] == 'unaligned':         # alignment error
-               # run a Trap but set DAR first
-                print("memory unaligned exception, DAR", e.dar)
+                # run a Trap but set DAR first
+                print("memory unaligned exception, DAR", e.dar, repr(e))
                 self.spr['DAR'] = SelectableInt(e.dar, 64)
                 self.call_trap(0x600, PIb.PRIV)    # 0x600, privileged
                 return
             elif e.args[0] == 'invalid':         # invalid
-               # run a Trap but set DAR first
+                # run a Trap but set DAR first
                 log("RADIX MMU memory invalid error, mode %s" % e.mode)
                 if e.mode == 'EXECUTE':
                     # XXX TODO: must set a few bits in SRR1,
@@ -1556,6 +1750,10 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
             # not supported yet:
             raise e                          # ... re-raise
 
+        # append the log file
+        with open("/tmp/insnlog.txt", "a+") as f:
+            f.write(" ".join(self.insnlog)+"\n")
+
         log("gprs after code", code)
         self.gpr.dump()
         crs = []
@@ -1736,14 +1934,21 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         # list of instructions not being supported by binutils (.long)
         dotstrp = asmop[:-1] if asmop[-1] == '.' else asmop
         if dotstrp in [*FPTRANS_INSNS,
+                       *LDST_UPDATE_INSNS,
                        'ffmadds', 'fdmadds', 'ffadds',
-                       'mins', 'maxs', 'minu', 'maxu',
+                       'minmax',
                        'setvl', 'svindex', 'svremap', 'svstep',
                        'svshape', 'svshape2',
                        'grev', 'ternlogi', 'bmask', 'cprop',
                        'absdu', 'absds', 'absdacs', 'absdacu', 'avgadd',
                        'fmvis', 'fishmv', 'pcdec', "maddedu", "divmod2du",
-                       "dsld", "dsrd",
+                       "dsld", "dsrd", "maddedus",
+                       "shadd", "shaddw", "shadduw",
+                       "fcvttg", "fcvttgo", "fcvttgs", "fcvttgso",
+                       "fmvtg", "fmvtgs",
+                       "fcvtfg", "fcvtfgs",
+                       "fmvfg", "fmvfgs",
+                       "maddsubrs", "maddrs"
                        ]:
             illegal = False
             ins_name = dotstrp
@@ -1790,15 +1995,17 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         if self.is_svp64_mode:
             ew_src = yield self.dec2.rm_dec.ew_src
             ew_dst = yield self.dec2.rm_dec.ew_dst
-            ew_src = 8 << (3-int(ew_src)) # convert to bitlength
-            ew_dst = 8 << (3-int(ew_dst)) # convert to bitlength
+            ew_src = 8 << (3-int(ew_src))  # convert to bitlength
+            ew_dst = 8 << (3-int(ew_dst))  # convert to bitlength
             xlen = max(ew_src, ew_dst)
             log("elwdith", ew_src, ew_dst)
         log("XLEN:", self.is_svp64_mode, xlen)
 
         # look up instruction in ISA.instrs, prepare namespace
-        if ins_name == 'pcdec': # grrrr yes there are others ("stbcx." etc.)
+        if ins_name == 'pcdec':  # grrrr yes there are others ("stbcx." etc.)
             info = self.instrs[ins_name+"."]
+        elif asmop[-1] == '.' and asmop in self.instrs:
+            info = self.instrs[asmop]
         else:
             info = self.instrs[ins_name]
         yield from self.prep_namespace(ins_name, info.form, info.op_fields,
@@ -1908,6 +2115,9 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
             end_loop = no_in_vec or srcstep == vl-1 or dststep == vl-1
             self.namespace['end_loop'] = SelectableInt(end_loop, 1)
 
+        inp_ca_ov = (self.spr['XER'][XER_bits['CA']].value,
+                     self.spr['XER'][XER_bits['OV']].value)
+
         # execute actual instruction here (finally)
         log("inputs", inputs)
         results = info.func(self, *inputs)
@@ -1937,12 +2147,13 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
 
         # detect if CA/CA32 already in outputs (sra*, basically)
         ca = outs.get("CA")
-        ca32 = outs.get("CA32 ")
+        ca32 = outs.get("CA32")
 
         log("carry already done?", ca, ca32, output_names)
         carry_en = yield self.dec2.e.do.output_carry
         if carry_en:
-            yield from self.handle_carry_(inputs, results[0], ca, ca32)
+            yield from self.handle_carry_(
+                inputs, results[0], ca, ca32, inp_ca_ov=inp_ca_ov)
 
         # get outout named "overflow" and "CR0"
         overflow = outs.get('overflow')
@@ -1954,7 +2165,8 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
             ov_ok = yield self.dec2.e.do.oe.ok
             log("internal overflow", ins_name, overflow, "en?", ov_en, ov_ok)
             if ov_en & ov_ok:
-                yield from self.handle_overflow(inputs, results[0], overflow)
+                yield from self.handle_overflow(
+                    inputs, results[0], overflow, inp_ca_ov=inp_ca_ov)
 
         # only do SVP64 dest predicated Rc=1 if dest-pred is not enabled
         rc_en = False
@@ -1986,7 +2198,7 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         ff_inv = yield self.dec2.rm_dec.inv
         cr_bit = yield self.dec2.rm_dec.cr_sel
         RC1 = yield self.dec2.rm_dec.RC1
-        vli_ = yield self.dec2.rm_dec.vli # VL inclusive if truncated
+        vli_ = yield self.dec2.rm_dec.vli  # VL inclusive if truncated
         log(" ff rm_mode", rc_en, rm_mode, SVP64RMMode.FFIRST.value)
         log("        inv", ff_inv)
         log("        RC1", RC1)
@@ -2024,8 +2236,8 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         is_setvl = ins_name in ('svstep', 'setvl')
         if is_setvl:
             result = SelectableInt(result.vl, 64)
-        else:
-            overflow = None  # do not override overflow except in setvl
+        #else:
+        #    overflow = None  # do not override overflow except in setvl
 
         # if there was not an explicit CR0 in the pseudocode, do implicit Rc=1
         if cr0 is None:
@@ -2036,14 +2248,16 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
             self.crl[regnum].eq(cr0)
 
     def do_outregs_nia(self, asmop, ins_name, info, outs,
-                       carry_en, rc_en, ffirst_hit, ew_dst):
+                       ca_en, rc_en, ffirst_hit, ew_dst):
         ffirst_hit, vli = ffirst_hit
-        # write out any regs for this instruction
-        for name, output in outs.items():
-            yield from self.check_write(info, name, output, carry_en, ew_dst)
+        # write out any regs for this instruction, but only if fail-first is ok
+        # XXX TODO: allow CR-vector to be written out even if ffirst fails
+        if not ffirst_hit or vli:
+            for name, output in outs.items():
+                yield from self.check_write(info, name, output, ca_en, ew_dst)
         # restore the CR value on non-VLI failfirst (from sv.cmp and others
         # which write directly to CR in the pseudocode (gah, what a mess)
-        #if ffirst_hit and not vli:
+        # if ffirst_hit and not vli:
         #    self.cr.value = self.cr_backup
 
         if ffirst_hit:
@@ -2052,7 +2266,7 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         else:
             # check advancement of src/dst/sub-steps and if PC needs updating
             nia_update = (yield from self.check_step_increment(rc_en,
-                                                           asmop, ins_name))
+                                                               asmop, ins_name))
         if nia_update:
             self.update_pc_next()
 
@@ -2075,14 +2289,14 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         if op == MicrOp.OP_LOAD.value:
             if remap_active:
                 offsmul = yield self.dec2.in1_step
-                log("D-field REMAP src", imm, offsmul)
+                log("D-field REMAP src", imm, offsmul, ldstmode)
             else:
                 offsmul = (srcstep * (subvl+1)) + ssubstep
-                log("D-field src", imm, offsmul)
+                log("D-field src", imm, offsmul, ldstmode)
         elif op == MicrOp.OP_STORE.value:
             # XXX NOTE! no bit-reversed STORE! this should not ever be used
             offsmul = (dststep * (subvl+1)) + dsubstep
-            log("D-field dst", imm, offsmul)
+            log("D-field dst", imm, offsmul, ldstmode)
         # Unit-Strided LD/ST adds offset*width to immediate
         if ldstmode == SVP64LDSTmode.UNITSTRIDE.value:
             ldst_len = yield self.dec2.e.do.data_len
@@ -2121,7 +2335,7 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         if isinstance(regnum, tuple):
             (regnum, base, offs) = regnum
         else:
-            base, offs = regnum, 0 # temporary HACK
+            base, offs = regnum, 0  # temporary HACK
 
         # in case getting the register number is needed, _RA, _RB
         # (HACK: only in straight non-svp64-mode for now, or elwidth == 64)
@@ -2136,8 +2350,10 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
             if name in fregs:
                 reg_val = SelectableInt(self.fpr(base, is_vec, offs, ew_src))
                 log("read reg %d/%d: 0x%x" % (base, offs, reg_val.value))
+                self.insnlog.append("rFPR:%d.%d/%d" % (base, offs, ew_src))
             elif name is not None:
                 reg_val = SelectableInt(self.gpr(base, is_vec, offs, ew_src))
+                self.insnlog.append("rGPR:%d.%d/%d" % (base, offs, ew_src))
                 log("read reg %d/%d: 0x%x" % (base, offs, reg_val.value))
         else:
             log('zero input reg %s %s' % (name, str(regnum)), is_vec)
@@ -2167,12 +2383,25 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         mi2 = self.svstate.mi2
         mo0 = self.svstate.mo0
         mo1 = self.svstate.mo1
-        steps = [(self.dec2.in1_step, mi0),  # RA
-                 (self.dec2.in2_step, mi1),  # RB
-                 (self.dec2.in3_step, mi2),  # RC
-                 (self.dec2.o_step, mo0),   # RT
-                 (self.dec2.o2_step, mo1),   # EA
+        steps = [[self.dec2.in1_step,  mi0],  # RA
+                 [self.dec2.in2_step,  mi1],  # RB
+                 [self.dec2.in3_step,  mi2],  # RC
+                 [self.dec2.o_step,  mo0],   # RT
+                 [self.dec2.o2_step,  mo1],   # EA
                  ]
+        if False:  # TODO
+            rnames = ['RA', 'RB', 'RC', 'RT', 'RS']
+            for i, reg in enumerate(rnames):
+                idx = yield from get_idx_map(self.dec2, reg)
+                if idx is None:
+                    idx = yield from get_idx_map(self.dec2, "F"+reg)
+                if idx == 1:  # RA
+                    steps[i][0] = self.dec2.in1_step
+                elif idx == 2:  # RB
+                    steps[i][0] = self.dec2.in2_step
+                elif idx == 3:  # RC
+                    steps[i][0] = self.dec2.in3_step
+                log("remap step", i, reg, idx, steps[i][1])
         remap_idxs = self.remap_idxs
         rremaps = []
         # now cross-index the required SHAPE for each of 3-in 2-out regs
@@ -2184,10 +2413,11 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
             if shape.value == 0x0:
                 continue
             # now set the actual requested step to the current index
-            yield dstep.eq(remap_idx)
+            if dstep is not None:
+                yield dstep.eq(remap_idx)
 
             # debug printout info
-            rremaps.append((shape.mode, hex(shape.value),
+            rremaps.append((shape.mode, hex(shape.value), dstep,
                             i, rnames[i], shape_idx, remap_idx))
         for x in rremaps:
             log("shape remap", x)
@@ -2198,7 +2428,7 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         if name == 'CR0':  # ignore, done already (above)
             return
         if isinstance(output, int):
-            output = SelectableInt(output, 256)
+            output = SelectableInt(output, EFFECTIVELY_UNLIMITED)
         # write carry flafs
         if name in ['CA', 'CA32']:
             if carry_en:
@@ -2235,17 +2465,20 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         # check zeroing due to predicate bit being zero
         if self.is_svp64_mode and self.pred_dst_zero:
             log('zeroing reg %s %s' % (str(regnum), str(output)), is_vec)
-            output = SelectableInt(0, 256)
+            output = SelectableInt(0, EFFECTIVELY_UNLIMITED)
         log("write reg %s%s 0x%x ew %d" % (reg_prefix, str(regnum),
                                            output.value, ew_dst),
             kind=LogKind.InstrInOuts)
         # zero-extend tov64 bit begore storing (should use EXT oh well)
         if output.bits > 64:
             output = SelectableInt(output.value, 64)
+        rnum, base, offset = regnum
         if name in fregs:
             self.fpr.write(regnum, output, is_vec, ew_dst)
+            self.insnlog.append("wFPR:%d.%d/%d" % (rnum, offset, ew_dst))
         else:
             self.gpr.write(regnum, output, is_vec, ew_dst)
+            self.insnlog.append("wGPR:%d.%d/%d" % (rnum, offset, ew_dst))
 
     def check_step_increment(self, rc_en, asmop, ins_name):
         # check if it is the SVSTATE.src/dest step that needs incrementing
@@ -2437,7 +2670,7 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         log("    reverse", reverse_gear)
         log("    out_vec", out_vec)
         log("    in_vec", in_vec)
-        log("    sv_ptype", sv_ptype, sv_ptype == SVPtype.P2.value)
+        log("    sv_ptype", sv_ptype, sv_ptype == SVPType.P2.value)
         # check if this was an sv.bc* and if so did it succeed
         if self.is_svp64_mode and insn_name.startswith("sv.bc"):
             end_loop = self.namespace['end_loop']
@@ -2449,7 +2682,7 @@ class ISACaller(ISACallerHelper, ISAFPHelpers, StepLoop):
         # check if srcstep needs incrementing by one, stop PC advancing
         # but for 2-pred both src/dest have to be checked.
         # XXX this might not be true! it may just be LD/ST
-        if sv_ptype == SVPtype.P2.value:
+        if sv_ptype == SVPType.P2.value:
             svp64_is_vector = (out_vec or in_vec)
         else:
             svp64_is_vector = out_vec