-
Notifications
You must be signed in to change notification settings - Fork 23
/
gocean1p0.py
2203 lines (1900 loc) · 95.2 KB
/
gocean1p0.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=too-many-lines
# -----------------------------------------------------------------------------
# BSD 3-Clause License
#
# Copyright (c) 2017-2020, Science and Technology Facilities Council.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# -----------------------------------------------------------------------------
# Authors R. W. Ford, A. R. Porter and S. Siso, STFC Daresbury Lab
# Modified work Copyright (c) 2018 by J. Henrichs, Bureau of Meteorology
'''This module implements the PSyclone GOcean 1.0 API by specialising
the required base classes for both code generation (PSy, Invokes,
Invoke, InvokeSchedule, Loop, Kern, Arguments and KernelArgument)
and parsing (Descriptor and KernelType). It adds a
GOKernelGridArgument class to capture information on kernel arguments
that supply properties of the grid (and are generated in the PSy
layer).
'''
from __future__ import print_function
import six
from psyclone.configuration import Config
from psyclone.parse.kernel import Descriptor, KernelType
from psyclone.parse.utils import ParseError
from psyclone.psyir.nodes import Loop, Literal, Schedule, Node
from psyclone.psyGen import PSy, Invokes, Invoke, InvokeSchedule, \
CodedKern, Arguments, Argument, KernelArgument, args_filter, \
KernelSchedule, AccessType, ACCEnterDataDirective
from psyclone.errors import GenerationError, InternalError
from psyclone.psyir.symbols import SymbolTable, ScalarType, ArrayType, \
INTEGER_TYPE, DataSymbol, Symbol
from psyclone.psyir.frontend.fparser2 import Fparser2Reader
import psyclone.expression as expr
# The different grid-point types that a field can live on
VALID_FIELD_GRID_TYPES = ["go_cu", "go_cv", "go_ct", "go_cf", "go_every"]
# The two scalar types we support
VALID_SCALAR_TYPES = ["go_i_scalar", "go_r_scalar"]
# Index-offset schemes (for the Arakawa C-grid)
VALID_OFFSET_NAMES = ["go_offset_se", "go_offset_sw",
"go_offset_ne", "go_offset_nw", "go_offset_any"]
# The offset schemes for which we can currently generate constant
# loop bounds in the PSy layer
SUPPORTED_OFFSETS = ["go_offset_ne", "go_offset_sw", "go_offset_any"]
# The sets of grid points that a kernel may operate on
VALID_ITERATES_OVER = ["go_all_pts", "go_internal_pts", "go_external_pts"]
# The list of valid stencil properties. We currently only support
# pointwise. This property could probably be removed from the
# GOcean API altogether.
VALID_STENCIL_NAMES = ["go_pointwise"]
# The valid types of loop. In this API we expect only doubly-nested
# loops.
VALID_LOOP_TYPES = ["inner", "outer"]
class GOPSy(PSy):
'''
The GOcean 1.0 specific PSy class. This creates a GOcean specific
invokes object (which controls all the required invocation calls).
Also overrides the PSy gen method so that we generate GOcean-
specific PSy module code.
:param invoke_info: An object containing the required invocation \
information for code optimisation and generation.
:type invoke_info: :py:class:`psyclone.parse.FileInfo`
'''
def __init__(self, invoke_info):
PSy.__init__(self, invoke_info)
self._invokes = GOInvokes(invoke_info.calls, self)
@property
def gen(self):
'''
Generate PSy code for the GOcean api v.1.0.
:rtype: ast
'''
from psyclone.f2pygen import ModuleGen, UseGen
# create an empty PSy layer module
psy_module = ModuleGen(self.name)
# include the kind_params module
psy_module.add(UseGen(psy_module, name="kind_params_mod"))
# include the field_mod module
psy_module.add(UseGen(psy_module, name="field_mod"))
self.invokes.gen_code(psy_module)
# inline kernels where requested
self.inline(psy_module)
return psy_module.root
class GOInvokes(Invokes):
'''
The GOcean specific invokes class. This passes the GOcean specific
invoke class to the base class so it creates the one we require.
:param alg_calls: The Invoke calls discovered in the Algorithm layer.
:type alg_calls: OrderedDict of :py:class:`psyclone.parse.InvokeCall` \
objects.
:param psy: the PSy object containing this GOInvokes object.
:type psy: :py:class:`psyclone.gocean1p0.GOPSy`
'''
def __init__(self, alg_calls, psy):
self._0_to_n = GOInvoke(None, None, None) # for pyreverse
Invokes.__init__(self, alg_calls, GOInvoke, psy)
index_offsets = []
# Loop over all of the kernels in all of the invoke() calls
# and check that they work on compatible grid-index offsets.
# Strictly speaking this check should be done in the parsing
# code since it is a check on the correctness of the meta-data.
# However, that would require a fundamental change to the parsing
# code since it requires information on all of the invokes and
# kernels in an application. Therefore it is much simpler to
# do it here where we have easy access to that information.
for invoke in self.invoke_list:
for kern_call in invoke.schedule.coded_kernels():
# We only care if the index offset is not offset_any (since
# that is compatible with any other offset)
if kern_call.index_offset != "go_offset_any":
# Loop over the offsets we've seen so far
for offset in index_offsets:
if offset != kern_call.index_offset:
raise GenerationError(
"Meta-data error in kernel {0}: "
"INDEX_OFFSET of '{1}' does not match that "
"({2}) of other kernels. This is not "
"supported.".format(kern_call.name,
kern_call.index_offset,
offset))
# Append the index-offset of this kernel to the list of
# those seen so far
index_offsets.append(kern_call.index_offset)
class GOInvoke(Invoke):
'''
The GOcean specific invoke class. This passes the GOcean specific
schedule class to the base class so it creates the one we require.
A set of GOcean infrastructure reserved names are also passed to
ensure that there are no name clashes. Also overrides the gen_code
method so that we generate GOcean specific invocation code and
provides three methods which separate arguments that are arrays from
arguments that are {integer, real} scalars.
:param alg_invocation: Node in the AST describing the invoke call.
:type alg_invocation: :py:class:`psyclone.parse.InvokeCall`
:param int idx: The position of the invoke in the list of invokes \
contained in the Algorithm.
:param invokes: the Invokes object containing this GOInvoke \
object.
:type invokes: :py:class:`psyclone.gocean1p0.GOInvokes`
'''
def __init__(self, alg_invocation, idx, invokes):
self._schedule = GOInvokeSchedule(None) # for pyreverse
Invoke.__init__(self, alg_invocation, idx, GOInvokeSchedule, invokes)
@property
def unique_args_arrays(self):
''' find unique arguments that are arrays (defined as those that are
field objects as opposed to scalars or properties of the grid). '''
result = []
for call in self._schedule.kernels():
for arg in call.arguments.args:
if arg.type == 'field' and arg.name not in result:
result.append(arg.name)
return result
@property
def unique_args_rscalars(self):
'''
:returns: the unique arguments that are scalars of type real \
(defined as those that are go_r_scalar 'space').
:rtype: list of str.
'''
result = []
for call in self._schedule.kernels():
for arg in args_filter(call.arguments.args, arg_types=["scalar"],
is_literal=False):
if arg.space.lower() == "go_r_scalar" and \
arg.name not in result:
result.append(arg.name)
return result
@property
def unique_args_iscalars(self):
'''
:returns: the unique arguments that are scalars of type integer \
(defined as those that are i_scalar 'space').
:rtype: list of str.
'''
result = []
for call in self._schedule.kernels():
for arg in args_filter(call.arguments.args, arg_types=["scalar"],
is_literal=False):
if arg.space.lower() == "go_i_scalar" and \
arg.name not in result:
result.append(arg.name)
return result
def gen_code(self, parent):
# pylint: disable=too-many-locals
'''
Generates GOcean specific invocation code (the subroutine called
by the associated invoke call in the algorithm layer). This
consists of the PSy invocation subroutine and the declaration of
its arguments.
:param parent: the node in the generated AST to which to add content.
:type parent: :py:class:`psyclone.f2pygen.ModuleGen`
'''
from psyclone.f2pygen import SubroutineGen, DeclGen, TypeDeclGen, \
CommentGen, AssignGen
# create the subroutine
invoke_sub = SubroutineGen(parent, name=self.name,
args=self.psy_unique_var_names)
parent.add(invoke_sub)
# add declarations for the variables holding the upper bounds
# of loops in i and j
if self.schedule.const_loop_bounds:
invoke_sub.add(DeclGen(invoke_sub, datatype="INTEGER",
entity_decls=[self.schedule.iloop_stop,
self.schedule.jloop_stop]))
# Generate the code body of this subroutine
self.schedule.gen_code(invoke_sub)
# If we're generating an OpenCL routine then the arguments must
# have the target attribute as we pass pointers to them in to
# the OpenCL run-time.
target = bool(self.schedule.opencl)
# add the subroutine argument declarations for fields
if self.unique_args_arrays:
my_decl_arrays = TypeDeclGen(invoke_sub, datatype="r2d_field",
intent="inout", target=target,
entity_decls=self.unique_args_arrays)
invoke_sub.add(my_decl_arrays)
# get the list of global symbols used in the invoke
global_names = [sym.name for sym in
self.schedule.symbol_table.global_symbols]
# add the subroutine argument declarations for real scalars which
# are not global symbols
real_decls = list(filter(lambda x: x not in global_names,
self.unique_args_rscalars))
if real_decls:
my_decl_rscalars = DeclGen(invoke_sub, datatype="REAL",
intent="inout", kind="go_wp",
entity_decls=real_decls)
invoke_sub.add(my_decl_rscalars)
# add the subroutine argument declarations for integer scalars
# which are not global symbols
int_decls = list(filter(lambda x: x not in global_names,
self.unique_args_iscalars))
if int_decls:
my_decl_iscalars = DeclGen(invoke_sub, datatype="INTEGER",
intent="inout",
entity_decls=int_decls)
invoke_sub.add(my_decl_iscalars)
if self._schedule.const_loop_bounds and self.unique_args_arrays:
# Look-up the loop bounds using the first field object in the
# list
api_config = Config.get().api_conf("gocean1.0")
xstop = api_config.grid_properties["go_grid_xstop"].fortran \
.format(self.unique_args_arrays[0])
ystop = api_config.grid_properties["go_grid_ystop"].fortran \
.format(self.unique_args_arrays[0])
position = invoke_sub.last_declaration()
invoke_sub.add(CommentGen(invoke_sub, ""),
position=["after", position])
invoke_sub.add(AssignGen(invoke_sub, lhs=self.schedule.jloop_stop,
rhs=ystop),
position=["after", position])
invoke_sub.add(AssignGen(invoke_sub, lhs=self.schedule.iloop_stop,
rhs=xstop),
position=["after", position])
invoke_sub.add(CommentGen(invoke_sub, " Look-up loop bounds"),
position=["after", position])
invoke_sub.add(CommentGen(invoke_sub, ""),
position=["after", position])
class GOInvokeSchedule(InvokeSchedule):
''' The GOcean specific InvokeSchedule sub-class. We call the base class
constructor and pass it factories to create GO-specific calls to both
user-supplied kernels and built-ins. '''
# Textual description of the node.
_text_name = "GOInvokeSchedule"
def __init__(self, alg_calls, reserved_names=None):
InvokeSchedule.__init__(self, GOKernCallFactory, GOBuiltInCallFactory,
alg_calls, reserved_names)
# Configuration of this InvokeSchedule - we default to having
# constant loop bounds. If we end up having a long list
# of configuration member variables here we may want
# to create a a new ScheduleConfig object to manage them.
self._const_loop_bounds = True
def node_str(self, colour=True):
''' Creates a text description of this node with (optional) control
codes to generate coloured output in a terminal that supports it.
:param bool colour: whether or not to include colour control codes.
:returns: description of this node, possibly coloured.
:rtype: str
'''
return "{0}[invoke='{1}', Constant loop bounds={2}]".format(
self.coloured_name(colour), self.invoke.name,
self._const_loop_bounds)
def __str__(self):
''' Returns the string representation of this GOInvokeSchedule '''
result = self.node_str(False) + ":\n"
for entity in self._children:
result += str(entity)+"\n"
result += "End Schedule"
return result
@property
def iloop_stop(self):
'''Returns the variable name to use for the upper bound of inner
loops if we're generating loops with constant bounds. Raises
an error if constant bounds are not being used.
'''
if self._const_loop_bounds:
return "istop"
raise GenerationError(
"Refusing to supply name of inner loop upper bound "
"because constant loop bounds are not being used.")
@property
def jloop_stop(self):
'''Returns the variable name to use for the upper bound of outer
loops if we're generating loops with constant bounds. Raises
an error if constant bounds are not being used.
'''
if self._const_loop_bounds:
return "jstop"
raise GenerationError(
"Refusing to supply name of outer loop upper bound "
"because constant loop bounds are not being used.")
@property
def const_loop_bounds(self):
''' Returns True if constant loop bounds are enabled for this
schedule. Returns False otherwise. '''
return self._const_loop_bounds
@const_loop_bounds.setter
def const_loop_bounds(self, obj):
''' Set whether the InvokeSchedule will use constant loop bounds or
will look them up from the field object for every loop '''
self._const_loop_bounds = obj
# pylint: disable=too-many-instance-attributes
class GOLoop(Loop):
''' The GOcean specific Loop class. This passes the GOcean specific
single loop information to the base class so it creates the one we
require. Adds a GOcean specific setBounds method which tells the loop
what to iterate over. Need to harmonise with the topology_name method
in the Dynamo api. '''
_bounds_lookup = {}
def __init__(self, parent=None,
topology_name="", loop_type=""):
'''Constructs a GOLoop instance.
:param parent: Optional parent node (default None).
:type parent: :py:class:`psyclone.psyGen.node`
:param str topology_name: Optional opology of the loop (unused atm).
:param str loop_type: Loop type - must be 'inner' or 'outer'.'''
# pylint: disable=unused-argument
Loop.__init__(self, parent=parent,
valid_loop_types=VALID_LOOP_TYPES)
self.loop_type = loop_type
# We set the loop variable name in the constructor so that it is
# available when we're determining which vars should be OpenMP
# PRIVATE (which is done *before* code generation is performed)
if self.loop_type == "inner":
tag = "inner_loop_idx"
suggested_name = "i"
elif self.loop_type == "outer":
tag = "outer_loop_idx"
suggested_name = "j"
else:
raise GenerationError(
"Invalid loop type of '{0}'. Expected one of {1}".
format(self._loop_type, VALID_LOOP_TYPES))
symtab = self.scope.symbol_table
try:
data_symbol = symtab.lookup_with_tag(tag)
except KeyError:
name = symtab.new_symbol_name(suggested_name)
data_symbol = DataSymbol(name, INTEGER_TYPE)
symtab.add(data_symbol, tag=tag)
self.variable = data_symbol
# Pre-initialise the Loop children # TODO: See issue #440
self.addchild(Literal("NOT_INITIALISED", INTEGER_TYPE,
parent=self)) # start
self.addchild(Literal("NOT_INITIALISED", INTEGER_TYPE,
parent=self)) # stop
self.addchild(Literal("1", INTEGER_TYPE, parent=self)) # step
self.addchild(Schedule(parent=self)) # loop body
if not GOLoop._bounds_lookup:
GOLoop.setup_bounds()
# -------------------------------------------------------------------------
@staticmethod
def setup_bounds():
'''Populates the GOLoop._bounds_lookup dictionary. This is
used by PSyclone to look up the loop boundaries for each loop
it creates.'''
for grid_offset in SUPPORTED_OFFSETS:
GOLoop._bounds_lookup[grid_offset] = {}
for gridpt_type in VALID_FIELD_GRID_TYPES:
GOLoop._bounds_lookup[grid_offset][gridpt_type] = {}
for itspace in VALID_ITERATES_OVER:
GOLoop._bounds_lookup[grid_offset][gridpt_type][
itspace] = {}
# Loop bounds for a mesh with NE offset
GOLoop._bounds_lookup['go_offset_ne']['go_ct']['go_all_pts'] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}+1"},
'outer': {'start': "{start}-1", 'stop': "{stop}+1"}}
GOLoop._bounds_lookup['go_offset_ne']['go_ct']['go_internal_pts'] = \
{'inner': {'start': "{start}", 'stop': "{stop}"},
'outer': {'start': "{start}", 'stop': "{stop}"}}
GOLoop._bounds_lookup['go_offset_ne']['go_cu']['go_all_pts'] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}"},
'outer': {'start': "{start}-1", 'stop': "{stop}+1"}}
GOLoop._bounds_lookup['go_offset_ne']['go_cu']['go_internal_pts'] = \
{'inner': {'start': "{start}", 'stop': "{stop}-1"},
'outer': {'start': "{start}", 'stop': "{stop}"}}
GOLoop._bounds_lookup['go_offset_ne']['go_cv']['go_all_pts'] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}+1"},
'outer': {'start': "{start}-1", 'stop': "{stop}"}}
GOLoop._bounds_lookup['go_offset_ne']['go_cv']['go_internal_pts'] = \
{'inner': {'start': "{start}", 'stop': "{stop}"},
'outer': {'start': "{start}", 'stop': "{stop}-1"}}
GOLoop._bounds_lookup['go_offset_ne']['go_cf']['go_all_pts'] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}"},
'outer': {'start': "{start}-1", 'stop': "{stop}"}}
GOLoop._bounds_lookup['go_offset_ne']['go_cf']['go_internal_pts'] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}-1"},
'outer': {'start': "{start}-1", 'stop': "{stop}-1"}}
# Loop bounds for a mesh with SE offset
GOLoop._bounds_lookup['go_offset_sw']['go_ct']['go_all_pts'] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}+1"},
'outer': {'start': "{start}-1", 'stop': "{stop}+1"}}
GOLoop._bounds_lookup['go_offset_sw']['go_ct']['go_internal_pts'] = \
{'inner': {'start': "{start}", 'stop': "{stop}"},
'outer': {'start': "{start}", 'stop': "{stop}"}}
GOLoop._bounds_lookup['go_offset_sw']['go_cu']['go_all_pts'] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}+1"},
'outer': {'start': "{start}-1", 'stop': "{stop}+1"}}
GOLoop._bounds_lookup['go_offset_sw']['go_cu']['go_internal_pts'] = \
{'inner': {'start': "{start}", 'stop': "{stop}+1"},
'outer': {'start': "{start}", 'stop': "{stop}"}}
GOLoop._bounds_lookup['go_offset_sw']['go_cv']['go_all_pts'] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}+1"},
'outer': {'start': "{start}-1", 'stop': "{stop}+1"}}
GOLoop._bounds_lookup['go_offset_sw']['go_cv']['go_internal_pts'] = \
{'inner': {'start': "{start}", 'stop': "{stop}"},
'outer': {'start': "{start}", 'stop': "{stop}+1"}}
GOLoop._bounds_lookup['go_offset_sw']['go_cf']['go_all_pts'] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}+1"},
'outer': {'start': "{start}-1", 'stop': "{stop}+1"}}
GOLoop._bounds_lookup['go_offset_sw']['go_cf']['go_internal_pts'] = \
{'inner': {'start': "{start}", 'stop': "{stop}+1"},
'outer': {'start': "{start}", 'stop': "{stop}+1"}}
# For offset 'any'
for gridpt_type in VALID_FIELD_GRID_TYPES:
for itspace in VALID_ITERATES_OVER:
GOLoop._bounds_lookup['go_offset_any'][gridpt_type][itspace] =\
{'inner': {'start': "{start}-1", 'stop': "{stop}"},
'outer': {'start': "{start}-1", 'stop': "{stop}"}}
# For 'every' grid-point type
for offset in SUPPORTED_OFFSETS:
for itspace in VALID_ITERATES_OVER:
GOLoop._bounds_lookup[offset]['go_every'][itspace] = \
{'inner': {'start': "{start}-1", 'stop': "{stop}+1"},
'outer': {'start': "{start}-1", 'stop': "{stop}+1"}}
# -------------------------------------------------------------------------
@staticmethod
def add_bounds(bound_info):
# pylint: disable=too-many-locals
'''
Adds a new iteration space to PSyclone. An iteration space in the
gocean1.0 API is for a certain offset type and field type. It defines
the loop boundaries for the outer and inner loop. The format is a
":" separated tuple:
bound_info = offset-type:field-type:iteration-space:outer-start:
outer-stop:inner-start:inner-stop
Example:
bound_info = go_offset_ne:go_ct:go_all_pts\
:{start}-1:{stop}+1:{start}:{stop}
The expressions {start} and {stop} will be replaced with the loop
indices that correspond to the inner points (i.e. non-halo or
boundary points) of the field. So the index {start}-1 is actually
on the halo / boundary.
:param str bound_info: A string that contains a ":" separated \
tuple with the iteration space definition.
:raises ValueError: if bound_info is not a string.
:raises ConfigurationError: if bound_info is not formatted correctly.
'''
if not isinstance(bound_info, str):
raise InternalError("The parameter 'bound_info' must be a string, "
"got '{0}' (type {1})"
.format(bound_info, type(bound_info)))
data = bound_info.split(":")
if len(data) != 7:
from psyclone.configuration import ConfigurationError
raise ConfigurationError("An iteration space must be in the form "
"\"offset-type:field-type:"
"iteration-space:outer-start:"
"outer-stop:inner-start:inner-stop\"\n"
"But got \"{0}\"".format(bound_info))
if not GOLoop._bounds_lookup:
GOLoop.setup_bounds()
# Check that all bound specifications (min and max index) are valid.
# ------------------------------------------------------------------
import re
# Regular expression that finds stings surrounded by {}
bracket_regex = re.compile("{[^}]+}")
for bound in data[3:7]:
all_expr = bracket_regex.findall(bound)
for bracket_expr in all_expr:
if bracket_expr not in ["{start}", "{stop}"]:
from psyclone.configuration import ConfigurationError
raise ConfigurationError("Only '{{start}}' and '{{stop}}' "
"are allowed as bracketed "
"expression in an iteration "
"space. But got "
"{0}".format(bracket_expr))
# Test if a loop with the given boundaries can actually be parsed.
from fparser.two.Fortran2003 import NoMatchError, Nonlabel_Do_Stmt
from fparser.two.parser import ParserFactory
# Necessary to setup the parser
ParserFactory().create(std="f2003")
# Test both the outer loop indices (index 3 and 4) and inner
# indices (index 5 and 6):
for bound in data[3:7]:
do_string = "do i=1, {0}".format(bound)
# Now replace any {start}/{stop} expression in the loop
# with a valid integer value:
do_string = do_string.format(start='15', stop='25')
# Check if the do loop can be parsed as a nonlabel do loop
try:
_ = Nonlabel_Do_Stmt(do_string)
except NoMatchError as err:
from psyclone.configuration import ConfigurationError
raise ConfigurationError("Expression '{0}' is not a "
"valid do loop boundary. Error "
"message: '{1}'."
.format(bound, str(err)))
# All tests successful, so add the new bounds:
# --------------------------------------------
current_bounds = GOLoop._bounds_lookup # Shortcut
# Check offset-type exists
if not data[0] in current_bounds:
current_bounds[data[0]] = {}
# Check field-type exists
if not data[1] in current_bounds[data[0]]:
current_bounds[data[0]][data[1]] = {}
# Check iteration space exists:
if not data[2] in current_bounds[data[0]][data[1]]:
current_bounds[data[0]][data[1]][data[2]] = {}
VALID_ITERATES_OVER.append(data[2])
current_bounds[data[0]][data[1]][data[2]] = \
{'outer': {'start': data[3], 'stop': data[4]},
'inner': {'start': data[5], 'stop': data[6]}}
# -------------------------------------------------------------------------
# pylint: disable=too-many-branches
def _upper_bound(self):
''' Creates the PSyIR of the upper bound of this loop.
This takes the field type and usage of const_loop_bounds
into account. In the case of const_loop_bounds it will be
using the data in GOLoop._bounds_lookup to find the appropriate
indices depending on offset, field type, and iteration space.
All occurences of {start} and {stop} in _bounds_lookup will
be replaced with the constant loop boundary variable, e.g.
"{stop}+1" will become "istop+1" (or "jstop+1 depending on
loop type).
:returns: the PSyIR for the upper bound of this loop.
:rtype: :py:class:`psyclone.psyir.nodes.Node`
'''
from psyclone.psyir.nodes import BinaryOperation
schedule = self.ancestor(GOInvokeSchedule)
if schedule.const_loop_bounds:
# Look for a child kernel in order to get the index offset.
# Since we have no guarantee of what state we expect our object
# to be in we allow for the case where we don't have any child
# kernels.
index_offset = ""
go_kernels = self.walk(GOKern)
if go_kernels:
index_offset = go_kernels[0].index_offset
if not index_offset:
return Literal("not_yet_set", INTEGER_TYPE, self)
if self._loop_type == "inner":
stop = schedule.iloop_stop
else:
stop = schedule.jloop_stop
# This strange line splitting was the only way I could find
# to avoid pep8 warnings: using [..._space]\ keeps on
# complaining about a white space
bounds = GOLoop._bounds_lookup[index_offset][self.field_space][
self._iteration_space][self._loop_type]
stop = bounds["stop"].format(start='2', stop=stop)
# Remove all white spaces
stop = "".join(stop.split())
# This common case is a bit of compile-time computation
# but it helps to fix all of the test cases.
if stop == "2-1":
stop = "1"
return Literal(stop, INTEGER_TYPE, self)
if self.field_space == "go_every":
# Bounds are independent of the grid-offset convention in use
# We look-up the upper bounds by enquiring about the SIZE of
# the array itself
stop = BinaryOperation(BinaryOperation.Operator.SIZE,
self)
# TODO 363 - needs to be updated once the PSyIR has support for
# Fortran derived types.
api_config = Config.get().api_conf("gocean1.0")
# Use the data property to access the member of the field that
# contains the actual grid points. The property value is a
# string with a placeholder ({0}) where the name of the field
# must go.
data = api_config.grid_properties["go_grid_data"].fortran \
.format(self.field_name)
stop.addchild(Literal(data, INTEGER_TYPE, parent=stop))
if self._loop_type == "inner":
stop.addchild(Literal("1", INTEGER_TYPE, parent=stop))
elif self._loop_type == "outer":
stop.addchild(Literal("2", INTEGER_TYPE, parent=stop))
return stop
# Loop bounds are pulled from the field object which
# is more straightforward for us but provides the
# Fortran compiler with less information.
if self._iteration_space.lower() == "go_internal_pts":
key = "internal"
elif self._iteration_space.lower() == "go_all_pts":
key = "whole"
else:
raise GenerationError("Unrecognised iteration space, '{0}'. "
"Cannot generate loop bounds.".
format(self._iteration_space))
api_config = Config.get().api_conf("gocean1.0")
props = api_config.grid_properties
# key is 'internal' or 'whole', and _loop_type is either
# 'inner' or 'outer'. The four possible combinations are
# defined in the config file:
stop_format = props["go_grid_{0}_{1}_stop"
.format(key, self._loop_type)].fortran
stop = stop_format.format(self.field_name)
# TODO 363 - this needs updating once the PSyIR has support for
# Fortran derived types.
return Literal(stop, INTEGER_TYPE, self)
# -------------------------------------------------------------------------
# pylint: disable=too-many-branches
def _lower_bound(self):
''' Returns the lower bound of this loop as a string.
This takes the field type and usage of const_loop_bounds
into account. In case of const_loop_bounds it will be
using the data in GOLoop._bounds_lookup to find the appropriate
indices depending on offset, field type, and iteration space.
All occurences of {start} and {stop} in _bounds_loopup will
be replaced with the constant loop boundary variable, e.g.
"{stop}+1" will become "istop+1" (or "jstop+1" depending on
loop type).
:returns: root of PSyIR sub-tree describing this lower bound.
:rtype: :py:class:`psyclone.psyir.nodes.Node`
'''
schedule = self.ancestor(GOInvokeSchedule)
if schedule.const_loop_bounds:
index_offset = ""
# Look for a child kernel in order to get the index offset.
# Since this is the __str__ method we have no guarantee
# what state we expect our object to be in so we allow
# for the case where we don't have any child kernels.
go_kernels = self.walk(GOKern)
if go_kernels:
index_offset = go_kernels[0].index_offset
if not index_offset:
return Literal("not_yet_set", INTEGER_TYPE, self)
if self._loop_type == "inner":
stop = schedule.iloop_stop
else:
stop = schedule.jloop_stop
# This strange line splitting was the only way I could find
# to avoid pep8 warnings: using [..._space]\ keeps on
# complaining about a white space
bounds = GOLoop._bounds_lookup[index_offset][self.field_space][
self._iteration_space][self._loop_type]
start = bounds["start"].format(start='2', stop=stop)
# Remove all white spaces
start = "".join(start.split())
# This common case is a bit of compile-time computation
# but it helps with fixing all of the test cases.
if start == "2-1":
start = "1"
return Literal(start, INTEGER_TYPE, self)
if self.field_space == "go_every":
# Bounds are independent of the grid-offset convention in use
return Literal("1", INTEGER_TYPE, self)
# Loop bounds are pulled from the field object which is more
# straightforward for us but provides the Fortran compiler
# with less information.
if self._iteration_space.lower() == "go_internal_pts":
key = "internal"
elif self._iteration_space.lower() == "go_all_pts":
key = "whole"
else:
raise GenerationError("Unrecognised iteration space, '{0}'. "
"Cannot generate loop bounds.".
format(self._iteration_space))
api_config = Config.get().api_conf("gocean1.0")
props = api_config.grid_properties
# key is 'internal' or 'whole', and _loop_type is either
# 'inner' or 'outer'. The four possible combinations are
# defined in the config file:
start_format = props["go_grid_{0}_{1}_start"
.format(key, self._loop_type)].fortran
start = start_format.format(self.field_name)
# TODO 363 - update once the PSyIR supports derived types
return Literal(start, INTEGER_TYPE, self)
def node_str(self, colour=True):
''' Creates a text description of this node with (optional) control
codes to generate coloured output in a terminal that supports it.
:param bool colour: whether or not to include colour control codes.
:returns: description of this node, possibly coloured.
:rtype: str
'''
# Generate the upper and lower loop bounds
self.start_expr = self._lower_bound()
self.stop_expr = self._upper_bound()
return super(GOLoop, self).node_str(colour)
def __str__(self):
''' Returns a string describing this Loop object '''
# Generate the upper and lower loop bounds
self.start_expr = self._lower_bound()
self.stop_expr = self._upper_bound()
return super(GOLoop, self).__str__()
def gen_code(self, parent):
''' Create the f2pygen AST for this loop (and update the PSyIR
representing the loop bounds if necessary).
:param parent: the node in the f2pygen AST to which to add content.
:type parent: :py:class:`psyclone.f2pygen.SubroutineGen`
:raises GenerationError: if we can't find an enclosing Schedule.
:raises GenerationError: if this loop does not enclose a Kernel.
:raises GenerationError: if constant loop bounds are enabled but are \
not supported for the current grid offset.
:raises GenerationError: if the kernels within this loop expect \
different different grid offsets.
'''
# Our schedule holds the names to use for the loop bounds.
# Climb up the tree looking for our enclosing GOInvokeSchedule
schedule = self.ancestor(GOInvokeSchedule)
if schedule is None or not isinstance(schedule, GOInvokeSchedule):
raise GenerationError("Internal error: cannot find parent"
" GOInvokeSchedule for this Do loop")
# Walk down the tree looking for a kernel so that we can
# look-up what index-offset convention we are to use
go_kernels = self.walk(GOKern)
if not go_kernels:
raise GenerationError("Internal error: cannot find the "
"GOcean Kernel enclosed by this loop")
index_offset = go_kernels[0].index_offset
if schedule.const_loop_bounds and \
index_offset not in SUPPORTED_OFFSETS:
raise GenerationError("Constant bounds generation"
" not implemented for a grid offset "
"of {0}. Supported offsets are {1}".
format(index_offset,
SUPPORTED_OFFSETS))
# Check that all kernels enclosed by this loop expect the same
# grid offset
for kernel in go_kernels:
if kernel.index_offset != index_offset:
raise GenerationError("All Kernels must expect the same "
"grid offset but kernel {0} has offset "
"{1} which does not match {2}".
format(kernel.name,
kernel.index_offset,
index_offset))
# Generate the upper and lower loop bounds
self.start_expr = self._lower_bound()
self.stop_expr = self._upper_bound()
Loop.gen_code(self, parent)
# pylint: disable=too-few-public-methods
class GOBuiltInCallFactory():
''' A GOcean-specific built-in call factory. No built-ins
are supported in GOcean at the moment. '''
@staticmethod
def create():
''' Placeholder to create a GOocean-specific built-in call.
This will require us to create a doubly-nested loop and then create
the body of the particular built-in operation. '''
raise GenerationError(
"Built-ins are not supported for the GOcean 1.0 API")
# pylint: disable=too-few-public-methods
class GOKernCallFactory():
''' A GOcean-specific kernel-call factory. A standard kernel call in
GOcean consists of a doubly-nested loop (over i and j) and a call to
the user-supplied kernel routine. '''
@staticmethod
def create(call, parent=None):
''' Create a new instance of a call to a GO kernel. Includes the
looping structure as well as the call to the kernel itself. '''
outer_loop = GOLoop(parent=parent, loop_type="outer")
inner_loop = GOLoop(parent=outer_loop.loop_body, loop_type="inner")
outer_loop.loop_body.addchild(inner_loop)
gocall = GOKern()
gocall.load(call, parent=inner_loop.loop_body)
inner_loop.loop_body.addchild(gocall)
# determine inner and outer loops space information from the
# child kernel call. This is only picked up automatically (by
# the inner loop) if the kernel call is passed into the inner
# loop.
inner_loop.iteration_space = gocall.iterates_over
outer_loop.iteration_space = inner_loop.iteration_space
inner_loop.field_space = gocall.\
arguments.iteration_space_arg().function_space
outer_loop.field_space = inner_loop.field_space
inner_loop.field_name = gocall.\
arguments.iteration_space_arg().name
outer_loop.field_name = inner_loop.field_name
return outer_loop
class GOKern(CodedKern):
'''
Stores information about GOcean Kernels as specified by the Kernel
metadata. Uses this information to generate appropriate PSy layer
code for the Kernel instance. Specialises the gen_code method to
create the appropriate GOcean specific kernel call.
'''
def __init__(self):
''' Create an empty GOKern object. The object is given state via
the load method '''
# pylint: disable=super-init-not-called, non-parent-init-called
# Can't use super() as the parent class has mandatory arguments that
# in GOKern are initialized with the load() method.
Node.__init__(self)
if False: # pylint: disable=using-constant-test
self._arguments = GOKernelArguments(None, None) # for pyreverse
# Create those member variables required for testing and to keep
# pylint happy
self._name = ""
self._index_offset = ""
def reference_accesses(self, var_accesses):
'''Get all variable access information. All accesses are marked
according to the kernel metadata.
:param var_accesses: VariablesAccessInfo instance that stores the\
information about variable accesses.
:type var_accesses: \
:py:class:`psyclone.core.access_info.VariablesAccessInfo`
'''
# Grid properties are accessed using one of the fields. This stores
# the field used to avoid repeatedly determining the best field:
field_for_grid_property = None
for arg in self.arguments.args:
if arg.type == "grid_property":
if not field_for_grid_property:
field_for_grid_property = \
self._arguments.find_grid_access()
var_name = arg.dereference(field_for_grid_property.name)
else:
var_name = arg.name
if arg.is_scalar():
# The argument is only a variable if it is not a constant:
if not arg.is_literal:
var_accesses.add_access(var_name, arg.access, self)
else:
# In case of an array for now add an arbitrary array
# reference so it is properly recognised as an array access
var_accesses.add_access(var_name, arg.access, self, [1])
super(GOKern, self).reference_accesses(var_accesses)
var_accesses.next_location()
def load(self, call, parent=None):
'''
Populate the state of this GOKern object.
:param call: information on the way in which this kernel is called \
from the Algorithm layer.
:type call: :py:class:`psyclone.parse.algorithm.KernelCall`