Debian Codegraph @

ffc/uflacs/language/cnodes.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2011-2017 Martin Sandve Alnæs
3 #
4 # This file is part of UFLACS.
5 #
6 # UFLACS is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Lesser General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # UFLACS is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public License
17 # along with UFLACS. If not, see <http://www.gnu.org/licenses/>.
18
19 import numpy
20 import numbers
21
22 from ffc.uflacs.language.format_value import format_value, format_float, format_int
23 from ffc.uflacs.language.format_lines import format_indented_lines, Indented
24 from ffc.uflacs.language.precedence import PRECEDENCE
25
26
27 """CNode TODO:
28 - Array copy statement
29 - Extend ArrayDecl and ArrayAccess with support for
30 flattened but conceptually multidimensional arrays,
31 maybe even with padding (FlattenedArray possibly covers what we need)
32 - Function declaration
33 - TypeDef
34 - Type
35 - TemplateArgumentList
36 - Class declaration
37 - Class definition
38 """
39
40
41 ############## Some helper functions
42
43 def assign_loop(dst, src, ranges):
44 """Generate a nested loop over a list of ranges, assigning src to dst in the innermost loop.
45
46 Ranges is a list on the format [(index, begin, end),...].
47 """
48 code = Assign(dst, src)
49 for i, b, e in reversed(ranges):
50 code = ForRange(i, b, e, code)
51 return code
52
53
54 def accumulate_loop(dst, src, ranges):
55 """Generate a nested loop over a list of ranges, adding src to dst in the innermost loop.
56
57 Ranges is a list on the format [(index, begin, end),...].
58 """
59 code = AssignAdd(dst, src)
60 for i, b, e in reversed(ranges):
61 code = ForRange(i, b, e, code)
62 return code
63
64
65 def scale_loop(dst, factor, ranges):
66 """Generate a nested loop over a list of ranges, multiplying dst with factor in the innermost loop.
67
68 Ranges is a list on the format [(index, begin, end),...].
69 """
70 code = AssignMul(dst, factor)
71 for i, b, e in reversed(ranges):
72 code = ForRange(i, b, e, code)
73 return code
74
75
76 def is_zero_cexpr(cexpr):
77 return (
78 (isinstance(cexpr, LiteralFloat) and cexpr.value == 0.0)
79 or (isinstance(cexpr, LiteralInt) and cexpr.value == 0)
80 )
81
82
83 def is_one_cexpr(cexpr):
84 return (
85 (isinstance(cexpr, LiteralFloat) and cexpr.value == 1.0)
86 or (isinstance(cexpr, LiteralInt) and cexpr.value == 1)
87 )
88
89
90 def is_negative_one_cexpr(cexpr):
91 return (
92 (isinstance(cexpr, LiteralFloat) and cexpr.value == -1.0)
93 or (isinstance(cexpr, LiteralInt) and cexpr.value == -1)
94 )
95
96
97 def float_product(factors):
98 "Build product of float factors, simplifying ones and zeros and returning 1.0 if empty sequence."
99 factors = [f for f in factors if not is_one_cexpr(f)]
100 if len(factors) == 0:
101 return LiteralFloat(1.0)
102 elif len(factors) == 1:
103 return factors[0]
104 else:
105 for f in factors:
106 if is_zero_cexpr(f):
107 return f
108 return Product(factors)
109
110
111 def MemZeroRange(name, begin, end):
112 name = as_cexpr_or_string_symbol(name)
113 return Call("std::fill", (name + begin, name + end, LiteralFloat(0.0)))
114 #return Call("std::fill", (AddressOf(name[begin]), AddressOf(name[end]), LiteralFloat(0.0)))
115
116
117 def MemZero(name, size):
118 name = as_cexpr_or_string_symbol(name)
119 size = as_cexpr(size)
120 return Call("std::fill_n", (name, size, LiteralFloat(0.0)))
121
122
123 def MemCopy(src, dst, size):
124 src = as_cexpr_or_string_symbol(src)
125 dst = as_cexpr_or_string_symbol(dst)
126 size = as_cexpr(size)
127 return Call("std::copy_n", (src, size, dst))
128
129
130 ############## CNode core
131
132 class CNode(object):
133 "Base class for all C AST nodes."
134 __slots__ = ()
135
136 def __str__(self):
137 name = self.__class__.__name__
138 raise NotImplementedError("Missing implementation of __str__ in " + name)
139
140 def __eq__(self, other):
141 name = self.__class__.__name__
142 raise NotImplementedError("Missing implementation of __eq__ in " + name)
143
144 def __ne__(self, other):
145 return not self.__eq__(other)
146
147
148 CNode.debug = False
149
150
151 ############## CExpr base classes
152
153 class CExpr(CNode):
154 """Base class for all C expressions.
155
156 All subtypes should define a 'precedence' class attribute.
157 """
158 __slots__ = ()
159
160 def ce_format(self, precision=None):
161 raise NotImplementedError("Missing implementation of ce_format() in CExpr.")
162
163 def __str__(self):
164 try:
165 s = self.ce_format()
166 except Exception:
167 if CNode.debug:
168 print("Error in CExpr string formatting. Inspect self.")
169 import IPython; IPython.embed()
170 raise
171 return s
172
173 def __getitem__(self, indices):
174 return ArrayAccess(self, indices)
175
176 def __neg__(self):
177 if isinstance(self, LiteralFloat):
178 return LiteralFloat(-self.value)
179 if isinstance(self, LiteralInt):
180 return LiteralInt(-self.value)
181 return Neg(self)
182
183 def __add__(self, other):
184 other = as_cexpr(other)
185 if is_zero_cexpr(self):
186 return other
187 if is_zero_cexpr(other):
188 return self
189 if isinstance(other, Neg):
190 return Sub(self, other.arg)
191 return Add(self, other)
192
193 def __radd__(self, other):
194 other = as_cexpr(other)
195 if is_zero_cexpr(self):
196 return other
197 if is_zero_cexpr(other):
198 return self
199 if isinstance(self, Neg):
200 return Sub(other, self.arg)
201 return Add(other, self)
202
203 def __sub__(self, other):
204 other = as_cexpr(other)
205 if is_zero_cexpr(self):
206 return -other
207 if is_zero_cexpr(other):
208 return self
209 if isinstance(other, Neg):
210 return Add(self, other.arg)
211 return Sub(self, other)
212
213 def __rsub__(self, other):
214 other = as_cexpr(other)
215 if is_zero_cexpr(self):
216 return other
217 if is_zero_cexpr(other):
218 return -self
219 if isinstance(self, Neg):
220 return Add(other, self.arg)
221 return Sub(other, self)
222
223 def __mul__(self, other):
224 other = as_cexpr(other)
225 if is_zero_cexpr(self):
226 return self
227 if is_zero_cexpr(other):
228 return other
229 if is_one_cexpr(self):
230 return other
231 if is_one_cexpr(other):
232 return self
233 if is_negative_one_cexpr(other):
234 return Neg(self)
235 if is_negative_one_cexpr(self):
236 return Neg(other)
237 return Mul(self, other)
238
239 def __rmul__(self, other):
240 other = as_cexpr(other)
241 if is_zero_cexpr(self):
242 return self
243 if is_zero_cexpr(other):
244 return other
245 if is_one_cexpr(self):
246 return other
247 if is_one_cexpr(other):
248 return self
249 if is_negative_one_cexpr(other):
250 return Neg(self)
251 if is_negative_one_cexpr(self):
252 return Neg(other)
253 return Mul(other, self)
254
255 def __div__(self, other):
256 other = as_cexpr(other)
257 if is_zero_cexpr(other):
258 raise ValueError("Division by zero!")
259 if is_zero_cexpr(self):
260 return self
261 return Div(self, other)
262
263 def __rdiv__(self, other):
264 other = as_cexpr(other)
265 if is_zero_cexpr(self):
266 raise ValueError("Division by zero!")
267 if is_zero_cexpr(other):
268 return other
269 return Div(other, self)
270
271 # TODO: Error check types? Can't do that exactly as symbols here have no type.
272 __truediv__ = __div__
273 __rtruediv__ = __rdiv__
274 __floordiv__ = __div__
275 __rfloordiv__ = __rdiv__
276
277 def __mod__(self, other):
278 other = as_cexpr(other)
279 if is_zero_cexpr(other):
280 raise ValueError("Division by zero!")
281 if is_zero_cexpr(self):
282 return self
283 return Mod(self, other)
284
285 def __rmod__(self, other):
286 other = as_cexpr(other)
287 if is_zero_cexpr(self):
288 raise ValueError("Division by zero!")
289 if is_zero_cexpr(other):
290 return other
291 return Mod(other, self)
292
293
294 class CExprOperator(CExpr):
295 """Base class for all C expression operator."""
296 __slots__ = ()
297 sideeffect = False
298
299
300 class CExprTerminal(CExpr):
301 """Base class for all C expression terminals."""
302 __slots__ = ()
303 sideeffect = False
304
305
306 ############## CExprTerminal types
307
308 class CExprLiteral(CExprTerminal):
309 "A float or int literal value."
310 __slots__ = ()
311 precedence = PRECEDENCE.LITERAL
312
313
314 class Null(CExprLiteral):
315 "A null pointer literal."
316 __slots__ = ()
317 precedence = PRECEDENCE.LITERAL
318
319 def ce_format(self, precision=None):
320 # C or old C++ version
321 #return "NULL"
322 # C++11 version
323 return "nullptr"
324
325 def __eq__(self, other):
326 return isinstance(other, Null)
327
328
329 class LiteralFloat(CExprLiteral):
330 "A floating point literal value."
331 __slots__ = ("value",)
332 precedence = PRECEDENCE.LITERAL
333
334 def __init__(self, value):
335 assert isinstance(value, (float, int, numpy.number))
336 self.value = value
337
338 def ce_format(self, precision=None):
339 return format_float(self.value, precision)
340
341 def __eq__(self, other):
342 return isinstance(other, LiteralFloat) and self.value == other.value
343
344 def __bool__(self):
345 return bool(self.value)
346
347 __nonzero__ = __bool__
348
349 def __float__(self):
350 return float(self.value)
351
352
353 class LiteralInt(CExprLiteral):
354 "An integer literal value."
355 __slots__ = ("value",)
356 precedence = PRECEDENCE.LITERAL
357
358 def __init__(self, value):
359 assert isinstance(value, (int, numpy.number))
360 self.value = value
361
362 def ce_format(self, precision=None):
363 return str(self.value)
364
365 def __eq__(self, other):
366 return isinstance(other, LiteralInt) and self.value == other.value
367
368 def __bool__(self):
369 return bool(self.value)
370
371 __nonzero__ = __bool__
372
373 def __int__(self):
374 return int(self.value)
375
376 def __float__(self):
377 return float(self.value)
378
379
380 class LiteralBool(CExprLiteral):
381 "A boolean literal value."
382 __slots__ = ("value",)
383 precedence = PRECEDENCE.LITERAL
384
385 def __init__(self, value):
386 assert isinstance(value, (bool,))
387 self.value = value
388
389 def ce_format(self, precision=None):
390 return "true" if self.value else "false"
391
392 def __eq__(self, other):
393 return isinstance(other, LiteralBool) and self.value == other.value
394
395 def __bool__(self):
396 return bool(self.value)
397
398 __nonzero__ = __bool__
399
400
401 class LiteralString(CExprLiteral):
402 "A boolean literal value."
403 __slots__ = ("value",)
404 precedence = PRECEDENCE.LITERAL
405
406 def __init__(self, value):
407 assert isinstance(value, (str,))
408 assert '"' not in value
409 self.value = value
410
411 def ce_format(self, precision=None):
412 return '"%s"' % (self.value,)
413
414 def __eq__(self, other):
415 return isinstance(other, LiteralString) and self.value == other.value
416
417
418 class Symbol(CExprTerminal):
419 "A named symbol."
420 __slots__ = ("name",)
421 precedence = PRECEDENCE.SYMBOL
422
423 def __init__(self, name):
424 assert isinstance(name, str)
425 self.name = name
426
427 def ce_format(self, precision=None):
428 return self.name
429
430 def __eq__(self, other):
431 return isinstance(other, Symbol) and self.name == other.name
432
433
434 class VerbatimExpr(CExprTerminal):
435 """A verbatim copy of an expression source string.
436
437 Handled as having the lowest precedence which will introduce parentheses around it most of the time."""
438 __slots__ = ("codestring",)
439 precedence = PRECEDENCE.LOWEST
440
441 def __init__(self, codestring):
442 assert isinstance(codestring, str)
443 self.codestring = codestring
444
445 def ce_format(self, precision=None):
446 return self.codestring
447
448 def __eq__(self, other):
449 return isinstance(other, VerbatimExpr) and self.codestring == other.codestring
450
451
452 class New(CExpr):
453 __slots__ = ("typename",)
454 def __init__(self, typename):
455 assert isinstance(typename, str)
456 self.typename = typename
457
458 def ce_format(self, precision=None):
459 return "new %s()" % (self.typename,)
460
461 def __eq__(self, other):
462 return isinstance(other, New) and self.typename == other.typename
463
464
465 ############## CExprOperator base classes
466
467 class UnaryOp(CExprOperator):
468 "Base class for unary operators."
469 __slots__ = ("arg",)
470 def __init__(self, arg):
471 self.arg = as_cexpr(arg)
472
473 def __eq__(self, other):
474 return isinstance(other, type(self)) and self.arg == other.arg
475
476
477 class PrefixUnaryOp(UnaryOp):
478 "Base class for prefix unary operators."
479 __slots__ = ()
480 def ce_format(self, precision=None):
481 arg = self.arg.ce_format(precision)
482 if self.arg.precedence >= self.precedence:
483 arg = '(' + arg + ')'
484 return self.op + arg
485
486 def __eq__(self, other):
487 return isinstance(other, type(self))
488
489
490 class PostfixUnaryOp(UnaryOp):
491 "Base class for postfix unary operators."
492 __slots__ = ()
493 def ce_format(self, precision=None):
494 arg = self.arg.ce_format(precision)
495 if self.arg.precedence >= self.precedence:
496 arg = '(' + arg + ')'
497 return arg + self.op
498
499 def __eq__(self, other):
500 return isinstance(other, type(self))
501
502
503 class BinOp(CExprOperator):
504 __slots__ = ("lhs", "rhs")
505 def __init__(self, lhs, rhs):
506 self.lhs = as_cexpr(lhs)
507 self.rhs = as_cexpr(rhs)
508
509 def ce_format(self, precision=None):
510 # Format children
511 lhs = self.lhs.ce_format(precision)
512 rhs = self.rhs.ce_format(precision)
513
514 # Apply parentheses
515 if self.lhs.precedence > self.precedence:
516 lhs = '(' + lhs + ')'
517 if self.rhs.precedence >= self.precedence:
518 rhs = '(' + rhs + ')'
519
520 # Return combined string
521 return lhs + (" " + self.op + " ") + rhs
522
523 def __eq__(self, other):
524 return (isinstance(other, type(self))
525 and self.lhs == other.lhs
526 and self.rhs == other.rhs)
527
528
529 class NaryOp(CExprOperator):
530 "Base class for special n-ary operators."
531 __slots__ = ("args",)
532 def __init__(self, args):
533 self.args = [as_cexpr(arg) for arg in args]
534
535 def ce_format(self, precision=None):
536 # Format children
537 args = [arg.ce_format(precision) for arg in self.args]
538
539 # Apply parentheses
540 for i in range(len(args)):
541 if self.args[i].precedence >= self.precedence:
542 args[i] = '(' + args[i] + ')'
543
544 # Return combined string
545 op = " " + self.op + " "
546 s = args[0]
547 for i in range(1, len(args)):
548 s += op + args[i]
549 return s
550
551 def __eq__(self, other):
552 return (isinstance(other, type(self))
553 and len(self.args) == len(other.args)
554 and all(a == b for a, b in zip(self.args, other.args)))
555
556
557 ############## CExpr unary operators
558
559 class Dereference(PrefixUnaryOp):
560 __slots__ = ()
561 precedence = PRECEDENCE.DEREFERENCE
562 op = "*"
563
564 class AddressOf(PrefixUnaryOp):
565 __slots__ = ()
566 precedence = PRECEDENCE.ADDRESSOF
567 op = "&"
568
569 class SizeOf(PrefixUnaryOp):
570 __slots__ = ()
571 precedence = PRECEDENCE.SIZEOF
572 op = "sizeof"
573
574 class Neg(PrefixUnaryOp):
575 __slots__ = ()
576 precedence = PRECEDENCE.NEG
577 op = "-"
578
579 class Pos(PrefixUnaryOp):
580 __slots__ = ()
581 precedence = PRECEDENCE.POS
582 op = "+"
583
584 class Not(PrefixUnaryOp):
585 __slots__ = ()
586 precedence = PRECEDENCE.NOT
587 op = "!"
588
589 class BitNot(PrefixUnaryOp):
590 __slots__ = ()
591 precedence = PRECEDENCE.BIT_NOT
592 op = "~"
593
594 class PreIncrement(PrefixUnaryOp):
595 __slots__ = ()
596 precedence = PRECEDENCE.PRE_INC
597 sideeffect = True
598 op = "++"
599
600 class PreDecrement(PrefixUnaryOp):
601 __slots__ = ()
602 precedence = PRECEDENCE.PRE_DEC
603 sideeffect = True
604 op = "--"
605
606 class PostIncrement(PostfixUnaryOp):
607 __slots__ = ()
608 precedence = PRECEDENCE.POST_INC
609 sideeffect = True
610 op = "++"
611
612 class PostDecrement(PostfixUnaryOp):
613 __slots__ = ()
614 precedence = PRECEDENCE.POST_DEC
615 sideeffect = True
616 op = "--"
617
618 ############## CExpr binary operators
619
620 class Add(BinOp):
621 __slots__ = ()
622 precedence = PRECEDENCE.ADD
623 op = "+"
624
625 class Sub(BinOp):
626 __slots__ = ()
627 precedence = PRECEDENCE.SUB
628 op = "-"
629
630 class Mul(BinOp):
631 __slots__ = ()
632 precedence = PRECEDENCE.MUL
633 op = "*"
634
635 class Div(BinOp):
636 __slots__ = ()
637 precedence = PRECEDENCE.DIV
638 op = "/"
639
640 class Mod(BinOp):
641 __slots__ = ()
642 precedence = PRECEDENCE.MOD
643 op = "%"
644
645 class EQ(BinOp):
646 __slots__ = ()
647 precedence = PRECEDENCE.EQ
648 op = "=="
649
650 class NE(BinOp):
651 __slots__ = ()
652 precedence = PRECEDENCE.NE
653 op = "!="
654
655 class LT(BinOp):
656 __slots__ = ()
657 precedence = PRECEDENCE.LT
658 op = "<"
659
660 class GT(BinOp):
661 __slots__ = ()
662 precedence = PRECEDENCE.GT
663 op = ">"
664
665 class LE(BinOp):
666 __slots__ = ()
667 precedence = PRECEDENCE.LE
668 op = "<="
669
670 class GE(BinOp):
671 __slots__ = ()
672 precedence = PRECEDENCE.GE
673 op = ">="
674
675 class And(BinOp):
676 __slots__ = ()
677 precedence = PRECEDENCE.AND
678 op = "&&"
679
680 class Or(BinOp):
681 __slots__ = ()
682 precedence = PRECEDENCE.OR
683 op = "||"
684
685 class BitAnd(BinOp):
686 __slots__ = ()
687 precedence = PRECEDENCE.BIT_AND
688 op = "&"
689
690 class BitXor(BinOp):
691 __slots__ = ()
692 precedence = PRECEDENCE.BIT_XOR
693 op = "^"
694
695 class BitOr(BinOp):
696 __slots__ = ()
697 precedence = PRECEDENCE.BIT_OR
698 op = "|"
699
700 class Sum(NaryOp):
701 "Sum of any number of operands."
702 __slots__ = ()
703 precedence = PRECEDENCE.ADD
704 op = "+"
705
706 class Product(NaryOp):
707 "Product of any number of operands."
708 __slots__ = ()
709 precedence = PRECEDENCE.MUL
710 op = "*"
711
712 class AssignOp(BinOp):
713 "Base class for assignment operators."
714 __slots__ = ()
715 precedence = PRECEDENCE.ASSIGN
716 sideeffect = True
717 def __init__(self, lhs, rhs):
718 BinOp.__init__(self, as_cexpr_or_string_symbol(lhs), rhs)
719
720 class Assign(AssignOp):
721 __slots__ = ()
722 op = "="
723
724 class AssignAdd(AssignOp):
725 __slots__ = ()
726 op = "+="
727
728 class AssignSub(AssignOp):
729 __slots__ = ()
730 op = "-="
731
732 class AssignMul(AssignOp):
733 __slots__ = ()
734 op = "*="
735
736 class AssignDiv(AssignOp):
737 __slots__ = ()
738 op = "/="
739
740 class AssignMod(AssignOp):
741 __slots__ = ()
742 op = "%="
743
744 class AssignLShift(AssignOp):
745 __slots__ = ()
746 op = "<<="
747
748 class AssignRShift(AssignOp):
749 __slots__ = ()
750 op = ">>="
751
752 class AssignAnd(AssignOp):
753 __slots__ = ()
754 op = "&&="
755
756 class AssignOr(AssignOp):
757 __slots__ = ()
758 op = "||="
759
760 class AssignBitAnd(AssignOp):
761 __slots__ = ()
762 op = "&="
763
764 class AssignBitXor(AssignOp):
765 __slots__ = ()
766 op = "^="
767
768 class AssignBitOr(AssignOp):
769 __slots__ = ()
770 op = "|="
771
772
773 ############## CExpr operators
774
775 class FlattenedArray(object):
776 """Syntax carrying object only, will get translated on __getitem__ to ArrayAccess."""
777 __slots__ = ("array", "strides", "offset", "dims")
778 def __init__(self, array, dummy=None, dims=None, strides=None, offset=None):
779 assert dummy is None, "Please use keyword arguments for strides or dims."
780
781 # Typecheck array argument
782 if isinstance(array, ArrayDecl):
783 self.array = array.symbol
784 elif isinstance(array, Symbol):
785 self.array = array
786 else:
787 assert isinstance(array, str)
788 self.array = Symbol(array)
789
790 # Allow expressions or literals as strides or dims and offset
791 if strides is None:
792 assert dims is not None, "Please provide either strides or dims."
793 assert isinstance(dims, (list, tuple))
794 dims = tuple(as_cexpr(i) for i in dims)
795 self.dims = dims
796 n = len(dims)
797 literal_one = LiteralInt(1)
798 strides = [literal_one]*n
799 for i in range(n-2, -1, -1):
800 s = strides[i+1]
801 d = dims[i+1]
802 if d == literal_one:
803 strides[i] = s
804 elif s == literal_one:
805 strides[i] = d
806 else:
807 strides[i] = d * s
808 else:
809 self.dims = None
810 assert isinstance(strides, (list, tuple))
811 strides = tuple(as_cexpr(i) for i in strides)
812 self.strides = strides
813 self.offset = None if offset is None else as_cexpr(offset)
814
815 def __getitem__(self, indices):
816 if not isinstance(indices, (list,tuple)):
817 indices = (indices,)
818 n = len(indices)
819 if n == 0:
820 # Handle scalar case, allowing dims=() and indices=() for A[0]
821 if len(self.strides) != 0:
822 raise ValueError("Empty indices for nonscalar array.")
823 flat = LiteralInt(0)
824 else:
825 i, s = (indices[0], self.strides[0])
826 literal_one = LiteralInt(1)
827 flat = (i if s == literal_one else s * i)
828 if self.offset is not None:
829 flat = self.offset + flat
830 for i, s in zip(indices[1:n], self.strides[1:n]):
831 flat = flat + (i if s == literal_one else s * i)
832 # Delay applying ArrayAccess until we have all indices
833 if n == len(self.strides):
834 return ArrayAccess(self.array, flat)
835 else:
836 return FlattenedArray(self.array, strides=self.strides[n:], offset=flat)
837
838
839 class ArrayAccess(CExprOperator):
840 __slots__ = ("array", "indices")
841 precedence = PRECEDENCE.SUBSCRIPT
842
843 def __init__(self, array, indices):
844 # Typecheck array argument
845 if isinstance(array, str):
846 array = Symbol(array)
847 if isinstance(array, Symbol):
848 self.array = array
849 elif isinstance(array, ArrayDecl):
850 self.array = array.symbol
851 else:
852 raise ValueError("Unexpected array type %s." % (type(array).__name__,))
853
854 # Allow expressions or literals as indices
855 if not isinstance(indices, (list, tuple)):
856 indices = (indices,)
857 self.indices = tuple(as_cexpr_or_string_symbol(i) for i in indices)
858
859 # Early error checking for negative array dimensions
860 if any(isinstance(i, int) and i < 0 for i in self.indices):
861 raise ValueError("Index value < 0.")
862
863 # Additional dimension checks possible if we get an ArrayDecl instead of just a name
864 if isinstance(array, ArrayDecl):
865 if len(self.indices) != len(array.sizes):
866 raise ValueError("Invalid number of indices.")
867 ints = (int, LiteralInt)
868 if any((isinstance(i, ints) and isinstance(d, ints) and int(i) >= int(d))
869 for i, d in zip(self.indices, array.sizes)):
870 raise ValueError("Index value >= array dimension.")
871
872 def __getitem__(self, indices):
873 "Handling nested expr[i][j]."
874 if isinstance(indices, list):
875 indices = tuple(indices)
876 elif not isinstance(indices, tuple):
877 indices = (indices,)
878 return ArrayAccess(self.array, self.indices + indices)
879
880 def ce_format(self, precision=None):
881 s = self.array.ce_format(precision)
882 for index in self.indices:
883 s += "[" + index.ce_format(precision) + "]"
884 return s
885
886 def __eq__(self, other):
887 return (isinstance(other, type(self))
888 and self.array == other.array
889 and self.indices == other.indices)
890
891
892 class Conditional(CExprOperator):
893 __slots__ = ("condition", "true", "false")
894 precedence = PRECEDENCE.CONDITIONAL
895
896 def __init__(self, condition, true, false):
897 self.condition = as_cexpr(condition)
898 self.true = as_cexpr(true)
899 self.false = as_cexpr(false)
900
901 def ce_format(self, precision=None):
902 # Format children
903 c = self.condition.ce_format(precision)
904 t = self.true.ce_format(precision)
905 f = self.false.ce_format(precision)
906
907 # Apply parentheses
908 if self.condition.precedence >= self.precedence:
909 c = '(' + c + ')'
910 if self.true.precedence >= self.precedence:
911 t = '(' + t + ')'
912 if self.false.precedence >= self.precedence:
913 f = '(' + f + ')'
914
915 # Return combined string
916 return c + " ? " + t + " : " + f
917
918 def __eq__(self, other):
919 return (isinstance(other, type(self))
920 and self.condition == other.condition
921 and self.true == other.true
922 and self.false == other.false)
923
924
925 class Call(CExprOperator):
926 __slots__ = ("function", "arguments")
927 precedence = PRECEDENCE.CALL
928 sideeffect = True
929
930 def __init__(self, function, arguments=None):
931 self.function = as_cexpr_or_string_symbol(function)
932
933 # Accept None, single, or multple arguments; literals or CExprs
934 if arguments is None:
935 arguments = ()
936 elif not isinstance(arguments, (tuple, list)):
937 arguments = (arguments,)
938 self.arguments = [as_cexpr(arg) for arg in arguments]
939
940 def ce_format(self, precision=None):
941 args = ", ".join(arg.ce_format(precision) for arg in self.arguments)
942 return self.function.ce_format(precision) + "(" + args + ")"
943
944 def __eq__(self, other):
945 return (isinstance(other, type(self))
946 and self.function == other.function
947 and self.arguments == other.arguments)
948
949 def Sqrt(x):
950 return Call("std::sqrt", x)
951
952
953 ############## Convertion function to expression nodes
954
955 def _is_zero_valued(values):
956 if isinstance(values, (numbers.Integral, LiteralInt)):
957 return int(values) == 0
958 elif isinstance(values, (numbers.Number, LiteralFloat)):
959 return float(values) == 0.0
960 else:
961 return numpy.count_nonzero(values) == 0
962
963
964 def as_cexpr(node):
965 """Typechecks and wraps an object as a valid CExpr.
966
967 Accepts CExpr nodes, treats int and float as literals, and treats a string as a symbol.
968 """
969 if isinstance(node, CExpr):
970 return node
971 elif isinstance(node, bool):
972 return LiteralBool(node)
973 elif isinstance(node, numbers.Integral):
974 return LiteralInt(node)
975 elif isinstance(node, numbers.Real):
976 return LiteralFloat(node)
977 elif isinstance(node, str):
978 raise RuntimeError("Got string for CExpr, this is ambiguous: %s" % (node,))
979 else:
980 raise RuntimeError("Unexpected CExpr type %s:\n%s" % (type(node), str(node)))
981
982
983 def as_cexpr_or_string_symbol(node):
984 if isinstance(node, str):
985 return Symbol(node)
986 return as_cexpr(node)
987
988
989 def as_cexpr_or_verbatim(node):
990 if isinstance(node, str):
991 return VerbatimExpr(node)
992 return as_cexpr(node)
993
994
995 def as_cexpr_or_literal(node):
996 if isinstance(node, str):
997 return LiteralString(node)
998 return as_cexpr(node)
999
1000
1001 def as_symbol(symbol):
1002 if isinstance(symbol, str):
1003 symbol = Symbol(symbol)
1004 assert isinstance(symbol, Symbol)
1005 return symbol
1006
1007
1008 def flattened_indices(indices, shape):
1009 """Given a tuple of indices and a shape tuple,
1010 return CNode expression for flattened indexing
1011 into multidimensional array.
1012
1013 Indices and shape entries can be int values, str symbol names, or CNode expressions.
1014 """
1015 n = len(shape)
1016 if n == 0:
1017 # Scalar
1018 return as_cexpr(0)
1019 elif n == 1:
1020 # Simple vector
1021 return as_cexpr(indices[0])
1022 else:
1023 # 2d or higher
1024 strides = [None]*(n-2) + [shape[-1], 1]
1025 for i in range(n-3, -1, -1):
1026 strides[i] = Mul(shape[i+1], strides[i+1])
1027 result = indices[-1]
1028 for i in range(n-2, -1, -1):
1029 result = Add(Mul(strides[i], indices[i]), result)
1030 return result
1031
1032
1033 ############## Base class for all statements
1034
1035 class CStatement(CNode):
1036 """Base class for all C statements.
1037
1038 Subtypes do _not_ define a 'precedence' class attribute.
1039 """
1040 __slots__ = ()
1041
1042 # True if statement contains its own scope, false by default to be on the safe side
1043 is_scoped = False
1044
1045 def cs_format(self, precision=None):
1046 "Return S: string | list(S) | Indented(S)."
1047 raise NotImplementedError("Missing implementation of cs_format() in CStatement.")
1048
1049 def __str__(self):
1050 try:
1051 s = self.cs_format()
1052 except Exception:
1053 if CNode.debug:
1054 print("Error in CStatement string formatting. Inspect self.")
1055 import IPython; IPython.embed()
1056 raise
1057 return format_indented_lines(s)
1058
1059
1060 ############## Statements
1061
1062 class VerbatimStatement(CStatement):
1063 "Wraps a source code string to be pasted verbatim into the source code."
1064 __slots__ = ("codestring",)
1065 is_scoped = False
1066
1067 def __init__(self, codestring):
1068 assert isinstance(codestring, str)
1069 self.codestring = codestring
1070
1071 def cs_format(self, precision=None):
1072 return self.codestring
1073
1074 def __eq__(self, other):
1075 return (isinstance(other, type(self))
1076 and self.codestring == other.codestring)
1077
1078
1079 class Statement(CStatement):
1080 "Make an expression into a statement."
1081 __slots__ = ("expr",)
1082 is_scoped = False
1083 def __init__(self, expr):
1084 self.expr = as_cexpr(expr)
1085
1086 def cs_format(self, precision=None):
1087 return self.expr.ce_format(precision) + ";"
1088
1089 def __eq__(self, other):
1090 return (isinstance(other, type(self))
1091 and self.expr == other.expr)
1092
1093
1094 class StatementList(CStatement):
1095 "A simple sequence of statements. No new scopes are introduced."
1096 __slots__ = ("statements",)
1097
1098 def __init__(self, statements):
1099 self.statements = [as_cstatement(st) for st in statements]
1100
1101 @property
1102 def is_scoped(self):
1103 return all(st.is_scoped for st in self.statements)
1104
1105 def cs_format(self, precision=None):
1106 return [st.cs_format(precision) for st in self.statements]
1107
1108 def __eq__(self, other):
1109 return (isinstance(other, type(self))
1110 and self.statements == other.statements)
1111
1112
1113 ############## Simple statements
1114
1115 class Using(CStatement):
1116 __slots__ = ("name",)
1117 is_scoped = True
1118 def __init__(self, name):
1119 assert isinstance(name, str)
1120 self.name = name
1121
1122 def cs_format(self, precision=None):
1123 return "using " + self.name + ";"
1124
1125 def __eq__(self, other):
1126 return (isinstance(other, type(self))
1127 and self.name == other.name)
1128
1129
1130 class Break(CStatement):
1131 __slots__ = ()
1132 is_scoped = True
1133 def cs_format(self, precision=None):
1134 return "break;"
1135
1136 def __eq__(self, other):
1137 return isinstance(other, type(self))
1138
1139
1140 class Continue(CStatement):
1141 __slots__ = ()
1142 is_scoped = True
1143 def cs_format(self, precision=None):
1144 return "continue;"
1145
1146 def __eq__(self, other):
1147 return isinstance(other, type(self))
1148
1149
1150 class Return(CStatement):
1151 __slots__ = ("value",)
1152 is_scoped = True
1153 def __init__(self, value=None):
1154 if value is None:
1155 self.value = None
1156 else:
1157 self.value = as_cexpr(value)
1158
1159 def cs_format(self, precision=None):
1160 if self.value is None:
1161 return "return;"
1162 else:
1163 return "return %s;" % (self.value.ce_format(precision),)
1164
1165 def __eq__(self, other):
1166 return (isinstance(other, type(self))
1167 and self.value == other.value)
1168
1169
1170 class Case(CStatement):
1171 __slots__ = ("value",)
1172 is_scoped = False
1173 def __init__(self, value):
1174 # NB! This is too permissive and will allow invalid case arguments.
1175 self.value = as_cexpr(value)
1176
1177 def cs_format(self, precision=None):
1178 return "case " + self.value.ce_format(precision) + ":"
1179
1180 def __eq__(self, other):
1181 return (isinstance(other, type(self))
1182 and self.value == other.value)
1183
1184
1185 class Default(CStatement):
1186 __slots__ = ()
1187 is_scoped = False
1188 def cs_format(self, precision=None):
1189 return "default:"
1190
1191 def __eq__(self, other):
1192 return isinstance(other, type(self))
1193
1194
1195 class Throw(CStatement):
1196 __slots__ = ("exception", "message")
1197 is_scoped = True
1198 def __init__(self, exception, message):
1199 assert isinstance(exception, str)
1200 assert isinstance(message, str)
1201 self.exception = exception
1202 self.message = message
1203
1204 def cs_format(self, precision=None):
1205 assert '"' not in self.message
1206 return "throw " + self.exception + '("' + self.message + '");'
1207
1208 def __eq__(self, other):
1209 return (isinstance(other, type(self))
1210 and self.message == other.message
1211 and self.exception == other.exception)
1212
1213
1214 class Comment(CStatement):
1215 "Line comment(s) used for annotating the generated code with human readable remarks."
1216 __slots__ = ("comment",)
1217 is_scoped = True
1218 def __init__(self, comment):
1219 assert isinstance(comment, str)
1220 self.comment = comment
1221
1222 def cs_format(self, precision=None):
1223 lines = self.comment.strip().split("\n")
1224 return ["// " + line.strip() for line in lines]
1225
1226 def __eq__(self, other):
1227 return (isinstance(other, type(self))
1228 and self.comment == other.comment)
1229
1230
1231 def NoOp():
1232 return Comment("Do nothing")
1233
1234
1235 def commented_code_list(code, comments):
1236 "Convenience wrapper for adding comment to code list if the list is not empty."
1237 if isinstance(code, CNode):
1238 code = [code]
1239 assert isinstance(code, list)
1240 if code:
1241 if not isinstance(comments, (list, tuple)):
1242 comments = [comments]
1243 comments = [Comment(c) for c in comments]
1244 code = comments + code
1245 return code
1246
1247
1248 class Pragma(CStatement):
1249 "Pragma comments used for compiler-specific annotations."
1250 __slots__ = ("comment",)
1251 is_scoped = True
1252 def __init__(self, comment):
1253 assert isinstance(comment, str)
1254 self.comment = comment
1255
1256 def cs_format(self, precision=None):
1257 assert "\n" not in self.comment
1258 return "#pragma " + self.comment
1259
1260 def __eq__(self, other):
1261 return (isinstance(other, type(self))
1262 and self.comment == other.comment)
1263
1264
1265 ############## Type and variable declarations
1266
1267 class VariableDecl(CStatement):
1268 "Declare a variable, optionally define initial value."
1269 __slots__ = ("typename", "symbol", "value")
1270 is_scoped = False
1271 def __init__(self, typename, symbol, value=None):
1272
1273 # No type system yet, just using strings
1274 assert isinstance(typename, str)
1275 self.typename = typename
1276
1277 # Allow Symbol or just a string
1278 self.symbol = as_symbol(symbol)
1279
1280 if value is not None:
1281 value = as_cexpr(value)
1282 self.value = value
1283
1284 def cs_format(self, precision=None):
1285 code = self.typename + " " + self.symbol.name
1286 if self.value is not None:
1287 code += " = " + self.value.ce_format(precision)
1288 return code + ";"
1289
1290 def __eq__(self, other):
1291 return (isinstance(other, type(self))
1292 and self.typename == other.typename
1293 and self.symbol == other.symbol
1294 and self.value == other.value)
1295
1296
1297 def leftover(size, padlen):
1298 "Return minimum integer to add to size to make it divisible by padlen."
1299 return (padlen - (size % padlen)) % padlen
1300
1301
1302 def pad_dim(dim, padlen):
1303 "Make dim divisible by padlen."
1304 return ((dim + padlen - 1) // padlen) * padlen
1305
1306
1307 def pad_innermost_dim(shape, padlen):
1308 "Make the last dimension in shape divisible by padlen."
1309 if not shape:
1310 return ()
1311 shape = list(shape)
1312 if padlen:
1313 shape[-1] = pad_dim(shape[-1], padlen)
1314 return tuple(shape)
1315
1316
1317 def build_1d_initializer_list(values, formatter, padlen=0, precision=None):
1318 '''Return a list containing a single line formatted like "{ 0.0, 1.0, 2.0 }"'''
1319 if formatter == str:
1320 formatter = lambda x, p: str(x)
1321 tokens = ["{ "]
•1322 if numpy.prod(values.shape) > 0:
1323 sep = ", "
1324 fvalues = [formatter(v, precision) for v in values]
1325 for v in fvalues[:-1]:
1326 tokens.append(v)
1327 tokens.append(sep)
1328 tokens.append(fvalues[-1])
1329 if padlen:
1330 # Add padding
1331 zero = formatter(values.dtype.type(0), precision)
1332 for i in range(leftover(len(values), padlen)):
1333 tokens.append(sep)
1334 tokens.append(zero)
1335 tokens += " }"
1336 return "".join(tokens)
1337
1338
1339 def build_initializer_lists(values, sizes, level, formatter, padlen=0, precision=None):
1340 """Return a list of lines with initializer lists for a multidimensional array.
1341
1342 Example output::
1343
1344 { { 0.0, 0.1 },
1345 { 1.0, 1.1 } }
1346 """
1347 if formatter == str:
1348 formatter = lambda x, p: str(x)
1349 values = numpy.asarray(values)
•1350 assert numpy.prod(values.shape) == numpy.prod(sizes)
1351 assert len(sizes) > 0
1352 assert len(values.shape) > 0
1353 assert len(sizes) == len(values.shape)
1354 assert numpy.all(values.shape == sizes)
1355
1356 r = len(sizes)
1357 assert r > 0
1358 if r == 1:
1359 return [build_1d_initializer_list(values, formatter, padlen=padlen, precision=precision)]
1360 else:
1361 # Render all sublists
1362 parts = []
1363 for val in values:
1364 sublist = build_initializer_lists(val, sizes[1:], level+1, formatter, padlen=padlen, precision=precision)
1365 parts.append(sublist)
1366 # Add comma after last line in each part except the last one
1367 for part in parts[:-1]:
1368 part[-1] += ","
1369 # Collect all lines in flat list
1370 lines = []
1371 for part in parts:
1372 lines.extend(part)
1373 # Enclose lines in '{ ' and ' }' and indent lines in between
1374 lines[0] = "{ " + lines[0]
1375 for i in range(1,len(lines)):
1376 lines[i] = " " + lines[i]
1377 lines[-1] += " }"
1378 return lines
1379
1380
1381 class ArrayDecl(CStatement):
1382 """A declaration or definition of an array.
1383
1384 Note that just setting values=0 is sufficient
1385 to initialize the entire array to zero.
1386
1387 Otherwise use nested lists of lists to represent
1388 multidimensional array values to initialize to.
1389 """
1390 __slots__ = ("typename", "symbol", "sizes", "alignas", "padlen", "values")
1391 is_scoped = False
1392 def __init__(self, typename, symbol, sizes=None, values=None, alignas=None, padlen=0):
1393 assert isinstance(typename, str)
1394 self.typename = typename
1395
1396 if isinstance(symbol, FlattenedArray):
1397 if sizes is None:
1398 assert symbol.dims is not None
1399 sizes = symbol.dims
1400 elif symbol.dims is not None:
1401 assert symbol.dims == sizes
1402 self.symbol = symbol.array
1403 else:
1404 self.symbol = as_symbol(symbol)
1405
1406 if isinstance(sizes, int):
1407 sizes = (sizes,)
1408 self.sizes = tuple(sizes)
1409
1410 # NB! No type checking, assuming nested lists of literal values. Not applying as_cexpr.
1411 if isinstance(values, (list, tuple)):
1412 self.values = numpy.asarray(values)
1413 else:
1414 self.values = values
1415
1416 self.alignas = alignas
1417 self.padlen = padlen
1418
1419 def __getitem__(self, indices):
1420 """Allow using array declaration object as the array when indexed.
1421
1422 A = ArrayDecl("int", "A", (2,3))
1423 code = [A, Assign(A[0,0], 1.0)]
1424 """
1425 return ArrayAccess(self, indices)
1426
1427 def cs_format(self, precision=None):
1428 # Pad innermost array dimension
1429 sizes = pad_innermost_dim(self.sizes, self.padlen)
1430
1431 # Add brackets
1432 brackets = ''.join("[%d]" % n for n in sizes)
1433
1434 # Join declaration
1435 decl = self.typename + " " + self.symbol.name + brackets
1436
1437 # NB! C++11 style alignas prefix syntax.
1438 # If trying other target languages, must use other syntax.
1439 if self.alignas:
1440 align = "alignas(%d)" % int(self.alignas)
1441 decl = align + " " + decl
1442
1443 if self.values is None:
1444 # Undefined initial values
1445 return decl + ";"
1446 elif _is_zero_valued(self.values):
1447 # Zero initial values
1448 # (NB! C++ style zero initialization, not sure about other target languages)
1449 return decl + " = {};"
1450 else:
1451 # Construct initializer lists for arbitrary multidimensional array values
1452 if self.values.dtype.kind == "f":
1453 formatter = format_float
1454 elif self.values.dtype.kind == "i":
1455 formatter = format_int
1456 else:
1457 formatter = format_value
1458 initializer_lists = build_initializer_lists(self.values, self.sizes, 0,
1459 formatter, padlen=self.padlen,
1460 precision=precision)
1461 if len(initializer_lists) == 1:
1462 return decl + " = " + initializer_lists[0] + ";"
1463 else:
1464 initializer_lists[-1] += ";" # Close statement on final line
1465 return (decl + " =", Indented(initializer_lists))
1466
1467 def __eq__(self, other):
1468 attributes = ("typename", "symbol", "sizes", "alignas", "padlen", "values")
1469 return (isinstance(other, type(self))
1470 and all(getattr(self, name) == getattr(self, name)
1471 for name in attributes))
1472
1473
1474
1475 ############## Scoped statements
1476
1477 class Scope(CStatement):
1478 __slots__ = ("body",)
1479 is_scoped = True
1480 def __init__(self, body):
1481 self.body = as_cstatement(body)
1482
1483 def cs_format(self, precision=None):
1484 return ("{", Indented(self.body.cs_format(precision)), "}")
1485
1486 def __eq__(self, other):
1487 return (isinstance(other, type(self))
1488 and self.body == other.body)
1489
1490
1491 class Namespace(CStatement):
1492 __slots__ = ("name", "body")
1493 is_scoped = True
1494 def __init__(self, name, body):
1495 assert isinstance(name, str)
1496 self.name = name
1497 self.body = as_cstatement(body)
1498
1499 def cs_format(self, precision=None):
1500 return ("namespace " + self.name,
1501 "{", Indented(self.body.cs_format(precision)), "}")
1502
1503 def __eq__(self, other):
1504 return (isinstance(other, type(self))
1505 and self.name == other.name
1506 and self.body == other.body)
1507
1508
1509 def _is_scoped_statement(body):
1510 return
1511
1512
1513 def _is_simple_if_body(body):
1514 if isinstance(body, StatementList):
1515 if len(body.statements) > 1:
1516 return False
1517 body, = body.statements
1518 return isinstance(body, (Return, AssignOp, Break, Continue))
1519
1520
1521 class If(CStatement):
1522 __slots__ = ("condition", "body")
1523 is_scoped = True
1524 def __init__(self, condition, body):
1525 self.condition = as_cexpr(condition)
1526 self.body = as_cstatement(body)
1527
1528 def cs_format(self, precision=None):
1529 statement = "if (" + self.condition.ce_format(precision) + ")"
1530 body_fmt = Indented(self.body.cs_format(precision))
1531 if _is_simple_if_body(self.body):
1532 return (statement, body_fmt)
1533 else:
1534 return (statement, "{", body_fmt, "}")
1535
1536 def __eq__(self, other):
1537 return (isinstance(other, type(self))
1538 and self.condition == other.condition
1539 and self.body == other.body)
1540
1541
1542 class ElseIf(CStatement):
1543 __slots__ = ("condition", "body")
1544 is_scoped = True
1545 def __init__(self, condition, body):
1546 self.condition = as_cexpr(condition)
1547 self.body = as_cstatement(body)
1548
1549 def cs_format(self, precision=None):
1550 statement = "else if (" + self.condition.ce_format(precision) + ")"
1551 body_fmt = Indented(self.body.cs_format(precision))
1552 if _is_simple_if_body(self.body):
1553 return (statement, body_fmt)
1554 else:
1555 return (statement, "{", body_fmt, "}")
1556
1557 def __eq__(self, other):
1558 return (isinstance(other, type(self))
1559 and self.condition == other.condition
1560 and self.body == other.body)
1561
1562
1563 class Else(CStatement):
1564 __slots__ = ("body",)
1565 is_scoped = True
1566 def __init__(self, body):
1567 self.body = as_cstatement(body)
1568
1569 def cs_format(self, precision=None):
1570 statement = "else"
1571 body_fmt = Indented(self.body.cs_format(precision))
1572 if _is_simple_if_body(self.body):
1573 return (statement, body_fmt)
1574 else:
1575 return (statement, "{", body_fmt, "}")
1576
1577 def __eq__(self, other):
1578 return (isinstance(other, type(self))
1579 and self.body == other.body)
1580
1581
1582 class While(CStatement):
1583 __slots__ = ("condition", "body")
1584 is_scoped = True
1585 def __init__(self, condition, body):
1586 self.condition = as_cexpr(condition)
1587 self.body = as_cstatement(body)
1588
1589 def cs_format(self, precision=None):
1590 return ("while (" + self.condition.ce_format(precision) + ")",
1591 "{", Indented(self.body.cs_format(precision)), "}")
1592
1593 def __eq__(self, other):
1594 return (isinstance(other, type(self))
1595 and self.condition == other.condition
1596 and self.body == other.body)
1597
1598
1599 class Do(CStatement):
1600 __slots__ = ("condition", "body")
1601 is_scoped = True
1602 def __init__(self, condition, body):
1603 self.condition = as_cexpr(condition)
1604 self.body = as_cstatement(body)
1605
1606 def cs_format(self, precision=None):
1607 return ("do", "{", Indented(self.body.cs_format(precision)),
1608 "} while (" + self.condition.ce_format(precision) + ");")
1609
1610 def __eq__(self, other):
1611 return (isinstance(other, type(self))
1612 and self.condition == other.condition
1613 and self.body == other.body)
1614
1615
1616 def as_pragma(pragma):
1617 if isinstance(pragma, str):
1618 return Pragma(pragma)
1619 elif isinstance(pragma, Pragma):
1620 return pragma
1621 return None
1622
1623
1624 def is_simple_inner_loop(code):
1625 if isinstance(code, (ForRange, For)) and code.pragma is None and is_simple_inner_loop(code.body):
1626 return True
1627 if isinstance(code, Statement) and isinstance(code.expr, AssignOp):
1628 return True
1629 return False
1630
1631
1632 class For(CStatement):
1633 __slots__ = ("init", "check", "update", "body", "pragma")
1634 is_scoped = True
1635 def __init__(self, init, check, update, body, pragma=None):
1636 self.init = as_cstatement(init)
1637 self.check = as_cexpr_or_verbatim(check)
1638 self.update = as_cexpr_or_verbatim(update)
1639 self.body = as_cstatement(body)
1640 self.pragma = as_pragma(pragma)
1641
1642 def cs_format(self, precision=None):
1643 # The C model here is a bit crude and this causes trouble
1644 # in the init statement/expression here:
1645 init = self.init.cs_format(precision)
1646 assert isinstance(init, str)
1647 init = init.rstrip(" ;")
1648
1649 check = self.check.ce_format(precision)
1650 update = self.update.ce_format(precision)
1651
1652 prelude = "for (" + init + "; " + check + "; " + update + ")"
1653 body = Indented(self.body.cs_format(precision))
1654
1655 # Reduce size of code with lots of simple loops by dropping {} in obviously safe cases
1656 if is_simple_inner_loop(self.body):
1657 code = (prelude, body)
1658 else:
1659 code = (prelude, "{", body, "}")
1660
1661 # Add pragma prefix if requested
1662 if self.pragma is not None:
1663 code = (self.pragma.cs_format(),) + code
1664
1665 return code
1666
1667 def __eq__(self, other):
1668 attributes = ("init", "check", "update", "body")
1669 return (isinstance(other, type(self))
1670 and all(getattr(self, name) == getattr(self, name)
1671 for name in attributes))
1672
1673
1674 class Switch(CStatement):
1675 __slots__ = ("arg", "cases", "default", "autobreak", "autoscope")
1676 is_scoped = True
1677 def __init__(self, arg, cases, default=None, autobreak=True, autoscope=True):
1678 self.arg = as_cexpr_or_string_symbol(arg)
1679 self.cases = [(as_cexpr(value), as_cstatement(body)) for value, body in cases]
1680 if default is not None:
1681 default = as_cstatement(default)
1682 defcase = [(None, default)]
1683 else:
1684 defcase = []
1685 self.default = default
1686 # If this is a switch where every case returns, scopes or breaks are never needed
1687 if all(isinstance(case[1], Return) for case in self.cases + defcase):
1688 autobreak = False
1689 autoscope = False
1690 if all(case[1].is_scoped for case in self.cases + defcase):
1691 autoscope = False
1692 assert autobreak in (True, False)
1693 assert autoscope in (True, False)
1694 self.autobreak = autobreak
1695 self.autoscope = autoscope
1696
1697 def cs_format(self, precision=None):
1698 cases = []
1699 for case in self.cases:
1700 caseheader = "case " + case[0].ce_format(precision) + ":"
1701 casebody = case[1].cs_format(precision)
1702 if self.autoscope:
1703 casebody = ("{", Indented(casebody), "}")
1704 if self.autobreak:
1705 casebody = (casebody, "break;")
1706 cases.extend([caseheader, Indented(casebody)])
1707
1708 if self.default is not None:
1709 caseheader = "default:"
1710 casebody = self.default.cs_format(precision)
1711 if self.autoscope:
1712 casebody = ("{", Indented(casebody), "}")
1713 cases.extend([caseheader, Indented(casebody)])
1714
1715 return ("switch (" + self.arg.ce_format(precision) + ")",
1716 "{", cases, "}")
1717
1718 def __eq__(self, other):
1719 attributes = ("arg", "cases", "default", "autobreak", "autoscope")
1720 return (isinstance(other, type(self))
1721 and all(getattr(self, name) == getattr(self, name)
1722 for name in attributes))
1723
1724
1725 class ForRange(CStatement):
1726 "Slightly higher-level for loop assuming incrementing an index over a range."
1727 __slots__ = ("index", "begin", "end", "body", "pragma", "index_type")
1728 is_scoped = True
1729 def __init__(self, index, begin, end, body, index_type="int", vectorize=None):
1730 self.index = as_cexpr_or_string_symbol(index)
1731 self.begin = as_cexpr(begin)
1732 self.end = as_cexpr(end)
1733 self.body = as_cstatement(body)
1734
1735 if vectorize:
1736 pragma = Pragma("omp simd")
1737 else:
1738 pragma = None
1739 self.pragma = pragma
1740
1741 self.index_type = index_type
1742
1743 def cs_format(self, precision=None):
1744 indextype = self.index_type
1745 index = self.index.ce_format(precision)
1746 begin = self.begin.ce_format(precision)
1747 end = self.end.ce_format(precision)
1748
1749 init = indextype + " " + index + " = " + begin
1750 check = index + " < " + end
1751 update = "++" + index
1752
1753 prelude = "for (" + init + "; " + check + "; " + update + ")"
1754 body = Indented(self.body.cs_format(precision))
1755
1756 # Reduce size of code with lots of simple loops by dropping {} in obviously safe cases
1757 if is_simple_inner_loop(self.body):
1758 code = (prelude, body)
1759 else:
1760 code = (prelude, "{", body, "}")
1761
1762 # Add vectorization hint if requested
1763 if self.pragma is not None:
1764 code = (self.pragma.cs_format(),) + code
1765
1766 return code
1767
1768 def __eq__(self, other):
1769 attributes = ("index", "begin", "end", "body", "pragma", "index_type")
1770 return (isinstance(other, type(self))
1771 and all(getattr(self, name) == getattr(self, name)
1772 for name in attributes))
1773
1774
1775 def ForRanges(*ranges, **kwargs):
1776 ranges = list(reversed(ranges))
1777 code = kwargs["body"]
1778 for r in ranges:
1779 kwargs["body"] = code
1780 code = ForRange(*r, **kwargs)
1781 return code
1782
1783
1784 ############## Convertion function to statement nodes
1785
1786 def as_cstatement(node):
1787 "Perform type checking on node and wrap in a suitable statement type if necessary."
1788 if isinstance(node, StatementList) and len(node.statements) == 1:
1789 # Cleans up the expression tree a bit
1790 return node.statements[0]
1791 elif isinstance(node, CStatement):
1792 # No-op
1793 return node
1794 elif isinstance(node, CExprOperator):
1795 if node.sideeffect:
1796 # Special case for using assignment expressions as statements
1797 return Statement(node)
1798 else:
1799 raise RuntimeError(
1800 "Trying to create a statement of CExprOperator type %s:\n%s"
1801 % (type(node), str(node)))
1802 elif isinstance(node, list):
1803 # Convenience case for list of statements
1804 if len(node) == 1:
1805 # Cleans up the expression tree a bit
1806 return as_cstatement(node[0])
1807 else:
1808 return StatementList(node)
1809 elif isinstance(node, str):
1810 # Backdoor for flexibility in code generation to allow verbatim pasted statements
1811 return VerbatimStatement(node)
1812 else:
1813 raise RuntimeError("Unexpected CStatement type %s:\n%s" % (type(node), str(node)))