firmware_tools/logic_memory_mapper/gen_hal.py

351 lines
15 KiB
Python

# -----------------------------------------------------------------------------
# Title : C++ register definition package generator
# Project : Generic FW tools
# -----------------------------------------------------------------------------
# File : gen_cpp.py
# Author : Simon Southwell
# Company : Global Inkjet Systems
# Created : 2017-12-04
# Last update: 2017-12-11
# Platform :
# Standard : Python 3.x
# -----------------------------------------------------------------------------
# Description:
# Definition of class to read JSON register definitions and generate a set
# of C++ declarations with constant definitions for address offsets and
# field start bits and masks for bit-slicing the sub-fields. Inherits
# MemMapperBase for methods to read JSON files and produce a model.
# -----------------------------------------------------------------------------
# Copyright (c) 2017 Global Inkjet Systems
# -----------------------------------------------------------------------------
import os
import sys
import argparse
# Import base class to locate and read JSON files, and present a model
# to derived child class.
import memMapperBase
from memMapperBase import MemMapperBase, attr, regtype
from gen_cpp import MemMapperCpp
# ---------------------------------------------------------
# ---------------------------------------------------------
class MemMapperHal(MemMapperBase):
def __init__(self):
print('MemMapperHal')
self.__useByteAddrs = False
MemMapperBase.__init__(self)
# ---------------------------------------------------------
# Configure the byte address output mode
# ---------------------------------------------------------
def setByteAddrMode(self, mode):
self.__useByteAddrs = mode
# ---------------------------------------------------------
# Open the function declaration file, and o/p preliminaries
# ---------------------------------------------------------
@staticmethod
def __openFuncFile(srcDir, sep, ip, opSuffix) :
# Open up the file for the field access functions
funcsFilename = srcDir + sep + ip + opSuffix + '.cpp'
ffp = open(funcsFilename, 'w')
ffp.write('#include <stdint.h>\n')
ffp.write('#include <' + ip + '.h>\n\n')
return ffp
# ---------------------------------------------------------
# Genereate a field name string from data
# ---------------------------------------------------------
@staticmethod
def __genFieldNameStr(bus, ip, regName, fieldName) :
fieldNameStr = bus.upper() + '_' + ip.upper() + '_' + regName.upper() + '_' + fieldName.upper()
return fieldNameStr
# ---------------------------------------------------------
# Generate a set of constant functions, and output to write
# streams
# ---------------------------------------------------------
def __genConstFuncs(self, wfp, ifp, bus, ip, regDict, regName, colWidth, funcSuffix='', constSuffix=''):
# Extract the fields section from the model
fields = regDict[regName][attr.FIELDS]
# Loop through each field entry
for fieldName in fields:
if fields[fieldName][attr.TYPE] != regtype.RESERVED:
fieldNameStr = self.__genFieldNameStr(bus, ip, regName, fieldName)
fieldMskStr = fieldNameStr + constSuffix
funcName = self._underScore2LowCamelCase(fieldName) + self._underScore2CamelCase(regName) + funcSuffix + '()'
if len(funcName) < colWidth:
funcName += ' ' * (colWidth - len(funcName))
rootStr = 'uint32_t ' + funcName
wfp.write(' inline ' + rootStr + ' const override {return ' + fieldMskStr + ';}\n')
ifp.write(' virtual ' + rootStr + ' const = 0;\n')
# ---------------------------------------------------------
# Overload virtual function with specific output generation,
# and generate a C/C++ header file with some useful
# constants in it.
# ---------------------------------------------------------
def genOutput(self, ip, opDir='', opSuffix=''):
colWidth = 60
ipCC = self._underScore2CamelCase(ip)
ipLCC = self._underScore2LowCamelCase(ip)
# ipCAP = ip.capitalize()
# Fetch the JSON path and the dictionary with the parsed data
jsonPath, jsonDict = self._getModel(ip)
# What's the path separator? Usually '\\' for windows, else '/'
sep = os.sep
# Generate specific output. Assumes src/ exists (or will be created) in level above JSON file location.
if opDir == '':
srcDir = sep.join(jsonPath.split(sep)[:-2]) + sep + 'src'
else:
srcDir = opDir
# Check destination directory exists, and create it if not
if not os.path.exists(srcDir) :
os.makedirs(srcDir)
for jsonBusDict in jsonDict :
# Get the bus name from the dictionary
bus = jsonBusDict[attr.BUS]
# If a hierarchy block, skip
# if attr.SUB_BLOCKS in jsonBusDict:
# self.__processSubBlocks(jsonBusDict, srcDir, bus, ip, sep, opSuffix)
if attr.REGISTERS not in jsonBusDict :
continue
regDict = jsonBusDict[attr.REGISTERS]
regKeys = regDict.keys()
# Open the main class definition output file
writeFileName = srcDir + sep + 'C' + ipCC + opSuffix + 'FPGA_auto.h'
wfp = open(writeFileName, 'w')
# Open the injection class definition output file
writeFileName = srcDir + sep + 'IFPGA' + ipLCC + opSuffix + '_auto.h'
ifp = open(writeFileName, 'w')
# Open template file for reading
templateFname = os.path.dirname(sys.argv[0]) + sep + 'templates' + sep + 'template_hal.h'
tfp = open(templateFname, 'r')
# Read in each line of the template, looking for tags
for line in tfp :
# If the line has no tags, send straight to output, unmodified
if '%%' not in line :
wfp.write(line)
ifp.write(line)
# When a tag present...
else :
# Split the line around the tag
tagLineSplit = line.split('%%')
# The tag is the second entry of the split list
tagStr = tagLineSplit[1]
# Decode the tag, and generate the appropriate output accordingly
if tagStr == 'HEADER' :
stemStr = ipCC + 'FPGA_auto.h\n *\n * >>> AUTO-GENERATED. DO NOT EDIT. <<<\n *\n */\n'
wfp.write('/*\n * C' + stemStr)
ifp.write('/*\n * I' + stemStr)
if tagStr == 'INCLUDEDEFS' :
stemStr = ip.upper() + 'FPGA_AUTO_H_\n'
wfp.write('#ifndef C' + stemStr)
wfp.write('#define C' + stemStr)
ifp.write('#ifndef I' + stemStr)
ifp.write('#define I' + stemStr)
if tagStr == 'INCLUDES' :
wfp.write('#include <IFPGA' + ipLCC + '.h>\n')
wfp.write('#include "' + ip + '.h"\n')
ifp.write('#include <stdint.h>\n')
if tagStr == 'CLASS' :
wfp.write('class C' + ipCC + 'FPGA_AUTO : public I' + ip.capitalize() + 'FPGA\n')
ifp.write('class I' + ipCC + 'FPGA_AUTO\n')
if tagStr == 'CONSTRUCTORS' :
stemStr = ipCC + 'FPGA_AUTO()'
wfp.write(' C' + stemStr + '{};\n')
wfp.write(' virtual ~C' + stemStr + '{};\n')
ifp.write(' I' + stemStr + '{};\n')
ifp.write(' virtual ~I' + stemStr + '{};\n')
if tagStr == 'OFFSETS' :
# Process the register offsets
for regName in regKeys:
addrVal = int(regDict[regName][attr.ADDRESS], 0)
if self.__useByteAddrs:
addrVal *= 4
# addrStr = '0x' + format(addrVal, '08x')
addrNameStr = bus.upper() + '_' + ip.upper() + '_' + regName.upper()
funcName = self._underScore2LowCamelCase(regName) + 'Offset()'
if len(funcName) < colWidth:
funcName += ' ' * (colWidth - len(funcName))
rootStr = 'uint32_t ' + funcName
wfp.write(' inline ' + rootStr + ' const override {return ' + addrNameStr + '; }\n')
ifp.write(' virtual ' + rootStr + ' const = 0;\n')
if tagStr == 'MASKS':
for regName in regKeys:
# If there are fields for this register, process them here
if attr.FIELDS in regDict[regName] :
self.__genConstFuncs(wfp, ifp, bus, ip, regDict, regName, colWidth, 'Mask', '_MASK')
if tagStr == 'BITPOS':
for regName in regKeys:
# If there are fields for this register, process them here
if attr.FIELDS in regDict[regName]:
self.__genConstFuncs(wfp, ifp, bus, ip, regDict, regName, colWidth, 'BitPos', '')
if tagStr == 'EXTRACTFUNCS' :
for regName in regKeys:
# If there are fields for this register, process them here
if attr.FIELDS in regDict[regName] :
# Extract the fields section from the model
fields = regDict[regName][attr.FIELDS]
# Loop through each field entry
for fieldName in fields:
if fields[fieldName][attr.TYPE] != regtype.RESERVED:
fieldNameStr = bus.upper() + '_' + ip.upper() + '_' + regName.upper() + '_' + fieldName.upper()
funcDeclaration = self._underScore2CamelCase(fieldNameStr) + '(uint32_t regVal)'
if len(funcDeclaration) < colWidth:
funcDeclaration += ' ' * (colWidth - len(funcDeclaration))
fieldNameCC = self._underScore2LowCamelCase(fieldName)
maskName = fieldNameCC + self._underScore2CamelCase(
regName) + 'Mask()'
bitPosName = fieldNameCC + self._underScore2CamelCase(
regName) + 'BitPos()'
wfp.write(' inline uint32_t ' + funcDeclaration + ' override {return ((regVal & ' + maskName + ') >> ' + bitPosName + '); }\n')
ifp.write(' virtual uint32_t ' + funcDeclaration + ' = 0;\n')
if tagStr == 'INJECTFUNCS' :
for regName in regKeys:
# If there are fields for this register, process them here
if attr.FIELDS in regDict[regName] :
# Extract the fields section from the model
fields = regDict[regName][attr.FIELDS]
# Loop through each field entry
for fieldName in fields:
if fields[fieldName][attr.TYPE] != regtype.RESERVED:
fieldNameStr = regName.upper() + '_' + fieldName.upper()
funcDeclaration = 'build' + self._underScore2CamelCase(fieldNameStr) + \
'(uint32_t regVal, uint32_t val)'
if len(funcDeclaration) < colWidth:
funcDeclaration += ' ' * (colWidth - len(funcDeclaration))
fieldNameCC = self._underScore2LowCamelCase(fieldName)
maskName = fieldNameCC + self._underScore2CamelCase(
regName) + 'Mask()'
bitPosName = fieldNameCC + self._underScore2CamelCase(
regName) + 'BitPos()'
wfp.write(' inline uint32_t ' + funcDeclaration +
' const override {return (regVal & ~' +
maskName + ') | ((val << ' + bitPosName + ') & ' + maskName + '); }\n')
ifp.write(' virtual uint32_t ' + funcDeclaration + ' const = 0;\n')
if tagStr == 'ENDIF' :
wfp.write('#endif /* C' + ip.upper() + 'FPGA_AUTO_H_ */\n')
# ifp.write('typedef I' + ipCC + 'FPGA* I' + ip.upper() + 'FPGA_PTR;\n\n')
ifp.write('#endif\n')
ifp.close()
wfp.close()
# --------------------------------------------------------------
# Parse the command line arguments
#
def processCmdLine():
# Create a parser object
parser = argparse.ArgumentParser(description='Process command line options.')
# Process common command line options with inherited static base class method
MemMapperHal.processCmdLine(parser)
return parser.parse_args()
# ###############################################################
# Only run if not imported (to test)
#
if __name__ == '__main__':
memMap = MemMapperHal()
memMapHdrs = MemMapperCpp()
# Process the command line options
cmdArgs = processCmdLine()
# Do initialisation for text object specific configurations
memMap.setByteAddrMode(True)
memMapHdrs.setByteAddrMode(True)
memMapHdrs.setHeadersMode(True)
# Run the program for C++ definitions generation
memMapHdrs.run(cmdArgs.topBlock, cmdArgs.busList, cmdArgs.repoDir, cmdArgs.opDir, cmdArgs.opFileSuffix, 'cpp', cmdArgs.jsonFile, cmdArgs.buildDir, cmdArgs.qsysSuffix)
# Run the program for C++ class generation
memMap.run(cmdArgs.topBlock, cmdArgs.busList, cmdArgs.repoDir, cmdArgs.opDir, cmdArgs.opFileSuffix, 'cpp', cmdArgs.jsonFile, cmdArgs.buildDir, cmdArgs.qsysSuffix)
del memMap