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 = 512 # 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
32 in_alt_op_start = 0 # 0=not started, 1=started, 2=ended
34 default_alt_op_dir = None
36 alt_opcode_locations = {}
38 label_prefix = ".L" # use ".L" to hide labels from gdb
39 alt_label_prefix = ".L_ALT" # use ".L" to hide labels from gdb
40 jmp_table = False # jump table vs. computed goto style
43 class DataParseError(SyntaxError):
44 "Failure when parsing data file"
47 # Set any omnipresent substitution values.
49 def getGlobalSubDict():
50 return { "handler_size_bits":handler_size_bits,
51 "handler_size_bytes":handler_size_bytes }
54 # Parse arch config file --
55 # Set handler_size_bytes to the value of tokens[1], and handler_size_bits to
56 # log2(handler_size_bytes). Throws an exception if "bytes" is not 0 or
59 def setHandlerSize(tokens):
60 global handler_size_bits, handler_size_bytes, jmp_table
62 raise DataParseError("handler-size requires one argument")
63 if handler_size_bits != -1000:
64 raise DataParseError("handler-size may only be set once")
66 # compute log2(n), and make sure n is 0 or a power of 2
67 handler_size_bytes = bytes = int(tokens[1])
68 if handler_size_bytes == 0:
70 handler_size_bits = 0;
74 bytes //= 2 # halve with truncating division
77 if handler_size_bytes == 0 or handler_size_bytes != (1 << bits):
78 raise DataParseError("handler-size (%d) must be power of 2" \
80 handler_size_bits = bits
83 # Parse arch config file --
84 # Copy a file in to the C or asm output file.
86 def importFile(tokens):
88 raise DataParseError("import requires one argument")
90 if source.endswith(".c"):
91 appendSourceFile(tokens[1], getGlobalSubDict(), c_fp, None)
92 elif source.endswith(".S"):
93 appendSourceFile(tokens[1], getGlobalSubDict(), asm_fp, None)
95 raise DataParseError("don't know how to import %s (expecting .c/.S)"
99 # Parse arch config file --
100 # Copy a file in to the C or asm output file.
102 def setAsmStub(tokens):
105 raise DataParseError("import requires one argument")
107 stub_fp = open(tokens[1])
108 asm_stub_text = stub_fp.readlines()
111 raise DataParseError("unable to load asm-stub: %s" % str(err))
115 # Parse arch config file --
116 # Start of opcode list.
120 global default_op_dir
122 raise DataParseError("opStart takes a directory name argument")
124 raise DataParseError("opStart can only be specified once")
125 default_op_dir = tokens[1]
129 # Parse arch config file
130 # Start of optional alternate opcode list.
132 def altOpStart(tokens):
133 global in_alt_op_start
134 global default_alt_op_dir
136 raise DataParseError("altOpStart takes a directory name argument")
137 if in_alt_op_start != 0:
138 raise DataParseError("altOpStart can only be specified once")
139 default_alt_op_dir = tokens[1]
143 # Parse arch config file --
144 # Set location of a single alt opcode's source file.
146 def altEntry(tokens):
147 #global alt_opcode_locations
149 raise DataParseError("alt requires exactly two arguments")
150 if in_alt_op_start != 1:
151 raise DataParseError("alt statements must be between opStart/opEnd")
153 index = opcodes.index(tokens[1])
155 raise DataParseError("unknown opcode %s" % tokens[1])
156 if alt_opcode_locations.has_key(tokens[1]):
157 print "Warning: alt overrides earlier %s (%s -> %s)" \
158 % (tokens[1], alt_opcode_locations[tokens[1]], tokens[2])
159 alt_opcode_locations[tokens[1]] = tokens[2]
162 # Parse arch config file --
163 # Set location of a single opcode's source file.
166 #global opcode_locations
168 raise DataParseError("op requires exactly two arguments")
170 raise DataParseError("op statements must be between opStart/opEnd")
172 index = opcodes.index(tokens[1])
174 raise DataParseError("unknown opcode %s" % tokens[1])
175 if opcode_locations.has_key(tokens[1]):
176 print "Warning: op overrides earlier %s (%s -> %s)" \
177 % (tokens[1], opcode_locations[tokens[1]], tokens[2])
178 opcode_locations[tokens[1]] = tokens[2]
181 # Parse arch config file --
182 # End of opcode list; emit instruction blocks.
187 raise DataParseError("opEnd takes no arguments")
189 raise DataParseError("opEnd must follow opStart, and only appear once")
197 def emitJmpTable(start_label, prefix):
198 asm_fp.write("\n .global %s\n" % start_label)
199 asm_fp.write(" .text\n")
200 asm_fp.write("%s:\n" % start_label)
201 for i in xrange(kNumPackedOpcodes):
203 dict = getGlobalSubDict()
204 dict.update({ "opcode":op, "opnum":i })
205 asm_fp.write(" .long " + prefix + \
206 "_%(opcode)s /* 0x%(opnum)02x */\n" % dict)
209 # Parse arch config file --
210 # End of alternate opcode list; emit instruction blocks.
211 # If jump table style, emit tables following
213 def altOpEnd(tokens):
214 global in_alt_op_start
216 raise DataParseError("altOpEnd takes no arguments")
217 if in_alt_op_start != 1:
218 raise DataParseError("altOpEnd follows altOStart, once")
221 loadAndEmitAltOpcodes()
224 emitJmpTable("dvmAsmInstructionStart", label_prefix);
225 emitJmpTable("dvmAsmAltInstructionStart", alt_label_prefix);
228 # Extract an ordered list of instructions from the VM sources. We use the
229 # "goto table" definition macro, which has exactly kNumPackedOpcodes
234 opcode_fp = open(interp_defs_file)
235 opcode_re = re.compile(r"^\s*H\(OP_(\w+)\),.*", re.DOTALL)
236 for line in opcode_fp:
237 match = opcode_re.match(line)
240 opcodes.append("OP_" + match.group(1))
243 if len(opcodes) != kNumPackedOpcodes:
244 print "ERROR: found %d opcodes in Interp.h (expected %d)" \
245 % (len(opcodes), kNumPackedOpcodes)
246 raise SyntaxError, "bad opcode count"
251 asm_fp.write(" .balign %d\n" % handler_size_bytes)
254 # Load and emit opcodes for all kNumPackedOpcodes instructions.
256 def loadAndEmitOpcodes():
258 assert len(opcodes) == kNumPackedOpcodes
259 need_dummy_start = False
261 start_label = "dvmAsmInstructionStartCode"
262 end_label = "dvmAsmInstructionEndCode"
264 start_label = "dvmAsmInstructionStart"
265 end_label = "dvmAsmInstructionEnd"
267 # point dvmAsmInstructionStart at the first handler or stub
268 asm_fp.write("\n .global %s\n" % start_label)
269 asm_fp.write(" .type %s, %%function\n" % start_label)
270 asm_fp.write("%s = " % start_label + label_prefix + "_OP_NOP\n")
271 asm_fp.write(" .text\n\n")
273 for i in xrange(kNumPackedOpcodes):
276 if opcode_locations.has_key(op):
277 location = opcode_locations[op]
279 location = default_op_dir
282 loadAndEmitC(location, i)
283 if len(asm_stub_text) == 0:
284 need_dummy_start = True
286 loadAndEmitAsm(location, i, sister_list)
288 # For a 100% C implementation, there are no asm handlers or stubs. We
289 # need to have the dvmAsmInstructionStart label point at OP_NOP, and it's
290 # too annoying to try to slide it in after the alignment psuedo-op, so
291 # we take the low road and just emit a dummy OP_NOP here.
294 asm_fp.write(label_prefix + "_OP_NOP: /* dummy */\n");
297 asm_fp.write(" .size %s, .-%s\n" % (start_label, start_label))
298 asm_fp.write(" .global %s\n" % end_label)
299 asm_fp.write("%s:\n" % end_label)
302 emitSectionComment("Sister implementations", asm_fp)
303 asm_fp.write(" .global dvmAsmSisterStart\n")
304 asm_fp.write(" .type dvmAsmSisterStart, %function\n")
305 asm_fp.write(" .text\n")
306 asm_fp.write(" .balign 4\n")
307 asm_fp.write("dvmAsmSisterStart:\n")
308 asm_fp.writelines(sister_list)
310 asm_fp.write("\n .size dvmAsmSisterStart, .-dvmAsmSisterStart\n")
311 asm_fp.write(" .global dvmAsmSisterEnd\n")
312 asm_fp.write("dvmAsmSisterEnd:\n\n")
315 # Load an alternate entry stub
317 def loadAndEmitAltStub(source, opindex):
318 op = opcodes[opindex]
320 print " alt emit %s --> stub" % source
321 dict = getGlobalSubDict()
322 dict.update({ "opcode":op, "opnum":opindex })
324 emitAsmHeader(asm_fp, dict, alt_label_prefix)
325 appendSourceFile(source, dict, asm_fp, None)
328 # Load and emit alternate opcodes for all kNumPackedOpcodes instructions.
330 def loadAndEmitAltOpcodes():
331 assert len(opcodes) == kNumPackedOpcodes
333 start_label = "dvmAsmAltInstructionStartCode"
334 end_label = "dvmAsmAltInstructionEndCode"
336 start_label = "dvmAsmAltInstructionStart"
337 end_label = "dvmAsmAltInstructionEnd"
339 # point dvmAsmInstructionStart at the first handler or stub
340 asm_fp.write("\n .global %s\n" % start_label)
341 asm_fp.write(" .type %s, %%function\n" % start_label)
342 asm_fp.write("%s:\n" % start_label)
343 asm_fp.write(" .text\n\n")
345 for i in xrange(kNumPackedOpcodes):
347 if alt_opcode_locations.has_key(op):
348 source = "%s/ALT_%s.S" % (alt_opcode_locations[op], op)
350 source = "%s/ALT_STUB.S" % default_alt_op_dir
351 loadAndEmitAltStub(source, i)
354 asm_fp.write(" .size %s, .-%s\n" % (start_label, start_label))
355 asm_fp.write(" .global %s\n" % end_label)
356 asm_fp.write("%s:\n" % end_label)
359 # Load a C fragment and emit it, then output an assembly stub.
361 def loadAndEmitC(location, opindex):
362 op = opcodes[opindex]
363 source = "%s/%s.c" % (location, op)
365 print " emit %s --> C" % source
366 dict = getGlobalSubDict()
367 dict.update({ "opcode":op, "opnum":opindex })
369 appendSourceFile(source, dict, c_fp, None)
371 if len(asm_stub_text) != 0:
372 emitAsmStub(asm_fp, dict)
375 # Load an assembly fragment and emit it.
377 def loadAndEmitAsm(location, opindex, sister_list):
378 op = opcodes[opindex]
379 source = "%s/%s.S" % (location, op)
380 dict = getGlobalSubDict()
381 dict.update({ "opcode":op, "opnum":opindex })
383 print " emit %s --> asm" % source
385 emitAsmHeader(asm_fp, dict, label_prefix)
386 appendSourceFile(source, dict, asm_fp, sister_list)
389 # Output the alignment directive and label for an assembly piece.
391 def emitAsmHeader(outfp, dict, prefix):
392 outfp.write("/* ------------------------------ */\n")
393 # The alignment directive ensures that the handler occupies
394 # at least the correct amount of space. We don't try to deal
395 # with overflow here.
397 # Emit a label so that gdb will say the right thing. We prepend an
398 # underscore so the symbol name doesn't clash with the Opcode enum.
399 outfp.write(prefix + "_%(opcode)s: /* 0x%(opnum)02x */\n" % dict)
402 # Output a generic instruction stub that updates the "glue" struct and
403 # calls the C implementation.
405 def emitAsmStub(outfp, dict):
406 emitAsmHeader(outfp, dict, label_prefix)
407 for line in asm_stub_text:
408 templ = Template(line)
409 outfp.write(templ.substitute(dict))
412 # Append the file specified by "source" to the open "outfp". Each line will
413 # be template-replaced using the substitution dictionary "dict".
415 # If the first line of the file starts with "%" it is taken as a directive.
416 # A "%include" line contains a filename and, optionally, a Python-style
417 # dictionary declaration with substitution strings. (This is implemented
420 # If "sister_list" is provided, and we find a line that contains only "&",
421 # all subsequent lines from the file will be appended to sister_list instead
422 # of copied to the output.
424 # This may modify "dict".
426 def appendSourceFile(source, dict, outfp, sister_list):
427 outfp.write("/* File: %s */\n" % source)
428 infp = open(source, "r")
431 if line.startswith("%include"):
432 # Parse the "include" line
433 tokens = line.strip().split(' ', 2)
435 raise DataParseError("malformed %%include in %s" % source)
437 alt_source = tokens[1].strip("\"")
438 if alt_source == source:
439 raise DataParseError("self-referential %%include in %s"
442 new_dict = dict.copy()
444 new_dict.update(eval(tokens[2]))
445 #print " including src=%s dict=%s" % (alt_source, new_dict)
446 appendSourceFile(alt_source, new_dict, outfp, sister_list)
449 elif line.startswith("%default"):
450 # copy keywords into dictionary
451 tokens = line.strip().split(' ', 1)
453 raise DataParseError("malformed %%default in %s" % source)
454 defaultValues = eval(tokens[1])
455 for entry in defaultValues:
456 dict.setdefault(entry, defaultValues[entry])
459 elif line.startswith("%verify"):
460 # more to come, someday
463 elif line.startswith("%break") and sister_list != None:
464 # allow more than one %break, ignoring all following the first
465 if not jmp_table and not in_sister:
467 sister_list.append("\n/* continuation for %(opcode)s */\n"%dict)
470 # perform keyword substitution if a dictionary was provided
472 templ = Template(line)
474 subline = templ.substitute(dict)
475 except KeyError, err:
476 raise DataParseError("keyword substitution failed in %s: %s"
477 % (source, str(err)))
479 print "ERROR: substitution failed: " + line
484 # write output to appropriate file
486 sister_list.append(subline)
493 # Emit a C-style section header comment.
495 def emitSectionComment(str, fp):
496 equals = "========================================" \
497 "==================================="
499 fp.write("\n/*\n * %s\n * %s\n * %s\n */\n" %
500 (equals, str, equals))
504 # ===========================================================================
511 if len(sys.argv) != 3:
512 print "Usage: %s target-arch output-dir" % sys.argv[0]
515 target_arch = sys.argv[1]
516 output_dir = sys.argv[2]
519 # Extract opcode list.
521 opcodes = getOpcodeList()
529 config_fp = open("config-%s" % target_arch)
531 print "Unable to open config file 'config-%s'" % target_arch
535 # Open and prepare output files.
538 c_fp = open("%s/InterpC-%s.c" % (output_dir, target_arch), "w")
539 asm_fp = open("%s/InterpAsm-%s.S" % (output_dir, target_arch), "w")
541 print "Unable to open output files"
542 print "Make sure directory '%s' exists and existing files are writable" \
544 # Ideally we'd remove the files to avoid confusing "make", but if they
545 # failed to open we probably won't be able to remove them either.
548 print "Generating %s, %s" % (c_fp.name, asm_fp.name)
551 * This file was generated automatically by gen-mterp.py for '%s'.
553 * --> DO NOT EDIT <--
558 c_fp.write(file_header)
559 asm_fp.write(file_header)
562 # Process the config file.
566 for line in config_fp:
567 line = line.strip() # remove CRLF, leading spaces
568 tokens = line.split(' ') # tokenize
569 #print "%d: %s" % (len(tokens), tokens)
570 if len(tokens[0]) == 0:
573 elif tokens[0][0] == '#':
577 if tokens[0] == "handler-size":
578 setHandlerSize(tokens)
579 elif tokens[0] == "import":
581 elif tokens[0] == "asm-stub":
583 elif tokens[0] == "op-start":
585 elif tokens[0] == "op-end":
587 elif tokens[0] == "op-alt-start":
589 elif tokens[0] == "op-alt-end":
591 elif tokens[0] == "alt":
593 elif tokens[0] == "op":
596 raise DataParseError, "unrecognized command '%s'" % tokens[0]
597 except DataParseError, err:
598 print "Failed: " + str(err)
599 # TODO: remove output files so "make" doesn't get confused