source: proto/Compiler/pablo.py @ 771

Last change on this file since 771 was 771, checked in by cameron, 9 years ago

AugAssign? removal

File size: 12.6 KB
Line 
1#
2# Pablo.py - parallel bitstream to bitblock
3#  2nd generation compiler
4#
5# Copyright 2010, Robert D. Cameron
6# All rights reserved.
7#
8import ast, copy, sys
9import Cgen
10
11
12# HELPER functions for AST recognition/construction
13
14def is_Advance_Call(fncall):   # extracted from old py2bitexpr.py
15        if isinstance(fncall.func, ast.Name): iscall = fncall.func.id == 'Advance'
16        elif isinstance(fncall.func, ast.Attribute) and isinstance(fncall.func.value, ast.Name):
17                 iscall = fncall.func.value.id == 'bitutil' and fncall.func.attr == 'Advance'
18        return iscall and len(fncall.args) == 1 and fncall.kwargs == None and fncall.starargs == None
19
20def is_ScanThru_Call(fncall):  # extracted from old py2bitexpr.py
21        if isinstance(fncall.func, ast.Name): iscall = fncall.func.id == 'ScanThru'
22        elif isinstance(fncall.func, ast.Attribute) and isinstance(fncall.func.value, ast.Name):
23                 iscall = fncall.func.value.id == 'bitutil' and fncall.func.attr == 'ScanThru'
24        return iscall and len(fncall.args) == 2 and fncall.kwargs == None and fncall.starargs == None
25
26def is_simd_not(e):
27  return isinstance(e, ast.Call) and isinstance(e.func, ast.Name) and e.func.id == 'simd_not'
28
29def mkQname(obj, field):
30  return ast.Attribute(ast.Name(obj, ast.Load()), field, ast.Load())
31
32def mkCall(fn_name, args):
33  if isinstance(fn_name, str): fn_name = ast.Name(fn_name, ast.Load())
34  return ast.Call(fn_name, args, [], None, None)
35
36def mkCallStmt(fn_name, args):
37  if isinstance(fn_name, str): fn_name = ast.Name(fn_name, ast.Load())
38  return ast.Expr(ast.Call(fn_name, args, [], None, None))
39
40#
41# Reducing AugAssign
42#
43class AugAssignRemoval(ast.NodeTransformer):
44  def xfrm(self, t):
45    return self.generic_visit(t)
46  def visit_AugAssign(self, e):
47    self.generic_visit(e)
48    return ast.Assign([e.target], ast.BinOp(e.target, e.op, e.value))
49
50#
51# Introducing BitBlock logical operations
52#
53class Bitwise_to_SIMD(ast.NodeTransformer):
54  """
55  Make the following substitutions:
56     x & y => simd_and(x, y)
57     x & ~y => simd_andc(x, y)
58     x | y => simd_or(x, y)
59     x ^ y => simd_xor(x, y)
60     ~x    => simd_not(x)
61     0     => simd_const_1(0)
62     -1    => simd_const_1(1)
63     if x: => if bitblock_has_bit(x):
64  while x: => while bitblock_has_bit(x):
65  >>> ast_show(Bitwise_to_SIMD().xfrm(ast.parse("pfx = bit0 & bit1; sfx = bit0 &~ bit1")))
66 
67  pfx = simd_and(bit0, bit1)
68  sfx = simd_and(bit0, simd_not(bit1))
69  >>>
70  """
71  def xfrm(self, t):
72    return self.generic_visit(t)
73  def visit_UnaryOp(self, t):
74    self.generic_visit(t)
75    if isinstance(t.op, ast.Invert):
76      return mkCall('simd_not', [t.operand])
77    else: return t
78  def visit_BinOp(self, t):
79    self.generic_visit(t)
80    if isinstance(t.op, ast.BitOr):
81      return mkCall('simd_or', [t.left, t.right])
82    elif isinstance(t.op, ast.BitAnd):
83      if is_simd_not(t.right): return mkCall('simd_andc', [t.left, t.right.args[0]])
84      elif is_simd_not(t.left): return mkCall('simd_andc', [t.right, t.left.args[0]])
85      else: return mkCall('simd_and', [t.left, t.right])
86    elif isinstance(t.op, ast.BitXor):
87      return mkCall('simd_xor', [t.left, t.right])
88    else: return t
89  def visit_Num(self, numnode):
90    n = numnode.n
91    if n == 0: return mkCall('simd_const_1', [numnode])
92    elif n == -1: return mkCall('simd_const_1', [ast.Num(1)])
93    else: return numnode
94  def visit_If(self, ifNode):
95    self.generic_visit(ifNode)
96    ifNode.test = mkCall('bitblock_has_bit', [ifNode.test])
97    return ifNode
98  def visit_While(self, whileNode):
99    self.generic_visit(whileNode)
100    whileNode.test = mkCall('bitblock_has_bit', [whileNode.test])
101    return whileNode
102  def visit_Subscript(self, numnode):
103    return numnode  # no recursive modifications of index expressions
104
105
106#
107#  Generating BitBlock declarations for Local Variables
108#
109#
110class LocalVars(ast.NodeVisitor):
111  def visit_Name(self, nm):
112    if isinstance(nm.ctx, ast.Param):
113      self.params.append(nm.id)
114    if isinstance(nm.ctx, ast.Store):
115      if nm.id not in self.stores: self.stores.append(nm.id)
116  def get(self, node): 
117    self.params=[]
118    self.stores=[]
119    self.generic_visit(node)
120    return [v for v in self.stores if not v in self.params]
121
122MAX_LINE_LENGTH = 80
123
124def BitBlock_decls_from_vars(varlist):
125  global MAX_LINE_LENGTH
126  decls = "  BitBlock"
127  pending = ""
128  linelgth = 10
129  for v in varlist:
130    if linelgth + len(v) + 2 <= MAX_LINE_LENGTH:
131      decls += pending + " " + v
132      linelgth += len(pending + v) + 1
133    else:
134      decls += ";\n  BitBlock " + v
135      linelgth = 11 + len(v)
136    pending = ","
137  decls += ";\n"
138  return decls
139
140def BitBlock_decls_of_fn(fndef):
141  return BitBlock_decls_from_vars(LocalVars().get(fndef))
142
143def BitBlock_header_of_fn(fndef):
144  Ccode = "static inline void " + fndef.name + "("
145  pending = ""
146  for arg in fndef.args.args:
147    if isinstance(arg, ast.Name):
148      Ccode += pending + arg.id.upper()[0] + arg.id[1:] + " & " + arg.id
149      pending = ", "
150  Ccode += ")"
151  return Ccode
152
153
154
155#
156#  Stream Initialization Statement Extraction
157#
158#  streamvar = 1 ==> streamvar = sisd_from_int(1) initially.
159class StreamInitializations(ast.NodeTransformer):
160  def xfrm(self, node):
161    self.stream_stmts = []
162    self.loop_post_inits = []
163    self.generic_visit(node)
164    return Cgen.py2C().gen(self.stream_stmts)
165  def visit_Assign(self, node):
166    if isinstance(node.value, ast.Num):
167      if node.value.n == 0: return node
168      elif node.value.n == -1: return node
169      else: 
170        stream_init = copy.deepcopy(node)
171        stream_init.value = mkCall('sisd_from_int', [node.value])
172        loop_init = copy.deepcopy(node)
173        loop_init.value.n = 0
174        self.stream_stmts.append(stream_init)
175        self.loop_post_inits.append(loop_init)
176        return None
177    else: return node
178  def visit_FunctionDef(self, node):
179    self.generic_visit(node)
180    node.body = node.body + self.loop_post_inits
181    return node
182
183
184#
185# Carry Introduction Transformation
186#
187
188class CarryCounter(ast.NodeVisitor):
189  def visit_Call(self, callnode):
190    self.generic_visit(callnode)
191    if is_Advance_Call(callnode) or is_ScanThru_Call(callnode): 
192      self.carry_count += 1
193  def visit_BinOp(self, exprnode):
194    self.generic_visit(exprnode)
195    if isinstance(exprnode.op, ast.Sub):
196      self.carry_count += 1
197    if isinstance(exprnode.op, ast.Add):
198      self.carry_count += 1
199  def count(self, nodeToVisit):
200    self.carry_count = 0
201    self.generic_visit(nodeToVisit)
202    return self.carry_count
203
204
205def Carry_decl_of_fn(fndef):
206  carry_count = CarryCounter().count(fndef)
207  if carry_count == 0: return ""
208  else: return "  CarryDeclare(carryQ, %i);\n" % carry_count
209
210                   
211class CarryIntro(ast.NodeTransformer):
212  def __init__(self, carryvar="carryQ", mode = "ci_co"):
213    self.carryvar = ast.Name(carryvar, ast.Load())
214    self.mode = mode
215  def any_carry_expr(self, fndef):
216    carry_count = CarryCounter().count(fndef)
217    carry_arglist = [self.carryvar, ast.Num(0), ast.Num(carry_count)]
218    return mkCall('CarryTest', carry_arglist)
219  def xfrm_fndef(self, fndef):
220    self.current_carry = 0
221    carry_count = CarryCounter().count(fndef)
222    if carry_count == 0: return fndef
223    self.generic_visit(fndef)
224#   
225#    fndef.body.insert(0, mkCallStmt('CarryDeclare', [self.carryvar, ast.Num(carry_count)]))
226    return fndef
227  def generic_xfrm(self, node):
228    self.current_carry = 0
229    carry_count = CarryCounter().count(node)
230    if carry_count == 0: return node
231    self.generic_visit(node)
232    return node
233  def visit_Call(self, callnode):
234    self.generic_visit(callnode)
235    if is_Advance_Call(callnode):
236      rtn = "BitBlock_advance_%s" % self.mode
237      c = mkCall(rtn, [callnode.args[0], self.carryvar, ast.Num(self.current_carry)])
238      self.current_carry += 1
239      return c
240    elif is_ScanThru_Call(callnode): 
241      rtn = "BitBlock_scanthru_%s" % self.mode
242      c = mkCall(rtn, [callnode.args[0], callnode.args[1], self.carryvar, ast.Num(self.current_carry)])
243      self.current_carry += 1
244      return c
245    else: return callnode
246  def visit_BinOp(self, exprnode):
247    self.generic_visit(exprnode)
248    if isinstance(exprnode.op, ast.Sub):
249      rtn = "BitBlock_sub_%s" % self.mode
250      c = mkCall(rtn, [exprnode.left, exprnode.right, self.carryvar, ast.Num(self.current_carry)])
251      self.current_carry += 1
252      return c
253    elif isinstance(exprnode.op, ast.Add):
254      rtn = "BitBlock_add_%s" % self.mode
255      c = mkCall(rtn, [exprnode.left, exprnode.right, self.carryvar, ast.Num(self.current_carry)])
256      self.current_carry += 1
257      return c
258    else: return exprnode
259  def visit_If(self, ifNode):
260    carry_base = self.current_carry
261    carries = CarryCounter().count(ifNode)
262    self.generic_visit(ifNode)
263    if carries == 0 or self.mode == "co": return ifNode
264    carry_arglist = [self.carryvar, ast.Num(carry_base), ast.Num(carries)]
265    new_test = ast.BoolOp(ast.Or(), [ifNode.test, mkCall('CarryTest', carry_arglist)])
266    new_else_part = [mkCallStmt('CarryDequeueEnqueue', carry_arglist)]
267    return ast.If(new_test, ifNode.body, new_else_part)
268  def visit_While(self, whileNode):
269    carry_base = self.current_carry
270    carries = CarryCounter().count(whileNode)
271    if carries == 0: return whileNode
272    carry_arglist = [self.carryvar, ast.Num(carry_base), ast.Num(carries)]
273    local_carryvar = 'sub'+self.carryvar.id
274    inner_while = CarryIntro(local_carryvar, 'co').generic_xfrm(copy.deepcopy(whileNode))
275    self.generic_visit(whileNode)
276    local_decl = mkCallStmt('CarryDeclare', [ast.Name(local_carryvar, ast.Load()), ast.Num(carries)])
277    inner_while.body.insert(0, local_decl)
278    final_combine = mkCallStmt('CarryCombine', [self.carryvar, ast.Name(local_carryvar, ast.Load()), ast.Num(carry_base), ast.Num(carries)])
279    inner_while.body.append(final_combine)
280    if self.mode == "co": new_test = whileNode.test
281    else: new_test = ast.BoolOp(ast.Or(), [whileNode.test, mkCall('CarryTest', carry_arglist)])
282    else_part = [mkCallStmt('CarryDequeueEnqueue', carry_arglist)]
283    return ast.If(new_test, whileNode.body + [inner_while], else_part)
284
285class StreamStructGen(ast.NodeVisitor):
286  """
287  Given a BitStreamSet subclass, generate the equivalent C struct.
288  >>> obj = ast.parse(r'''
289  ... class S1(BitStreamSet):
290  ...   a1 = 0
291  ...   a2 = 0
292  ...   a3 = 0
293  ...
294  ... class S2(BitStreamSet):
295  ...   x1 = 0
296  ...   x2 = 0
297  ... ''')
298  >>> print StreamStructGen().gen(obj)
299  struct S1 {
300    BitBlock a1;
301    BitBlock a2;
302    BitBlock a3;
303  }
304 
305  struct S2 {
306    BitBlock x1;
307    BitBlock x2;
308  }
309  """
310  def __init__(self):
311    pass
312  def gen(self, tree):
313    self.Ccode=""
314    self.generic_visit(tree)
315    return self.Ccode
316  def visit_ClassDef(self, node):
317#    self.Ccode += "typedef struct {\n"
318    self.Ccode += "struct {\n"
319    for stmt in node.body:
320      if isinstance(stmt, ast.Assign):
321        for v in stmt.targets:
322          if isinstance(v, ast.Name):
323            self.Ccode += "  BitBlock " + v.id + ";\n"
324    self.Ccode += "} " + node.name + ";\n\n"
325 
326class StreamFunctionDecl(ast.NodeVisitor):
327  def __init__(self):
328    pass
329  def gen(self, tree):
330    self.Ccode=""
331    self.generic_visit(tree)
332    return self.Ccode
333  def visit_FunctionDef(self, node):
334    self.Ccode += "static inline void " + node.name + "("
335    pending = ""
336    for arg in node.args.args:
337      if isinstance(arg, ast.Name):
338        self.Ccode += pending + arg.id.upper()[0] + arg.id[1:] + " & " + arg.id
339        pending = ", "
340    self.Ccode += ");\n"
341
342
343
344#  Translate a function
345#
346
347class FunctionXlator(ast.NodeVisitor):
348  def xlat(self, node):
349    self.Ccode=""
350    self.generic_visit(node)
351    return self.Ccode
352  def visit_FunctionDef(self, fndef):
353    AugAssignRemoval().xfrm(fndef)
354    Bitwise_to_SIMD().xfrm(fndef)
355    self.Ccode += BitBlock_header_of_fn(fndef) + " {\n"
356    self.Ccode += BitBlock_decls_of_fn(fndef)
357    CarryIntro().xfrm_fndef(fndef)
358    self.Ccode += Cgen.py2C().gen(fndef.body)
359    self.Ccode += "\n}\n"
360
361def main(infilename, outfile = sys.stdout):
362  t = ast.parse(file(infilename).read())
363  outfile.write(StreamStructGen().gen(t))
364  outfile.write(FunctionXlator().xlat(t))
365
366#
367#
368#  Routines for compatibility with the old compiler/template.
369#  Quick and dirty hacks for now - Dec. 2010.
370#
371def gen_declarations(main_module, main_fn):
372  Cdecls = StreamStructGen().gen(main_module)
373  Cdecls += BitBlock_decls_of_fn(main_fn)
374  Cdecls += Carry_decl_of_fn(main_fn)
375  return Cdecls
376
377def stream_stmts(main_fn):
378  return StreamInitializations().xfrm(main_fn)
379
380def block_stmts(main_fn):
381  AugAssignRemoval().xfrm(main_fn)
382  Bitwise_to_SIMD().xfrm(main_fn)
383  CarryIntro().xfrm_fndef(main_fn)
384  return Cgen.py2C().gen(main_fn.body)
385
386def any_carry_expr(main_fn):
387  return Cgen.py2C().gen(CarryIntro().any_carry_expr(main_fn))
388
389if __name__ == "__main__":
390                import doctest
391                doctest.testmod()
392
393
Note: See TracBrowser for help on using the repository browser.