3 # Copyright (C) 2007 The Android Open Source Project
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
18 # Using instructions from an architecture-specific config file, generate C
19 # and assembly source files for the Dalvik interpreter.
22 import sys, string, re, time
23 from string import Template
25 interp_defs_file = "../../libdex/DexOpcodes.h" # need opcode list
26 kNumPackedOpcodes = 256 # TODO: Derive this from DexOpcodes.h.
29 handler_size_bits = -1000
30 handler_size_bytes = -1000
31 in_op_start = 0 # 0=not started, 1=started, 2=ended
35 label_prefix = ".L" # use ".L" to hide labels from gdb
38 class DataParseError(SyntaxError):
39 "Failure when parsing data file"
42 # Set any omnipresent substitution values.
44 def getGlobalSubDict():
45 return { "handler_size_bits":handler_size_bits,
46 "handler_size_bytes":handler_size_bytes }
49 # Parse arch config file --
50 # Set handler_size_bytes to the value of tokens[1], and handler_size_bits to
51 # log2(handler_size_bytes). Throws an exception if "bytes" is not a power
54 def setHandlerSize(tokens):
55 global handler_size_bits, handler_size_bytes
57 raise DataParseError("handler-size requires one argument")
58 if handler_size_bits != -1000:
59 raise DataParseError("handler-size may only be set once")
61 # compute log2(n), and make sure n is a power of 2
62 handler_size_bytes = bytes = int(tokens[1])
65 bytes //= 2 # halve with truncating division
68 if handler_size_bytes == 0 or handler_size_bytes != (1 << bits):
69 raise DataParseError("handler-size (%d) must be power of 2 and > 0" \
71 handler_size_bits = bits
74 # Parse arch config file --
75 # Copy a file in to the C or asm output file.
77 def importFile(tokens):
79 raise DataParseError("import requires one argument")
81 if source.endswith(".c"):
82 appendSourceFile(tokens[1], getGlobalSubDict(), c_fp, None)
83 elif source.endswith(".S"):
84 appendSourceFile(tokens[1], getGlobalSubDict(), asm_fp, None)
86 raise DataParseError("don't know how to import %s (expecting .c/.S)"
90 # Parse arch config file --
91 # Copy a file in to the C or asm output file.
93 def setAsmStub(tokens):
96 raise DataParseError("import requires one argument")
98 stub_fp = open(tokens[1])
99 asm_stub_text = stub_fp.readlines()
102 raise DataParseError("unable to load asm-stub: %s" % str(err))
106 # Parse arch config file --
107 # Start of opcode list.
111 global default_op_dir
113 raise DataParseError("opStart takes a directory name argument")
115 raise DataParseError("opStart can only be specified once")
116 default_op_dir = tokens[1]
120 # Parse arch config file --
121 # Set location of a single opcode's source file.
124 #global opcode_locations
126 raise DataParseError("op requires exactly two arguments")
128 raise DataParseError("op statements must be between opStart/opEnd")
130 index = opcodes.index(tokens[1])
132 raise DataParseError("unknown opcode %s" % tokens[1])
133 if opcode_locations.has_key(tokens[1]):
134 print "Warning: op overrides earlier %s (%s -> %s)" \
135 % (tokens[1], opcode_locations[tokens[1]], tokens[2])
136 opcode_locations[tokens[1]] = tokens[2]
139 # Parse arch config file --
140 # End of opcode list; emit instruction blocks.
145 raise DataParseError("opEnd takes no arguments")
147 raise DataParseError("opEnd must follow opStart, and only appear once")
154 # Extract an ordered list of instructions from the VM sources. We use the
155 # "goto table" definition macro, which has exactly kNumPackedOpcodes
160 opcode_fp = open(interp_defs_file)
161 opcode_re = re.compile(r"^\s*H\(OP_(\w+)\),.*", re.DOTALL)
162 for line in opcode_fp:
163 match = opcode_re.match(line)
166 opcodes.append("OP_" + match.group(1))
169 if len(opcodes) != kNumPackedOpcodes:
170 print "ERROR: found %d opcodes in Interp.h (expected %d)" \
171 % (len(opcodes), kNumPackedOpcodes)
172 raise SyntaxError, "bad opcode count"
177 # Load and emit opcodes for all kNumPackedOpcodes instructions.
179 def loadAndEmitOpcodes():
181 assert len(opcodes) == kNumPackedOpcodes
182 need_dummy_start = False
184 # point dvmAsmInstructionStart at the first handler or stub
185 asm_fp.write("\n .global dvmAsmInstructionStart\n")
186 asm_fp.write(" .type dvmAsmInstructionStart, %function\n")
187 asm_fp.write("dvmAsmInstructionStart = " + label_prefix + "_OP_NOP\n")
188 asm_fp.write(" .text\n\n")
190 for i in xrange(kNumPackedOpcodes):
193 if opcode_locations.has_key(op):
194 location = opcode_locations[op]
196 location = default_op_dir
199 loadAndEmitC(location, i)
200 if len(asm_stub_text) == 0:
201 need_dummy_start = True
203 loadAndEmitAsm(location, i, sister_list)
205 # For a 100% C implementation, there are no asm handlers or stubs. We
206 # need to have the dvmAsmInstructionStart label point at OP_NOP, and it's
207 # too annoying to try to slide it in after the alignment psuedo-op, so
208 # we take the low road and just emit a dummy OP_NOP here.
210 asm_fp.write(" .balign %d\n" % handler_size_bytes)
211 asm_fp.write(label_prefix + "_OP_NOP: /* dummy */\n");
213 asm_fp.write("\n .balign %d\n" % handler_size_bytes)
214 asm_fp.write(" .size dvmAsmInstructionStart, .-dvmAsmInstructionStart\n")
215 asm_fp.write(" .global dvmAsmInstructionEnd\n")
216 asm_fp.write("dvmAsmInstructionEnd:\n")
218 emitSectionComment("Sister implementations", asm_fp)
219 asm_fp.write(" .global dvmAsmSisterStart\n")
220 asm_fp.write(" .type dvmAsmSisterStart, %function\n")
221 asm_fp.write(" .text\n")
222 asm_fp.write(" .balign 4\n")
223 asm_fp.write("dvmAsmSisterStart:\n")
224 asm_fp.writelines(sister_list)
226 asm_fp.write("\n .size dvmAsmSisterStart, .-dvmAsmSisterStart\n")
227 asm_fp.write(" .global dvmAsmSisterEnd\n")
228 asm_fp.write("dvmAsmSisterEnd:\n\n")
231 # Load a C fragment and emit it, then output an assembly stub.
233 def loadAndEmitC(location, opindex):
234 op = opcodes[opindex]
235 source = "%s/%s.c" % (location, op)
237 print " emit %s --> C" % source
238 dict = getGlobalSubDict()
239 dict.update({ "opcode":op, "opnum":opindex })
241 appendSourceFile(source, dict, c_fp, None)
243 if len(asm_stub_text) != 0:
244 emitAsmStub(asm_fp, dict)
247 # Load an assembly fragment and emit it.
249 def loadAndEmitAsm(location, opindex, sister_list):
250 op = opcodes[opindex]
251 source = "%s/%s.S" % (location, op)
252 dict = getGlobalSubDict()
253 dict.update({ "opcode":op, "opnum":opindex })
255 print " emit %s --> asm" % source
257 emitAsmHeader(asm_fp, dict)
258 appendSourceFile(source, dict, asm_fp, sister_list)
261 # Output the alignment directive and label for an assembly piece.
263 def emitAsmHeader(outfp, dict):
264 outfp.write("/* ------------------------------ */\n")
265 # The alignment directive ensures that the handler occupies
266 # at least the correct amount of space. We don't try to deal
267 # with overflow here.
268 outfp.write(" .balign %d\n" % handler_size_bytes)
269 # Emit a label so that gdb will say the right thing. We prepend an
270 # underscore so the symbol name doesn't clash with the Opcode enum.
271 outfp.write(label_prefix + "_%(opcode)s: /* 0x%(opnum)02x */\n" % dict)
274 # Output a generic instruction stub that updates the "glue" struct and
275 # calls the C implementation.
277 def emitAsmStub(outfp, dict):
278 emitAsmHeader(outfp, dict)
279 for line in asm_stub_text:
280 templ = Template(line)
281 outfp.write(templ.substitute(dict))
284 # Append the file specified by "source" to the open "outfp". Each line will
285 # be template-replaced using the substitution dictionary "dict".
287 # If the first line of the file starts with "%" it is taken as a directive.
288 # A "%include" line contains a filename and, optionally, a Python-style
289 # dictionary declaration with substitution strings. (This is implemented
292 # If "sister_list" is provided, and we find a line that contains only "&",
293 # all subsequent lines from the file will be appended to sister_list instead
294 # of copied to the output.
296 # This may modify "dict".
298 def appendSourceFile(source, dict, outfp, sister_list):
299 outfp.write("/* File: %s */\n" % source)
300 infp = open(source, "r")
303 if line.startswith("%include"):
304 # Parse the "include" line
305 tokens = line.strip().split(' ', 2)
307 raise DataParseError("malformed %%include in %s" % source)
309 alt_source = tokens[1].strip("\"")
310 if alt_source == source:
311 raise DataParseError("self-referential %%include in %s"
314 new_dict = dict.copy()
316 new_dict.update(eval(tokens[2]))
317 #print " including src=%s dict=%s" % (alt_source, new_dict)
318 appendSourceFile(alt_source, new_dict, outfp, sister_list)
321 elif line.startswith("%default"):
322 # copy keywords into dictionary
323 tokens = line.strip().split(' ', 1)
325 raise DataParseError("malformed %%default in %s" % source)
326 defaultValues = eval(tokens[1])
327 for entry in defaultValues:
328 dict.setdefault(entry, defaultValues[entry])
331 elif line.startswith("%verify"):
332 # more to come, someday
335 elif line.startswith("%break") and sister_list != None:
336 # allow more than one %break, ignoring all following the first
339 sister_list.append("\n/* continuation for %(opcode)s */\n"%dict)
342 # perform keyword substitution if a dictionary was provided
344 templ = Template(line)
346 subline = templ.substitute(dict)
347 except KeyError, err:
348 raise DataParseError("keyword substitution failed in %s: %s"
349 % (source, str(err)))
351 print "ERROR: substitution failed: " + line
356 # write output to appropriate file
358 sister_list.append(subline)
365 # Emit a C-style section header comment.
367 def emitSectionComment(str, fp):
368 equals = "========================================" \
369 "==================================="
371 fp.write("\n/*\n * %s\n * %s\n * %s\n */\n" %
372 (equals, str, equals))
376 # ===========================================================================
383 if len(sys.argv) != 3:
384 print "Usage: %s target-arch output-dir" % sys.argv[0]
387 target_arch = sys.argv[1]
388 output_dir = sys.argv[2]
391 # Extract opcode list.
393 opcodes = getOpcodeList()
401 config_fp = open("config-%s" % target_arch)
403 print "Unable to open config file 'config-%s'" % target_arch
407 # Open and prepare output files.
410 c_fp = open("%s/InterpC-%s.c" % (output_dir, target_arch), "w")
411 asm_fp = open("%s/InterpAsm-%s.S" % (output_dir, target_arch), "w")
413 print "Unable to open output files"
414 print "Make sure directory '%s' exists and existing files are writable" \
416 # Ideally we'd remove the files to avoid confusing "make", but if they
417 # failed to open we probably won't be able to remove them either.
420 print "Generating %s, %s" % (c_fp.name, asm_fp.name)
423 * This file was generated automatically by gen-mterp.py for '%s'.
425 * --> DO NOT EDIT <--
430 c_fp.write(file_header)
431 asm_fp.write(file_header)
434 # Process the config file.
438 for line in config_fp:
439 line = line.strip() # remove CRLF, leading spaces
440 tokens = line.split(' ') # tokenize
441 #print "%d: %s" % (len(tokens), tokens)
442 if len(tokens[0]) == 0:
445 elif tokens[0][0] == '#':
449 if tokens[0] == "handler-size":
450 setHandlerSize(tokens)
451 elif tokens[0] == "import":
453 elif tokens[0] == "asm-stub":
455 elif tokens[0] == "op-start":
457 elif tokens[0] == "op-end":
459 elif tokens[0] == "op":
462 raise DataParseError, "unrecognized command '%s'" % tokens[0]
463 except DataParseError, err:
464 print "Failed: " + str(err)
465 # TODO: remove output files so "make" doesn't get confused