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

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
    def subs(self, subs_dict) -> None:
Martin Bauer's avatar
Martin Bauer committed
33
        """Inplace! substitute, similar to sympy's but modifies the AST inplace."""
34
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
35
            a.subs(subs_dict)
36

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
        super(Conditional, self).__init__(parent=None)

Martin Bauer's avatar
Martin Bauer committed
67
        self.condition_expr = condition_expr
Martin Bauer's avatar
Martin Bauer committed
68
69

        def handle_child(c):
70
71
72
73
74
75
76
            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
77
78
        self.true_block = handle_child(true_block)
        self.false_block = handle_child(false_block)
79

Martin Bauer's avatar
Martin Bauer committed
80
81
    def subs(self, subs_dict):
        self.true_block.subs(subs_dict)
Martin Bauer's avatar
Martin Bauer committed
82
        if self.false_block:
Martin Bauer's avatar
Martin Bauer committed
83
84
            self.false_block.subs(subs_dict)
        self.condition_expr = self.condition_expr.subs(subs_dict)
85
86
87

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

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

    @property
Martin Bauer's avatar
Martin Bauer committed
98
    def undefined_symbols(self):
Martin Bauer's avatar
Martin Bauer committed
99
100
101
102
        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))
103
104
105
        return result

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

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

111
112
113
114
115
116
117
118
    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 [])

119

120
121
class KernelFunction(Node):

122
123
124
125
126
127
128
129
130
131
132
133
134
135
    class Parameter:
        """Function parameter.

        Each undefined symbol in a `KernelFunction` node becomes a parameter to the function.
        Parameters are either symbols introduced by the user that never occur on the left hand side of an
        Assignment, or are related to fields/arrays passed to the function.

        A parameter consists of the typed symbol (symbol property). For field related parameters this is a symbol
        defined in pystencils.kernelparameters.
        If the parameter is related to one or multiple fields, these fields are referenced in the fields property.
        """
        def __init__(self, symbol, fields):
            self.symbol = symbol  # type: TypedSymbol
            self.fields = fields  # type: Sequence[Field]
136

137
        def __repr__(self):
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
            return repr(self.symbol)

        @property
        def is_field_stride(self):
            return isinstance(self.symbol, FieldStrideSymbol)

        @property
        def is_field_shape(self):
            return isinstance(self.symbol, FieldShapeSymbol)

        @property
        def is_field_pointer(self):
            return isinstance(self.symbol, FieldPointerSymbol)

        @property
        def is_field_parameter(self):
            return self.is_field_pointer or self.is_field_shape or self.is_field_stride

        @property
        def field_name(self):
            return self.fields[0].name
159

Martin Bauer's avatar
Martin Bauer committed
160
    def __init__(self, body, ghost_layers=None, function_name="kernel", backend=""):
161
162
        super(KernelFunction, self).__init__()
        self._body = body
163
        body.parent = self
Martin Bauer's avatar
Martin Bauer committed
164
        self.function_name = function_name
165
        self._body.parent = self
Martin Bauer's avatar
Martin Bauer committed
166
        self.compile = None
Martin Bauer's avatar
Martin Bauer committed
167
        self.ghost_layers = ghost_layers
168
        # these variables are assumed to be global, so no automatic parameter is generated for them
Martin Bauer's avatar
Martin Bauer committed
169
        self.global_variables = set()
170
        self.backend = backend
Martin Bauer's avatar
Martin Bauer committed
171
        self.instruction_set = None  # used in `vectorize` function to tell the backend which i.s. (SSE,AVX) to use
172
173

    @property
Martin Bauer's avatar
Martin Bauer committed
174
    def symbols_defined(self):
175
176
177
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
178
    def undefined_symbols(self):
179
180
181
182
183
184
        return set()

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

Martin Bauer's avatar
Martin Bauer committed
185
186
187
188
189
    @body.setter
    def body(self, value):
        self._body = value
        self._body.parent = self

190
191
    @property
    def args(self):
Jan Hoenig's avatar
Jan Hoenig committed
192
        return [self._body]
193

194
    @property
195
    def fields_accessed(self) -> Set['ResolvedFieldAccess']:
196
        """Set of Field instances: fields which are accessed inside this kernel function"""
Martin Bauer's avatar
Martin Bauer committed
197
        return set(o.field for o in self.atoms(ResolvedFieldAccess))
198

199
200
201
202
203
    def get_parameters(self) -> Sequence['KernelFunction.Parameter']:
        """Returns list of parameters for this function.

        This function is expensive, cache the result where possible!
        """
204
        field_map = {f.name: f for f in self.fields_accessed}
205
206
207
208
209
210
211

        def get_fields(symbol):
            if hasattr(symbol, 'field_name'):
                return field_map[symbol.field_name],
            elif hasattr(symbol, 'field_names'):
                return tuple(field_map[fn] for fn in symbol.field_names)
            return ()
212

213
214
        argument_symbols = self._body.undefined_symbols - self.global_variables
        parameters = [self.Parameter(symbol, get_fields(symbol)) for symbol in argument_symbols]
215
216
        if hasattr(self, 'indexing'):
            parameters += [self.Parameter(s, []) for s in self.indexing.symbolic_parameters()]
217
218
        parameters.sort(key=lambda p: p.symbol.name)
        return parameters
219

220
    def __str__(self):
221
222
        params = [p.symbol for p in self.get_parameters()]
        return '{0} {1}({2})\n{3}'.format(type(self).__name__, self.function_name, params,
Michael Kuron's avatar
Michael Kuron committed
223
                                          ("\t" + "\t".join(str(self.body).splitlines(True))))
224
225

    def __repr__(self):
226
227
        params = [p.symbol for p in self.get_parameters()]
        return '{0} {1}({2})'.format(type(self).__name__, self.function_name, params)
228

229

Martin Bauer's avatar
Martin Bauer committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
class SkipIteration(Node):
    @property
    def args(self):
        return []

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

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


244
class Block(Node):
Martin Bauer's avatar
Martin Bauer committed
245
246
247
    def __init__(self, nodes: List[Node]):
        super(Block, self).__init__()
        self._nodes = nodes
248
        self.parent = None
249
250
251
252
253
254
255
        for n in self._nodes:
            n.parent = self

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

Martin Bauer's avatar
Martin Bauer committed
256
257
258
259
    def subs(self, subs_dict) -> None:
        for a in self.args:
            a.subs(subs_dict)

Martin Bauer's avatar
Martin Bauer committed
260
    def insert_front(self, node):
261
262
263
        node.parent = self
        self._nodes.insert(0, node)

Martin Bauer's avatar
Martin Bauer committed
264
265
266
    def insert_before(self, new_node, insert_before):
        new_node.parent = self
        idx = self._nodes.index(insert_before)
267
268

        # move all assignment (definitions to the top)
Martin Bauer's avatar
Martin Bauer committed
269
        if isinstance(new_node, SympyAssignment) and new_node.is_declaration:
Martin Bauer's avatar
Martin Bauer committed
270
271
272
273
274
275
            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
276
        self._nodes.insert(idx, new_node)
Martin Bauer's avatar
Martin Bauer committed
277

278
    def append(self, node):
279
280
281
282
283
284
285
        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)
286

Martin Bauer's avatar
Martin Bauer committed
287
    def take_child_nodes(self):
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
        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
304
    def symbols_defined(self):
305
306
        result = set()
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
307
            result.update(a.symbols_defined)
308
309
310
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
311
    def undefined_symbols(self):
312
        result = set()
Martin Bauer's avatar
Martin Bauer committed
313
        defined_symbols = set()
314
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
315
316
            result.update(a.undefined_symbols)
            defined_symbols.update(a.symbols_defined)
Martin Bauer's avatar
Martin Bauer committed
317
        return result - defined_symbols
318

319
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
320
        return "Block " + ''.join('{!s}\n'.format(node) for node in self._nodes)
321
322

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
323
        return "Block"
324

325
326

class PragmaBlock(Block):
Martin Bauer's avatar
Martin Bauer committed
327
328
    def __init__(self, pragma_line, nodes):
        super(PragmaBlock, self).__init__(nodes)
Martin Bauer's avatar
Martin Bauer committed
329
        self.pragma_line = pragma_line
Martin Bauer's avatar
Martin Bauer committed
330
        for n in nodes:
Martin Bauer's avatar
Martin Bauer committed
331
332
333
            n.parent = self

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
334
        return self.pragma_line
335
336
337
338


class LoopOverCoordinate(Node):
    LOOP_COUNTER_NAME_PREFIX = "ctr"
Martin Bauer's avatar
Martin Bauer committed
339
    BlOCK_LOOP_COUNTER_NAME_PREFIX = "_blockctr"
340

Martin Bauer's avatar
Martin Bauer committed
341
    def __init__(self, body, coordinate_to_loop_over, start, stop, step=1, is_block_loop=False):
Martin Bauer's avatar
Martin Bauer committed
342
        super(LoopOverCoordinate, self).__init__(parent=None)
343
        self.body = body
344
        body.parent = self
Martin Bauer's avatar
Martin Bauer committed
345
        self.coordinate_to_loop_over = coordinate_to_loop_over
346
347
348
349
        self.start = start
        self.stop = stop
        self.step = step
        self.body.parent = self
Martin Bauer's avatar
Martin Bauer committed
350
        self.prefix_lines = []
Martin Bauer's avatar
Martin Bauer committed
351
        self.is_block_loop = is_block_loop
352

Martin Bauer's avatar
Martin Bauer committed
353
    def new_loop_with_different_body(self, new_body):
Martin Bauer's avatar
Martin Bauer committed
354
355
        result = LoopOverCoordinate(new_body, self.coordinate_to_loop_over, self.start, self.stop,
                                    self.step, self.is_block_loop)
Martin Bauer's avatar
Martin Bauer committed
356
        result.prefix_lines = [l for l in self.prefix_lines]
357
358
        return result

Martin Bauer's avatar
Martin Bauer committed
359
360
    def subs(self, subs_dict):
        self.body.subs(subs_dict)
361
        if hasattr(self.start, "subs"):
Martin Bauer's avatar
Martin Bauer committed
362
            self.start = self.start.subs(subs_dict)
363
        if hasattr(self.stop, "subs"):
Martin Bauer's avatar
Martin Bauer committed
364
            self.stop = self.stop.subs(subs_dict)
365
        if hasattr(self.step, "subs"):
Martin Bauer's avatar
Martin Bauer committed
366
            self.step = self.step.subs(subs_dict)
367

368
369
    @property
    def args(self):
370
371
        result = [self.body]
        for e in [self.start, self.stop, self.step]:
Martin Bauer's avatar
Martin Bauer committed
372
373
            if hasattr(e, "args"):
                result.append(e)
374
375
        return result

376
377
378
379
380
381
382
383
384
385
    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

386
    @property
Martin Bauer's avatar
Martin Bauer committed
387
388
    def symbols_defined(self):
        return {self.loop_counter_symbol}
389
390

    @property
Martin Bauer's avatar
Martin Bauer committed
391
392
    def undefined_symbols(self):
        result = self.body.undefined_symbols
Martin Bauer's avatar
Martin Bauer committed
393
394
395
        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
396
        return result - {self.loop_counter_symbol}
397

Martin Bauer's avatar
Martin Bauer committed
398
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
399
400
    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
401

Martin Bauer's avatar
Martin Bauer committed
402
403
404
405
    @staticmethod
    def get_block_loop_counter_name(coordinate_to_loop_over):
        return "%s_%s" % (LoopOverCoordinate.BlOCK_LOOP_COUNTER_NAME_PREFIX, coordinate_to_loop_over)

406
    @property
Martin Bauer's avatar
Martin Bauer committed
407
    def loop_counter_name(self):
Martin Bauer's avatar
Martin Bauer committed
408
409
410
411
        if self.is_block_loop:
            return LoopOverCoordinate.get_block_loop_counter_name(self.coordinate_to_loop_over)
        else:
            return LoopOverCoordinate.get_loop_counter_name(self.coordinate_to_loop_over)
Martin Bauer's avatar
Martin Bauer committed
412

413
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
414
    def is_loop_counter_symbol(symbol):
415
416
417
        prefix = LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX
        if not symbol.name.startswith(prefix):
            return None
Martin Bauer's avatar
Martin Bauer committed
418
        if symbol.dtype != create_type('int'):
419
            return None
Martin Bauer's avatar
Martin Bauer committed
420
        coordinate = int(symbol.name[len(prefix) + 1:])
421
422
        return coordinate

Martin Bauer's avatar
Martin Bauer committed
423
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
424
425
    def get_loop_counter_symbol(coordinate_to_loop_over):
        return TypedSymbol(LoopOverCoordinate.get_loop_counter_name(coordinate_to_loop_over), 'int')
426

Martin Bauer's avatar
Martin Bauer committed
427
428
429
430
    @staticmethod
    def get_block_loop_counter_symbol(coordinate_to_loop_over):
        return TypedSymbol(LoopOverCoordinate.get_block_loop_counter_name(coordinate_to_loop_over), 'int')

431
    @property
Martin Bauer's avatar
Martin Bauer committed
432
    def loop_counter_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
433
434
435
436
        if self.is_block_loop:
            return self.get_block_loop_counter_symbol(self.coordinate_to_loop_over)
        else:
            return self.get_loop_counter_symbol(self.coordinate_to_loop_over)
437
438

    @property
Martin Bauer's avatar
Martin Bauer committed
439
    def is_outermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
440
441
        from pystencils.transformations import get_next_parent_of_type
        return get_next_parent_of_type(self, LoopOverCoordinate) is None
442
443

    @property
Martin Bauer's avatar
Martin Bauer committed
444
    def is_innermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
445
        return len(self.atoms(LoopOverCoordinate)) == 0
446

447
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
448
449
450
        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,
451
                                                                    ("\t" + "\t".join(str(self.body).splitlines(True))))
452
453

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
454
455
456
        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)
457

458
459

class SympyAssignment(Node):
Martin Bauer's avatar
Martin Bauer committed
460
461
    def __init__(self, lhs_symbol, rhs_expr, is_const=True):
        super(SympyAssignment, self).__init__(parent=None)
Martin Bauer's avatar
Martin Bauer committed
462
        self._lhs_symbol = lhs_symbol
Martin Bauer's avatar
Martin Bauer committed
463
        self.rhs = rhs_expr
Martin Bauer's avatar
Martin Bauer committed
464
        self._is_const = is_const
Martin Bauer's avatar
Martin Bauer committed
465
466
467
468
469
470
471
472
        self._is_declaration = self.__is_declaration()

    def __is_declaration(self):
        if isinstance(self._lhs_symbol, cast_func):
            return False
        if any(isinstance(self._lhs_symbol, c) for c in (Field.Access, sp.Indexed, TemporaryMemoryAllocation)):
            return False
        return True
473
474
475

    @property
    def lhs(self):
Martin Bauer's avatar
Martin Bauer committed
476
        return self._lhs_symbol
477
478

    @lhs.setter
Martin Bauer's avatar
Martin Bauer committed
479
    def lhs(self, new_value):
Martin Bauer's avatar
Martin Bauer committed
480
        self._lhs_symbol = new_value
Martin Bauer's avatar
Martin Bauer committed
481
        self._is_declaration = self.__is_declaration()
482

Martin Bauer's avatar
Martin Bauer committed
483
484
485
    def subs(self, subs_dict):
        self.lhs = fast_subs(self.lhs, subs_dict)
        self.rhs = fast_subs(self.rhs, subs_dict)
486

487
488
    @property
    def args(self):
Martin Bauer's avatar
Martin Bauer committed
489
        return [self._lhs_symbol, self.rhs]
490
491

    @property
Martin Bauer's avatar
Martin Bauer committed
492
    def symbols_defined(self):
Martin Bauer's avatar
Martin Bauer committed
493
        if not self._is_declaration:
494
            return set()
Martin Bauer's avatar
Martin Bauer committed
495
        return {self._lhs_symbol}
496
497

    @property
Martin Bauer's avatar
Martin Bauer committed
498
    def undefined_symbols(self):
499
        result = self.rhs.atoms(sp.Symbol)
500
        # Add loop counters if there a field accesses
Martin Bauer's avatar
Martin Bauer committed
501
        loop_counters = set()
502
503
504
        for symbol in result:
            if isinstance(symbol, Field.Access):
                for i in range(len(symbol.offsets)):
Martin Bauer's avatar
Martin Bauer committed
505
506
                    loop_counters.add(LoopOverCoordinate.get_loop_counter_symbol(i))
        result.update(loop_counters)
Martin Bauer's avatar
Martin Bauer committed
507
        result.update(self._lhs_symbol.atoms(sp.Symbol))
508
509
510
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
511
    def is_declaration(self):
Martin Bauer's avatar
Martin Bauer committed
512
        return self._is_declaration
513
514

    @property
Martin Bauer's avatar
Martin Bauer committed
515
    def is_const(self):
Martin Bauer's avatar
Martin Bauer committed
516
        return self._is_const
517

Jan Hoenig's avatar
Jan Hoenig committed
518
519
    def replace(self, child, replacement):
        if child == self.lhs:
520
521
            replacement.parent = self
            self.lhs = replacement
Jan Hoenig's avatar
Jan Hoenig committed
522
523
524
525
526
527
        elif child == self.rhs:
            replacement.parent = self
            self.rhs = replacement
        else:
            raise ValueError('%s is not in args of %s' % (replacement, self.__class__))

528
    def __repr__(self):
529
        return repr(self.lhs) + " ← " + repr(self.rhs)
530

Martin Bauer's avatar
Martin Bauer committed
531
532
533
    def _repr_html_(self):
        printed_lhs = sp.latex(self.lhs)
        printed_rhs = sp.latex(self.rhs)
Martin Bauer's avatar
Martin Bauer committed
534
        return "${printed_lhs} \\leftarrow {printed_rhs}$".format(printed_lhs=printed_lhs, printed_rhs=printed_rhs)
Martin Bauer's avatar
Martin Bauer committed
535

536

Martin Bauer's avatar
Martin Bauer committed
537
class ResolvedFieldAccess(sp.Indexed):
Martin Bauer's avatar
Martin Bauer committed
538
    def __new__(cls, base, linearized_index, field, offsets, idx_coordinate_values):
539
540
        if not isinstance(base, sp.IndexedBase):
            base = sp.IndexedBase(base, shape=(1,))
Martin Bauer's avatar
Martin Bauer committed
541
        obj = super(ResolvedFieldAccess, cls).__new__(cls, base, linearized_index)
Martin Bauer's avatar
Martin Bauer committed
542
543
        obj.field = field
        obj.offsets = offsets
Martin Bauer's avatar
Martin Bauer committed
544
        obj.idx_coordinate_values = idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
545
546
547
548
549
        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
550
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
551

Martin Bauer's avatar
Martin Bauer committed
552
553
554
555
556
    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
557
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
558
559

    def _hashable_content(self):
Martin Bauer's avatar
Martin Bauer committed
560
        super_class_contents = super(ResolvedFieldAccess, self)._hashable_content()
Martin Bauer's avatar
Martin Bauer committed
561
        return super_class_contents + tuple(self.offsets) + (repr(self.idx_coordinate_values), hash(self.field))
Martin Bauer's avatar
Martin Bauer committed
562
563

    @property
Martin Bauer's avatar
Martin Bauer committed
564
    def typed_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
565
566
567
568
        return self.base.label

    def __str__(self):
        top = super(ResolvedFieldAccess, self).__str__()
Martin Bauer's avatar
Martin Bauer committed
569
        return "%s (%s)" % (top, self.typed_symbol.dtype)
Martin Bauer's avatar
Martin Bauer committed
570
571

    def __getnewargs__(self):
Martin Bauer's avatar
Martin Bauer committed
572
        return self.base, self.indices[0], self.field, self.offsets, self.idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
573
574


575
class TemporaryMemoryAllocation(Node):
Martin Bauer's avatar
Martin Bauer committed
576
577
578
579
580
581
582
583
584
585
    """Node for temporary memory buffer allocation.

    Always allocates aligned memory.

    Args:
        typed_symbol: symbol used as pointer (has to be typed)
        size: number of elements to allocate
        align_offset: the align_offset's element is aligned
    """
    def __init__(self, typed_symbol: TypedSymbol, size, align_offset):
Martin Bauer's avatar
Martin Bauer committed
586
587
        super(TemporaryMemoryAllocation, self).__init__(parent=None)
        self.symbol = typed_symbol
588
        self.size = size
Martin Bauer's avatar
Martin Bauer committed
589
590
        self.headers = ['<stdlib.h>']
        self._align_offset = align_offset
591
592

    @property
Martin Bauer's avatar
Martin Bauer committed
593
594
    def symbols_defined(self):
        return {self.symbol}
595
596

    @property
Martin Bauer's avatar
Martin Bauer committed
597
    def undefined_symbols(self):
598
599
600
601
        if isinstance(self.size, sp.Basic):
            return self.size.atoms(sp.Symbol)
        else:
            return set()
602
603
604

    @property
    def args(self):
605
        return [self.symbol]
606

Martin Bauer's avatar
Martin Bauer committed
607
608
609
610
611
612
    def offset(self, byte_alignment):
        """Number of ELEMENTS to skip for a pointer that is aligned to byte_alignment."""
        np_dtype = self.symbol.dtype.base_type.numpy_dtype
        assert byte_alignment % np_dtype.itemsize == 0
        return -self._align_offset % (byte_alignment / np_dtype.itemsize)

613
614

class TemporaryMemoryFree(Node):
Martin Bauer's avatar
Martin Bauer committed
615
    def __init__(self, alloc_node):
Martin Bauer's avatar
Martin Bauer committed
616
        super(TemporaryMemoryFree, self).__init__(parent=None)
Martin Bauer's avatar
Martin Bauer committed
617
618
619
620
621
622
623
624
        self.alloc_node = alloc_node

    @property
    def symbol(self):
        return self.alloc_node.symbol

    def offset(self, byte_alignment):
        return self.alloc_node.offset(byte_alignment)
625
626

    @property
Martin Bauer's avatar
Martin Bauer committed
627
    def symbols_defined(self):
628
629
630
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
631
    def undefined_symbols(self):
632
633
634
635
636
        return set()

    @property
    def args(self):
        return []
Martin Bauer's avatar
Martin Bauer committed
637
638
639
640
641


def early_out(condition):
    from pystencils.cpu.vectorization import vec_all
    return Conditional(vec_all(condition), Block([SkipIteration()]))