ast.py 10.3 KB
Newer Older
1
import sympy as sp
2
import textwrap as textwrap
3
4
5
6
7
from sympy.tensor import IndexedBase, Indexed
from pystencils.field import Field
from pystencils.typedsymbol import TypedSymbol


8
class Node(object):
Martin Bauer's avatar
Martin Bauer committed
9
10
    """Base class for all AST nodes"""

11
12
13
14
    def __init__(self, parent=None):
        self.parent = parent

    def args(self):
Martin Bauer's avatar
Martin Bauer committed
15
        """Returns all arguments/children of this node"""
16
17
18
19
        return []

    @property
    def symbolsDefined(self):
20
        """Set of symbols which are defined by this node. """
21
22
23
        return set()

    @property
24
25
26
    def undefinedSymbols(self):
        """Symbols which are use but are not defined inside this node"""
        raise NotImplementedError()
27
28

    def atoms(self, argType):
Martin Bauer's avatar
Martin Bauer committed
29
30
31
        """
        Returns a set of all children which are an instance of the given argType
        """
32
33
34
35
36
37
38
        result = set()
        for arg in self.args:
            if isinstance(arg, argType):
                result.add(arg)
            result.update(arg.atoms(argType))
        return result

39
40
41
42
43
44
    def parents(self):
        return None

    def children(self):
        return None

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

class KernelFunction(Node):

    class Argument:
        def __init__(self, name, dtype):
            self.name = name
            self.dtype = dtype
            self.isFieldPtrArgument = False
            self.isFieldShapeArgument = False
            self.isFieldStrideArgument = False
            self.isFieldArgument = False
            self.fieldName = ""
            self.coordinate = None

            if name.startswith(Field.DATA_PREFIX):
                self.isFieldPtrArgument = True
                self.isFieldArgument = True
                self.fieldName = name[len(Field.DATA_PREFIX):]
            elif name.startswith(Field.SHAPE_PREFIX):
                self.isFieldShapeArgument = True
                self.isFieldArgument = True
                self.fieldName = name[len(Field.SHAPE_PREFIX):]
            elif name.startswith(Field.STRIDE_PREFIX):
                self.isFieldStrideArgument = True
                self.isFieldArgument = True
                self.fieldName = name[len(Field.STRIDE_PREFIX):]

72
73
74
        def __repr__(self):
            return '<{0} {1}>'.format(self.dtype, self.name)

75
76
77
78
79
80
    def __init__(self, body, functionName="kernel"):
        super(KernelFunction, self).__init__()
        self._body = body
        self._parameters = None
        self._functionName = functionName
        self._body.parent = self
81
82
        # these variables are assumed to be global, so no automatic parameter is generated for them
        self.globalVariables = set()
83
84
85
86
87
88

    @property
    def symbolsDefined(self):
        return set()

    @property
89
    def undefinedSymbols(self):
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
        return set()

    @property
    def parameters(self):
        self._updateParameters()
        return self._parameters

    @property
    def body(self):
        return self._body

    @property
    def args(self):
        return [self._body]

    @property
    def functionName(self):
        return self._functionName

    def _updateParameters(self):
110
        undefinedSymbols = self._body.undefinedSymbols - self.globalVariables
111
112
113
114
115
        self._parameters = [KernelFunction.Argument(s.name, s.dtype) for s in undefinedSymbols]
        self._parameters.sort(key=lambda l: (l.fieldName, l.isFieldPtrArgument, l.isFieldShapeArgument,
                                             l.isFieldStrideArgument, l.name),
                              reverse=True)

116
117
118
119
120
    def children(self):
        yield self.body

    def __repr__(self):
        self._updateParameters()
121
122
        return '{0} {1}({2})\n{3}'.format(type(self).__name__, self.functionName, self.parameters,
                                          textwrap.indent(repr(self.body), '\t'))
123

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

class Block(Node):
    def __init__(self, listOfNodes):
        super(Node, self).__init__()
        self._nodes = listOfNodes
        for n in self._nodes:
            n.parent = self

    @property
    def args(self):
        return self._nodes

    def insertFront(self, node):
        node.parent = self
        self._nodes.insert(0, node)

Martin Bauer's avatar
Martin Bauer committed
140
    def insertBefore(self, newNode, insertBefore):
141
        newNode.parent = self
Martin Bauer's avatar
Martin Bauer committed
142
143
144
        idx = self._nodes.index(insertBefore)
        self._nodes.insert(idx, newNode)

145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    def append(self, node):
        node.parent = self
        self._nodes.append(node)

    def takeChildNodes(self):
        tmp = self._nodes
        self._nodes = []
        return tmp

    def replace(self, child, replacements):
        idx = self._nodes.index(child)
        del self._nodes[idx]
        if type(replacements) is list:
            for e in replacements:
                e.parent = self
            self._nodes = self._nodes[:idx] + replacements + self._nodes[idx:]
        else:
            replacements.parent = self
            self._nodes.insert(idx, replacements)

    @property
    def symbolsDefined(self):
        result = set()
        for a in self.args:
            result.update(a.symbolsDefined)
        return result

    @property
173
    def undefinedSymbols(self):
174
        result = set()
175
        definedSymbols = set()
176
        for a in self.args:
177
178
179
            result.update(a.undefinedSymbols)
            definedSymbols.update(a.symbolsDefined)
        return result - definedSymbols
180

181
182
183
184
    def children(self):
        yield self._nodes

    def __repr__(self):
185
        return ''.join('{!r}\n'.format(node) for node in self._nodes)
186

187
188
189
190
191
192
193
194
195
196

class PragmaBlock(Block):
    def __init__(self, pragmaLine, listOfNodes):
        super(PragmaBlock, self).__init__(listOfNodes)
        self.pragmaLine = pragmaLine


class LoopOverCoordinate(Node):
    LOOP_COUNTER_NAME_PREFIX = "ctr"

Martin Bauer's avatar
Martin Bauer committed
197
    def __init__(self, body, coordinateToLoopOver, start, stop, step=1):
198
199
        self._body = body
        self._coordinateToLoopOver = coordinateToLoopOver
Martin Bauer's avatar
Martin Bauer committed
200
201
202
        self._begin = start
        self._end = stop
        self._increment = step
203
204
205
206
        self._body.parent = self
        self.prefixLines = []

    def newLoopWithDifferentBody(self, newBody):
Martin Bauer's avatar
Martin Bauer committed
207
        result = LoopOverCoordinate(newBody, self._coordinateToLoopOver, self._begin, self._end, self._increment)
208
209
210
211
212
213
        result.prefixLines = self.prefixLines
        return result

    @property
    def args(self):
        result = [self._body]
Martin Bauer's avatar
Martin Bauer committed
214
215
216
        for e in [self._begin, self._end, self._increment]:
            if hasattr(e, "args"):
                result.append(e)
217
218
219
220
221
222
223
        return result

    @property
    def body(self):
        return self._body

    @property
Martin Bauer's avatar
Martin Bauer committed
224
225
226
227
228
229
230
231
232
233
    def start(self):
        return self._begin

    @property
    def stop(self):
        return self._end

    @property
    def step(self):
        return self._increment
234
235
236
237
238
239
240

    @property
    def coordinateToLoopOver(self):
        return self._coordinateToLoopOver

    @property
    def symbolsDefined(self):
241
242
243
244
245
246
247
248
249
        return set([self.loopCounterSymbol])

    @property
    def undefinedSymbols(self):
        result = self._body.undefinedSymbols
        for possibleSymbol in [self._begin, self._end, self._increment]:
            if isinstance(possibleSymbol, Node) or isinstance(possibleSymbol, sp.Basic):
                result.update(possibleSymbol.atoms(sp.Symbol))
        return result - set([self.loopCounterSymbol])
250

Martin Bauer's avatar
Martin Bauer committed
251
252
253
254
    @staticmethod
    def getLoopCounterName(coordinateToLoopOver):
        return "%s_%s" % (LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX, coordinateToLoopOver)

255
256
    @property
    def loopCounterName(self):
Martin Bauer's avatar
Martin Bauer committed
257
258
259
260
261
        return LoopOverCoordinate.getLoopCounterName(self.coordinateToLoopOver)

    @staticmethod
    def getLoopCounterSymbol(coordinateToLoopOver):
        return TypedSymbol(LoopOverCoordinate.getLoopCounterName(coordinateToLoopOver), "int")
262
263
264

    @property
    def loopCounterSymbol(self):
Martin Bauer's avatar
Martin Bauer committed
265
        return LoopOverCoordinate.getLoopCounterSymbol(self.coordinateToLoopOver)
266
267
268

    @property
    def isOutermostLoop(self):
Martin Bauer's avatar
Martin Bauer committed
269
270
        from pystencils.transformations import getNextParentOfType
        return getNextParentOfType(self, LoopOverCoordinate) is None
271
272
273

    @property
    def isInnermostLoop(self):
Martin Bauer's avatar
Martin Bauer committed
274
        return len(self.atoms(LoopOverCoordinate)) == 0
275
276
277
278
279

    @property
    def coordinateToLoopOver(self):
        return self._coordinateToLoopOver

280
281
282
283
    def children(self):
        return self.body

    def __repr__(self):
284
285
        return 'loop:{!s} in {!s}:{!s}:{!s}\n{!s}'.format(self.loopCounterName, self.start, self.stop, self.step,
                                                          textwrap.indent(repr(self.body), '\t'))
286

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318

class SympyAssignment(Node):

    def __init__(self, lhsSymbol, rhsTerm, isConst=True):
        self._lhsSymbol = lhsSymbol
        self.rhs = rhsTerm
        self._isDeclaration = True
        if isinstance(self._lhsSymbol, Field.Access) or isinstance(self._lhsSymbol, IndexedBase):
            self._isDeclaration = False
        self._isConst = isConst

    @property
    def lhs(self):
        return self._lhsSymbol

    @lhs.setter
    def lhs(self, newValue):
        self._lhsSymbol = newValue
        self._isDeclaration = True
        if isinstance(self._lhsSymbol, Field.Access) or isinstance(self._lhsSymbol, Indexed):
            self._isDeclaration = False

    @property
    def args(self):
        return [self._lhsSymbol, self.rhs]

    @property
    def symbolsDefined(self):
        if not self._isDeclaration:
            return set()
        return set([self._lhsSymbol])

319

320
    @property
321
    def undefinedSymbols(self):
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
        result = self.rhs.atoms(sp.Symbol)
        result.update(self._lhsSymbol.atoms(sp.Symbol))
        return result

    @property
    def isDeclaration(self):
        return self._isDeclaration

    @property
    def isConst(self):
        return self._isConst

    def __repr__(self):
        return repr(self.lhs) + " = " + repr(self.rhs)


class TemporaryMemoryAllocation(Node):
    def __init__(self, typedSymbol, size):
        self.symbol = typedSymbol
        self.size = size

    @property
    def symbolsDefined(self):
345
        return set([self.symbol])
346
347

    @property
348
349
350
351
352
    def undefinedSymbols(self):
        if isinstance(self.size, sp.Basic):
            return self.size.atoms(sp.Symbol)
        else:
            return set()
353
354
355

    @property
    def args(self):
356
        return [self.symbol]
357
358
359
360


class TemporaryMemoryFree(Node):
    def __init__(self, typedSymbol):
361
        self.symbol = typedSymbol
362
363
364
365
366
367

    @property
    def symbolsDefined(self):
        return set()

    @property
368
    def undefinedSymbols(self):
369
370
371
372
373
374
        return set()

    @property
    def args(self):
        return []