Debian Codegraph @

rpython/jit/tl/tiny2_hotpath.py

raw symbols SCIP
1 """
2 An interpreter for a strange word-based language: the program is a list
3 of space-separated words. Most words push themselves on a stack; some
4 words have another action. The result is the space-separated words
5 from the stack.
6
7 Hello World => 'Hello World'
8 6 7 ADD => '13' 'ADD' is a special word
9 7 * 5 = 7 5 MUL => '7 * 5 = 35' '*' and '=' are not special words
10
11 Arithmetic on non-integers gives a 'symbolic' result:
12
13 X 2 MUL => 'X*2'
14
15 Input arguments can be passed on the command-line, and used as #1, #2, etc.:
16
17 #1 1 ADD => one more than the argument on the command-line,
18 or if it was not an integer, concatenates '+1'
19
20 You can store back into an (existing) argument index with ->#N:
21
22 #1 5 ADD ->#1
23
24 Braces { } delimitate a loop. Don't forget spaces around each one.
25 The '}' pops an integer value off the stack and loops if it is not zero:
26
27 { #1 #1 1 SUB ->#1 #1 } => when called with 5, gives '5 4 3 2 1'
28
29 """
30 from rpython.rlib.jit import hint, promote, JitDriver
31
32 #
33 # See pypy/doc/jit.txt for a higher-level overview of the JIT techniques
34 # detailed in the following comments.
35 #
36
37
38 class Box:
39 # Although all words are in theory strings, we use two subclasses
40 # to represent the strings differently from the words known to be integers.
41 # This is an optimization that is essential for the JIT and merely
42 # useful for the basic interpreter.
43 pass
44
45 class IntBox(Box):
46 _immutable_ = True
47 def __init__(self, intval):
48 self.intval = intval
49 def as_int(self):
50 return self.intval
51 def as_str(self):
52 return str(self.intval)
53
54 class StrBox(Box):
55 _immutable_ = True
56 def __init__(self, strval):
57 self.strval = strval
58 def as_int(self):
59 return myint(self.strval)
60 def as_str(self):
61 return self.strval
62
63
64 def func_add_int(ix, iy): return ix + iy
65 def func_sub_int(ix, iy): return ix - iy
66 def func_mul_int(ix, iy): return ix * iy
67
68 def func_add_str(sx, sy): return sx + '+' + sy
69 def func_sub_str(sx, sy): return sx + '-' + sy
70 def func_mul_str(sx, sy): return sx + '*' + sy
71
72 def op2(stack, func_int, func_str):
73 # Operate on the top two stack items. The promotion hints force the
74 # class of each arguments (IntBox or StrBox) to turn into a compile-time
75 # constant if they weren't already. The effect we seek is to make the
76 # calls to as_int() direct calls at compile-time, instead of indirect
77 # ones. The JIT compiler cannot look into indirect calls, but it
78 # can analyze and inline the code in directly-called functions.
79 stack, y = stack.pop()
80 promote(y.__class__)
81 stack, x = stack.pop()
82 promote(x.__class__)
83 try:
84 z = IntBox(func_int(x.as_int(), y.as_int()))
85 except ValueError:
86 z = StrBox(func_str(x.as_str(), y.as_str()))
87 stack = Stack(z, stack)
88 return stack
89
90 class Stack(object):
91 def __init__(self, value, next=None):
92 self.next = next
93 self.value = value
94
95 def pop(self):
96 return self.next, self.value
97
98 def empty_stack():
99 return None
100
101
102 class TinyJitDriver(JitDriver):
103 reds = ['args', 'loops', 'stack']
104 greens = ['bytecode', 'pos']
105
106 def compute_invariants(self, reds, bytecode, pos):
107 # Some of the information that we maintain only really depends on
108 # bytecode and pos: the whole 'loops' list has this property.
109 # By being a bit careful we could also put len(args) in the
110 # invariants, but although it doesn't make much sense it is a
111 # priori possible for the same bytecode to be run with
112 # different len(args).
113 return reds.loops
114
115 def on_enter_jit(self, invariants, reds, bytecode, pos):
116 # Now some strange code that makes a copy of the 'args' list in
117 # a complicated way... this is a workaround forcing the whole 'args'
118 # list to be virtual. It is a way to tell the JIT compiler that it
119 # doesn't have to worry about the 'args' list being unpredictably
120 # modified.
121 oldloops = invariants
122 oldargs = reds.args
123 argcount = promote(len(oldargs))
124 args = []
125 n = 0
126 while n < argcount:
127 hint(n, concrete=True)
128 args.append(oldargs[n])
129 n += 1
130 reds.args = args
131 # turn the green 'loops' from 'invariants' into a virtual list
132 oldloops = hint(oldloops, deepfreeze=True)
133 argcount = len(oldloops)
134 loops = []
135 n = 0
136 while n < argcount:
137 hint(n, concrete=True)
138 loops.append(oldloops[n])
139 n += 1
140 reds.loops = loops
141
142 tinyjitdriver = TinyJitDriver()
143
144 def interpret(bytecode, args):
145 """The interpreter's entry point and portal function.
146 """
147 loops = []
148 stack = empty_stack()
149 pos = 0
150 while True:
151 tinyjitdriver.jit_merge_point(args=args, loops=loops, stack=stack,
152 bytecode=bytecode, pos=pos)
153 bytecode = hint(bytecode, deepfreeze=True)
154 if pos >= len(bytecode):
155 break
156 opcode = bytecode[pos]
157 hint(opcode, concrete=True) # same as in tiny1.py
158 pos += 1
159 if opcode == 'ADD':
160 stack = op2(stack, func_add_int, func_add_str)
161 elif opcode == 'SUB':
162 stack = op2(stack, func_sub_int, func_sub_str)
163 elif opcode == 'MUL':
164 stack = op2(stack, func_mul_int, func_mul_str)
165 elif opcode[0] == '#':
166 n = myint(opcode, start=1)
167 stack = Stack(args[n-1], stack)
168 elif opcode.startswith('->#'):
169 n = myint(opcode, start=3)
170 if n > len(args):
171 raise IndexError
172 stack, args[n-1] = stack.pop()
173 elif opcode == '{':
174 loops.append(pos)
175 elif opcode == '}':
176 stack, flag = stack.pop()
177 if flag.as_int() == 0:
178 loops.pop()
179 else:
180 pos = loops[-1]
181 # A common problem when interpreting loops or jumps: the 'pos'
182 # above is read out of a list, so the hint-annotator thinks
183 # it must be red (not a compile-time constant). But the
184 # hint(opcode, concrete=True) in the next iteration of the
185 # loop requires all variables the 'opcode' depends on to be
186 # green, including this 'pos'. We promote 'pos' to a green
187 # here, as early as possible. Note that in practice the 'pos'
188 # read out of the 'loops' list will be a compile-time constant
189 # because it was pushed as a compile-time constant by the '{'
190 # case above into 'loops', which is a virtual list, so the
191 # promotion below is just a way to make the colors match.
192 pos = promote(pos)
193 tinyjitdriver.can_enter_jit(args=args, loops=loops, stack=stack,
194 bytecode=bytecode, pos=pos)
195 else:
196 stack = Stack(StrBox(opcode), stack)
197 return stack
198
199
200 def repr(stack):
201 # this bit moved out of the portal function because JIT'ing it is not
202 # very useful, and the JIT generator is confused by the 'for' right now...
203 lst = []
204 while stack:
205 stack, x = stack.pop()
206 lst.append(x.as_str())
207 lst.reverse()
208 return ' '.join(lst)
209
210
211 # ------------------------------
212 # Pure workaround code! It will eventually be unnecessary.
213 # For now, myint(s, n) is a JIT-friendly way to spell int(s[n:]).
214 # We don't support negative numbers, though.
215 def myint_internal(s, start=0):
216 if start >= len(s):
217 return -1
218 res = 0
219 while start < len(s):
220 c = s[start]
221 n = ord(c) - ord('0')
222 if not (0 <= n <= 9):
223 return -1
224 res = res * 10 + n
225 start += 1
226 return res
227 def myint(s, start=0):
228 n = myint_internal(s, start)
229 if n < 0:
230 raise ValueError
231 return n
232 # ------------------------------
233
234
235 def test_main():
236 main = """#1 5 ADD""".split()
237 res = interpret(main, [IntBox(20)])
238 assert repr(res) == '25'
239 res = interpret(main, [StrBox('foo')])
240 assert repr(res) == 'foo+5'
241
242 FACTORIAL = """The factorial of #1 is
243 1 { #1 MUL #1 1 SUB ->#1 #1 }""".split()
244
245 def test_factorial():
246 res = interpret(FACTORIAL, [IntBox(5)])
247 assert repr(res) == 'The factorial of 5 is 120'
248
249 FIBONACCI = """Fibonacci numbers:
250 { #1 #2 #1 #2 ADD ->#2 ->#1 #3 1 SUB ->#3 #3 }""".split()
251
252 def test_fibonacci():
253 res = interpret(FIBONACCI, [IntBox(1), IntBox(1), IntBox(10)])
254 assert repr(res) == "Fibonacci numbers: 1 1 2 3 5 8 13 21 34 55"
255
256
257 FIBONACCI_SINGLE = """#3 1 SUB ->#3 { #2 #1 #2 ADD ->#2 ->#1 #3 1 SUB ->#3 #3 } #1""".split()
258
259 def test_fibonacci_single():
260 res = interpret(FIBONACCI_SINGLE, [IntBox(1), IntBox(1), IntBox(11)])
261 assert repr(res) == "89"