File: autogen.py

package info (click to toggle)
intel-graphics-compiler 1.0.17791.18-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 102,312 kB
  • sloc: cpp: 935,343; lisp: 286,143; ansic: 16,196; python: 3,279; yacc: 2,487; lex: 1,642; pascal: 300; sh: 174; makefile: 27
file content (249 lines) | stat: -rwxr-xr-x 9,495 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# ========================== begin_copyright_notice ============================
#
# Copyright (C) 2017-2023 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
# =========================== end_copyright_notice =============================

import os
import sys
import errno
import re
from typing import List, Tuple, TextIO, Callable, Generator

class DeclHeader:
    # line contains the entire string of the line the decl was found on
    line: str
    # declName is just the identifier name
    declName: str
    # fields contains a list of all the names of the fields in the structure
    fields: List[str]

    def __init__(self, line: str, declName: str, fields: List[str]):
        self.line     = line
        self.declName = declName
        self.fields   = fields

enumNames: List[DeclHeader] = []
structureNames: List[DeclHeader] = []

def parseCmdArgs() -> Tuple[str, str]:
    if (len(sys.argv) != 3):
        sys.exit("usage: autogen.py <path_to_MDFrameWork.h> <path_to_MDNodeFuncs.gen>")

    __MDFrameWorkFile__ = sys.argv[1]
    __genFile__         = sys.argv[2]

    if not os.path.isfile(__MDFrameWorkFile__):
        sys.exit(f"Could not find the file {__MDFrameWorkFile__}")

    __genDir__ = os.path.dirname(__genFile__)
    if not os.path.exists(__genDir__):
        try:
            os.makedirs(__genDir__)
        except OSError as err:
            if err.errno != errno.EEXIST:
                sys.exit(f"Failed to create the directory {__genDir__}")

    return __MDFrameWorkFile__ , __genFile__

def extractStructField(line: str, declHeader: DeclHeader):
    if line.strip() == '':
        return
    vars = line.split()
    if "=" in line:
        declHeader.fields.append(vars[vars.index("=") - 1] + ";")
    else:
        declHeader.fields.append(vars[-1])

def extractEnumVal(line: str, declHeader: DeclHeader):
    vars = line.split()
    if len(vars) == 0 or "{" in line:
        return

    val = vars[0]
    if val[-1] == ',':
        val = val[:-1]

    declHeader.fields.append(val)

def lines(s: str) -> Generator[str, None, None]:
    for line in s.split('\n'):
        yield line

def parseHeader(fileContents: str):
    insideIGCNameSpace = False
    pcount = 0
    file = lines(fileContents)
    for line in file:
        line = line.split("//")[0]
        if "namespace IGC" in line:
            while "{" not in line:
                line = next(file, None)
                if line is None:
                    sys.exit('missing opening brace!')
            insideIGCNameSpace = True
            pcount += 1
        if insideIGCNameSpace:
            blockType = re.search("struct|enum", line)
            if blockType:
                words = line.split()
                idx = 2 if 'class' in words else 1
                foundDecl = DeclHeader(line, words[idx], [])
                opcount = pcount
                namesList = structureNames
                extractFunc = extractStructField
                if blockType[0] == 'enum':
                    namesList = enumNames
                    extractFunc = extractEnumVal
                while True:
                    line = next(file, None)
                    if line is None:
                        sys.exit(f"EOF reached with unclosed enum or struct, check formatting")
                    line = line.split("//")[0]
                    pcount += line.count("{") - line.count("}")
                    if pcount <= opcount:
                        break
                    extractFunc(re.sub("{|}","", line), foundDecl)
                assert pcount == opcount, f"Unexpected struct/enum ending, check formatting"
                namesList.append(foundDecl)
            elif "}" in line and "};" not in line:
                insideIGCNameSpace = False
                pcount -= 1
    assert pcount == 0, f"EOF reached, with unclosed IGC namespace, check formatting"

def stripBlockComments(text: str) -> str:
    return re.sub(r'/\*(.|\s)*?\*/', '', text)

def expandIncludes(fileName: str) -> str:
    try:
        file = open(fileName, 'r')
    except:
        sys.exit(f"Failed to open the file {fileName}")

    text = file.read()
    while True:
        # look for includes of the form: #include "myinclude.h" // ^MDFramework^
        includes: List[Tuple[str, str]] = []
        for m in re.finditer(r'#include\s+"(\S+)"\s*//\s*\^MDFramework\^:\s*(\S+)', text):
            include_file = os.path.basename(m.group(1))
            relative_path = m.group(2)
            parent_dir = os.path.dirname(fileName)
            include_file_path = os.path.normpath(
                os.path.join(parent_dir, relative_path, include_file))
            includes.append((m.group(0), include_file_path))

        if len(includes) == 0:
            break

        for (include_string, include_path) in includes:
            try:
                file = open(include_path, 'r')
            except:
                sys.exit(f"Failed to open the file {include_path}")
            include_contents = file.read()
            text = text.replace(include_string, include_contents)

    return text

def printStructCalls(structDecl: DeclHeader, outputFile: TextIO):
    outputFile.write("    Metadata* v[] = \n")
    outputFile.write("    { \n")
    outputFile.write("        MDString::get(module->getContext(), name),\n")
    for item in structDecl.fields:
        item = item[:-1]
        outputFile.write(f"        CreateNode({structDecl.declName}Var.{item}, module, ")
        outputFile.write(f'"{item}"')
        outputFile.write("),\n")
    outputFile.write("    };\n")
    outputFile.write("    MDNode* node = MDNode::get(module->getContext(), v);\n")
    outputFile.write("    return node;\n")

def printEnumCalls(enumDecl: DeclHeader, outputFile: TextIO):
    outputFile.write("    StringRef enumName;\n")
    outputFile.write(f"    switch({enumDecl.declName}Var)\n")
    outputFile.write("    {\n")
    for item in enumDecl.fields:
        outputFile.write(f"        case IGC::{enumDecl.declName}::{item}:\n")
        outputFile.write("            enumName = ")
        outputFile.write(f'"{item}"')
        outputFile.write(";\n")
        outputFile.write("            break;\n" )
    outputFile.write("    }\n")
    outputFile.write("    Metadata* v[] = \n")
    outputFile.write("    { \n")
    outputFile.write("        MDString::get(module->getContext(), name),\n")
    outputFile.write("        MDString::get(module->getContext(), enumName),\n")
    outputFile.write("    };\n")
    outputFile.write("    MDNode* node = MDNode::get(module->getContext(), v);\n")
    outputFile.write("    return node;\n")

def printStructReadCalls(structDecl: DeclHeader, outputFile: TextIO):
     for item in structDecl.fields:
        item = item[:-1]
        outputFile.write(f"    readNode({structDecl.declName}Var.{item}, node , ")
        outputFile.write(f'"{item}"')
        outputFile.write(");\n")

def printEnumReadCalls(enumDecl: DeclHeader, outputFile: TextIO):
    outputFile.write("    StringRef s = cast<MDString>(node->getOperand(1))->getString();\n")
    outputFile.write("    std::string str = s.str();\n")
    outputFile.write(f"    {enumDecl.declName}Var = (IGC::{enumDecl.declName})(0);\n")

    for item in enumDecl.fields:
        outputFile.write(f'    if((str.size() == sizeof("{item}")-1) && (::memcmp(str.c_str(),')
        outputFile.write(f'"{item}"')
        outputFile.write(",str.size())==0))\n")
        outputFile.write("    {\n")
        outputFile.write(f"            {enumDecl.declName}Var = IGC::{enumDecl.declName}::{item};\n")
        outputFile.write("    } else\n")

    outputFile.write("    {\n")
    outputFile.write(f"            {enumDecl.declName}Var = (IGC::{enumDecl.declName})(0);\n")
    outputFile.write("    }\n")

def emitCodeBlock(names: List[DeclHeader], fmtFn: Callable[[str], str], printFn: Callable[[DeclHeader, TextIO], None], outputFile: TextIO):
    for item in names:
        outputFile.write(fmtFn(item.declName))
        outputFile.write("{\n")
        printFn(item, outputFile)
        outputFile.write("}\n\n")

def emitEnumCreateNode(outputFile: TextIO):
    def fmtFn(item: str):
        return f"MDNode* CreateNode(IGC::{item} {item}Var, Module* module, StringRef name)\n"
    emitCodeBlock(enumNames, fmtFn, printEnumCalls, outputFile)

def emitStructCreateNode(outputFile: TextIO):
    def fmtFn(item: str):
        return f"MDNode* CreateNode(const IGC::{item}& {item}Var, Module* module, StringRef name)\n"
    emitCodeBlock(structureNames, fmtFn, printStructCalls, outputFile)

def emitEnumReadNode(outputFile: TextIO):
    def fmtFn(item: str):
        return f"void readNode( IGC::{item} &{item}Var, MDNode* node)\n"
    emitCodeBlock(enumNames, fmtFn, printEnumReadCalls, outputFile)

def emitStructReadNode(outputFile: TextIO):
    def fmtFn(item: str):
        return f"void readNode( IGC::{item} &{item}Var, MDNode* node)\n"
    emitCodeBlock(structureNames, fmtFn, printStructReadCalls, outputFile)

def genCode(fileName: str):
    try:
        outputFile = open(fileName, 'w')
    except:
        sys.exit(f"Failed to open the file {fileName}")

    emitEnumCreateNode(outputFile)
    emitStructCreateNode(outputFile)
    emitEnumReadNode(outputFile)
    emitStructReadNode(outputFile)

if __name__ == '__main__':
    __MDFrameWorkFile__ , __genFile__ = parseCmdArgs()
    expansion = expandIncludes(__MDFrameWorkFile__)
    expansion = stripBlockComments(expansion)
    parseHeader(expansion)
    genCode(__genFile__)