astnodes.py 19 KB
Newer Older
1
import sympy as sp
2
from sympy.tensor import IndexedBase
3
from pystencils.field import Field
Martin Bauer's avatar
Martin Bauer committed
4
from pystencils.data_types import TypedSymbol, create_type, cast_func
Martin Bauer's avatar
Martin Bauer committed
5
from pystencils.sympyextensions import fast_subs
Martin Bauer's avatar
Martin Bauer committed
6
7
8
from typing import List, Set, Optional, Union, Any

NodeOrExpr = Union['Node', sp.Expr]
9
10


11
class Node:
Martin Bauer's avatar
Martin Bauer committed
12
    """Base class for all AST nodes."""
Martin Bauer's avatar
Martin Bauer committed
13

Martin Bauer's avatar
Martin Bauer committed
14
    def __init__(self, parent: Optional['Node'] = None):
15
16
        self.parent = parent

Martin Bauer's avatar
Martin Bauer committed
17
18
19
    @property
    def args(self) -> List[NodeOrExpr]:
        """Returns all arguments/children of this node."""
Martin Bauer's avatar
Martin Bauer committed
20
        raise NotImplementedError()
21
22

    @property
Martin Bauer's avatar
Martin Bauer committed
23
24
    def symbols_defined(self) -> Set[sp.Symbol]:
        """Set of symbols which are defined by this node."""
Martin Bauer's avatar
Martin Bauer committed
25
        raise NotImplementedError()
26
27

    @property
Martin Bauer's avatar
Martin Bauer committed
28
29
    def undefined_symbols(self) -> Set[sp.Symbol]:
        """Symbols which are used but are not defined inside this node."""
30
        raise NotImplementedError()
31

Martin Bauer's avatar
Martin Bauer committed
32
33
    def subs(self, *args, **kwargs) -> None:
        """Inplace! substitute, similar to sympy's but modifies the AST inplace."""
34
35
36
        for a in self.args:
            a.subs(*args, **kwargs)

37
38
39
40
    @property
    def func(self):
        return self.__class__

Martin Bauer's avatar
Martin Bauer committed
41
42
    def atoms(self, arg_type) -> Set[Any]:
        """Returns a set of all descendants recursively, which are an instance of the given type."""
43
44
        result = set()
        for arg in self.args:
Martin Bauer's avatar
Martin Bauer committed
45
            if isinstance(arg, arg_type):
46
                result.add(arg)
Martin Bauer's avatar
Martin Bauer committed
47
            result.update(arg.atoms(arg_type))
48
49
50
        return result


51
class Conditional(Node):
Martin Bauer's avatar
Martin Bauer committed
52
53
54
55
56
57
58
59
60
61
62
    """Conditional that maps to a 'if' statement in C/C++.

    Try to avoid using this node inside of loops, since currently this construction can not be vectorized.
    Consider using assignments with sympy.Piecewise in this case.

    Args:
        condition_expr: sympy relational expression
        true_block: block which is run if conditional is true
        false_block: optional block which is run if conditional is false
    """

Martin Bauer's avatar
Martin Bauer committed
63
64
    def __init__(self, condition_expr: sp.Basic, true_block: Union['Block', 'SympyAssignment'],
                 false_block: Optional['Block'] = None) -> None:
Martin Bauer's avatar
Martin Bauer committed
65
66
67
        super(Conditional, self).__init__(parent=None)

        assert condition_expr.is_Boolean or condition_expr.is_Relational
Martin Bauer's avatar
Martin Bauer committed
68
        self.condition_expr = condition_expr
Martin Bauer's avatar
Martin Bauer committed
69
70

        def handle_child(c):
71
72
73
74
75
76
77
            if c is None:
                return None
            if not isinstance(c, Block):
                c = Block([c])
            c.parent = self
            return c

Martin Bauer's avatar
Martin Bauer committed
78
79
        self.true_block = handle_child(true_block)
        self.false_block = handle_child(false_block)
80
81

    def subs(self, *args, **kwargs):
Martin Bauer's avatar
Martin Bauer committed
82
83
84
85
        self.true_block.subs(*args, **kwargs)
        if self.false_block:
            self.false_block.subs(*args, **kwargs)
        self.condition_expr = self.condition_expr.subs(*args, **kwargs)
86
87
88

    @property
    def args(self):
Martin Bauer's avatar
Martin Bauer committed
89
90
91
        result = [self.condition_expr, self.true_block]
        if self.false_block:
            result.append(self.false_block)
92
93
94
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
95
    def symbols_defined(self):
96
97
98
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
99
    def undefined_symbols(self):
Martin Bauer's avatar
Martin Bauer committed
100
101
102
103
        result = self.true_block.undefined_symbols
        if self.false_block:
            result.update(self.false_block.undefined_symbols)
        result.update(self.condition_expr.atoms(sp.Symbol))
104
105
106
        return result

    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
107
        return 'if:({!s}) '.format(self.condition_expr)
108
109

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
110
        return 'if:({!r}) '.format(self.condition_expr)
111

112
113
114
115
116
117
118
119
    def replace_by_true_block(self):
        """Replaces the conditional by its True block"""
        self.parent.replace(self, [self.true_block])

    def replace_by_false_block(self):
        """Replaces the conditional by its False block"""
        self.parent.replace(self, [self.false_block] if self.false_block else [])

120

121
122
123
class KernelFunction(Node):

    class Argument:
Martin Bauer's avatar
Martin Bauer committed
124
        def __init__(self, name, dtype, symbol, kernel_function_node):
Martin Bauer's avatar
Martin Bauer committed
125
            from pystencils.transformations import symbol_name_to_variable_name
126
            self.name = name
127
            self.dtype = dtype
Martin Bauer's avatar
Martin Bauer committed
128
129
130
131
            self.is_field_ptr_argument = False
            self.is_field_shape_argument = False
            self.is_field_stride_argument = False
            self.is_field_argument = False
Martin Bauer's avatar
Martin Bauer committed
132
            self.field_name = ""
133
            self.coordinate = None
134
            self.symbol = symbol
135
136

            if name.startswith(Field.DATA_PREFIX):
Martin Bauer's avatar
Martin Bauer committed
137
138
                self.is_field_ptr_argument = True
                self.is_field_argument = True
Martin Bauer's avatar
Martin Bauer committed
139
                self.field_name = name[len(Field.DATA_PREFIX):]
140
            elif name.startswith(Field.SHAPE_PREFIX):
Martin Bauer's avatar
Martin Bauer committed
141
142
                self.is_field_shape_argument = True
                self.is_field_argument = True
Martin Bauer's avatar
Martin Bauer committed
143
                self.field_name = name[len(Field.SHAPE_PREFIX):]
144
            elif name.startswith(Field.STRIDE_PREFIX):
Martin Bauer's avatar
Martin Bauer committed
145
146
                self.is_field_stride_argument = True
                self.is_field_argument = True
Martin Bauer's avatar
Martin Bauer committed
147
                self.field_name = name[len(Field.STRIDE_PREFIX):]
148

149
            self.field = None
Martin Bauer's avatar
Martin Bauer committed
150
            if self.is_field_argument:
Martin Bauer's avatar
Martin Bauer committed
151
152
                field_map = {symbol_name_to_variable_name(f.name): f for f in kernel_function_node.fields_accessed}
                self.field = field_map[self.field_name]
153

154
155
        def __lt__(self, other):
            def score(l):
Martin Bauer's avatar
Martin Bauer committed
156
                if l.is_field_ptr_argument:
157
                    return -4
Martin Bauer's avatar
Martin Bauer committed
158
                elif l.is_field_shape_argument:
159
                    return -3
Martin Bauer's avatar
Martin Bauer committed
160
                elif l.is_field_stride_argument:
161
162
163
164
165
166
167
168
169
170
                    return -2
                return 0

            if score(self) < score(other):
                return True
            elif score(self) == score(other):
                return self.name < other.name
            else:
                return False

171
172
173
        def __repr__(self):
            return '<{0} {1}>'.format(self.dtype, self.name)

Martin Bauer's avatar
Martin Bauer committed
174
    def __init__(self, body, ghost_layers=None, function_name="kernel", backend=""):
175
176
        super(KernelFunction, self).__init__()
        self._body = body
177
        body.parent = self
178
        self._parameters = None
Martin Bauer's avatar
Martin Bauer committed
179
        self.function_name = function_name
180
        self._body.parent = self
Martin Bauer's avatar
Martin Bauer committed
181
        self.compile = None
Martin Bauer's avatar
Martin Bauer committed
182
        self.ghost_layers = ghost_layers
183
        # these variables are assumed to be global, so no automatic parameter is generated for them
Martin Bauer's avatar
Martin Bauer committed
184
        self.global_variables = set()
185
        self.backend = backend
186
187

    @property
Martin Bauer's avatar
Martin Bauer committed
188
    def symbols_defined(self):
189
190
191
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
192
    def undefined_symbols(self):
193
194
195
196
        return set()

    @property
    def parameters(self):
Martin Bauer's avatar
Martin Bauer committed
197
        self._update_parameters()
198
199
200
201
202
203
204
205
        return self._parameters

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

    @property
    def args(self):
Jan Hoenig's avatar
Jan Hoenig committed
206
        return [self._body]
207

208
    @property
Martin Bauer's avatar
Martin Bauer committed
209
    def fields_accessed(self):
210
        """Set of Field instances: fields which are accessed inside this kernel function"""
Martin Bauer's avatar
Martin Bauer committed
211
        return set(o.field for o in self.atoms(ResolvedFieldAccess))
212

Martin Bauer's avatar
Martin Bauer committed
213
    def _update_parameters(self):
Martin Bauer's avatar
Martin Bauer committed
214
        undefined_symbols = self._body.undefined_symbols - self.global_variables
Martin Bauer's avatar
Martin Bauer committed
215
        self._parameters = [KernelFunction.Argument(s.name, s.dtype, s, self) for s in undefined_symbols]
216
217

        self._parameters.sort()
218

219
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
220
        self._update_parameters()
Martin Bauer's avatar
Martin Bauer committed
221
        return '{0} {1}({2})\n{3}'.format(type(self).__name__, self.function_name, self.parameters,
Michael Kuron's avatar
Michael Kuron committed
222
                                          ("\t" + "\t".join(str(self.body).splitlines(True))))
223
224

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
225
        self._update_parameters()
Martin Bauer's avatar
Martin Bauer committed
226
        return '{0} {1}({2})'.format(type(self).__name__, self.function_name, self.parameters)
227

228
229

class Block(Node):
Martin Bauer's avatar
Martin Bauer committed
230
231
232
    def __init__(self, nodes: List[Node]):
        super(Block, self).__init__()
        self._nodes = nodes
233
        self.parent = None
234
235
236
237
238
239
240
        for n in self._nodes:
            n.parent = self

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

Martin Bauer's avatar
Martin Bauer committed
241
    def insert_front(self, node):
242
243
244
        node.parent = self
        self._nodes.insert(0, node)

Martin Bauer's avatar
Martin Bauer committed
245
246
247
    def insert_before(self, new_node, insert_before):
        new_node.parent = self
        idx = self._nodes.index(insert_before)
248
249

        # move all assignment (definitions to the top)
Martin Bauer's avatar
Martin Bauer committed
250
        if isinstance(new_node, SympyAssignment) and new_node.is_declaration:
Martin Bauer's avatar
Martin Bauer committed
251
252
253
254
255
256
            while idx > 0:
                pn = self._nodes[idx - 1]
                if isinstance(pn, LoopOverCoordinate) or isinstance(pn, Conditional):
                    idx -= 1
                else:
                    break
Martin Bauer's avatar
Martin Bauer committed
257
        self._nodes.insert(idx, new_node)
Martin Bauer's avatar
Martin Bauer committed
258

259
    def append(self, node):
260
261
262
263
264
265
266
        if isinstance(node, list) or isinstance(node, tuple):
            for n in node:
                n.parent = self
                self._nodes.append(n)
        else:
            node.parent = self
            self._nodes.append(node)
267

Martin Bauer's avatar
Martin Bauer committed
268
    def take_child_nodes(self):
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
        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
Martin Bauer's avatar
Martin Bauer committed
285
    def symbols_defined(self):
286
287
        result = set()
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
288
            result.update(a.symbols_defined)
289
290
291
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
292
    def undefined_symbols(self):
293
        result = set()
Martin Bauer's avatar
Martin Bauer committed
294
        defined_symbols = set()
295
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
296
297
            result.update(a.undefined_symbols)
            defined_symbols.update(a.symbols_defined)
Martin Bauer's avatar
Martin Bauer committed
298
        return result - defined_symbols
299

300
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
301
        return "Block " + ''.join('{!s}\n'.format(node) for node in self._nodes)
302
303

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
304
        return "Block"
305

306
307

class PragmaBlock(Block):
Martin Bauer's avatar
Martin Bauer committed
308
309
    def __init__(self, pragma_line, nodes):
        super(PragmaBlock, self).__init__(nodes)
Martin Bauer's avatar
Martin Bauer committed
310
        self.pragma_line = pragma_line
Martin Bauer's avatar
Martin Bauer committed
311
        for n in nodes:
Martin Bauer's avatar
Martin Bauer committed
312
313
314
            n.parent = self

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
315
        return self.pragma_line
316
317
318
319
320


class LoopOverCoordinate(Node):
    LOOP_COUNTER_NAME_PREFIX = "ctr"

Martin Bauer's avatar
Martin Bauer committed
321
322
    def __init__(self, body, coordinate_to_loop_over, start, stop, step=1):
        super(LoopOverCoordinate, self).__init__(parent=None)
323
        self.body = body
324
        body.parent = self
Martin Bauer's avatar
Martin Bauer committed
325
        self.coordinate_to_loop_over = coordinate_to_loop_over
326
327
328
329
        self.start = start
        self.stop = stop
        self.step = step
        self.body.parent = self
Martin Bauer's avatar
Martin Bauer committed
330
        self.prefix_lines = []
331

Martin Bauer's avatar
Martin Bauer committed
332
    def new_loop_with_different_body(self, new_body):
Martin Bauer's avatar
Martin Bauer committed
333
334
        result = LoopOverCoordinate(new_body, self.coordinate_to_loop_over, self.start, self.stop, self.step)
        result.prefix_lines = [l for l in self.prefix_lines]
335
336
        return result

337
338
339
340
341
342
343
344
345
    def subs(self, *args, **kwargs):
        self.body.subs(*args, **kwargs)
        if hasattr(self.start, "subs"):
            self.start = self.start.subs(*args, **kwargs)
        if hasattr(self.stop, "subs"):
            self.stop = self.stop.subs(*args, **kwargs)
        if hasattr(self.step, "subs"):
            self.step = self.step.subs(*args, **kwargs)

346
347
    @property
    def args(self):
348
349
        result = [self.body]
        for e in [self.start, self.stop, self.step]:
Martin Bauer's avatar
Martin Bauer committed
350
351
            if hasattr(e, "args"):
                result.append(e)
352
353
        return result

354
355
356
357
358
359
360
361
362
363
    def replace(self, child, replacement):
        if child == self.body:
            self.body = replacement
        elif child == self.start:
            self.start = replacement
        elif child == self.step:
            self.step = replacement
        elif child == self.stop:
            self.stop = replacement

364
    @property
Martin Bauer's avatar
Martin Bauer committed
365
366
    def symbols_defined(self):
        return {self.loop_counter_symbol}
367
368

    @property
Martin Bauer's avatar
Martin Bauer committed
369
370
    def undefined_symbols(self):
        result = self.body.undefined_symbols
Martin Bauer's avatar
Martin Bauer committed
371
372
373
        for possible_symbol in [self.start, self.stop, self.step]:
            if isinstance(possible_symbol, Node) or isinstance(possible_symbol, sp.Basic):
                result.update(possible_symbol.atoms(sp.Symbol))
Martin Bauer's avatar
Martin Bauer committed
374
        return result - {self.loop_counter_symbol}
375

Martin Bauer's avatar
Martin Bauer committed
376
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
377
378
    def get_loop_counter_name(coordinate_to_loop_over):
        return "%s_%s" % (LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX, coordinate_to_loop_over)
Martin Bauer's avatar
Martin Bauer committed
379

380
    @property
Martin Bauer's avatar
Martin Bauer committed
381
    def loop_counter_name(self):
Martin Bauer's avatar
Martin Bauer committed
382
        return LoopOverCoordinate.get_loop_counter_name(self.coordinate_to_loop_over)
Martin Bauer's avatar
Martin Bauer committed
383

384
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
385
    def is_loop_counter_symbol(symbol):
386
387
388
        prefix = LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX
        if not symbol.name.startswith(prefix):
            return None
Martin Bauer's avatar
Martin Bauer committed
389
        if symbol.dtype != create_type('int'):
390
            return None
Martin Bauer's avatar
Martin Bauer committed
391
        coordinate = int(symbol.name[len(prefix) + 1:])
392
393
        return coordinate

Martin Bauer's avatar
Martin Bauer committed
394
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
395
396
    def get_loop_counter_symbol(coordinate_to_loop_over):
        return TypedSymbol(LoopOverCoordinate.get_loop_counter_name(coordinate_to_loop_over), 'int')
397
398

    @property
Martin Bauer's avatar
Martin Bauer committed
399
    def loop_counter_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
400
        return LoopOverCoordinate.get_loop_counter_symbol(self.coordinate_to_loop_over)
401
402

    @property
Martin Bauer's avatar
Martin Bauer committed
403
    def is_outermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
404
405
        from pystencils.transformations import get_next_parent_of_type
        return get_next_parent_of_type(self, LoopOverCoordinate) is None
406
407

    @property
Martin Bauer's avatar
Martin Bauer committed
408
    def is_innermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
409
        return len(self.atoms(LoopOverCoordinate)) == 0
410

411
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
412
413
414
        return 'for({!s}={!s}; {!s}<{!s}; {!s}+={!s})\n{!s}'.format(self.loop_counter_name, self.start,
                                                                    self.loop_counter_name, self.stop,
                                                                    self.loop_counter_name, self.step,
415
                                                                    ("\t" + "\t".join(str(self.body).splitlines(True))))
416
417

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
418
419
420
        return 'for({!s}={!s}; {!s}<{!s}; {!s}+={!s})'.format(self.loop_counter_name, self.start,
                                                              self.loop_counter_name, self.stop,
                                                              self.loop_counter_name, self.step)
421

422
423

class SympyAssignment(Node):
Martin Bauer's avatar
Martin Bauer committed
424
425
    def __init__(self, lhs_symbol, rhs_expr, is_const=True):
        super(SympyAssignment, self).__init__(parent=None)
Martin Bauer's avatar
Martin Bauer committed
426
        self._lhs_symbol = lhs_symbol
Martin Bauer's avatar
Martin Bauer committed
427
        self.rhs = rhs_expr
Martin Bauer's avatar
Martin Bauer committed
428
429
430
431
432
        self._is_declaration = True
        is_cast = self._lhs_symbol.func == cast_func
        if isinstance(self._lhs_symbol, Field.Access) or isinstance(self._lhs_symbol, ResolvedFieldAccess) or is_cast:
            self._is_declaration = False
        self._is_const = is_const
433
434
435

    @property
    def lhs(self):
Martin Bauer's avatar
Martin Bauer committed
436
        return self._lhs_symbol
437
438

    @lhs.setter
Martin Bauer's avatar
Martin Bauer committed
439
    def lhs(self, new_value):
Martin Bauer's avatar
Martin Bauer committed
440
441
442
443
444
        self._lhs_symbol = new_value
        self._is_declaration = True
        is_cast = self._lhs_symbol.func == cast_func
        if isinstance(self._lhs_symbol, Field.Access) or isinstance(self._lhs_symbol, sp.Indexed) or is_cast:
            self._is_declaration = False
445

446
    def subs(self, *args, **kwargs):
Martin Bauer's avatar
Martin Bauer committed
447
448
        self.lhs = fast_subs(self.lhs, *args, **kwargs)
        self.rhs = fast_subs(self.rhs, *args, **kwargs)
449

450
451
    @property
    def args(self):
Martin Bauer's avatar
Martin Bauer committed
452
        return [self._lhs_symbol, self.rhs]
453
454

    @property
Martin Bauer's avatar
Martin Bauer committed
455
    def symbols_defined(self):
Martin Bauer's avatar
Martin Bauer committed
456
        if not self._is_declaration:
457
            return set()
Martin Bauer's avatar
Martin Bauer committed
458
        return {self._lhs_symbol}
459
460

    @property
Martin Bauer's avatar
Martin Bauer committed
461
    def undefined_symbols(self):
462
        result = self.rhs.atoms(sp.Symbol)
463
        # Add loop counters if there a field accesses
Martin Bauer's avatar
Martin Bauer committed
464
        loop_counters = set()
465
466
467
        for symbol in result:
            if isinstance(symbol, Field.Access):
                for i in range(len(symbol.offsets)):
Martin Bauer's avatar
Martin Bauer committed
468
469
                    loop_counters.add(LoopOverCoordinate.get_loop_counter_symbol(i))
        result.update(loop_counters)
Martin Bauer's avatar
Martin Bauer committed
470
        result.update(self._lhs_symbol.atoms(sp.Symbol))
471
472
473
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
474
    def is_declaration(self):
Martin Bauer's avatar
Martin Bauer committed
475
        return self._is_declaration
476
477

    @property
Martin Bauer's avatar
Martin Bauer committed
478
    def is_const(self):
Martin Bauer's avatar
Martin Bauer committed
479
        return self._is_const
480

Jan Hoenig's avatar
Jan Hoenig committed
481
482
    def replace(self, child, replacement):
        if child == self.lhs:
483
484
            replacement.parent = self
            self.lhs = replacement
Jan Hoenig's avatar
Jan Hoenig committed
485
486
487
488
489
490
        elif child == self.rhs:
            replacement.parent = self
            self.rhs = replacement
        else:
            raise ValueError('%s is not in args of %s' % (replacement, self.__class__))

491
    def __repr__(self):
492
        return repr(self.lhs) + " ← " + repr(self.rhs)
493

Martin Bauer's avatar
Martin Bauer committed
494
495
496
    def _repr_html_(self):
        printed_lhs = sp.latex(self.lhs)
        printed_rhs = sp.latex(self.rhs)
497
        return "${printed_lhs} \leftarrow {printed_rhs}$".format(printed_lhs=printed_lhs, printed_rhs=printed_rhs)
Martin Bauer's avatar
Martin Bauer committed
498

499

Martin Bauer's avatar
Martin Bauer committed
500
class ResolvedFieldAccess(sp.Indexed):
Martin Bauer's avatar
Martin Bauer committed
501
    def __new__(cls, base, linearized_index, field, offsets, idx_coordinate_values):
Martin Bauer's avatar
Martin Bauer committed
502
503
        if not isinstance(base, IndexedBase):
            base = IndexedBase(base, shape=(1,))
Martin Bauer's avatar
Martin Bauer committed
504
        obj = super(ResolvedFieldAccess, cls).__new__(cls, base, linearized_index)
Martin Bauer's avatar
Martin Bauer committed
505
506
        obj.field = field
        obj.offsets = offsets
Martin Bauer's avatar
Martin Bauer committed
507
        obj.idx_coordinate_values = idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
508
509
510
511
512
        return obj

    def _eval_subs(self, old, new):
        return ResolvedFieldAccess(self.args[0],
                                   self.args[1].subs(old, new),
Martin Bauer's avatar
Martin Bauer committed
513
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
514

Martin Bauer's avatar
Martin Bauer committed
515
516
517
518
519
    def fast_subs(self, substitutions):
        if self in substitutions:
            return substitutions[self]
        return ResolvedFieldAccess(self.args[0].subs(substitutions),
                                   self.args[1].subs(substitutions),
Martin Bauer's avatar
Martin Bauer committed
520
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
521
522

    def _hashable_content(self):
Martin Bauer's avatar
Martin Bauer committed
523
        super_class_contents = super(ResolvedFieldAccess, self)._hashable_content()
Martin Bauer's avatar
Martin Bauer committed
524
        return super_class_contents + tuple(self.offsets) + (repr(self.idx_coordinate_values), hash(self.field))
Martin Bauer's avatar
Martin Bauer committed
525
526

    @property
Martin Bauer's avatar
Martin Bauer committed
527
    def typed_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
528
529
530
531
        return self.base.label

    def __str__(self):
        top = super(ResolvedFieldAccess, self).__str__()
Martin Bauer's avatar
Martin Bauer committed
532
        return "%s (%s)" % (top, self.typed_symbol.dtype)
Martin Bauer's avatar
Martin Bauer committed
533
534

    def __getnewargs__(self):
Martin Bauer's avatar
Martin Bauer committed
535
        return self.base, self.indices[0], self.field, self.offsets, self.idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
536
537


538
class TemporaryMemoryAllocation(Node):
Martin Bauer's avatar
Martin Bauer committed
539
540
541
    def __init__(self, typed_symbol, size):
        super(TemporaryMemoryAllocation, self).__init__(parent=None)
        self.symbol = typed_symbol
542
543
544
        self.size = size

    @property
Martin Bauer's avatar
Martin Bauer committed
545
546
    def symbols_defined(self):
        return {self.symbol}
547
548

    @property
Martin Bauer's avatar
Martin Bauer committed
549
    def undefined_symbols(self):
550
551
552
553
        if isinstance(self.size, sp.Basic):
            return self.size.atoms(sp.Symbol)
        else:
            return set()
554
555
556

    @property
    def args(self):
557
        return [self.symbol]
558
559
560


class TemporaryMemoryFree(Node):
Martin Bauer's avatar
Martin Bauer committed
561
562
563
    def __init__(self, typed_symbol):
        super(TemporaryMemoryFree, self).__init__(parent=None)
        self.symbol = typed_symbol
564
565

    @property
Martin Bauer's avatar
Martin Bauer committed
566
    def symbols_defined(self):
567
568
569
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
570
    def undefined_symbols(self):
571
572
573
574
575
        return set()

    @property
    def args(self):
        return []