-
Notifications
You must be signed in to change notification settings - Fork 1
/
grid_codegen_OCL.js
executable file
·4264 lines (2947 loc) · 136 KB
/
grid_codegen_OCL.js
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
/*
Copyright (c) 2014, Intel Corporation
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 Intel Corporation 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 OWNER 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.
*/
//----------------------------------------------------------------------------
//Purpose: Grid Language OpenCL Code Generation (work in progress)
//Author : Konstantinos Krommydas
//Started: November 11, 2014
//Updated: December 18, 2015
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// PART A: Global Variables.
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// This is used to define the target device (code generation paths are
// different for FPGA (and in the future specific optimizations will target
// each different type of device).
// Another option would be to generate code that would include all cases, and
// what would run would depend on user selection at run-time.
// TODO: Line 566 from grid_codegen.js (from auto-tuning code generation for
// the OpenCL case, depending on user's choice of platform). At that
// point substitute this variable on main code_generation function for
// OpenCL and delete this from here.
// OR: change the saveOCLstring() and pass parameter there accordingly.
var Device_type;
// If DataTran == 1, generate the general OpenCL code with data transfers
// using clEnqueueReadBuffer, etc.
// If DataTran == 0, generate the OpenCL code using SVM.
var DataTran;
var DevT = {
CPU: 1,
GPU: 2,
MIC: 3,
FPGA: 4,
}
// This saves the cl_mem pointers passed to host functions when needed.
// The reason we are saving this information is so that when building
// clSetKernelArgs() for passing arguments to parallel steps within a
// functions we know to pass the pointer as (void *) arg, instead of
// (void *) &arg, which would be the case for a non-pointer cl_mem var.
// Reinitialized per function.
var CLMEMSinFunc;
// Keeps track of functions called from step Used for renaming/
// identifying __device functions, for the case when functions
// are called from within the context of a __kernel.
var CalledFuncsFromStep;
// Holds ALL functions that have been called at least one
// from within a kernel.
var CalledFuncsFromKernels;
// Records prototypes of auxiliary device functions (inlined) in ocl file.
var DeviceAuxPrototypes;
// Variable to save the strings for all function prototypes.
var Func_prototypes;
// Used to save grid objects used in current function. Reinitialized per func.
var GridsInFuncOCL;
// Array of OCL_step_grids_info objects. Re-initialized per function.
var OCL_steps_dataTran;
var CL_Funcs; // TO save OpenCL kernels in .cl file
var Func_code_ser; // To save serial device code to be in .cl file
// OpenCL global variables, to be prepended in each OpenCL program's C file.
// They are used in all OpenCL-related functions.
// index_data: used to hold the information for start/step of each of the 3
// (max) global dimensions - used within the kernel to identify which
// array element to access (e.g., if row=grid(start:end0:step) in host
// side), then the global dimension will have ceil(end-start+1)/step)
// work-items, and accessing each in the kernel will be by
// row=start+get_global_id(0)*step.
var OCL_glob_vars = "cl_platform_id plat_id;\n" +
"cl_device_id dev_id;\n" +
"cl_context context;\n" +
"cl_command_queue commands;\n" +
"cl_kernel kernel_cl;\n" +
"cl_int error;\n" +
"cl_program program;\n" +
"int *index_data;\n";
// Sets up the OpenCL environment (device, queues, etc.)
// To be called from the main function of an OpenCL program's C file.
// TODO: Right now hardcoded device type (e.g., CPU/GPU/MIC...)
var OCL_setup_dev_code = "void setup_OCL_dev() {\n" + addIndentation(0) +
"error = clGetPlatformIDs(1, &plat_id, NULL);\n" + addIndentation(0) +
"assert(error == CL_SUCCESS);\n" + addIndentation(0) +
"error = clGetDeviceIDs(plat_id, __DEV_TYP__, 1, &dev_id, NULL);\n" +
addIndentation(0) +
"assert(error == CL_SUCCESS);\n" + addIndentation(0) +
"context = clCreateContext(NULL, 1, &dev_id, NULL, NULL, &error);\n" +
addIndentation(0) +
"assert(error == CL_SUCCESS);\n" + addIndentation(0) +
"commands = clCreateCommandQueue(context, dev_id, 0, &error);\n" +
addIndentation(0) +
"assert(error == CL_SUCCESS);\n" + addIndentation(0) +
"FILE* kernel_fp = fopen(\"ocl_kernels.cl\", \"r\");\n" +
addIndentation(0) +
"fseek(kernel_fp, 0, SEEK_END);\n" + addIndentation(0) +
"size_t kernel_size = (size_t)ftell(kernel_fp);\n" +
addIndentation(0) +
"rewind(kernel_fp);\n" + addIndentation(0) +
"__KERN_ALLOC__" +
addIndentation(0) +
"fread((void* )kernel_source, kernel_size, 1, kernel_fp);\n" +
addIndentation(0) +
"fclose(kernel_fp);\n" + addIndentation(0) +
"__CREATE_PROG__" +
addIndentation(0) +
"assert(error == CL_SUCCESS);\n" + addIndentation(0) +
"error = clBuildProgram(program, 1, &dev_id, NULL, NULL, NULL);\n" +
addIndentation(0) +
"if (error == CL_BUILD_PROGRAM_FAILURE) {\n" + addIndentation(1) +
"char *logTxt;\n" + addIndentation(1) +
"size_t logSize;\n" + addIndentation(1) +
"clGetProgramBuildInfo(program, dev_id, CL_PROGRAM_BUILD_LOG, 0," +
" NULL, &logSize);\n" + addIndentation(1) +
"logTxt = (char* )malloc(sizeof(char)*logSize);\n" +
addIndentation(1) +
"clGetProgramBuildInfo(program, dev_id, CL_PROGRAM_BUILD_LOG, " +
"logSize, (void* )logTxt, NULL);\n" + addIndentation(1) +
"fprintf(stderr, \"Build Error Log:\\n%s\", logTxt);\n" +
addIndentation(0) +
"}\n" + addIndentation(0) +
"assert(error == CL_SUCCESS);\n" +
"}\n\n";
var OCL_checkSVM = "int checkSVMAvailability (cl_device_id device) {\n" +
addIndentation(0) +
"cl_device_svm_capabilities caps;\n" + addIndentation(0) +
"int gran;\n" + addIndentation(0) +
"cl_int err = clGetDeviceInfo(device, CL_DEVICE_SVM_CAPABILITIES, " +
"sizeof(cl_device_svm_capabilities), &caps, 0);\n" +
addIndentation(0) +
"gran = (err == CL_SUCCESS && (caps & " +
"CL_DEVICE_SVM_FINE_GRAIN_BUFFER));\n" + addIndentation(0) +
"if (gran == 1) return 1;\n" + addIndentation(0) +
"gran = (err == CL_SUCCESS && (caps & " +
"CL_DEVICE_SVM_COARSE_GRAIN_BUFFER));\n" + addIndentation(0) +
"if (gran == 1) return 2;\n" + addIndentation(0) +
"return 0;\n}\n\n";
var OCL_alignedMem = "#define AOCL_ALIGNMENT 1024\n" +
"void *alignedMalloc(size_t size) {\n" + addIndentation(0) +
"void *result = NULL;\n" + addIndentation(0) +
"posix_memalign (&result, AOCL_ALIGNMENT, size);\n" +
addIndentation(0) +
"return result;\n}\n\n" +
"void alignedFree(void *ptr) {\n" + addIndentation(0) +
"free(ptr);\n}\n\n";
// Finalizes OpenCL environment.
// To be called at the end of main function of OpenCL program's C file.
var OCL_finalize_code = "void finalize_OCL_dev() {\n" +
addIndentation(0) +
"clReleaseKernel(kernel_cl);\n" +
addIndentation(0) +
"clReleaseProgram(program);\n" +
addIndentation(0) +
"clReleaseCommandQueue(commands);\n" +
addIndentation(0)+
"clReleaseContext(context);\n" +
"}\n\n";
var SVM_util_code = "#define N 40\n\n" +
"//Contains the level of SVM support on device\n" +
"//0=no SVM, 1=coarse-grained buffer, 2=fine-grained buffer, " +
"3=fine-grained system\n" +
"int SVM_Support;\n\n" +
"//Marks next available entry on AddressInfo/MapInfo arrays\n" +
"//Initialized in Main on program start\n" +
"int NextAvail;\n\n" +
"//Contains address information for SVM pointers\n" +
"void* AddressInfo[N];\n\n" +
"//Contains info about whether a given SVM pointer\n" +
"//is mapped on the host side\n" +
"int MapInfo[N];\n\n" +
"void addNewAddress(void* address) {\n\n" + addIndentation(0) +
"//Set address\n" + addIndentation(0) +
"AddressInfo[NextAvail] = address;\n" + addIndentation(0) +
"//Initialize MapInfo[] to zero\n" + addIndentation(0) +
"MapInfo[NextAvail++] = 0;\n\n" +
"}\n\n" +
"int findAddress(void* address) {\n\n" + addIndentation(0) +
"int i;\n\n" + addIndentation(0) +
"for (i = 0; i < N; i++) {\n" + addIndentation(1) +
"if (AddressInfo[i] == address)\n" + addIndentation(1) +
"return i;\n" + addIndentation(0) +
"}\n\n" + addIndentation(0) +
"return -1; //Should not happen\n\n" +
"}\n\n" +
"int checkMapped(void* address) {\n\n" + addIndentation(0) +
"return MapInfo[findAddress(address)];\n\n" +
"}\n\n" +
"void SVM_Map(void * address, int size) {\n\n" + addIndentation(0) +
"if (!checkMapped(address)) {\n" + addIndentation(1) +
"clEnqueueSVMMap(commands, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, " +
"address, size, 0, 0, 0);\n" +
addIndentation(1) +
"MapInfo[findAddress((void*)address)] = 1;\n" + addIndentation(0) +
"}\n\n" +
"}\n\n" +
"void SVM_Unmap(void * address) {\n\n" + addIndentation(0) +
"if (checkMapped(address)) {\n" + addIndentation(1) +
"clEnqueueSVMUnmap(commands, address, 0, 0, 0);\n" +
addIndentation(1) +
"MapInfo[findAddress((void*)address)] = 0;\n" + addIndentation(0) +
"}\n\n" +
"}\n\n";
var DataTran_util_code = "#define N 40\n\n" +
"//Marks next available entry on AddressInfo/MapInfo arrays\n" +
"//Initialized in Main on program start\n" +
"int NextAvail;\n\n" +
"//Contains address information for malloc'd pointers\n" +
"void* AddressInfo[N];\n\n" +
"//Contains address information for cl_mem addresses\n" +
"cl_mem* ClMemAddressInfo[N];\n\n" +
"//Contains info about whether a given SVM pointer\n" +
"//is mapped on the host side\n" +
"int MapInfo[N];\n\n" +
"void addNewAddress(void* address, cl_mem* clMemAddress) {\n\n" +
addIndentation(0) +
"//Set address\n" + addIndentation(0) +
"AddressInfo[NextAvail] = address;\n" + addIndentation(0) +
"ClMemAddressInfo[NextAvail] = clMemAddress;\n" + addIndentation(0) +
"//Initialize MapInfo[] to zero\n" + addIndentation(0) +
"MapInfo[NextAvail++] = 0;\n\n" +
"}\n\n" +
"int findAddress(void* address) {\n\n" + addIndentation(0) +
"int i;\n\n" + addIndentation(0) +
"for (i = 0; i < N; i++) {\n" + addIndentation(1) +
"if (AddressInfo[i] == address)\n" + addIndentation(1) +
"return i;\n" + addIndentation(0) +
"}\n\n" + addIndentation(0) +
"return -1; //Should not happen\n\n" +
"}\n\n" +
"int checkMapped(void* address) {\n\n" + addIndentation(0) +
"return MapInfo[findAddress(address)];\n\n" +
"}\n\n" +
"void d2h_tran(void * address, int size) {\n\n" + addIndentation(0) +
"if (!checkMapped(address)) {\n" + addIndentation(1) +
"cl_mem* tmp_buff = ClMemAddressInfo[findAddress((void*)address)];\n" +
addIndentation(1) +
"if (checkMapped(address) != -1)\n" + addIndentation(2) +
"clEnqueueReadBuffer(commands, *tmp_buff, CL_TRUE, 0, size, " +
"address, 0, NULL, NULL);\n" + addIndentation(1) +
"MapInfo[findAddress((void*)address)] = 1;\n" + addIndentation(0) +
"}\n\n" +
"}\n\n" +
"void h2d_tran(void * address, int size) {\n\n" + addIndentation(0) +
"if (checkMapped(address)) {\n" + addIndentation(1) +
"cl_mem* tmp_buff = ClMemAddressInfo[findAddress((void*)address)];\n" +
addIndentation(1) +
"clEnqueueWriteBuffer(commands, *tmp_buff, CL_TRUE, 0, size, " +
"address, 0, NULL, NULL);\n" + addIndentation(1) +
"MapInfo[findAddress((void*)address)] = 0;\n" + addIndentation(0) +
"}\n\n" +
"}\n\n";
//----------------------------------------------------------------------------
// Contains information for a grid for a *single* step needed so that we know
// how to construct the H2D copies (clEnqueueWriteBuffer) and D2H copies
// (clEnqueueReadBuffer) before and after a kernel call. The latter is needed
// only when isWritten is 1 for a grid.
// TODO: Superseded by new method.
// Info used for constructing setting kernel arguments (depending on whether
// they are cl_mem objects -true for nonscalar grids- in which case we must
// call the setKernelArgs OCL function with sizeof(cl_mem) or if scalar with
// sizeof(TYPE).
// CAUTION: The code for isNonScalar starts from tmp_length+1 and
// goes down to 2 for STRUCTS. This is done so that in setting the kernel
// arguments (getOCLargCalls()) we know when to add dynamic size - last
// (IF dynamic size is used for dimX's). General simple non-scalar
// grids have isNonScalar == 1 and scalar ones have isNonScalar == 0.
//----------------------------------------------------------------------------
function OCL_grid_info(gO, name, size) {
this.gO = gO;
this.name = name; // Does not contain 'ft_' prefix.
this.size = size;
this.isWritten = 0;
this.isNonScalar = 0;
}
//----------------------------------------------------------------------------
// Object type that will form an array for all steps of a function.
// Info will be used to identify whether H2D/D2H data transfers are needed
// (essentially it keeps track of the validity of data across host/device).
// gridsInStep is an *ASSOCIATIVE* array: indexed by the NAME of the (non-
// scalar) grid and it's value is 0:not written in step, 1:written in step.
//----------------------------------------------------------------------------
function OCL_step_grids_info() {
this.typeOfStep; // 0=Host(serial), 1=Device(parallel)
this.gridsInStep = new Array();
this.gridsSizes = new Array();
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// PART B: OpenCL Code Generation Workflow Core Code
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Save the OpenCL/C string generated for the program
// parallel: save parallel version if 1. Serial if 0.
// show: To be passed in showOCLstr to alert(code) if 1.
// Else, just to return the code string to caller.
//----------------------------------------------------------------------------
function saveOCLstr(parallel, show) {
// TODO: In saveOCL() we'll pass the Device_type as given in the
// auto-tuning menu. For now, we set manually for testing.
Device_type = DevT.FPGA;
// TODO: Choose this from the auto-tuning menu as an option.
DataTran = 1;
// Get the JSON string
//Regenerate code every time, otherwise may save old one if updated
TypesAllFuncs = new Array();
NamesAllFuncs = new Array();
var str = encodeURIComponent(showOCLstr(1, parallel, show));
//TODO: Is SoA by default (hence '1' as first argument)
download2SaveFortran(str, CurProgObj.fileName);
str = "";
for (var i = 1; i < DeviceAuxPrototypes.length; i++) {
str += DeviceAuxPrototypes[i] + "\n";
}
str += "\n";
// (start from 3 - i.e., AFTER main function)
for (var i = 3; i < Func_code_ser.length; i++) {
var t_func = CurModObj.allFuncs[i].funcCallExpr.str;
if (CalledFuncsFromKernels.indexOf(t_func) != -1)
str += "inline " + Func_code_ser[i];
}
for (var i = 0; i < CL_Funcs.length; i++) {
str += CL_Funcs[i] + "\n\n";
}
str = encodeURIComponent(str);
download2SaveFortran(str, "ocl_kernels.cl");
// Adding helper functions
str = OCL_glob_vars;
if (DataTran == 1) str += "cl_mem index_data_dev;\n";
str += "\n";
if (Device_type != DevT.FPGA) {
var tmp = OCL_setup_dev_code.replace("__CREATE_PROG__", "program = " +
"clCreateProgramWithSource(context, 1, (const char **)" +
"&kernel_source, &kernel_size, &error);\n");
tmp = tmp.replace("__KERN_ALLOC__", "char* " +
"kernel_source = (char *)malloc(sizeof(char)*kernel_size);\n");
str += tmp.replace("__DEV_TYP__", "CL_DEVICE_TYPE_GPU");
} else {
var tmp = OCL_setup_dev_code.replace("__CREATE_PROG__", "program = " +
"clCreateProgramWithBinary(context, 1, &dev_id, " +
"&kernel_size, (const unsigned char **)&kernel_source, " +
"NULL, " +
"&error);\n");
tmp = tmp.replace("ocl_kernels.cl", "ocl_kernels.aocx");
tmp = tmp.replace("__KERN_ALLOC__", "unsigned char* " +
"kernel_source = (unsigned char *)malloc(sizeof(unsigned " +
"char)*kernel_size);\n");
str += tmp.replace("__DEV_TYP__", "CL_DEVICE_TYPE_ACCELERATOR");
}
str += OCL_finalize_code;
if (DataTran == 0) {
if (Device_type != DevT.FPGA) {
str += OCL_checkSVM + SVM_util_code;
} else {
str += OCL_alignedMem;
}
} else {
str += DataTran_util_code;
}
str = encodeURIComponent(str);
download2SaveFortran(str, "ocl_util.h");
}
//----------------------------------------------------------------------------
// Show the OpenCL/C string generated for the program
// strOfArr: Use structures of arrays (SoA) if 1. Arrays of structures (AoS)
// if 0.
// show: Show code in JS (using alert) if 1. Just return code string if 0.
//----------------------------------------------------------------------------
function showOCLstr(strOfArr, parallel, show) {
Soa = strOfArr;
Soa = 1; //TODO: CAUTION. For OpenCL we cannot pass structs.
ShowParallel = parallel;
// If parallel code generation selected first we need to analyze.
if (ShowParallel) {
var mO = CurModObj; // TODO: Generalize for multiple modules.
var fO = mO.allFuncs[getFuncIdByName(mO, "Main")];
analyzeParallelismAll(fO, 0);
}
TypesAllFuncs = new Array();
NamesAllFuncs = new Array();
CL_Funcs = new Array(); // Save OpenCL code for .cl file.
Func_code_ser = new Array(); // Contains SERIAL (for __device)
CalledFuncsFromKernels = new Array();
DeviceAuxPrototypes = new Array();
var code = getOCLstr();
if (show) {
alert(code);
} else {
return code;
}
}
//----------------------------------------------------------------------------
// Returns OpenCL/C for the current step in current funtion that the
// user is currently working on
//----------------------------------------------------------------------------
function getOCLstr() {
var mO = CurModObj;
// First, generate code for all functions, including 'main()'
// Will be elements of the func_code array.
var func_code = new Array(); // Used to store code for EACH function.
// Variable to store all include statements needed.
var inclStmts = "#include <stdio.h>\n" +
"#include <stdlib.h>\n" +
"#include <assert.h>\n";
if (ShowParallel) {
if (Device_type != DevT.FPGA) {
inclStmts += "#include <CL/cl.h>\n";
} else {
inclStmts += "#include \"CL/opencl.h\"\n";
}
inclStmts += "#include \"ocl_util.h\"\n";
}
TypeStr = ""; // Used to store TYPEs (i.e., structures).
Func_prototypes = new Array();
// A single string that contains all function code.
var func_code_all = "";
// TODO: Be careful with global variables. If not initialized every time,
// they'll hold the value, until exiting program!
GID_function = 0;
for (var f = mO.FuncStartID; f < mO.allFuncs.length; f++) {
var func_code_tmp = getOCLstr4Func(mO, f);
Func_code_ser[f] = func_code_tmp[0].replace(/^.*?#pragma omp.*\n?/mg,
"");
func_code[f] = func_code_tmp[1];
// Note: Be careful where TypesAllFuncs starts != mO.allFuncs[start].
func_code_all += TypesAllFuncs[f - mO.FuncStartID] + " " +
func_code[f];
}
// Code generation generates memory allocations with clSVMAlloc().
// For the FPGA case, where fine-grained system SVM is supported
// we don't need clSVMAlloc(), but *aligned* regular memory allocation.
// So, we substitute all instances accordingly.
// Last, we need to substitute clSetKernelArgSVMPointer() to
// clSetKernelArgSVMPointerAltera()
if (Device_type == DevT.FPGA && DataTran == 0) {
func_code_all = func_code_all.replace(/clSetKernelArgSVMPointer/g,
"clSetKernelArgSVMPointerAltera");
// Also, replace clSVMAlloc() with alignedMalloc()
// clSVMAlloc(context, CL_MEM_READ_WRITE, <SIZE>, 0);\n
// alignedMalloc(<SIZE>);\n
func_code_all = func_code_all.replace(
/clSVMAlloc\(context, CL\_MEM\_READ\_WRITE, (.+?), 0\)/g,
"alignedMalloc($1)");
// Also, replace clSVMFree() with alignedFree().
func_code_all = func_code_all.replace(
/clSVMFree\(context, (.+)\)/g,
"alignedFree($1)");
}
// Generate code for main method.
var main_call = "int main(int argc, char *argv[]) {\n";
//TODO:C: Use startup arguments grid as *argv[]. Add more flexibility.
var t_mainFunc = CurModObj.allFuncs[DefMainFuncInd];
main_call += addIndentation(0) + "char *" +
var2OCL(t_mainFunc.allGrids[1].caption)+"[4];\n";
main_call += addIndentation(0) + "int " +
var2OCL(t_mainFunc.allGrids[0].caption) + ";\n";
// If generating parallel implementation, setting nested parallelism off
// by default.
// TODO: This may be an option for the auto-tuner.
// If no parallel step in program, no need.
if (ShowParallel) {
main_call += addIndentation(0) + "setup_OCL_dev();\n";
}
if (DataTran == 0) {
main_call += addIndentation(0) + "index_data = (int *)clSVMAlloc(" +
"context, CL_MEM_READ_WRITE, sizeof(int)*9, 0);\n";
} else {
main_call += addIndentation(0) + "index_data = (int *)malloc(" +
"sizeof(int)*9);\n";
main_call += addIndentation(0) + "index_data_dev = clCreateBuffer(" +
"context, CL_MEM_READ_WRITE, " +
"sizeof(int)*9, NULL, &error);\n";
}
// If device type is not FPGA (i.e., is CPU/GPU/MIC, then query the
// device for degree of SVM_SUPPORT.
// NOTE: We only support OpenCL on devices that support OpenCL 2.0
if (Device_type != DevT.FPGA && DataTran == 0) {
main_call += addIndentation(0) + "SVM_Support = " +
"checkSVMAvailability(dev_id);\n";
main_call += addIndentation(0) + "if (SVM_Support==2) {\n" +
addIndentation(1) + "addNewAddress(index_data);\n" +
addIndentation(0) + "}\n";
} else if (DataTran == 1) {
main_call += addIndentation(0) +
"addNewAddress(index_data, &index_data_dev);\n";
}
// Else, if FPGA, do nothing (any required changes are done cumulatively
// at the end of code generation.
main_call += addIndentation(0) +
var2OCL(CurModObj.allFuncs[DefMainFuncInd].allGrids[0].caption) +
" = " + var2OCL(DefMainFuncName) +
"(" +
var2OCL(CurModObj.allFuncs[DefMainFuncInd].allGrids[1].caption) +
");\n";
main_call += addIndentation(0) + "finalize_OCL_dev();\n";
if (DataTran == 0) {
main_call += addIndentation(0) + "clSVMFree(context, index_data);\n}\n";
} else {
main_call += addIndentation(0) + "free(index_data);\n";
main_call += addIndentation(0) +
"clReleaseMemObject(index_data_dev);\n}\n";
}
if (Device_type == DevT.FPGA) {
main_call = main_call.replace(
/clSVMAlloc\(context, CL\_MEM\_READ\_WRITE, (.+?), 0\)/g,
"alignedMalloc($1)");
main_call = main_call.replace(
/clSVMFree\(context, (.+)\)/g,
"alignedFree($1)");
}
// Check if any math functions have been called in the program, so as to
// add the math library in the include statements.
if (InclMath) {
inclStmts += "#include <math.h>\n\n";
} else {
inclStmts += "\n";
}
// Construct function prototypes
var func_protos = "";
for (var i = mO.FuncStartID; i < mO.allFuncs.length; i++) {
func_protos += TypesAllFuncs[i - mO.FuncStartID] + " " +
Func_prototypes[i - mO.FuncStartID];
//TODO: What about serial/parallel version if both abailable?
}
func_protos += "\n\n";
// Final generated code will contain the TYPEs code, the library functions
// code (e.g., for read/write CSV), the functions' code (that contains all
// functions, including ft_Main), and the PROGRAM "int main" that calls
// Main function and subsequently any other functions.
var returnedCode = inclStmts + TypeStr + func_protos +
func_code_all + "\n" + main_call;
returnedCode = returnedCode.replace(/UNIQUEIND/g, "int"); //TT
return returnedCode;
}
//----------------------------------------------------------------------------
// Returns OpenCL/C code for a single function
//----------------------------------------------------------------------------
function getOCLstr4Func(mO, f) {
var fO = mO.allFuncs[f];
// This is the GID_function id of current function corresponding to
// TypesAllFuncs and NamesAllFuncs.
var gID_f = 0;
// Initialize current step numbering for current function to zero.
CurStep = 0;
// Initialize GridsInFuncOCL.
GridsInFuncOCL = new Array();
Loop_var_per_dim = new Array();
Index_end_per_dim = new Array();
OCL_steps_dataTran = new Array();
CLMEMSinFunc = new Array();
if (var2OCL(fO.funcCallExpr.str) == "ft_Main") {
// Add an INTEGER as main's return value (TypesAllFuncs[0])
TypesAllFuncs.push("int");
//gID_f = 1; //NEXT one
GID_function = 1; //NEXT one
} else {
for (var i = 0; i < TypesAllFuncs.length; i++) {
if (NamesAllFuncs[i] == var2OCL(fO.funcCallExpr.str)) {
//alert("FOUND in i=" + i + "Callee="+NamesAllFuncs[i] +
//"type="+TypesAllFuncs[i]);
//TODO: (check) Add a dummy type entry for function
//return value. Will be updated later
//(TypesAllFuncs[gID])
TypesAllFuncs.push(TypesAllFuncs[i]);
gID_f = i; //Set, so it can be used to assign the
//required type to temp return value.
}
}
}
// Used for recording functions once (and then recording
// their types and names to be used in other places of
// code generation.
// Initialize to blank at the start of each new function
Func_decl = "";
// See their declaration (global scope) for details on below:
Row_col_decl = "";
Index_end_decl = "";
Grids_new_decl = "";
TitleDefs_decl = "";
AllocFreePerFunc = "";
// Create function header (function type plus name). Arguments to be
// added in subsequent steps.
// TODO:C: Commented out.
var func_name = var2OCL(fO.funcCallExpr.str);
var func_head = "(";
// Head part for OCL device inline (auxiliary functions (where pointers
// will be __global).
var func_head_OCL_dev = "(";
// In func_vars we declare the type and name of any grids that were passed
// as parameters in the current function for which we are generating code.
var func_vars = "";
var func_val_init = "";
var arr_dynValues = new Array();
// Add argument list to function header. To do that, go through ALL grids
// in the function and add those who are incoming args.
for (var g = 0; g < fO.allGrids.length; g++) {
var gO = fO.allGrids[g];
// TODO: If a grid with specific indices e.g. array[3][1] treat as
// passed by value!
if (gO.inArgNum >= 0) { // This grid is an incoming arg.
if (gO.numDims > 1 && gO.typesInDim != -1) {
if (gO.inArgNum > 0) {
func_head += ", "; // arg separator
func_head_OCL_dev += ", "; // arg separator
}
if (!Soa) func_head += getDataTypeString_OCL(gO) + " *";
//TODO: CAUTION: This is for the case of TYPE variable
// passed using its name (i.e., no specific element).
func_head += expandStruct(gO, 1); //"typvar_" + gO.caption;
func_head_OCL_dev += expandStruct(gO, 2);
} else {
if (gO.numDims >= 1) {
if (gO.inArgNum > 0) {
func_head += ", "; // arg separator
func_head_OCL_dev += ", "; // arg separator
}
// If called function contains at least a parallel step, we
// will need a cl_mem pointer that will be used if need be.
// TODO: Can be optimized in case this variable is NOT used
// in the parallel step of called function (i.e., not pass).
if (DataTran == 1) {
if (funcContainsParStep(mO,f) &&
func_name != "ft_Main") {
func_head += "cl_mem *" + var2OCL(gO.caption) +
"_dev, ";
CLMEMSinFunc.push(gO.caption);
}
}
func_head += getDataTypeString_OCL(gO) + " ";
func_head += "*" + var2OCL(gO.caption);
func_head_OCL_dev += "__global " +
getDataTypeString_OCL(gO) +
"* " + var2OCL(gO.caption);
// Grid caption as arg name
} else {
// Ensure has not been implicitly declared via a
// dynamically sized non-scalar grid (see below).
var regex = new RegExp(var2OCL(gO.caption + "[, )]"));
if (func_head.search(regex) == -1) {
if (gO.inArgNum > 0) {
func_head += ", "; // arg separator
func_head_OCL_dev += ", "; // arg separator
}
func_head += getDataTypeString_OCL(gO) + " " +
var2OCL(gO.caption);
func_head_OCL_dev += getDataTypeString_OCL(gO) + " " +
var2OCL(gO.caption);
}
// else do not declare at all.
}
}
if (gO.numDims >=1) {
// Given we dynamically allocate all non-scalar grids, we
// need to pass dimensions that are variables (the constant
// dimensions are auto-generated as numbers in resulting
// code). They are also needed to be used in loops (in
// Fortran we could get this info using SIZE(), but in C
// there is nothing similar).
var dynVals = ", ";
for (var i = 0; i < gO.dimActSize.length; i++) {
var t_sz = gO.dimDynSize[i];
if (t_sz != null) {
// The second check takes care of scalars that may have
// been passed as parameters (i.e., explicitly), while
// the first is for implicit passing (scalar grids used
// for dynamic size of non-scalar grids).
if(arr_dynValues.indexOf(var2OCL(t_sz))==-1 &&
func_head.indexOf(var2OCL(t_sz))==-1) {
arr_dynValues.push(var2OCL(t_sz));
dynVals += "int "+var2OCL(t_sz) + ",";
}
}
}
if (dynVals != ", ") {
func_head += dynVals.replace(/,+$/, "");
func_head_OCL_dev += dynVals.replace(/,+$/, "");
}
} else {
// For scalar-grids, we have to copy the src value into a temp
// variable called fun_<src_var_name>.
// TODO: Can fuse with earlier similar loop for function
// header.
func_vars += addIndentation(0) + getDataTypeString_OCL(gO,
null) + " fun_" + gO.caption + ";\n";
func_val_init += addIndentation(0) + "fun_" + gO.caption +
" = " + var2OCL(gO.caption) + ";\n";
}
}
}
func_head += ")";
Func_prototypes.push(func_name + func_head + ";\n");
func_head += " {\n";
var func_ret_type = getDataTypeString_OCL(fO.allGrids[0], null);
// TODO: Only add if called from a __kernel function in the .cl file.
DeviceAuxPrototypes.push(func_ret_type + " " + func_name + "_device" +
func_head_OCL_dev + ");");
func_head_OCL_dev += ") {\n";
// At this point we have completed in func_head the function header
// that contains the type of function, the function name, and its
// arguments contained in parentheses.
// Used for declaration of the ret value declaration within the func.
// This is always in position 0 in fO.allGrids[].
func_vars += addIndentation(0) + getDataTypeString_OCL(fO.allGrids[0],
null) + " " + var2OCL(fO.allGrids[0].caption) + ";\n";
// STEP: Code for each step in the function.
// Two positions ([0] is serial for __device, [1] is for parallel).
var step_code = new Array();
step_code[0] = "";
step_code[1] = "";