cbackend.py 25.8 KB
Newer Older
Martin Bauer's avatar
Martin Bauer committed
1
from collections import namedtuple
2
from typing import Set
3

4
import numpy as np
5
6
import sympy as sp
from sympy.core import S
7
from sympy.printing.ccode import C89CodePrinter
8

9
from pystencils.astnodes import KernelFunction, Node
10
from pystencils.cpu.vectorization import vec_all, vec_any
Martin Bauer's avatar
Martin Bauer committed
11
from pystencils.data_types import (
12
13
    PointerType, VectorType, address_of, cast_func, create_type, get_type_of_expression,
    reinterpret_cast_func, vector_memory_access)
Martin Bauer's avatar
Martin Bauer committed
14
15
from pystencils.fast_approximation import fast_division, fast_inv_sqrt, fast_sqrt
from pystencils.integer_functions import (
16
17
    bit_shift_left, bit_shift_right, bitwise_and, bitwise_or, bitwise_xor,
    int_div, int_power_of_2, modulo_ceil)
18

Martin Bauer's avatar
Martin Bauer committed
19
20
try:
    from sympy.printing.ccode import C99CodePrinter as CCodePrinter
Martin Bauer's avatar
Martin Bauer committed
21
22
except ImportError:
    from sympy.printing.ccode import CCodePrinter  # for sympy versions < 1.1
Martin Bauer's avatar
Martin Bauer committed
23

24
__all__ = ['generate_c', 'CustomCodeNode', 'PrintNode', 'get_headers', 'CustomSympyPrinter']
25

26
27
KERNCRAFT_NO_TERNARY_MODE = False

Martin Bauer's avatar
Fixes    
Martin Bauer committed
28

29
30
31
32
33
def generate_c(ast_node: Node,
               signature_only: bool = False,
               dialect='c',
               custom_backend=None,
               with_globals=True) -> str:
Martin Bauer's avatar
Martin Bauer committed
34
35
36
37
38
39
40
41
42
    """Prints an abstract syntax tree node as C or CUDA code.

    This function does not need to distinguish between C, C++ or CUDA code, it just prints 'C-like' code as encoded
    in the abstract syntax tree (AST). The AST is built differently for C or CUDA by calling different create_kernel
    functions.

    Args:
        ast_node:
        signature_only:
43
        dialect: 'c' or 'cuda'
Martin Bauer's avatar
Martin Bauer committed
44
45
    Returns:
        C-like code for the ast node and its descendants
Martin Bauer's avatar
Martin Bauer committed
46
    """
47
48
49
50
51
52
    global_declarations = get_global_declarations(ast_node)
    for d in global_declarations:
        if hasattr(ast_node, "global_variables"):
            ast_node.global_variables.update(d.symbols_defined)
        else:
            ast_node.global_variables = d.symbols_defined
53
54
55
    if custom_backend:
        printer = custom_backend
    elif dialect == 'c':
56
57
58
59
        try:
            instruction_set = ast_node.instruction_set
        except Exception:
            instruction_set = None
60
        printer = CBackend(signature_only=signature_only,
61
                           vector_instruction_set=instruction_set)
62
63
64
    elif dialect == 'cuda':
        from pystencils.backends.cuda_backend import CudaBackend
        printer = CudaBackend(signature_only=signature_only)
Stephan Seitz's avatar
Stephan Seitz committed
65
    elif dialect == 'opencl':
66
67
        from pystencils.backends.opencl_backend import OpenClBackend
        printer = OpenClBackend(signature_only=signature_only)
68
    else:
Martin Bauer's avatar
Martin Bauer committed
69
        raise ValueError("Unknown dialect: " + str(dialect))
70
71
    code = printer(ast_node)
    if not signature_only and isinstance(ast_node, KernelFunction):
72
73
74
75
        if with_globals and global_declarations:
            code = "\n" + code
            for declaration in global_declarations:
                code = printer(declaration) + "\n" + code
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

    return code


def get_global_declarations(ast):
    global_declarations = []

    def visit_node(sub_ast):
        if hasattr(sub_ast, "required_global_declarations"):
            nonlocal global_declarations
            global_declarations += sub_ast.required_global_declarations

        if hasattr(sub_ast, "args"):
            for node in sub_ast.args:
                visit_node(node)

    visit_node(ast)

94
    return sorted(set(global_declarations), key=lambda x: str(x))
95
96


Martin Bauer's avatar
Martin Bauer committed
97
98
def get_headers(ast_node: Node) -> Set[str]:
    """Return a set of header files, necessary to compile the printed C-like code."""
99
100
    headers = set()

Martin Bauer's avatar
Martin Bauer committed
101
102
103
    if isinstance(ast_node, KernelFunction) and ast_node.instruction_set:
        headers.update(ast_node.instruction_set['headers'])

Martin Bauer's avatar
Martin Bauer committed
104
105
106
    if hasattr(ast_node, 'headers'):
        headers.update(ast_node.headers)
    for a in ast_node.args:
107
        if isinstance(a, Node):
Martin Bauer's avatar
Martin Bauer committed
108
            headers.update(get_headers(a))
109

110
111
112
113
    for g in get_global_declarations(ast_node):
        if isinstance(g, Node):
            headers.update(get_headers(g))

114
    return sorted(headers)
115
116


117
118
119
# --------------------------------------- Backend Specific Nodes -------------------------------------------------------


120
class CustomCodeNode(Node):
Martin Bauer's avatar
Martin Bauer committed
121
    def __init__(self, code, symbols_read, symbols_defined, parent=None):
122
        super(CustomCodeNode, self).__init__(parent=parent)
123
        self._code = "\n" + code
124
125
        self._symbols_read = set(symbols_read)
        self._symbols_defined = set(symbols_defined)
126
        self.headers = []
127

128
    def get_code(self, dialect, vector_instruction_set):
129
130
131
132
133
134
135
        return self._code

    @property
    def args(self):
        return []

    @property
Martin Bauer's avatar
Martin Bauer committed
136
    def symbols_defined(self):
137
        return self._symbols_defined
138
139

    @property
Martin Bauer's avatar
Martin Bauer committed
140
    def undefined_symbols(self):
141
        return self._symbols_read - self._symbols_defined
142

143
144
145
146
147
148
    def __eq___(self, other):
        return self._code == other._code

    def __hash__(self):
        return hash(self._code)

149

150
class PrintNode(CustomCodeNode):
Martin Bauer's avatar
Martin Bauer committed
151
152
153
154
    # noinspection SpellCheckingInspection
    def __init__(self, symbol_to_print):
        code = '\nstd::cout << "%s  =  " << %s << std::endl; \n' % (symbol_to_print.name, symbol_to_print.name)
        super(PrintNode, self).__init__(code, symbols_read=[symbol_to_print], symbols_defined=set())
155
        self.headers.append("<iostream>")
156
157
158
159


# ------------------------------------------- Printer ------------------------------------------------------------------

160

Martin Bauer's avatar
Martin Bauer committed
161
162
# noinspection PyPep8Naming
class CBackend:
163

Martin Bauer's avatar
Martin Bauer committed
164
    def __init__(self, sympy_printer=None, signature_only=False, vector_instruction_set=None, dialect='c'):
Martin Bauer's avatar
Martin Bauer committed
165
166
        if sympy_printer is None:
            if vector_instruction_set is not None:
167
                self.sympy_printer = VectorizedCustomSympyPrinter(vector_instruction_set)
168
            else:
169
                self.sympy_printer = CustomSympyPrinter()
170
        else:
Martin Bauer's avatar
Martin Bauer committed
171
            self.sympy_printer = sympy_printer
172

173
        self._vector_instruction_set = vector_instruction_set
174
        self._indent = "   "
175
        self._dialect = dialect
Martin Bauer's avatar
Martin Bauer committed
176
        self._signatureOnly = signature_only
177
178

    def __call__(self, node):
Martin Bauer's avatar
Martin Bauer committed
179
        prev_is = VectorType.instruction_set
180
        VectorType.instruction_set = self._vector_instruction_set
181
        result = str(self._print(node))
Martin Bauer's avatar
Martin Bauer committed
182
        VectorType.instruction_set = prev_is
183
        return result
184
185

    def _print(self, node):
Stephan Seitz's avatar
Stephan Seitz committed
186
187
        if isinstance(node, str):
            return node
188
        for cls in type(node).__mro__:
Martin Bauer's avatar
Martin Bauer committed
189
190
191
            method_name = "_print_" + cls.__name__
            if hasattr(self, method_name):
                return getattr(self, method_name)(node)
192
        raise NotImplementedError(self.__class__.__name__ + " does not support node of type " + node.__class__.__name__)
193

194
195
196
    def _print_Type(self, node):
        return str(node)

197
    def _print_KernelFunction(self, node):
198
        function_arguments = ["%s %s" % (self._print(s.symbol.dtype), s.symbol.name) for s in node.get_parameters()]
199
        launch_bounds = ""
200
        if self._dialect == 'cuda':
201
202
203
204
205
            max_threads = node.indexing.max_threads_per_block()
            if max_threads:
                launch_bounds = "__launch_bounds__({}) ".format(max_threads)
        func_declaration = "FUNC_PREFIX %svoid %s(%s)" % (launch_bounds, node.function_name,
                                                          ", ".join(function_arguments))
206
        if self._signatureOnly:
Martin Bauer's avatar
Martin Bauer committed
207
            return func_declaration
208

209
        body = self._print(node.body)
Martin Bauer's avatar
Martin Bauer committed
210
        return func_declaration + "\n" + body
211
212

    def _print_Block(self, node):
Martin Bauer's avatar
Martin Bauer committed
213
214
        block_contents = "\n".join([self._print(child) for child in node.args])
        return "{\n%s\n}" % (self._indent + self._indent.join(block_contents.splitlines(True)))
215
216

    def _print_PragmaBlock(self, node):
Martin Bauer's avatar
Martin Bauer committed
217
        return "%s\n%s" % (node.pragma_line, self._print_Block(node))
218
219

    def _print_LoopOverCoordinate(self, node):
Martin Bauer's avatar
Martin Bauer committed
220
        counter_symbol = node.loop_counter_name
Martin Bauer's avatar
Martin Bauer committed
221
222
223
224
        start = "int %s = %s" % (counter_symbol, self.sympy_printer.doprint(node.start))
        condition = "%s < %s" % (counter_symbol, self.sympy_printer.doprint(node.stop))
        update = "%s += %s" % (counter_symbol, self.sympy_printer.doprint(node.step),)
        loop_str = "for (%s; %s; %s)" % (start, condition, update)
225

Martin Bauer's avatar
Martin Bauer committed
226
        prefix = "\n".join(node.prefix_lines)
227
228
        if prefix:
            prefix += "\n"
Martin Bauer's avatar
Martin Bauer committed
229
        return "%s%s\n%s" % (prefix, loop_str, self._print(node.body))
230
231

    def _print_SympyAssignment(self, node):
Martin Bauer's avatar
Martin Bauer committed
232
        if node.is_declaration:
Stephan Seitz's avatar
Lint    
Stephan Seitz committed
233
234
235
236
            if node.is_const:
                prefix = 'const '
            else:
                prefix = ''
237
            data_type = prefix + self._print(node.lhs.dtype).replace(' const', '') + " "
238
239
            return "%s%s = %s;" % (data_type, self.sympy_printer.doprint(node.lhs),
                                   self.sympy_printer.doprint(node.rhs))
240
        else:
Martin Bauer's avatar
Martin Bauer committed
241
            lhs_type = get_type_of_expression(node.lhs)
Martin Bauer's avatar
Martin Bauer committed
242
243
244
245
246
247
            if type(lhs_type) is VectorType and isinstance(node.lhs, cast_func):
                arg, data_type, aligned, nontemporal = node.lhs.args
                instr = 'storeU'
                if aligned:
                    instr = 'stream' if nontemporal else 'storeA'

248
249
250
251
252
253
                rhs_type = get_type_of_expression(node.rhs)
                if type(rhs_type) is not VectorType:
                    rhs = cast_func(node.rhs, VectorType(rhs_type))
                else:
                    rhs = node.rhs

254
255
                return self._vector_instruction_set[instr].format("&" + self.sympy_printer.doprint(node.lhs.args[0]),
                                                                  self.sympy_printer.doprint(rhs)) + ';'
256
            else:
Martin Bauer's avatar
Martin Bauer committed
257
                return "%s = %s;" % (self.sympy_printer.doprint(node.lhs), self.sympy_printer.doprint(node.rhs))
258
259

    def _print_TemporaryMemoryAllocation(self, node):
260
        align = 64
Martin Bauer's avatar
Martin Bauer committed
261
262
263
264
265
266
        np_dtype = node.symbol.dtype.base_type.numpy_dtype
        required_size = np_dtype.itemsize * node.size + align
        size = modulo_ceil(required_size, align)
        code = "{dtype} {name}=({dtype})aligned_alloc({align}, {size}) + {offset};"
        return code.format(dtype=node.symbol.dtype,
                           name=self.sympy_printer.doprint(node.symbol.name),
267
                           size=self.sympy_printer.doprint(size),
Martin Bauer's avatar
Martin Bauer committed
268
269
                           offset=int(node.offset(align)),
                           align=align)
270
271

    def _print_TemporaryMemoryFree(self, node):
272
        align = 64
Martin Bauer's avatar
Martin Bauer committed
273
        return "free(%s - %d);" % (self.sympy_printer.doprint(node.symbol.name), node.offset(align))
274

Martin Bauer's avatar
Martin Bauer committed
275
    def _print_SkipIteration(self, _):
276
        return "continue;"
Martin Bauer's avatar
Martin Bauer committed
277

278
279
    def _print_CustomCodeNode(self, node):
        return node.get_code(self._dialect, self._vector_instruction_set)
280

281
282
283
284
285
286
    def _print_SourceCodeComment(self, node):
        return "/* " + node.text + " */"

    def _print_EmptyLine(self, node):
        return ""

287
    def _print_Conditional(self, node):
288
289
290
        cond_type = get_type_of_expression(node.condition_expr)
        if isinstance(cond_type, VectorType):
            raise ValueError("Problem with Conditional inside vectorized loop - use vec_any or vec_all")
Martin Bauer's avatar
Martin Bauer committed
291
292
        condition_expr = self.sympy_printer.doprint(node.condition_expr)
        true_block = self._print_Block(node.true_block)
Martin Bauer's avatar
Martin Bauer committed
293
        result = "if (%s)\n%s " % (condition_expr, true_block)
Martin Bauer's avatar
Martin Bauer committed
294
295
        if node.false_block:
            false_block = self._print_Block(node.false_block)
Martin Bauer's avatar
Martin Bauer committed
296
            result += "else " + false_block
297
298
        return result

299
300
301
302

# ------------------------------------------ Helper function & classes -------------------------------------------------


Martin Bauer's avatar
Martin Bauer committed
303
# noinspection PyPep8Naming
304
class CustomSympyPrinter(CCodePrinter):
Martin Bauer's avatar
Martin Bauer committed
305

306
    def __init__(self):
Martin Bauer's avatar
Martin Bauer committed
307
        super(CustomSympyPrinter, self).__init__()
308
        self._float_type = create_type("float32")
309
310
311
312
        if 'Min' in self.known_functions:
            del self.known_functions['Min']
        if 'Max' in self.known_functions:
            del self.known_functions['Max']
Martin Bauer's avatar
Martin Bauer committed
313

314
315
    def _print_Pow(self, expr):
        """Don't use std::pow function, for small integer exponents, write as multiplication"""
Martin Bauer's avatar
Martin Bauer committed
316
317
318
        if not expr.free_symbols:
            return self._typed_number(expr.evalf(), get_type_of_expression(expr))

319
        if expr.exp.is_integer and expr.exp.is_number and 0 < expr.exp < 8:
320
            return "(" + self._print(sp.Mul(*[expr.base] * expr.exp, evaluate=False)) + ")"
321
322
        elif expr.exp.is_integer and expr.exp.is_number and - 8 < expr.exp < 0:
            return "1 / ({})".format(self._print(sp.Mul(*[expr.base] * (-expr.exp), evaluate=False)))
323
324
325
326
327
        else:
            return super(CustomSympyPrinter, self)._print_Pow(expr)

    def _print_Rational(self, expr):
        """Evaluate all rationals i.e. print 0.25 instead of 1.0/4.0"""
Martin Bauer's avatar
Martin Bauer committed
328
329
        res = str(expr.evalf().num)
        return res
330
331
332
333
334
335
336
337

    def _print_Equality(self, expr):
        """Equality operator is not printable in default printer"""
        return '((' + self._print(expr.lhs) + ") == (" + self._print(expr.rhs) + '))'

    def _print_Piecewise(self, expr):
        """Print piecewise in one line (remove newlines)"""
        result = super(CustomSympyPrinter, self)._print_Piecewise(expr)
Martin Bauer's avatar
Martin Bauer committed
338
339
        return result.replace("\n", "")

340
    def _print_Function(self, expr):
341
        infix_functions = {
Martin Bauer's avatar
Martin Bauer committed
342
343
344
345
346
            bitwise_xor: '^',
            bit_shift_right: '>>',
            bit_shift_left: '<<',
            bitwise_or: '|',
            bitwise_and: '&',
Martin Bauer's avatar
Martin Bauer committed
347
        }
Martin Bauer's avatar
Martin Bauer committed
348
349
        if hasattr(expr, 'to_c'):
            return expr.to_c(self._print)
350
351
352
        if isinstance(expr, reinterpret_cast_func):
            arg, data_type = expr.args
            return "*((%s)(& %s))" % (PointerType(data_type, restrict=False), self._print(arg))
353
354
355
        elif isinstance(expr, address_of):
            assert len(expr.args) == 1, "address_of must only have one argument"
            return "&(%s)" % self._print(expr.args[0])
356
        elif isinstance(expr, cast_func):
Martin Bauer's avatar
Martin Bauer committed
357
            arg, data_type = expr.args
358
            if isinstance(arg, sp.Number) and arg.is_finite:
359
360
                return self._typed_number(arg, data_type)
            else:
361
362
                return "((%s)(%s))" % (data_type, self._print(arg))
        elif isinstance(expr, fast_division):
363
            return "({})".format(self._print(expr.args[0] / expr.args[1]))
364
        elif isinstance(expr, fast_sqrt):
365
            return "({})".format(self._print(sp.sqrt(expr.args[0])))
366
367
        elif isinstance(expr, vec_any) or isinstance(expr, vec_all):
            return self._print(expr.args[0])
368
        elif isinstance(expr, fast_inv_sqrt):
369
            return "({})".format(self._print(1 / sp.sqrt(expr.args[0])))
370
371
        elif expr.func in infix_functions:
            return "(%s %s %s)" % (self._print(expr.args[0]), infix_functions[expr.func], self._print(expr.args[1]))
372
373
374
375
        elif expr.func == int_power_of_2:
            return "(1 << (%s))" % (self._print(expr.args[0]))
        elif expr.func == int_div:
            return "((%s) / (%s))" % (self._print(expr.args[0]), self._print(expr.args[1]))
376
        else:
377
            return super(CustomSympyPrinter, self)._print_Function(expr)
Martin Bauer's avatar
Martin Bauer committed
378

379
380
    def _typed_number(self, number, dtype):
        res = self._print(number)
381
382
383
384
        if dtype.numpy_dtype == np.float32:
            return res + '.0f' if '.' not in res else res + 'f'
        elif dtype.numpy_dtype == np.float64:
            return res + '.0' if '.' not in res else res
385
386
        else:
            return res
387

Stephan Seitz's avatar
Stephan Seitz committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    def _print_Sum(self, expr):
        template = """[&]() {{
    {dtype} sum = ({dtype}) 0;
    for ( {iterator_dtype} {var} = {start}; {condition}; {var} += {increment} ) {{
        sum += {expr};
    }}
    return sum;
}}()"""
        var = expr.limits[0][0]
        start = expr.limits[0][1]
        end = expr.limits[0][2]
        code = template.format(
            dtype=get_type_of_expression(expr.args[0]),
            iterator_dtype='int',
            var=self._print(var),
            start=self._print(start),
            end=self._print(end),
            expr=self._print(expr.function),
            increment=str(1),
            condition=self._print(var) + ' <= ' + self._print(end)  # if start < end else '>='
        )
        return code

    def _print_Product(self, expr):
        template = """[&]() {{
    {dtype} product = ({dtype}) 1;
    for ( {iterator_dtype} {var} = {start}; {condition}; {var} += {increment} ) {{
        product *= {expr};
    }}
    return product;
}}()"""
        var = expr.limits[0][0]
        start = expr.limits[0][1]
        end = expr.limits[0][2]
        code = template.format(
            dtype=get_type_of_expression(expr.args[0]),
            iterator_dtype='int',
            var=self._print(var),
            start=self._print(start),
            end=self._print(end),
            expr=self._print(expr.function),
            increment=str(1),
            condition=self._print(var) + ' <= ' + self._print(end)  # if start < end else '>='
        )
        return code
433

434
435
436
    def _print_ConditionalFieldAccess(self, node):
        return self._print(sp.Piecewise((node.outofbounds_value, node.outofbounds_condition), (node.access, True)))

437
438
439
    _print_Max = C89CodePrinter._print_Max
    _print_Min = C89CodePrinter._print_Min

440

Martin Bauer's avatar
Martin Bauer committed
441
# noinspection PyPep8Naming
442
443
444
class VectorizedCustomSympyPrinter(CustomSympyPrinter):
    SummandInfo = namedtuple("SummandInfo", ['sign', 'term'])

445
446
    def __init__(self, instruction_set):
        super(VectorizedCustomSympyPrinter, self).__init__()
Martin Bauer's avatar
Martin Bauer committed
447
        self.instruction_set = instruction_set
448

Martin Bauer's avatar
Martin Bauer committed
449
450
451
452
    def _scalarFallback(self, func_name, expr, *args, **kwargs):
        expr_type = get_type_of_expression(expr)
        if type(expr_type) is not VectorType:
            return getattr(super(VectorizedCustomSympyPrinter, self), func_name)(expr, *args, **kwargs)
453
        else:
Martin Bauer's avatar
Martin Bauer committed
454
            assert self.instruction_set['width'] == expr_type.width
455
456
            return None

457
    def _print_Function(self, expr):
458
        if isinstance(expr, vector_memory_access):
Martin Bauer's avatar
Martin Bauer committed
459
460
461
            arg, data_type, aligned, _ = expr.args
            instruction = self.instruction_set['loadA'] if aligned else self.instruction_set['loadU']
            return instruction.format("& " + self._print(arg))
462
        elif isinstance(expr, cast_func):
Martin Bauer's avatar
Martin Bauer committed
463
464
            arg, data_type = expr.args
            if type(data_type) is VectorType:
Martin Bauer's avatar
Martin Bauer committed
465
                return self.instruction_set['makeVec'].format(self._print(arg))
466
        elif expr.func == fast_division:
467
468
            result = self._scalarFallback('_print_Function', expr)
            if not result:
469
470
                result = self.instruction_set['/'].format(self._print(expr.args[0]), self._print(expr.args[1]))
            return result
471
472
473
        elif expr.func == fast_sqrt:
            return "({})".format(self._print(sp.sqrt(expr.args[0])))
        elif expr.func == fast_inv_sqrt:
474
475
476
477
478
479
            result = self._scalarFallback('_print_Function', expr)
            if not result:
                if self.instruction_set['rsqrt']:
                    return self.instruction_set['rsqrt'].format(self._print(expr.args[0]))
                else:
                    return "({})".format(self._print(1 / sp.sqrt(expr.args[0])))
480
481
482
483
484
485
486
487
488
489
490
491
492
        elif isinstance(expr, vec_any):
            expr_type = get_type_of_expression(expr.args[0])
            if type(expr_type) is not VectorType:
                return self._print(expr.args[0])
            else:
                return self.instruction_set['any'].format(self._print(expr.args[0]))
        elif isinstance(expr, vec_all):
            expr_type = get_type_of_expression(expr.args[0])
            if type(expr_type) is not VectorType:
                return self._print(expr.args[0])
            else:
                return self.instruction_set['all'].format(self._print(expr.args[0]))

493
494
        return super(VectorizedCustomSympyPrinter, self)._print_Function(expr)

495
496
497
498
499
    def _print_And(self, expr):
        result = self._scalarFallback('_print_And', expr)
        if result:
            return result

Martin Bauer's avatar
Martin Bauer committed
500
501
502
503
        arg_strings = [self._print(a) for a in expr.args]
        assert len(arg_strings) > 0
        result = arg_strings[0]
        for item in arg_strings[1:]:
Martin Bauer's avatar
Martin Bauer committed
504
            result = self.instruction_set['&'].format(result, item)
505
506
507
508
509
510
511
        return result

    def _print_Or(self, expr):
        result = self._scalarFallback('_print_Or', expr)
        if result:
            return result

Martin Bauer's avatar
Martin Bauer committed
512
513
514
515
        arg_strings = [self._print(a) for a in expr.args]
        assert len(arg_strings) > 0
        result = arg_strings[0]
        for item in arg_strings[1:]:
Martin Bauer's avatar
Martin Bauer committed
516
            result = self.instruction_set['|'].format(result, item)
517
518
        return result

519
    def _print_Add(self, expr, order=None):
520
521
522
        result = self._scalarFallback('_print_Add', expr)
        if result:
            return result
523
524
525
526

        summands = []
        for term in expr.args:
            if term.func == sp.Mul:
Martin Bauer's avatar
Martin Bauer committed
527
                sign, t = self._print_Mul(term, inside_add=True)
528
529
530
531
532
533
534
535
536
537
538
539
540
            else:
                t = self._print(term)
                sign = 1
            summands.append(self.SummandInfo(sign, t))
        # Use positive terms first
        summands.sort(key=lambda e: e.sign, reverse=True)
        # if no positive term exists, prepend a zero
        if summands[0].sign == -1:
            summands.insert(0, self.SummandInfo(1, "0"))

        assert len(summands) >= 2
        processed = summands[0].term
        for summand in summands[1:]:
Martin Bauer's avatar
Martin Bauer committed
541
            func = self.instruction_set['-'] if summand.sign == -1 else self.instruction_set['+']
542
543
544
            processed = func.format(processed, summand.term)
        return processed

545
    def _print_Pow(self, expr):
546
547
548
        result = self._scalarFallback('_print_Pow', expr)
        if result:
            return result
549

550
551
        one = self.instruction_set['makeVec'].format(1.0)

552
553
        if expr.exp.is_integer and expr.exp.is_number and 0 < expr.exp < 8:
            return "(" + self._print(sp.Mul(*[expr.base] * expr.exp, evaluate=False)) + ")"
554
555
556
557
558
        elif expr.exp == -1:
            one = self.instruction_set['makeVec'].format(1.0)
            return self.instruction_set['/'].format(one, self._print(expr.base))
        elif expr.exp == 0.5:
            return self.instruction_set['sqrt'].format(self._print(expr.base))
559
560
561
        elif expr.exp == -0.5:
            root = self.instruction_set['sqrt'].format(self._print(expr.base))
            return self.instruction_set['/'].format(one, root)
562
563
564
        elif expr.exp.is_integer and expr.exp.is_number and - 8 < expr.exp < 0:
            return self.instruction_set['/'].format(one,
                                                    self._print(sp.Mul(*[expr.base] * (-expr.exp), evaluate=False)))
565
        else:
566
            raise ValueError("Generic exponential not supported: " + str(expr))
567

Martin Bauer's avatar
Martin Bauer committed
568
569
570
571
    def _print_Mul(self, expr, inside_add=False):
        # noinspection PyProtectedMember
        from sympy.core.mul import _keep_coeff

572
573
574
        result = self._scalarFallback('_print_Mul', expr)
        if result:
            return result
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602

        c, e = expr.as_coeff_Mul()
        if c < 0:
            expr = _keep_coeff(-c, e)
            sign = -1
        else:
            sign = 1

        a = []  # items in the numerator
        b = []  # items that are in the denominator (if any)

        # Gather args for numerator/denominator
        for item in expr.as_ordered_factors():
            if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
                if item.exp != -1:
                    b.append(sp.Pow(item.base, -item.exp, evaluate=False))
                else:
                    b.append(sp.Pow(item.base, -item.exp))
            else:
                a.append(item)

        a = a or [S.One]

        a_str = [self._print(x) for x in a]
        b_str = [self._print(x) for x in b]

        result = a_str[0]
        for item in a_str[1:]:
Martin Bauer's avatar
Martin Bauer committed
603
            result = self.instruction_set['*'].format(result, item)
604
605
606
607

        if len(b) > 0:
            denominator_str = b_str[0]
            for item in b_str[1:]:
Martin Bauer's avatar
Martin Bauer committed
608
609
                denominator_str = self.instruction_set['*'].format(denominator_str, item)
            result = self.instruction_set['/'].format(result, denominator_str)
610

Martin Bauer's avatar
Martin Bauer committed
611
        if inside_add:
612
613
614
            return sign, result
        else:
            if sign < 0:
Martin Bauer's avatar
Martin Bauer committed
615
                return self.instruction_set['*'].format(self._print(S.NegativeOne), result)
616
617
618
            else:
                return result

619
    def _print_Relational(self, expr):
620
621
622
        result = self._scalarFallback('_print_Relational', expr)
        if result:
            return result
Martin Bauer's avatar
Martin Bauer committed
623
        return self.instruction_set[expr.rel_op].format(self._print(expr.lhs), self._print(expr.rhs))
624
625

    def _print_Equality(self, expr):
626
627
628
        result = self._scalarFallback('_print_Equality', expr)
        if result:
            return result
Martin Bauer's avatar
Martin Bauer committed
629
        return self.instruction_set['=='].format(self._print(expr.lhs), self._print(expr.rhs))
630
631

    def _print_Piecewise(self, expr):
632
633
634
        result = self._scalarFallback('_print_Piecewise', expr)
        if result:
            return result
635

Martin Bauer's avatar
Martin Bauer committed
636
        if expr.args[-1].cond.args[0] is not sp.sympify(True):
637
638
639
640
641
642
643
644
645
            # We need the last conditional to be a True, otherwise the resulting
            # function may not return a result.
            raise ValueError("All Piecewise expressions must contain an "
                             "(expr, True) statement to be used as a default "
                             "condition. Without one, the generated "
                             "expression may not evaluate to anything under "
                             "some condition.")

        result = self._print(expr.args[-1][0])
Martin Bauer's avatar
Martin Bauer committed
646
        for true_expr, condition in reversed(expr.args[:-1]):
647
            if isinstance(condition, cast_func) and get_type_of_expression(condition.args[0]) == create_type("bool"):
648
649
650
651
652
                if not KERNCRAFT_NO_TERNARY_MODE:
                    result = "(({}) ? ({}) : ({}))".format(self._print(condition.args[0]), self._print(true_expr),
                                                           result)
                else:
                    print("Warning - skipping ternary op")
653
654
655
            else:
                # noinspection SpellCheckingInspection
                result = self.instruction_set['blendv'].format(result, self._print(true_expr), self._print(condition))
656
        return result