예제 #1
0
def test():
    filelist = [codedir + 'supply.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None
    
    analyzer = VerilogDataflowAnalyzer(filelist, topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()

    directives = analyzer.get_directives()
    instances = analyzer.getInstances()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    output = []
    
    for bk, bv in sorted(binddict.items(), key=lambda x:str(x[0])):
        for bvi in bv:
            output.append(bvi.tostr())
            output.append('\n')
            
    rslt = ''.join(output)

    print(rslt)
    assert(expected == rslt)
예제 #2
0
def test():
    filelist = [codedir + 'signed_task.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None
    
    analyzer = VerilogDataflowAnalyzer(filelist, topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()

    directives = analyzer.get_directives()
    instances = analyzer.getInstances()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    output = []
    output.append(list(binddict.values())[0][0].tostr())
    output.append('\n')
            
    rslt = ''.join(output)

    print(rslt)
    assert(expected == rslt)
예제 #3
0
def main():

    from wavedump import VcdComparator
    from pyverilog.dataflow.dataflow_analyzer import VerilogDataflowAnalyzer

    filelist = ['./problem/code_ref.v']

    topmodule = 'top_module'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)

    analyzer.generate()
    terms = analyzer.getTerms()

    compare_list = []
    for tk, tv in sorted(terms.items(), key=lambda x: str(x[0])):
        if 'Input' in tv.termtype or 'Output' in tv.termtype:
            compare_list.append('root/testbench/' + str(tk.scopechain[1]))

    print('compare list')
    print(compare_list)
    cmpr = VcdComparator("./out_ref.vcd", "./out_code.vcd", compare_list)
    ret, msg = cmpr.compare()
    return (ret, msg)
def test():
    filelist = [(codedir + 'irregular_reset0.v'),
                (codedir + 'irregular_reset1.v'),
                (codedir + 'irregular_reset2.v'),
                (codedir + 'irregular_reset3.v'),
                (codedir + 'irregular_reset4.v')]

    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None

    for i, file in enumerate(filelist):
        topmodule = 'TOP' + str(i)
        analyzer = VerilogDataflowAnalyzer(filelist, topmodule,
                                           noreorder=noreorder,
                                           nobind=nobind,
                                           preprocess_include=include,
                                           preprocess_define=define)
        try:
            analyzer.generate()
        except verror.FormatError:
            del analyzer
        else:
            raise Exception('Irregal reset code is passed.@' + file)
예제 #5
0
def test():
    filelist = [codedir + 'case.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()

    directives = analyzer.get_directives()
    instances = analyzer.getInstances()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    output = []
    output.append(list(binddict.values())[0][0].tostr())
    output.append('\n')

    rslt = ''.join(output)

    print(rslt)
    assert (expected == rslt)
예제 #6
0
def test():
    filelist = [codedir + 'primitive.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()

    directives = analyzer.get_directives()
    instances = analyzer.getInstances()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    output = []

    for bk, bv in sorted(binddict.items(), key=lambda x: str(x[0])):
        for bvi in bv:
            output.append(bvi.tostr())
            output.append('\n')

    rslt = ''.join(output)

    print(rslt)
    assert (expected == rslt)
예제 #7
0
파일: vmerge.py 프로젝트: nghocheung/vmerge
def generateDataFlow(filelist, topmodule, noreorder, nobind,
                     preprocess_include, preprocess_define):

    analyzer = VerilogDataflowAnalyzer(filelist, topmodule, noreorder, nobind,
                                       preprocess_include, preprocess_define)
    analyzer.generate()

    return analyzer
예제 #8
0
def main():
    from pyDigitalWaveTools.vcd.parser import VcdParser
    from wavedump import VcdConverter
    from pyverilog.dataflow.dataflow_analyzer import VerilogDataflowAnalyzer

    filelist = ['./problem/code_ref.v']

    topmodule = 'top_module'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist, topmodule,
                                      noreorder=noreorder,
                                      nobind=nobind,
                                      preprocess_include=include,
                                      preprocess_define=define)

    analyzer.generate()
    terms = analyzer.getTerms()

    input_list = []
    output_list = []
    compare_list = []

    for tk, tv in sorted(terms.items(), key=lambda x:str(x[0])):
      if 'Input' in tv.termtype:
        input_list.append('root/testbench/'+str(tk.scopechain[1]))

      if 'Output' in tv.termtype:
        output_list.append('root/testbench/'+str(tk.scopechain[1]))
        compare_list.append(str(tk.scopechain[1]))

    with open("./out_ref.vcd") as vcd_ref_file:
        vcd = VcdParser()
        vcd.parse(vcd_ref_file)
        data_ref = vcd.scope.toJson()

    with open("./out_code.vcd") as vcd_dut_file:
        vcd = VcdParser()
        vcd.parse(vcd_dut_file)
        data_dut = vcd.scope.toJson()

    vc_ref = VcdConverter(data_ref)
    time = vc_ref.addToWaveJsonSeparate(signal_names=input_list+output_list, prefix = "reference_")

    vc_dut = VcdConverter(data_dut)
    vc_dut.addToWaveJsonSeparate_modify(signal_names=output_list, time_max=time,prefix= "your_")

    vc_ref.mergeWaveDict(vc_dut.emitWaveDict())

    vc_ref.addCompare(compare_list,"your_","reference_",1)

    out = vc_ref.emitWaveJson()

    with open("./appdata.txt", "w") as f:
        f.write(out)
예제 #9
0
def main():
    INFO = "Verilog dataflow optimizer with Pyverilog"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_optimizer.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()
    
    optparser = OptionParser()
    optparser.add_option("-v","--version",action="store_true",dest="showversion",
                         default=False,help="Show the version")
    optparser.add_option("-t","--top",dest="topmodule",
                         default="TOP",help="Top module, Default=TOP")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)
    optimizer.resolveConstant()

    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    print('Directive:')
    for dr in directives:
        print(dr)

    print('Term:')
    for tk, tv in sorted(resolved_terms.items(), key=lambda x:len(x[0])):
        print(tv.tostr())

    print('Bind:')
    for bk, bv in sorted(resolved_binddict.items(), key=lambda x:len(x[0])):
        for bvi in bv:
            print(bvi.tostr())

    print('Const:')
    for ck, cv in sorted(constlist.items(), key=lambda x:len(x[0])):
        print(ck, cv)
예제 #10
0
def test():
    filelist = [codedir + 'reset.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist, topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()
예제 #11
0
def test():
    filelist = [codedir + 'reset.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()
예제 #12
0
def test():
    filelist = [codedir + 'led.v']
    topmodule = 'led'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()

    directives = analyzer.get_directives()
    instances = analyzer.getInstances()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    output = []

    output.append('Directive:\n')
    for dr in sorted(directives, key=lambda x: str(x)):
        output.append(str(dr))
        output.append('\n')

    output.append('Instance:\n')
    for module, instname in sorted(instances, key=lambda x: str(x[1])):
        output.append(str((module, instname)))
        output.append('\n')

    output.append('Term:\n')
    for tk, tv in sorted(terms.items(), key=lambda x: str(x[0])):
        output.append(tv.tostr())
        output.append('\n')

    output.append('Bind:\n')
    for bk, bv in sorted(binddict.items(), key=lambda x: str(x[0])):
        for bvi in bv:
            output.append(bvi.tostr())
            output.append('\n')

    rslt = ''.join(output)

    print(rslt)
    assert (expected == rslt)
예제 #13
0
def test():
    filelist = [codedir + 'blocking.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None
    
    analyzer = VerilogDataflowAnalyzer(filelist, topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()

    directives = analyzer.get_directives()
    instances = analyzer.getInstances()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    output = []
    
    output.append('Directive:\n')
    for dr in sorted(directives, key=lambda x:str(x)):
        output.append(str(dr))
        output.append('\n')

    output.append('Instance:\n')
    for module, instname in sorted(instances, key=lambda x:str(x[1])):
        output.append(str((module, instname)))
        output.append('\n')

    output.append('Term:\n')
    for tk, tv in sorted(terms.items(), key=lambda x:str(x[0])):
        output.append(tv.tostr())
        output.append('\n')
        
    output.append('Bind:\n')
    for bk, bv in sorted(binddict.items(), key=lambda x:str(x[0])):
        for bvi in bv:
            output.append(bvi.tostr())
            output.append('\n')
            
    rslt = ''.join(output)

    print(rslt)
    assert(expected == rslt)
예제 #14
0
def compile_module(module_def, other_modules):
    analyzer = VerilogDataflowAnalyzer(sys.argv[1:], module_def.name)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)
    optimizer.resolveConstant()

    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    print('Directive:')
    for dr in directives:
        print(dr)

    print('Term:')
    for tk, tv in sorted(resolved_terms.items(), key=lambda x: len(x[0])):
        print(tv.tostr())

    print('Bind:')
    for bk, bv in sorted(resolved_binddict.items(), key=lambda x: len(x[0])):
        print('bk:', bk)
        for bvi in bv:
            print('bvi:')
            print(bvi.tocode())

    print('Const:')
    for ck, cv in sorted(constlist.items(), key=lambda x: len(x[0])):
        print(ck, cv)

    instances = []
    for item in module_def.items:
        if isinstance(item, InstanceList):
            for instance in item.instances:
                instances.append(instance)

    print(instances)

    res = VLowering(module_def.name, resolved_terms, resolved_binddict,
                    instances, other_modules)
    res.transform()

    return res.module, res.circuit, res.required_intrinsics
예제 #15
0
    def _create_graphgen_obj(self, verilog_file, top_module, generate_cfg,
                             generate_ast):
        dataflow_analyzer = PyDataflowAnalyzer(verilog_file, top_module)
        dataflow_analyzer.generate()
        binddict = dataflow_analyzer.getBinddict()
        terms = dataflow_analyzer.getTerms()

        dataflow_optimizer = PyDataflowOptimizer(terms, binddict)
        dataflow_optimizer.resolveConstant()
        resolved_terms = dataflow_optimizer.getResolvedTerms()
        resolved_binddict = dataflow_optimizer.getResolvedBinddict()
        constlist = dataflow_optimizer.getConstlist()

        if generate_cfg:
            fsm_vars = tuple(['fsm', 'state', 'count', 'cnt', 'step', 'mode'])
            self.cfg_graph_generator = PyControlflowAnalyzer(
                "top", terms, binddict, resolved_terms, resolved_binddict,
                constlist, fsm_vars)
        elif generate_ast:
            #when generating AST, determines which substructure (dictionary/array) to generate
            #before converting the json-like structure into actual json
            self.DICTIONARY_GEN = [
                "Source", "Description", "Ioport", "Decl", "Lvalue"
            ]
            self.ARRAY_GEN = [
                "ModuleDef", "Paramlist", "Portlist", "Input", "Width", "Reg",
                "Wire", "Rvalue", "ParseSelect", "Uplus", "Uminus", "Ulnot",
                "Unot", "Uand", "Unand", "Uor", "Unor", "Uxnor", "Power",
                "Times", "Divide", "Mod", "Plus", "Minus", "Sll", "Srl", "Sla",
                "Sra", "LessThan", "GreaterThan", "LessEq", "GreaterEq", "Eq",
                "Eql", "NotEq", "Eql", "NotEql", "And", "Xor", "Xnor", "Or",
                "Land", "Lor", "Cond", "Assign", "Always", "AlwaysFF",
                "AlwaysComb", "AlwaysLatch", "SensList", "Sens",
                "Substitution", "BlockingSubstitution",
                "NonblockingSubstitution", "IfStatement", "Block", "Initial",
                "Plus", "Output", "Partselect"
            ]
            self.CONST_DICTIONARY_GEN = [
                "IntConst", "FloatConst", "StringConst", "Identifier"
            ]

            self.ast, _ = parse([verilog_file])

        else:  #generate dfg
            self.dfg_graph_generator = PyGraphGenerator(
                top_module, terms, binddict, resolved_terms, resolved_binddict,
                constlist, f'{self.output_directory}seperate_modules.pdf')
def test():
    filelist = [codedir + 'partselect_assign.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()

    directives = analyzer.get_directives()
    instances = analyzer.getInstances()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)
    optimizer.resolveConstant()

    c_analyzer = VerilogControlflowAnalyzer(
        topmodule,
        terms,
        binddict,
        resolved_terms=optimizer.getResolvedTerms(),
        resolved_binddict=optimizer.getResolvedBinddict(),
        constlist=optimizer.getConstlist())

    output = []
    for tk in sorted(c_analyzer.resolved_terms.keys(), key=lambda x: str(x)):
        tree = c_analyzer.makeTree(tk)
        output.append(str(tk) + ': ' + tree.tocode())

    rslt = '\n'.join(output) + '\n'

    print(rslt)

    assert (expected == rslt)
예제 #17
0
def test():
    filelist = [codedir + 'partselect_assign.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist, topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()

    directives = analyzer.get_directives()
    instances = analyzer.getInstances()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)
    optimizer.resolveConstant()

    c_analyzer = VerilogControlflowAnalyzer(topmodule, terms,
                                            binddict,
                                            resolved_terms=optimizer.getResolvedTerms(),
                                            resolved_binddict=optimizer.getResolvedBinddict(),
                                            constlist=optimizer.getConstlist()
                                            )

    output = []
    for tk in sorted(c_analyzer.resolved_terms.keys(), key=lambda x:str(x)):
        tree = c_analyzer.makeTree(tk)
        output.append(str(tk) + ': ' + tree.tocode())

    rslt = '\n'.join(output) + '\n'

    print(rslt)
    
    assert(expected == rslt)
예제 #18
0
def main():
    # produces an arr of ['file1', 'file2', ...]
    sample_files = glob(RELATIVE_SAMPLE_INPUT_LOCATION)

    analysis = VerilogDataflowAnalyzer(
        sample_files, topmodule=TOP_MODULE_NAME)  # Default is 'TOP'

    # Needed to generate analysis
    analysis.generate()

    # Getting Terms for each item
    print('\n\nTERMS')
    terms_map = analysis.getTerms()
    term_list = list(terms_map.values())
    for term in term_list:
        print(term.tostr())
        # rtype: str
        print('Term Name: {}'.format(term.name))
        # rtype: set
        print('Term Type: {}'.format(term.termtype))
        # rtype: int
        print('Term msb {} and lsb {}'.format(term.msb, term.lsb))
        print('\n')

    # Getting Bind for each item
    print('\n\nBINDS')
    binds_map = analysis.getBinddict()
    for key, dataflow_bind in binds_map.items():
        print(dataflow_bind[0].tostr())
        # rtype: pyverilog.dataflow.dataflow.DFOperator
        print('Bind Tree: {}'.format(dataflow_bind[0].tree))
        # rtype: str
        print('Bind Tree Code: {}'.format(dataflow_bind[0].tree.tocode))
        print('\n')

    # top_ver.intsig Bind data
    intsig = list(binds_map.values())[2][0]
    table_demo(intsig, terms_map)
예제 #19
0
def test():
    filelist = [codedir + 'reset.v']
    topmodule = 'TOP'
    noreorder = False
    nobind = False
    include = None
    define = None

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       topmodule,
                                       noreorder=noreorder,
                                       nobind=nobind,
                                       preprocess_include=include,
                                       preprocess_define=define)
    analyzer.generate()
    directives = analyzer.get_directives()
    instances = analyzer.getInstances()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    sens_info = []
    for tk in sorted(binddict.keys(), key=lambda x: str(x)):
        sens_info.append(str(tk) + ': ')
        reset_info = (str(binddict[tk][0].getResetEdge()) + ' ' +
                      str(binddict[tk][0].getResetName()) + '[' +
                      str(binddict[tk][0].getResetBit()) + ']')
        clock_info = (str(binddict[tk][0].getClockEdge()) + ' ' +
                      str(binddict[tk][0].getClockName()) + '[' +
                      str(binddict[tk][0].getClockBit()) + ']')
        sens_info.append(reset_info + clock_info)
        sens_info.append('\n')

    rslt = ''.join(sens_info)

    print(rslt)
    assert (expected == rslt)
예제 #20
0
def generateMuxTemplate(prefixName, design_num, bind_list, bindMuxinfo,
                        sigdiffStr_Refmax, sigdiffScope_Maxbit, sigStr_Type):
    #mux_file = open(prefixName + "_mux.v", "w")

    for sig in sigdiffStr_Refmax:
        print(sig)

    analyzer = VerilogDataflowAnalyzer([prefixName + "__mux.v"],
                                       "mux_template",
                                       noreorder=False,
                                       nobind=False,
                                       preprocess_include=[],
                                       preprocess_define=[])
    analyzer.generate()
    muxterm_dict = analyzer.getTerms()
    muxbind_dict = analyzer.getBinddict()

    # print("\nBind list for mux")
    # muxbind_list = sorted(muxbind_dict.items(), key=lambda x: str(x[0]))
    # for bi, bv in muxbind_list:
    #       #print("bi>>>>>>>>>>>>>>>>", bi)
    #       for bve in bv:
    #           print(bve.tostr())
    """1st: This is a hack, convert the binddest object from scope to str
        to support faster search later"""
    [muxtermStr_ind_dict, muxtermStr_val_dict, muxbindStr_head_dict, muxbindStr_tree_dict] = \
                                                            scopeToStr_MuxDataStruct(muxterm_dict, muxbind_dict)

    mux_binddest_list = []
    """ 2nd: create the list of dest for replacement in mux_binddest_dict
    """
    for mux_binddest_str in mux_binddest_static_list:
        mux_binddest_list.append(mux_binddest_str)

        # that depends on the number of designs, which determine the number of inputs to mux
        m = re.search("\d", mux_binddest_str)
        if m:
            digit_loc = m.start()
            for digi in range(1, design_num):
                mux_binddest_str2 = mux_binddest_str.replace('0', str(digi))
                mux_binddest_list.append(mux_binddest_str2)

    for i in range(0, len(sigdiffStr_Refmax) * design_num):
        mux_rn2 = mux_rn.replace('0', str(i))
        mux_binddest_list.append(mux_rn2)
    """ 3rd: start from bind tree perspective, help the signal to create mux (term will be changed with another function)
        Note the signal name in the mux file is composed of <level0>_<level1>_<old_sig_name>, so we need to convert it
        back to old_sig_name for terms and binddest
    """
    for bi, bv in bind_list:
        bi_str = str(bi)
        muxIdfy = bindMuxinfo[bi_str]

        if muxIdfy.headmux == True:
            # entire bind tree multi-bit
            #if muxIdfy.termNum == muxIdfy.termMultiNum:
            signame = bi_str
            signame = signame.replace('.', '_')

            lowlevelsigname = bi.scopechain[-1].scopename

            #natvigate the bind tree of mux, change the content correspondingly

            #(3a)place the scopes from NORMAL binddest for the MUX_binddest tree use,
            #   based on the scope of the signals in the USER DESIGNS
            scope_addtotree = []
            for binddests_scope in reversed(bi.scopechain[:-1]):
                # this doesn't do deep copy
                scope_addtotree.insert(0, binddests_scope)

            # (3b)take care of the head in MUX_bind_dest
            #       it always has the format mux_template.mux_<original signal name>.<_rn0_q or d0.....>
            for mux_binddest_str in mux_binddest_list:
                muxforSig = 'mux_template.mux_' + signame + '.' + mux_binddest_str
                dinbool = mux_binddest_str[
                    0] == 'd'  #hack; determine if it is an input
                # (3c) (3d) in the function
                # check the case for rnq first
                if muxforSig in muxbindStr_head_dict:
                    chgMuxBindScope(None, dinbool, muxforSig,
                                    muxbindStr_head_dict, muxbindStr_tree_dict,
                                    scope_addtotree, bi)

                    chgMuxTermScope(None, muxforSig, muxtermStr_ind_dict,
                                    muxtermStr_val_dict, scope_addtotree, bi)

            # (3e) Hack: hardcode the final case, which is the output signal for the mux
            muxforSig = 'mux_template.' + signame  #+ '.' + mux_signalout
            chgMuxBindScope(lowlevelsigname,
                            False,
                            muxforSig,
                            muxbindStr_head_dict,
                            muxbindStr_tree_dict,
                            scope_addtotree,
                            bi,
                            q=True)

            chgMuxTermScope(lowlevelsigname,
                            muxforSig,
                            muxtermStr_ind_dict,
                            muxtermStr_val_dict,
                            scope_addtotree,
                            bi,
                            q=True,
                            sigStr_Type=sigStr_Type)

            # (3f) Handling the unhandle signal name, usually they are on the top level
            # case 1: entire tree multi-bit
            if muxIdfy.termMultiNum == muxIdfy.termNum and not muxIdfy.hasCmp:
                muxforSig = 'mux_template.' + signame + '_mux'
                chgMuxTermScope(lowlevelsigname + '_mux',
                                muxforSig,
                                muxtermStr_ind_dict,
                                muxtermStr_val_dict,
                                scope_addtotree,
                                bi,
                                q=True)

            # case 2/3: entire tree NO multi-bit, or some nodes in tree are NON-multi-bit/ with multi-bit,
            else:
                for d in range(0, design_num):
                    muxforSig = 'mux_template.' + signame + '_mux' + str(d)
                    chgMuxTermScope(lowlevelsigname + '_mux' + str(d),
                                    muxforSig,
                                    muxtermStr_ind_dict,
                                    muxtermStr_val_dict,
                                    scope_addtotree,
                                    bi,
                                    q=True)

            #Hack: the top sel signal
            muxforSig = 'mux_template.sel'
            chgMuxTermScope(None,
                            muxforSig,
                            muxtermStr_ind_dict,
                            muxtermStr_val_dict,
                            scope_addtotree,
                            bi,
                            q=True)

    muxbind_list = sorted(muxbind_dict.items(), key=lambda x: str(x[0]))

    # for bi, bv in muxbind_list:
    #     #print("bi>>>>>>>>>>>>>>>>", bi)
    #     for bve in bv:
    #         print(bve.tostr())

    for ti, tv in muxterm_dict.items():
        print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", ti, tv.termtype)
    """ 4nd: return a correct data structure to enable fast deletion in vmerge
    """
    [muxterm_dict, muxbind_dict, muxtermStr_ind_dict, muxtermStr_val_dict, muxbindStr_head_dict, muxbindStr_tree_dict] = \
                                                            scopeToStr_MuxDataStruct(muxterm_dict, muxbind_dict, reNewDict=True)

    return [
        muxterm_dict, muxtermStr_ind_dict, muxtermStr_val_dict, muxbind_dict,
        muxbindStr_head_dict, muxbindStr_tree_dict
    ]
예제 #21
0
def main():
    INFO = "Code generator from Verilog dataflow definitions"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_dataflow_codegen.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()
    
    optparser = OptionParser()
    optparser.add_option("-v","--version",action="store_true",dest="showversion",
                         default=False,help="Show the version")
    optparser.add_option("-I","--include",dest="include",action="append",
                         default=[],help="Include path")
    optparser.add_option("-D",dest="define",action="append",
                         default=[],help="Macro Definition")
    optparser.add_option("-t","--top",dest="topmodule",
                         default="TOP",help="Top module, Default=TOP")
    optparser.add_option("--nobind",action="store_true",dest="nobind",
                         default=False,help="No binding traversal, Default=False")
    optparser.add_option("--noreorder",action="store_true",dest="noreorder",
                         default=False,help="No reordering of binding dataflow, Default=False")
    optparser.add_option("-s","--search",dest="searchtarget",action="append",
                         default=[],help="Search Target Signal")
    optparser.add_option("-o","--output",dest="outputfile",
                         default="helperthread.v",help="Output File name, Default=helperthread.v")
    optparser.add_option("--clockname",dest="clockname",
                         default="CLK",help="Clock signal name")
    optparser.add_option("--resetname",dest="resetname",
                         default="RST_X",help="Reset signal name")
    optparser.add_option("--clockedge",dest="clockedge",
                         default="posedge",help="Clock signal edge")
    optparser.add_option("--resetedge",dest="resetedge",
                         default="negedge",help="Reset signal edge")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    codegen = VerilogCodeGenerator(options.topmodule, terms, binddict,
                                   resolved_terms, resolved_binddict, constlist)
    codegen.set_clock_info(options.clockname, options.clockedge)
    codegen.set_reset_info(options.resetname, options.resetedge)
    code = codegen.generateCode(options.searchtarget)

    f = open(options.outputfile, 'w')
    f.write(code)
    f.close()
예제 #22
0
def main():
    ##    CIRCUIT = "dma_rrarb"
    CIRCUIT = "add_serial"

    if CIRCUIT == "dma_rrarb":
        src = "dma_rrarb/"
        filelist = ["dma_rrarb_mod.v"]
        topmodule = "dma_rrarb"
    elif CIRCUIT == "add_serial":
        src = "add_serial/"
        filelist = ["add_serial_mod.v"]
        topmodule = "add_serial"
    dst = "./"
    new_files = []
    for file_name in os.listdir(src):
        full_file_name = os.path.join(src, file_name)
        if os.path.isfile(full_file_name):
            shutil.copy(full_file_name, dst)
            new_files.append(file_name)

    noreorder = False
    nobind = False
    include = []
    define = []

    analyzer = VerilogDataflowAnalyzer(filelist, topmodule, noreorder, nobind,
                                       include, define)
    analyzer.generate()

    ##    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)
    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    fsm_vars = tuple(['state'])
    canalyzer = VerilogControlflowAnalyzer(topmodule, terms, binddict,
                                           resolved_terms, resolved_binddict,
                                           constlist, fsm_vars)
    fsms = canalyzer.getFiniteStateMachines()

    name = topmodule
    if CIRCUIT == "dma_rrarb":
        state_var = CDFG.newScope('dma_rrarb', 'state')
        clk = CDFG.newScope('dma_rrarb', 'HCLK')
        rst = CDFG.newScope('dma_rrarb', 'HRSTn')
        state_list = [
            CDFG.newScope('dma_rrarb', 'grant0'),
            CDFG.newScope('dma_rrarb', 'grant1'),
            CDFG.newScope('dma_rrarb', 'grant2'),
            CDFG.newScope('dma_rrarb', 'grant3'),
            CDFG.newScope('dma_rrarb', 'grant4'),
            CDFG.newScope('dma_rrarb', 'grant5'),
            CDFG.newScope('dma_rrarb', 'grant6'),
            CDFG.newScope('dma_rrarb', 'grant7'),
        ]
    elif CIRCUIT == "add_serial":
        state_var = CDFG.newScope('add_serial', 'state')
        clk = CDFG.newScope('add_serial', 'clk')
        rst = CDFG.newScope('add_serial', 'rst')
        state_list = [
            CDFG.newScope('add_serial', 'IDLE'),
            CDFG.newScope('add_serial', 'ADD'),
            CDFG.newScope('add_serial', 'DONE')
        ]

    max_trials = 20
    max_bits = 6
    max_num_ex_states = 8

    for num_ex_states in range(max_num_ex_states + 1):
        ##    for num_ex_states in [3,4,5]:
        print("num_ex_states = " + str(num_ex_states))
        codegen_dir = "{}/codegen/nonZeroCopyState/d{}/".format(
            topmodule, num_ex_states)
        try:
            os.makedirs(codegen_dir)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        f = open(codegen_dir + "edge_count_d{}.csv".format(num_ex_states), "w")
        for i in range(max_bits):
            num_bits = i + 1
            for trial in range(max_trials):
                print("generating code for num_bits = {}, trial = {}".format(
                    num_bits, trial + 1))
                fsm_obj = copy.deepcopy(fsms[state_var])
                cur_state_list = copy.deepcopy(state_list)
                cur_constlist = copy.deepcopy(constlist)
                cur_terms = copy.deepcopy(resolved_terms)
                cur_binddict = copy.deepcopy(resolved_binddict)

                cdfg =\
                     CDFG.ControlDataFlowGraph(name, fsm_obj, state_var, clk, rst,
                                               cur_state_list, cur_constlist,
                                               cur_terms, cur_binddict)
                cdfg.generate()
                PIs = cdfg.getPIs()
                # exempt clk
                PIs.remove(cdfg.clk)
                # and reset from scrambling
                if cdfg.rst:
                    PIs.remove(cdfg.rst)
                total_bits = 0
                for PI in PIs:
                    total_bits += cdfg.getNumBitsOfVar(PI)
                cdfg.scramblePIBits(total_bits / 2)
                for ex_state_i in range(num_ex_states):
                    src = cdfg.state_list[ex_state_i]
                    dst = cdfg.state_list[ex_state_i + 1]
                    delay = CDFG.newScope(topmodule, 'delay' + str(ex_state_i))
                    ##                    cdfg.insDelayState(src, dst, delay)
                    cdfg.insCopyState(src, dst, delay)
                (all_trans_freqs, num_PIs) = cdfg.getTransFreqs()
                for state in cur_state_list:
                    src_i = cdfg.state_list.index(state)
                    trans_freqs = all_trans_freqs[src_i]
                    trans_freqs = cdfg.nonZeroStates(trans_freqs, state,
                                                     num_bits)
                    all_trans_freqs[src_i] = trans_freqs
                cdfg.toCode(
                    topmodule, codegen_dir + "{}_d{}_b{}_t{}.v".format(
                        topmodule, num_ex_states, num_bits, trial + 1))
                metric_val = cdfg.countConnects(all_trans_freqs)
                f.write(str(metric_val) + ",")
            f.write("\n")
        f.close()

    print("\n")
    print("done")

    for file_name in new_files:
        os.remove(file_name)
예제 #23
0
def main():
    INFO = "Active condition analyzer (Obsoluted)"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_active_range.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()
    
    optparser = OptionParser()
    optparser.add_option("-v","--version",action="store_true",dest="showversion",
                         default=False,help="Show the version")
    optparser.add_option("-t","--top",dest="topmodule",
                         default="TOP",help="Top module, Default=TOP")
    optparser.add_option("-s","--search",dest="searchtarget",action="append",
                         default=[],help="Search Target Signal")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    aanalyzer = VerilogActiveAnalyzer(options.topmodule, terms, binddict, 
                                      resolved_terms, resolved_binddict, constlist)

    for target in options.searchtarget:
        signal = util.toTermname(target)

        print('Active Conditions: %s' % signal)
        active_conditions = aanalyzer.getActiveConditions( signal )
        print(sorted(active_conditions, key=lambda x:str(x)))

        print('Changed Conditions')
        changed_conditions = aanalyzer.getChangedConditions( signal )
        print(sorted(changed_conditions, key=lambda x:str(x)))
    
        print('Changed Condition Dict')
        changed_conditiondict = aanalyzer.getChangedConditionsWithAssignments( signal )
        print(sorted(changed_conditiondict.items(), key=lambda x:str(x[0])))
    
        print('Unchanged Conditions')
        unchanged_conditions = aanalyzer.getUnchangedConditions( signal )
        print(sorted(unchanged_conditions, key=lambda x:str(x)))
예제 #24
0
def main():
    INFO = "Verilog module signal/module dataflow analyzer"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_dataflow_analyzer.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()

    optparser = OptionParser()
    optparser.add_option("-v",
                         "--version",
                         action="store_true",
                         dest="showversion",
                         default=False,
                         help="Show the version")
    optparser.add_option("-I",
                         "--include",
                         dest="include",
                         action="append",
                         default=[],
                         help="Include path")
    optparser.add_option("-D",
                         dest="define",
                         action="append",
                         default=[],
                         help="Macro Definition")
    optparser.add_option("-t",
                         "--top",
                         dest="topmodule",
                         default="TOP",
                         help="Top module, Default=TOP")
    optparser.add_option("--nobind",
                         action="store_true",
                         dest="nobind",
                         default=False,
                         help="No binding traversal, Default=False")
    optparser.add_option(
        "--noreorder",
        action="store_true",
        dest="noreorder",
        default=False,
        help="No reordering of binding dataflow, Default=False")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    CIRCUIT = options.topmodule

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    top = options.topmodule
    fsm_vars = tuple(['state'])
    ##    fsm_vars = tuple(['dpll_state'])
    ##    fsm_vars = tuple(['s1','s0'])
    canalyzer = VerilogControlflowAnalyzer(options.topmodule, terms, binddict,
                                           resolved_terms, resolved_binddict,
                                           constlist, fsm_vars)
    fsms = canalyzer.getFiniteStateMachines()
    print("")

    name = 'test'

    if CIRCUIT == "add_serial":
        state_var = CDFG.newScope('add_serial', 'state')
        clk = CDFG.newScope('add_serial', 'clk')
        rst = CDFG.newScope('add_serial', 'rst')
    elif CIRCUIT == "bbara":
        state_var = CDFG.newScope('top', 'state')
        clk = CDFG.newScope('top', 'clk')
        rst = None
    elif CIRCUIT == "dma_rrarb":
        state_var = CDFG.newScope('dma_rrarb', 'state')
        clk = CDFG.newScope('dma_rrarb', 'HCLK')
        rst = CDFG.newScope('dma_rrarbrb', 'HRSTn')
    elif CIRCUIT == "mc_timing":
        state_var = CDFG.newScope('mc_timing', 'state')
        clk = CDFG.newScope('mc_timing', 'clk')
        rst = CDFG.newScope('mc_timing', 'rst')
    elif CIRCUIT == "correlator":
        state_var = CDFG.newScope('correlator', 'state')
        clk = CDFG.newScope('correlator', 'clk')
        rst = CDFG.newScope('correlator', 'rst_n')

    fsm_obj = fsms[state_var]

    if CIRCUIT == "add_serial":
        state_list = [
            CDFG.newScope('add_serial', 'IDLE'),
            CDFG.newScope('add_serial', 'ADD'),
            CDFG.newScope('add_serial', 'DONE')
        ]
    elif CIRCUIT == "bbara":
        state_list = [
            CDFG.newScope('top', 'st0'),
            CDFG.newScope('top', 'st1'),
            CDFG.newScope('top', 'st2'),
            CDFG.newScope('top', 'st3'),
            CDFG.newScope('top', 'st4'),
            CDFG.newScope('top', 'st5'),
            CDFG.newScope('top', 'st6'),
            CDFG.newScope('top', 'st7'),
            CDFG.newScope('top', 'st8'),
            CDFG.newScope('top', 'st9')
        ]
    elif CIRCUIT == "dma_rrarb":
        state_list = [
            CDFG.newScope('dma_rrarb', 'grant0'),
            CDFG.newScope('dma_rrarb', 'grant1'),
            CDFG.newScope('dma_rrarb', 'grant2'),
            CDFG.newScope('dma_rrarb', 'grant3'),
            CDFG.newScope('dma_rrarb', 'grant4'),
            CDFG.newScope('dma_rrarb', 'grant5'),
            CDFG.newScope('dma_rrarb', 'grant6'),
            CDFG.newScope('dma_rrarb', 'grant7'),
        ]
    elif CIRCUIT == "mc_timing":
        state_list = [
            CDFG.newScope('mc_timing', 'POR'),
            CDFG.newScope('mc_timing', 'IDLE'),
            CDFG.newScope('mc_timing', 'IDLE_T'),
            CDFG.newScope('mc_timing', 'IDLE_T2'),
            CDFG.newScope('mc_timing', 'PRECHARGE'),
            CDFG.newScope('mc_timing', 'PRECHARGE_W'),
            CDFG.newScope('mc_timing', 'ACTIVATE'),
            CDFG.newScope('mc_timing', 'ACTIVATE_W'),
            CDFG.newScope('mc_timing', 'SD_RD_WR'),
            CDFG.newScope('mc_timing', 'SD_RD'),
            CDFG.newScope('mc_timing', 'SD_RD_W'),
            CDFG.newScope('mc_timing', 'SD_RD_LOOP'),
            CDFG.newScope('mc_timing', 'SD_RD_W2'),
            CDFG.newScope('mc_timing', 'SD_WR'),
            CDFG.newScope('mc_timing', 'SD_WR_W'),
            CDFG.newScope('mc_timing', 'BT'),
            CDFG.newScope('mc_timing', 'BT_W'),
            CDFG.newScope('mc_timing', 'REFR'),
            CDFG.newScope('mc_timing', 'LMR0'),
            CDFG.newScope('mc_timing', 'LMR1'),
            CDFG.newScope('mc_timing', 'LMR2'),
            CDFG.newScope('mc_timing', 'INIT0'),
            CDFG.newScope('mc_timing', 'INIT'),
            CDFG.newScope('mc_timing', 'INIT_W'),
            CDFG.newScope('mc_timing', 'INIT_REFR1'),
            CDFG.newScope('mc_timing', 'INIT_REFR1_W'),
            CDFG.newScope('mc_timing', 'INIT_LMR'),
            CDFG.newScope('mc_timing', 'SUSP1'),
            CDFG.newScope('mc_timing', 'SUSP2'),
            CDFG.newScope('mc_timing', 'SUSP3'),
            CDFG.newScope('mc_timing', 'SUSP4'),
            CDFG.newScope('mc_timing', 'RESUME1'),
            CDFG.newScope('mc_timing', 'RESUME2'),
            CDFG.newScope('mc_timing', 'BG0'),
            CDFG.newScope('mc_timing', 'BG1'),
            CDFG.newScope('mc_timing', 'BG2'),
            CDFG.newScope('mc_timing', 'ACS_RD'),
            CDFG.newScope('mc_timing', 'ACS_RD1'),
            CDFG.newScope('mc_timing', 'ACS_RD2A'),
            CDFG.newScope('mc_timing', 'ACS_RD2'),
            CDFG.newScope('mc_timing', 'ACS_RD3'),
            CDFG.newScope('mc_timing', 'ACS_RD_8_1'),
            CDFG.newScope('mc_timing', 'ACS_RD_8_2'),
            CDFG.newScope('mc_timing', 'ACS_RD_8_3'),
            CDFG.newScope('mc_timing', 'ACS_RD_8_4'),
            CDFG.newScope('mc_timing', 'ACS_RD_8_5'),
            CDFG.newScope('mc_timing', 'ACS_RD_8_6'),
            CDFG.newScope('mc_timing', 'ACS_WR'),
            CDFG.newScope('mc_timing', 'ACS_WR1'),
            CDFG.newScope('mc_timing', 'ACS_WR2'),
            CDFG.newScope('mc_timing', 'ACS_WR3'),
            CDFG.newScope('mc_timing', 'ACS_WR4'),
            CDFG.newScope('mc_timing', 'SRAM_RD'),
            CDFG.newScope('mc_timing', 'SRAM_RD0'),
            CDFG.newScope('mc_timing', 'SRAM_RD1'),
            CDFG.newScope('mc_timing', 'SRAM_RD2'),
            CDFG.newScope('mc_timing', 'SRAM_RD3'),
            CDFG.newScope('mc_timing', 'SRAM_RD4'),
            CDFG.newScope('mc_timing', 'SRAM_WR'),
            CDFG.newScope('mc_timing', 'SRAM_WR0'),
            CDFG.newScope('mc_timing', 'SCS_RD'),
            CDFG.newScope('mc_timing', 'SCS_RD1'),
            CDFG.newScope('mc_timing', 'SCS_RD2'),
            CDFG.newScope('mc_timing', 'SCS_WR'),
            CDFG.newScope('mc_timing', 'SCS_WR1'),
            CDFG.newScope('mc_timing', 'SCS_ERR')
        ]
    elif CIRCUIT == "correlator":
        state_list = [
            CDFG.newScope('correlator', 'WAITING'),
            CDFG.newScope('correlator', 'DECIDING'),
            CDFG.newScope('correlator', 'OFFSETTING'),
            CDFG.newScope('correlator', 'RUNNING'),
            CDFG.newScope('correlator', 'IDLE'),
            CDFG.newScope('correlator', 'LOCKED'),
            CDFG.newScope('correlator', 'READ_RANK'),
            CDFG.newScope('correlator', 'default')
        ]

    cdfg =\
         CDFG.ControlDataFlowGraph(name, fsm_obj, state_var, clk, rst,
                                   state_list, constlist,
                                   resolved_terms, resolved_binddict)
    cdfg.generate()

    # fsm
    cdfg.fsm_obj.view()
    print("")

    PIs = cdfg.getPIs()
    # exempt clk
    PIs.remove(cdfg.clk)
    # and reset from scrambling
    if cdfg.rst:
        PIs.remove(cdfg.rst)
    total_bits = 0
    for PI in PIs:
        total_bits += cdfg.getNumBitsOfVar(PI)
    print("number of scrambled bits: " + str(total_bits / 2))
    cdfg.scramblePIBits(total_bits / 2)

    num_ex_states = 1
    for ex_state_i in range(num_ex_states):
        src = cdfg.state_list[ex_state_i]
        dst = cdfg.state_list[ex_state_i + 1]
        delay = CDFG.newScope(top, 'delay' + str(ex_state_i))
        ##        delay = CDFG.newScope('add_serial', 'delay'+str(ex_state_i))
        cdfg.insCopyState(src, dst, delay)
##        cdfg.insDelayState(src, dst, delay)

    num_bits = 6
    # nonZeroStates test
    (all_trans_freqs, num_PIs) = cdfg.getTransFreqs()
    for row in all_trans_freqs:
        print(row)
    print("")
    for i in range(len(cdfg.state_list)):
        trans_freqs = cdfg.nonZeroStates(all_trans_freqs[i],\
                                         cdfg.state_list[i], num_bits)
        all_trans_freqs[i] = trans_freqs
##    (all_trans_freqs, num_PIs) = cdfg.getTransFreqs()
    for row in all_trans_freqs:
        print(row)
    print("")

    ##    cdfg.toCode(options.topmodule, options.topmodule + '_codegen.v')

    ##    cdfg.toCode('add_serial', 'add_serial_uniform.v')

    ##    cdfg.toCode('add_serial', 'add_serial_scramb.v')

    ##    cdfg.updateBinddict()
    ##    cdfg.toCode('dma_rrarb', 'dma_rrarb_uniform_s0.v')

    ##    cdfg.updateBinddict()
    ##    cdfg.toCode('dma_rrarb', 'dma_rrarb_scramb_s0_b{}.v'
    ##                .format(num_bits))
    ##    cdfg.toCode('dma_rrarb', 'dma_rrarb_scramb_delay_b{}.v'.format(num_bits))

    print("\n")
    ##    print("num_edits = {}".format(num_edits))

    ##    # original binds
    ##    for var, bind in cdfg.binddict.items():
    ##        print(var)
    ##        print(bind[0].tostr())
    ####        print(bind[0].isCombination())
    ####        print(bind[0].alwaysinfo)
    ####        print(bind[0].parameterinfo)
    ##    print("")
    ##
    # binds by state
    for state, binddict in cdfg.state_binddict.items():
        print(state)
        for var, binds in binddict.items():
            print(var)
            for bind in binds:
                print(bind.tostr())
##                print(bind.dest)
##                print(type(bind.dest))
##                print(bind.msb)
##                print(type(bind.msb))
##                print(bind.lsb)
##                print(type(bind.lsb))
##                print(bind.ptr)
##                print(type(bind.ptr))
##                print(bind.alwaysinfo)
##                print(type(bind.alwaysinfo))
##                print(bind.parameterinfo)
##                print(type(bind.parameterinfo))
##                print("")
        print("")
    print("")
def main():
    INFO = "Control-flow analyzer for Verilog definitions"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_controlflow_analyzer.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()

    optparser = OptionParser()
    optparser.add_option("-v",
                         "--version",
                         action="store_true",
                         dest="showversion",
                         default=False,
                         help="Show the version")
    optparser.add_option("-t",
                         "--top",
                         dest="topmodule",
                         default="TOP",
                         help="Top module, Default=TOP")
    optparser.add_option("-s",
                         "--search",
                         dest="searchtarget",
                         action="append",
                         default=[],
                         help="Search Target Signal")
    optparser.add_option("--graphformat",
                         dest="graphformat",
                         default="png",
                         help="Graph file format, Default=png")
    optparser.add_option("--nograph",
                         action="store_true",
                         dest="nograph",
                         default=False,
                         help="Non graph generation")
    optparser.add_option("--nolabel",
                         action="store_true",
                         dest="nolabel",
                         default=False,
                         help="State Machine Graph without Labels")
    optparser.add_option("-I",
                         "--include",
                         dest="include",
                         action="append",
                         default=[],
                         help="Include path")
    optparser.add_option("-D",
                         dest="define",
                         action="append",
                         default=[],
                         help="Macro Definition")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       options.topmodule,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()
    fsm_vars = tuple(['fsm', 'state', 'count', 'cnt', 'step', 'mode'] +
                     options.searchtarget)

    canalyzer = VerilogControlflowAnalyzer(options.topmodule, terms, binddict,
                                           resolved_terms, resolved_binddict,
                                           constlist, fsm_vars)
    fsms = canalyzer.getFiniteStateMachines()

    for signame, fsm in fsms.items():
        print('# SIGNAL NAME: %s' % signame)
        print('# DELAY CNT: %d' % fsm.delaycnt)
        fsm.view()
        if not options.nograph:
            fsm.tograph(filename=util.toFlatname(signame) + '.' +
                        options.graphformat,
                        nolabel=options.nolabel)
        loops = fsm.get_loop()
        print('Loop')
        for loop in loops:
            print(loop)
예제 #26
0
class VlogAutoInst:
    """Verilog Auto Instantiation.

    Args:
    :param tuple flist: verilog file list. If macros defined, put macro files prior to design file.
    :param str top_mod: top module.
    """

    def __init__(self, flist, top_mod):
        self.mod = top_mod 
        self.flist = flist
        self.param_dict = None
        self.port_dict = None
        self.analyzer = VerilogDataflowAnalyzer(flist, top_mod)
        self.error = 0
        try:
            self.analyzer.generate()
        except DefinitionError as de:
            print(de)
            self.error = 1
        except ParseError as pe:
            print(pe)
            self.error = 2

        # get params and ports
        if self.error == 0:
            self.param_dict = self._get_params()
            self.port_dict = self._get_ports()

    def _get_param_value(self, param_list):
        param_dict = {}
        for k, v in self.analyzer.getBinddict().items():
            if k in param_list:
                if isinstance(v[0].tree, DFIntConst):
                    param_dict.update({str(k): v[0].tree})
                else:
                    print('Error: paramater tree is not a constant')
        return param_dict

    def _get_xsb_value(self, node):
        """Get the msb and lsb value of an terms.
        """

        node_val = None
        if isinstance(node, DFIntConst):
            node_val = node.eval()
        elif isinstance(node, DFOperator):
            node_val = int(eval(self._expr_map(node.tocode())))
        else:
            print(f'Invalid node format: {type(node)}:{node.tostr()}')
        return node_val

    def _expr_map(self, expr):
        """Replace parameters in expression with values.
        """

        new_expr = expr
        for k, v in self.param_dict.items():
            # change . to _
            name = str(k).replace('.', '_')
            new_expr = str(new_expr).replace(name, f'{v.eval()}')
        # print(f'expr={expr}, new_expr={new_expr}')
        return new_expr

    def _get_params(self):
        param_list = []
        for k, v in self.analyzer.getTerms().items():
            if 'Parameter' in v.termtype:
                param_list.append(v.name)
        return self._get_param_value(param_list)

    def _get_ports(self):
        port_dict = {}
        for k, v in self.analyzer.getTerms().items():
            port_dir = list({'Input', 'Output', 'Inout'} & v.termtype)
            if port_dir:
                msb_v, lsb_v = (None, None)
                direction = 'I' if port_dir[0] == 'Input' else \
                            ('O' if port_dir[0] == 'Output' else 'IO')
                msb_v = self._get_xsb_value(v.msb)
                lsb_v = self._get_xsb_value(v.lsb)
                port_dict.update({str(k).split('.')[-1]: {'dir': direction,
                                      'slice': f'[{msb_v}:{lsb_v}]' if msb_v != lsb_v else '',
                                      'instp': str(k).split('.')[-1],
                                      'type': 'W'
                                     }})
        return port_dict

    def reset(self, flist=None):
        """Re-instantiate the whole design.

        Args:
        :param tuple flist: new file list for parse. If set to None, use the old flist.
        """

        new_flist = self.flist if flist is None else flist
        self.analyzer = VerilogDataflowAnalyzer(new_flist, self.mod)
        self.analyzer.generate()
        # get params
        self.param_dict = self._get_params()
        # get port_dict
        self.port_dict = self._get_ports()

    def update(self, param_dict=None, port_dict=None, port_regexp=None):
        """Update parameter value and port based on custom changes.

        Args:
        :param dict param_dict: parameter dict {param: 'value'}
        :param dict port_dict: port dict {port_name: instport_name}
        :param tuple port_regexp: regexp for changing instport name, (pattern, sub_pattern)
        """

        # Update parameters' value
        if param_dict:
            # Convert str to DFIntConst first
            new_param_dict = {f'{self.mod}.{k}':DFIntConst(v) for k, v in param_dict.items()}
            self.param_dict.update(new_param_dict)
            # update port width
            self.port_dict = self._get_ports()

        # update instport name according to regexp and user's manual changes.
        if port_dict:
            for k, v in self.port_dict.items():
                if k in port_dict:
					# only need to update instp and type
                    self.port_dict[k]['type'] = port_dict[k]['type']
                    self.port_dict[k]['instp'] = port_dict[k]['instp']
        if port_regexp:
			# apply regexp on instp
            re_pat = re.compile(rf'{port_regexp[0]}')
            for k, v in self.port_dict.items():
                self.port_dict[k]['instp'] = re_pat.sub(rf'{port_regexp[1]}', v['instp'])

    def generate_code(self, inst_name, indent=0):
        """Generate instantiation code.
        """

        indent_lvl0 = ' ' * indent
        indent_lvl1 = f'{indent_lvl0}    '

        code = f'{indent_lvl0}{self.mod} '
        if self.param_dict:
            code += f'#(\n{indent_lvl1} .'
            # find the max length of parameter length
            max_k_len = max([len(str(k).split(".")[-1]) for k in self.param_dict.keys()])
            max_v_len = max([len(v.value) for v in self.param_dict.values()])
            param_list = [f'{str(k).split(".")[-1]:{max_k_len}} ({v.value:{max_v_len}})'
                          for k, v in self.param_dict.items()]
            code += f'\n{indent_lvl1},.'.join(param_list)
            code += f'\n{indent_lvl0}) '

        code += f'{inst_name} ( /* {directives["AI"]} */\n{indent_lvl1} .'
        # find the max length of port length
        len_list = [(len(k), len(f'{v["instp"]}{v["slice"]}')) for k, v in self.port_dict.items()]
        max_k_len, max_v_len = tuple(map(max, list(zip(*len_list))))
        # print(f'max_k={max_k_len}, max_v={max_v_len}')
        ports = [f'{k:{max_k_len}} ({v["instp"]+v["slice"]:{max_v_len}}) //{v["type"]}{v["dir"]}'
                 for k, v in self.port_dict.items()]
        code += f'\n{indent_lvl1},.'.join(ports)
        code += f'\n{indent_lvl0}); // end of {inst_name}'

        return code

    def generate_wire_declare(self, indent=0):
        """Generate wire declaration.
        """

        indent_lvl0 = ' ' * indent
        code = f'{indent_lvl0}'

        # find the max length of port width slice
        len_list = [(len(v["instp"]), len(v["slice"])) for v in self.port_dict.values()]
        max_instp_len, max_slice_len = tuple(map(max, list(zip(*len_list))))
        ports = [f'wire {v["slice"]:{max_slice_len}} {v["instp"]:{max_instp_len}};'
                 for v in self.port_dict.values() if v['type'] == 'W']
        code += f'\n{indent_lvl0}'.join(ports)
        return code


    def generate_port_declare(self, indent=0):
        """Generate external port declaration.
        """

        indent_lvl0 = ' ' * indent
        code = f'{indent_lvl0}'

        # find the max length of port width slice
        max_slice_len = max([len(v["slice"]) for v in self.port_dict.values()])
        ports = [(f'{"input" if v["dir"] == "I" else ("output" if v["dir"] == "O" else "inout")} '
                 f'{v["slice"]:{max_slice_len}} {v["instp"]}')
                 for v in self.port_dict.values() if v['type'] == 'P']
        code += f'\n{indent_lvl0},'.join(ports)
        return code
예제 #27
0
def main():
    INFO = "Dataflow walker"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_walker.py -t TOPMODULE -s TARGETSIGNAL file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()
    
    optparser = OptionParser()
    optparser.add_option("-v","--version",action="store_true",dest="showversion",
                         default=False,help="Show the version")
    optparser.add_option("-I","--include",dest="include",action="append",
                         default=[],help="Include path")
    optparser.add_option("-D",dest="define",action="append",
                         default=[],help="Macro Definition")
    optparser.add_option("-t","--top",dest="topmodule",
                         default="TOP",help="Top module, Default=TOP")
    optparser.add_option("--nobind",action="store_true",dest="nobind",
                         default=False,help="No binding traversal, Default=False")
    optparser.add_option("--noreorder",action="store_true",dest="noreorder",
                         default=False,help="No reordering of binding dataflow, Default=False")
    optparser.add_option("-s","--search",dest="searchtarget",action="append",
                         default=[],help="Search Target Signal")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    walker = VerilogDataflowWalker(options.topmodule, terms, binddict, resolved_terms,
                                   resolved_binddict, constlist)

    for target in options.searchtarget:
        tree = walker.walkBind(target)
        print('target: %s' % target)
        print(tree.tostr())
예제 #28
0
def main():
    INFO = "Active condition analyzer"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_active_analyzer.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()
    
    optparser = OptionParser()
    optparser.add_option("-v","--version",action="store_true",dest="showversion",
                         default=False,help="Show the version")
    optparser.add_option("-t","--top",dest="topmodule",
                         default="TOP",help="Top module, Default=TOP")
    optparser.add_option("-s","--search",dest="searchtarget",action="append",
                         default=[],help="Search Target Signal")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    canalyzer = VerilogActiveConditionAnalyzer(options.topmodule, terms, binddict, 
                                               resolved_terms, resolved_binddict, constlist)

    for target in options.searchtarget:
        signal = util.toTermname(target)

        active_conditions = canalyzer.getActiveConditions( signal )
        #active_conditions = canalyzer.getActiveConditions( signal, condition=splitter.active_modify )
        #active_conditions = canalyzer.getActiveConditions( signal, condition=splitter.active_unmodify )

        print('Active Cases: %s' % signal)
        for fsm_sig, active_conditions in sorted(active_conditions.items(), key=lambda x:str(x[0])):
            print('FSM: %s' % fsm_sig)
            for state, active_condition in sorted(active_conditions, key=lambda x:str(x[0])):
                s = []
                s.append('state: %d -> ' % state)
                if active_condition: s.append(active_condition.tocode())
                else: s.append('empty')
                print(''.join(s))
예제 #29
0
def main():
    INFO = "Verilog module signal/module dataflow analyzer"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_dataflow_analyzer.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()
    
    optparser = OptionParser()
    optparser.add_option("-v","--version",action="store_true",dest="showversion",
                         default=False,help="Show the version")
    optparser.add_option("-I","--include",dest="include",action="append",
                         default=[],help="Include path")
    optparser.add_option("-D",dest="define",action="append",
                         default=[],help="Macro Definition")
    optparser.add_option("-t","--top",dest="topmodule",
                         default="TOP",help="Top module, Default=TOP")
    optparser.add_option("--nobind",action="store_true",dest="nobind",
                         default=False,help="No binding traversal, Default=False")
    optparser.add_option("--noreorder",action="store_true",dest="noreorder",
                         default=False,help="No reordering of binding dataflow, Default=False")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    print('Directive:')
    for dr in sorted(directives, key=lambda x:str(x)):
        print(dr)

    instances = analyzer.getInstances()
    print('Instance:')
    for module, instname in sorted(instances, key=lambda x:str(x[1])):
        print((module, instname))

    if options.nobind:
        print('Signal:')
        signals = analyzer.getSignals()
        for sig in signals:
            print(sig)

        print('Const:')
        consts = analyzer.getConsts()
        for con in consts:
            print(con)

    else:
        terms = analyzer.getTerms()
        print('Term:')
        for tk, tv in sorted(terms.items(), key=lambda x:str(x[0])):
            print(tv.tostr())
   
        binddict = analyzer.getBinddict()
        print('Bind:')
        for bk, bv in sorted(binddict.items(), key=lambda x:str(x[0])):
            for bvi in bv:
                print(bvi.tostr())
def main():
    INFO = "Control-flow analyzer for Verilog definitions"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_controlflow_analyzer.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()
    
    optparser = OptionParser()
    optparser.add_option("-v","--version",action="store_true",dest="showversion",
                         default=False,help="Show the version")
    optparser.add_option("-t","--top",dest="topmodule",
                         default="TOP",help="Top module, Default=TOP")
    optparser.add_option("-s","--search",dest="searchtarget",action="append",
                         default=[],help="Search Target Signal")
    optparser.add_option("--graphformat",dest="graphformat",
                         default="png",help="Graph file format, Default=png")
    optparser.add_option("--nograph",action="store_true",dest="nograph",
                         default=False,help="Non graph generation")
    optparser.add_option("--nolabel",action="store_true",dest="nolabel",
                         default=False,help="State Machine Graph without Labels")
    optparser.add_option("-I","--include",dest="include",action="append",
                         default=[],help="Include path")
    optparser.add_option("-D",dest="define",action="append",
                         default=[],help="Macro Definition")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()
    fsm_vars = tuple(['fsm', 'state', 'count', 'cnt', 'step', 'mode'] + options.searchtarget)
    
    canalyzer = VerilogControlflowAnalyzer(options.topmodule, terms, binddict,
                                           resolved_terms, resolved_binddict, constlist, fsm_vars)
    fsms = canalyzer.getFiniteStateMachines()

    for signame, fsm in fsms.items():
        print('# SIGNAL NAME: %s' % signame)
        print('# DELAY CNT: %d' % fsm.delaycnt)
        fsm.view()
        if not options.nograph:
            fsm.tograph(filename=util.toFlatname(signame)+'.'+options.graphformat, nolabel=options.nolabel)
        loops = fsm.get_loop()
        print('Loop')
        for loop in loops:
            print(loop)
예제 #31
0
    optparser.add_option("-s","--search",dest="searchtarget",action="append",
                         default=[],help="Search Target Signal")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    canalyzer = VerilogActiveConditionAnalyzer(options.topmodule, terms, binddict, 
                                               resolved_terms, resolved_binddict, constlist)
예제 #32
0
def main():
    INFO = "Dataflow merge module"
    VERSION = pyverilog.__version__
    USAGE = "Usage: python example_merge.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()

    optparser = OptionParser()
    optparser.add_option("-v",
                         "--version",
                         action="store_true",
                         dest="showversion",
                         default=False,
                         help="Show the version")
    optparser.add_option("-I",
                         "--include",
                         dest="include",
                         action="append",
                         default=[],
                         help="Include path")
    optparser.add_option("-D",
                         dest="define",
                         action="append",
                         default=[],
                         help="Macro Definition")
    optparser.add_option("-t",
                         "--top",
                         dest="topmodule",
                         default="TOP",
                         help="Top module, Default=TOP")
    optparser.add_option("--nobind",
                         action="store_true",
                         dest="nobind",
                         default=False,
                         help="No binding traversal, Default=False")
    optparser.add_option(
        "--noreorder",
        action="store_true",
        dest="noreorder",
        default=False,
        help="No reordering of binding dataflow, Default=False")
    optparser.add_option("-s",
                         "--search",
                         dest="searchtarget",
                         action="append",
                         default=[],
                         help="Search Target Signal")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f):
            raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)
    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    merge = VerilogDataflowMerge(options.topmodule, terms, binddict,
                                 resolved_terms, resolved_binddict, constlist)

    for target in options.searchtarget:
        termname = util.toTermname(target)
        tree = merge.getTree(termname)
        print('target: %s' % target)
        print(tree.tostr())
예제 #33
0
def main():
    INFO = "Active condition analyzer (Obsoluted)"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_active_range.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()

    optparser = OptionParser()
    optparser.add_option("-v",
                         "--version",
                         action="store_true",
                         dest="showversion",
                         default=False,
                         help="Show the version")
    optparser.add_option("-t",
                         "--top",
                         dest="topmodule",
                         default="TOP",
                         help="Top module, Default=TOP")
    optparser.add_option("-s",
                         "--search",
                         dest="searchtarget",
                         action="append",
                         default=[],
                         help="Search Target Signal")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    aanalyzer = VerilogActiveAnalyzer(options.topmodule, terms, binddict,
                                      resolved_terms, resolved_binddict,
                                      constlist)

    for target in options.searchtarget:
        signal = util.toTermname(target)

        print('Active Conditions: %s' % signal)
        active_conditions = aanalyzer.getActiveConditions(signal)
        print(sorted(active_conditions, key=lambda x: str(x)))

        print('Changed Conditions')
        changed_conditions = aanalyzer.getChangedConditions(signal)
        print(sorted(changed_conditions, key=lambda x: str(x)))

        print('Changed Condition Dict')
        changed_conditiondict = aanalyzer.getChangedConditionsWithAssignments(
            signal)
        print(sorted(changed_conditiondict.items(), key=lambda x: str(x[0])))

        print('Unchanged Conditions')
        unchanged_conditions = aanalyzer.getUnchangedConditions(signal)
        print(sorted(unchanged_conditions, key=lambda x: str(x)))
예제 #34
0
def main():
    INFO = "Subset generator from Verilog dataflow definitions"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_subset.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()

    optparser = OptionParser()
    optparser.add_option("-v",
                         "--version",
                         action="store_true",
                         dest="showversion",
                         default=False,
                         help="Show the version")
    optparser.add_option("-I",
                         "--include",
                         dest="include",
                         action="append",
                         default=[],
                         help="Include path")
    optparser.add_option("-D",
                         dest="define",
                         action="append",
                         default=[],
                         help="Macro Definition")
    optparser.add_option("-t",
                         "--top",
                         dest="topmodule",
                         default="TOP",
                         help="Top module, Default=TOP")
    optparser.add_option("--nobind",
                         action="store_true",
                         dest="nobind",
                         default=False,
                         help="No binding traversal, Default=False")
    optparser.add_option(
        "--noreorder",
        action="store_true",
        dest="noreorder",
        default=False,
        help="No reordering of binding dataflow, Default=False")
    optparser.add_option("-s",
                         "--search",
                         dest="searchtarget",
                         action="append",
                         default=[],
                         help="Search Target Signal")
    optparser.add_option("--clockname",
                         dest="clockname",
                         default="CLK",
                         help="Clock signal name")
    optparser.add_option("--resetname",
                         dest="resetname",
                         default="RST_X",
                         help="Reset signal name")
    optparser.add_option("--clockedge",
                         dest="clockedge",
                         default="posedge",
                         help="Clock signal edge")
    optparser.add_option("--resetedge",
                         dest="resetedge",
                         default="negedge",
                         help="Reset signal edge")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    subset = VerilogSubset(options.topmodule, terms, binddict, resolved_terms,
                           resolved_binddict, constlist)

    subset.set_clock_info(options.clockname, options.clockedge)
    subset.set_reset_info(options.resetname, options.resetedge)

    sub_binds, sub_terms = subset.getBindSourceSubset(options.searchtarget)
    terms, parameter, assign, always_clockedge, always_combination = subset.getSubset(
        options.searchtarget)

    for k, v in terms.items():
        print(v.tocode())
    for k, v in parameter.items():
        print(v.tocode())
    for k, v in assign.items():
        for vv in v:
            print(vv.tocode())
    for k, v in always_clockedge.items():
        for vv in v:
            print(vv.tocode())
    for k, v in always_combination.items():
        for vv in v:
            print(vv.tocode())
예제 #35
0
def main():
    INFO = "Verilog module signal/module dataflow analyzer"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_dataflow_analyzer.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()

    optparser = OptionParser()
    optparser.add_option("-v",
                         "--version",
                         action="store_true",
                         dest="showversion",
                         default=False,
                         help="Show the version")
    optparser.add_option("-I",
                         "--include",
                         dest="include",
                         action="append",
                         default=[],
                         help="Include path")
    optparser.add_option("-D",
                         dest="define",
                         action="append",
                         default=[],
                         help="Macro Definition")
    optparser.add_option("-t",
                         "--top",
                         dest="topmodule",
                         default="TOP",
                         help="Top module, Default=TOP")
    optparser.add_option("--nobind",
                         action="store_true",
                         dest="nobind",
                         default=False,
                         help="No binding traversal, Default=False")
    optparser.add_option(
        "--noreorder",
        action="store_true",
        dest="noreorder",
        default=False,
        help="No reordering of binding dataflow, Default=False")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    print('Directive:')
    for dr in sorted(directives, key=lambda x: str(x)):
        print(dr)

    instances = analyzer.getInstances()
    print('Instance:')
    for module, instname in sorted(instances, key=lambda x: str(x[1])):
        print((module, instname))

    if options.nobind:
        print('Signal:')
        signals = analyzer.getSignals()
        for sig in signals:
            print(sig)

        print('Const:')
        consts = analyzer.getConsts()
        for con in consts:
            print(con)

    else:
        terms = analyzer.getTerms()
        print('Term:')
        for tk, tv in sorted(terms.items(), key=lambda x: str(x[0])):
            print(tv.tostr())

        binddict = analyzer.getBinddict()
        print('Bind:')
        for bk, bv in sorted(binddict.items(), key=lambda x: str(x[0])):
            for bvi in bv:
                print(bvi.tostr())
예제 #36
0
def main():
    INFO = "Subset generator from Verilog dataflow definitions"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_subset.py -t TOPMODULE file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()
    
    optparser = OptionParser()
    optparser.add_option("-v","--version",action="store_true",dest="showversion",
                         default=False,help="Show the version")
    optparser.add_option("-I","--include",dest="include",action="append",
                         default=[],help="Include path")
    optparser.add_option("-D",dest="define",action="append",
                         default=[],help="Macro Definition")
    optparser.add_option("-t","--top",dest="topmodule",
                         default="TOP",help="Top module, Default=TOP")
    optparser.add_option("--nobind",action="store_true",dest="nobind",
                         default=False,help="No binding traversal, Default=False")
    optparser.add_option("--noreorder",action="store_true",dest="noreorder",
                         default=False,help="No reordering of binding dataflow, Default=False")
    optparser.add_option("-s","--search",dest="searchtarget",action="append",
                         default=[],help="Search Target Signal")
    optparser.add_option("--clockname",dest="clockname",
                         default="CLK",help="Clock signal name")
    optparser.add_option("--resetname",dest="resetname",
                         default="RST_X",help="Reset signal name")
    optparser.add_option("--clockedge",dest="clockedge",
                         default="posedge",help="Clock signal edge")
    optparser.add_option("--resetedge",dest="resetedge",
                         default="negedge",help="Reset signal edge")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    subset = VerilogSubset(options.topmodule, terms, binddict, 
                           resolved_terms, resolved_binddict, constlist)

    subset.set_clock_info(options.clockname, options.clockedge)
    subset.set_reset_info(options.resetname, options.resetedge)

    sub_binds, sub_terms = subset.getBindSourceSubset(options.searchtarget)
    terms, parameter, assign, always_clockedge, always_combination = subset.getSubset(options.searchtarget)

    for k, v in terms.items():
        print(v.tocode())
    for k, v in parameter.items():
        print(v.tocode())
    for k, v in assign.items():
        for vv in v:
            print(vv.tocode())
    for k, v in always_clockedge.items():
        for vv in v:
            print(vv.tocode())
    for k, v in always_combination.items():
        for vv in v:
            print(vv.tocode())
예제 #37
0
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    walker = VerilogDataflowWalker(options.topmodule, terms, binddict,
                                   resolved_terms, resolved_binddict,
                                   constlist)
예제 #38
0
def main():
    INFO = "Graph generator from dataflow"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_graphgen.py -t TOPMODULE -s TARGETSIGNAL file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()

    optparser = OptionParser()
    optparser.add_option("-v",
                         "--version",
                         action="store_true",
                         dest="showversion",
                         default=False,
                         help="Show the version")
    optparser.add_option("-I",
                         "--include",
                         dest="include",
                         action="append",
                         default=[],
                         help="Include path")
    optparser.add_option("-D",
                         dest="define",
                         action="append",
                         default=[],
                         help="Macro Definition")
    optparser.add_option("-t",
                         "--top",
                         dest="topmodule",
                         default="TOP",
                         help="Top module, Default=TOP")
    optparser.add_option("--nobind",
                         action="store_true",
                         dest="nobind",
                         default=False,
                         help="No binding traversal, Default=False")
    optparser.add_option(
        "--noreorder",
        action="store_true",
        dest="noreorder",
        default=False,
        help="No reordering of binding dataflow, Default=False")
    optparser.add_option("-s",
                         "--search",
                         dest="searchtarget",
                         action="append",
                         default=[],
                         help="Search Target Signal")
    optparser.add_option("-o",
                         "--output",
                         dest="outputfile",
                         default="out.png",
                         help="Graph file name, Default=out.png")
    optparser.add_option("--identical",
                         action="store_true",
                         dest="identical",
                         default=False,
                         help="# Identical Laef, Default=False")
    optparser.add_option("--walk",
                         action="store_true",
                         dest="walk",
                         default=False,
                         help="Walk contineous signals, Default=False")
    optparser.add_option("--step",
                         dest="step",
                         type='int',
                         default=1,
                         help="# Search Steps, Default=1")
    optparser.add_option("--reorder",
                         action="store_true",
                         dest="reorder",
                         default=False,
                         help="Reorder the contineous tree, Default=False")
    optparser.add_option("--delay",
                         action="store_true",
                         dest="delay",
                         default=False,
                         help="Inset Delay Node to walk Regs, Default=False")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist,
                                       options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    graphgen = VerilogGraphGenerator(options.topmodule, terms, binddict,
                                     resolved_terms, resolved_binddict,
                                     constlist, options.outputfile)

    for target in options.searchtarget:
        graphgen.generate(target,
                          walk=options.walk,
                          identical=options.identical,
                          step=options.step,
                          reorder=options.reorder,
                          delay=options.delay)

    graphgen.draw()
예제 #39
0
    def get_dataflow(self, code_file_name, topmodule='', config_file=None):
        optparser = OptionParser()
        optparser.add_option("-t",
                             "--top",
                             dest="topmodule",
                             default="TOP",
                             help="Top module, Default=TOP")

        optparser.add_option("-I",
                             "--include",
                             dest="include",
                             action="append",
                             default=[],
                             help="Include path")
        optparser.add_option("-D",
                             dest="define",
                             action="append",
                             default=[],
                             help="Macro Definition")
        optparser.add_option("-S",
                             dest="config_file",
                             default=[],
                             help="config_file")
        optparser.add_option("-s",
                             "--search",
                             dest="searchtarget",
                             action="append",
                             default=[],
                             help="Search Target Signal")

        (options, args) = optparser.parse_args()

        if args:
            filelist = args
        elif code_file_name:
            if hasattr(code_file_name,
                       "__iter__") and not isinstance(code_file_name, str):
                filelist = code_file_name
            else:
                filelist = (code_file_name, )
        else:
            raise Exception("Verilog file is not assigned.")

        for f in filelist:
            if not os.path.exists(f): raise IOError("file not found: " + f)

        if not topmodule:
            topmodule = options.topmodule

        analyzer = VerilogDataflowAnalyzer(filelist,
                                           topmodule,
                                           preprocess_include=options.include,
                                           preprocess_define=options.define)
        analyzer.generate()

        directives = analyzer.get_directives()
        terms = analyzer.getTerms()
        binddict = analyzer.getBinddict()

        optimizer = VerilogDataflowOptimizer(terms, binddict)

        optimizer.resolveConstant()
        resolved_terms = optimizer.getResolvedTerms()
        resolved_binddict = optimizer.getResolvedBinddict()
        constlist = optimizer.getConstlist()
        if config_file:
            self.config_file = config_file
        elif options.config_file:
            self.config_file = options.config_file

        fsm_vars = (['fsm', 'state', 'count', 'cnt', 'step', 'mode'] +
                    options.searchtarget)
        return options.topmodule, terms, binddict, resolved_terms, resolved_binddict, constlist, fsm_vars
예제 #40
0
def main():
    INFO = "Graph generator from dataflow"
    VERSION = pyverilog.utils.version.VERSION
    USAGE = "Usage: python example_graphgen.py -t TOPMODULE -s TARGETSIGNAL file ..."

    def showVersion():
        print(INFO)
        print(VERSION)
        print(USAGE)
        sys.exit()
    
    optparser = OptionParser()
    optparser.add_option("-v","--version",action="store_true",dest="showversion",
                         default=False,help="Show the version")
    optparser.add_option("-I","--include",dest="include",action="append",
                         default=[],help="Include path")
    optparser.add_option("-D",dest="define",action="append",
                         default=[],help="Macro Definition")
    optparser.add_option("-t","--top",dest="topmodule",
                         default="TOP",help="Top module, Default=TOP")
    optparser.add_option("--nobind",action="store_true",dest="nobind",
                         default=False,help="No binding traversal, Default=False")
    optparser.add_option("--noreorder",action="store_true",dest="noreorder",
                         default=False,help="No reordering of binding dataflow, Default=False")
    optparser.add_option("-s","--search",dest="searchtarget",action="append",
                         default=[],help="Search Target Signal")
    optparser.add_option("-o","--output",dest="outputfile",
                         default="out.png",help="Graph file name, Default=out.png")
    optparser.add_option("--identical",action="store_true",dest="identical",
                         default=False,help="# Identical Laef, Default=False")
    optparser.add_option("--walk",action="store_true",dest="walk",
                         default=False,help="Walk contineous signals, Default=False")
    optparser.add_option("--step",dest="step",type='int', 
                         default=1,help="# Search Steps, Default=1")
    optparser.add_option("--reorder",action="store_true",dest="reorder",
                         default=False,help="Reorder the contineous tree, Default=False")
    optparser.add_option("--delay",action="store_true",dest="delay",
                         default=False,help="Inset Delay Node to walk Regs, Default=False")
    (options, args) = optparser.parse_args()

    filelist = args
    if options.showversion:
        showVersion()

    for f in filelist:
        if not os.path.exists(f): raise IOError("file not found: " + f)

    if len(filelist) == 0:
        showVersion()

    analyzer = VerilogDataflowAnalyzer(filelist, options.topmodule,
                                       noreorder=options.noreorder,
                                       nobind=options.nobind,
                                       preprocess_include=options.include,
                                       preprocess_define=options.define)
    analyzer.generate()

    directives = analyzer.get_directives()
    terms = analyzer.getTerms()
    binddict = analyzer.getBinddict()

    optimizer = VerilogDataflowOptimizer(terms, binddict)

    optimizer.resolveConstant()
    resolved_terms = optimizer.getResolvedTerms()
    resolved_binddict = optimizer.getResolvedBinddict()
    constlist = optimizer.getConstlist()

    graphgen = VerilogGraphGenerator(options.topmodule, terms, binddict, 
                                     resolved_terms, resolved_binddict, constlist, options.outputfile)

    for target in options.searchtarget:
        graphgen.generate(target, walk=options.walk, identical=options.identical, 
                          step=options.step, reorder=options.reorder, delay=options.delay)

    graphgen.draw()