source: proto/Compiler/pablo.py @ 753

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

Pablo/compiler2 project initial check-in

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