forked from kaigai/pg_strom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpupreagg.c
More file actions
4773 lines (4369 loc) · 130 KB
/
gpupreagg.c
File metadata and controls
4773 lines (4369 loc) · 130 KB
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
/*
* gpupreagg.c
*
* Aggregate Pre-processing with GPU acceleration
* ----
* Copyright 2011-2014 (C) KaiGai Kohei <kaigai@kaigai.gr.jp>
* Copyright 2014 (C) The PG-Strom Development Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "postgres.h"
#include "access/nbtree.h"
#include "access/sysattr.h"
#include "catalog/namespace.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/nodeAgg.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_func.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/numeric.h"
#include "utils/syscache.h"
#include <math.h>
#include "pg_strom.h"
#include "opencl_gpupreagg.h"
static CustomPlanMethods gpupreagg_plan_methods;
static bool enable_gpupreagg;
static bool debug_force_gpupreagg;
typedef struct
{
CustomPlan cplan;
int numCols; /* number of grouping columns */
AttrNumber *grpColIdx; /* their indexes in the target list */
bool outer_bulkload;
double num_groups; /* estimated number of groups */
List *outer_quals; /* device quals pulled-up */
const char *kern_source;
int extra_flags;
List *used_params; /* referenced Const/Param */
Bitmapset *outer_attrefs; /* bitmap of referenced outer attributes */
Bitmapset *tlist_attrefs; /* bitmap of referenced tlist attributes */
bool has_numeric; /* if true, result contains numeric val */
} GpuPreAggPlan;
typedef struct
{
CustomPlanState cps;
TupleDesc scan_desc;
TupleTableSlot *scan_slot;
ProjectionInfo *bulk_proj;
TupleTableSlot *bulk_slot;
double num_groups; /* estimated number of groups */
double ntups_per_page; /* average number of tuples per page */
List *outer_quals;
bool outer_done;
bool outer_bulkload;
TupleTableSlot *outer_overflow;
pgstrom_queue *mqueue;
Datum dprog_key;
kern_parambuf *kparams;
bool needs_grouping;
bool has_numeric;
pgstrom_gpupreagg *curr_chunk;
cl_uint curr_index;
bool curr_recheck;
cl_uint num_rechecks;
cl_uint num_running;
dlist_head ready_chunks;
pgstrom_perfmon pfm; /* performance counter */
} GpuPreAggState;
/* declaration of static functions */
static void clserv_process_gpupreagg(pgstrom_message *message);
/*
* Arguments of alternative functions.
*/
#define ALTFUNC_EXPR_NROWS 101 /* NROWS(X) */
#define ALTFUNC_EXPR_PMIN 102 /* PMIN(X) */
#define ALTFUNC_EXPR_PMAX 103 /* PMAX(X) */
#define ALTFUNC_EXPR_PSUM 104 /* PSUM(X) */
#define ALTFUNC_EXPR_PSUM_X2 105 /* PSUM_X2(X) = PSUM(X^2) */
#define ALTFUNC_EXPR_PCOV_X 106 /* PCOV_X(X,Y) */
#define ALTFUNC_EXPR_PCOV_Y 107 /* PCOV_Y(X,Y) */
#define ALTFUNC_EXPR_PCOV_X2 108 /* PCOV_X2(X,Y) */
#define ALTFUNC_EXPR_PCOV_Y2 109 /* PCOV_Y2(X,Y) */
#define ALTFUNC_EXPR_PCOV_XY 110 /* PCOV_XY(X,Y) */
/*
* List of supported aggregate functions
*/
typedef struct {
/* aggregate function can be preprocessed */
const char *aggfn_name;
int aggfn_nargs;
Oid aggfn_argtypes[4];
/* alternative function to generate same result.
* prefix indicates the schema that stores the alternative functions
* c: pg_catalog ... the system default
* s: pgstrom ... PG-Strom's special ones
*/
const char *altfn_name;
int altfn_nargs;
Oid altfn_argtypes[8];
int altfn_argexprs[8];
int altfn_flags;
} aggfunc_catalog_t;
static aggfunc_catalog_t aggfunc_catalog[] = {
/* AVG(X) = EX_AVG(NROWS(), PSUM(X)) */
{ "avg", 1, {INT2OID},
"s:avg", 2, {INT4OID, INT8OID},
{ALTFUNC_EXPR_NROWS, ALTFUNC_EXPR_PSUM}, 0
},
{ "avg", 1, {INT4OID},
"s:avg", 2, {INT4OID, INT8OID},
{ALTFUNC_EXPR_NROWS, ALTFUNC_EXPR_PSUM}, 0
},
{ "avg", 1, {INT8OID},
"s:avg_numeric", 2, {INT4OID, INT8OID},
{ALTFUNC_EXPR_NROWS, ALTFUNC_EXPR_PSUM}, 0
},
{ "avg", 1, {FLOAT4OID},
"s:avg", 2, {INT4OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS, ALTFUNC_EXPR_PSUM}, 0
},
{ "avg", 1, {FLOAT8OID},
"s:avg", 2, {INT4OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS, ALTFUNC_EXPR_PSUM}, 0
},
{ "avg", 1, {NUMERICOID},
"s:avg", 2, {INT4OID, NUMERICOID},
{ALTFUNC_EXPR_NROWS, ALTFUNC_EXPR_PSUM}, DEVFUNC_NEEDS_NUMERIC
},
/* COUNT(*) = SUM(NROWS(*|X)) */
{ "count", 0, {},
"c:sum", 1, {INT4OID},
{ALTFUNC_EXPR_NROWS}, 0},
{ "count", 1, {ANYOID},
"c:sum", 1, {INT4OID},
{ALTFUNC_EXPR_NROWS}, 0},
/* MAX(X) = MAX(PMAX(X)) */
{ "max", 1, {INT2OID}, "c:max", 1, {INT2OID}, {ALTFUNC_EXPR_PMAX}, 0},
{ "max", 1, {INT4OID}, "c:max", 1, {INT4OID}, {ALTFUNC_EXPR_PMAX}, 0},
{ "max", 1, {INT8OID}, "c:max", 1, {INT8OID}, {ALTFUNC_EXPR_PMAX}, 0},
{ "max", 1, {FLOAT4OID}, "c:max", 1, {FLOAT4OID}, {ALTFUNC_EXPR_PMAX}, 0},
{ "max", 1, {FLOAT8OID}, "c:max", 1, {FLOAT8OID}, {ALTFUNC_EXPR_PMAX}, 0},
{ "max", 1, {NUMERICOID},"c:max", 1, {NUMERICOID},
{ALTFUNC_EXPR_PMAX}, DEVFUNC_NEEDS_NUMERIC},
/* MIX(X) = MIN(PMIN(X)) */
{ "min", 1, {INT2OID}, "c:min", 1, {INT2OID}, {ALTFUNC_EXPR_PMIN}, 0},
{ "min", 1, {INT4OID}, "c:min", 1, {INT4OID}, {ALTFUNC_EXPR_PMIN}, 0},
{ "min", 1, {INT8OID}, "c:min", 1, {INT8OID}, {ALTFUNC_EXPR_PMIN}, 0},
{ "min", 1, {FLOAT4OID}, "c:min", 1, {FLOAT4OID}, {ALTFUNC_EXPR_PMIN}, 0},
{ "min", 1, {FLOAT8OID}, "c:min", 1, {FLOAT8OID}, {ALTFUNC_EXPR_PMIN}, 0},
{ "min", 1, {NUMERICOID},"c:min", 1, {NUMERICOID},
{ALTFUNC_EXPR_PMIN}, DEVFUNC_NEEDS_NUMERIC},
/* SUM(X) = SUM(PSUM(X)) */
{ "sum", 1, {INT2OID}, "s:sum", 1, {INT8OID}, {ALTFUNC_EXPR_PSUM}, 0},
{ "sum", 1, {INT4OID}, "s:sum", 1, {INT8OID}, {ALTFUNC_EXPR_PSUM}, 0},
{ "sum", 1, {FLOAT4OID}, "c:sum", 1, {FLOAT4OID}, {ALTFUNC_EXPR_PSUM}, 0},
{ "sum", 1, {FLOAT8OID}, "c:sum", 1, {FLOAT8OID}, {ALTFUNC_EXPR_PSUM}, 0},
{ "sum", 1, {NUMERICOID},"c:sum", 1, {NUMERICOID},
{ALTFUNC_EXPR_PSUM}, DEVFUNC_NEEDS_NUMERIC},
/* STDDEV(X) = EX_STDDEV(NROWS(),PSUM(X),PSUM(X*X)) */
{ "stddev", 1, {FLOAT4OID},
"s:stddev", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "stddev", 1, {FLOAT8OID},
"s:stddev", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "stddev", 1, {NUMERICOID},
"s:stddev", 3, {INT4OID, NUMERICOID, NUMERICOID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, DEVFUNC_NEEDS_NUMERIC
},
{ "stddev_pop", 1, {FLOAT4OID},
"s:stddev_pop", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "stddev_pop", 1, {FLOAT8OID},
"s:stddev_pop", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "stddev_pop", 1, {NUMERICOID},
"s:stddev_pop", 3, {INT4OID, NUMERICOID, NUMERICOID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, DEVFUNC_NEEDS_NUMERIC
},
{ "stddev_samp", 1, {FLOAT4OID},
"s:stddev_samp", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "stddev_samp", 1, {FLOAT8OID},
"s:stddev_samp", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "stddev_samp", 1, {NUMERICOID},
"s:stddev_samp", 3, {INT4OID, NUMERICOID, NUMERICOID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, DEVFUNC_NEEDS_NUMERIC
},
/* VARIANCE(X) = PGSTROM.VARIANCE(NROWS(), PSUM(X),PSUM(X^2)) */
{ "variance", 1, {FLOAT4OID},
"s:variance", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "variance", 1, {FLOAT8OID},
"s:variance", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "variance", 1, {NUMERICOID},
"s:variance", 3, {INT4OID, NUMERICOID, NUMERICOID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, DEVFUNC_NEEDS_NUMERIC
},
{ "var_pop", 1, {FLOAT4OID},
"s:var_pop", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "var_pop", 1, {FLOAT8OID},
"s:var_pop", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "var_pop", 1, {NUMERICOID},
"s:var_pop", 3, {INT4OID, NUMERICOID, NUMERICOID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, DEVFUNC_NEEDS_NUMERIC
},
{ "var_samp", 1, {FLOAT4OID},
"s:var_samp", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "var_samp", 1, {FLOAT8OID},
"s:var_samp", 3, {INT4OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, 0
},
{ "var_samp", 1, {NUMERICOID},
"s:var_samp", 3, {INT4OID, NUMERICOID, NUMERICOID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PSUM,
ALTFUNC_EXPR_PSUM_X2}, DEVFUNC_NEEDS_NUMERIC
},
/*
* CORR(X,Y) = PGSTROM.CORR(NROWS(X,Y),
* PCOV_X(X,Y), PCOV_Y(X,Y)
* PCOV_X2(X,Y), PCOV_Y2(X,Y),
* PCOV_XY(X,Y))
*/
{ "corr", 2, {FLOAT8OID, FLOAT8OID},
"s:corr", 6,
{INT4OID, FLOAT8OID, FLOAT8OID, FLOAT8OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PCOV_X,
ALTFUNC_EXPR_PCOV_X2,
ALTFUNC_EXPR_PCOV_Y,
ALTFUNC_EXPR_PCOV_Y2,
ALTFUNC_EXPR_PCOV_XY}, 0},
{ "covar_pop", 2, {FLOAT8OID, FLOAT8OID},
"s:covar_pop", 6,
{INT4OID, FLOAT8OID, FLOAT8OID, FLOAT8OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PCOV_X,
ALTFUNC_EXPR_PCOV_X2,
ALTFUNC_EXPR_PCOV_Y,
ALTFUNC_EXPR_PCOV_Y2,
ALTFUNC_EXPR_PCOV_XY}, 0},
{ "covar_samp", 2, {FLOAT8OID, FLOAT8OID},
"s:covar_samp", 6,
{INT4OID, FLOAT8OID, FLOAT8OID, FLOAT8OID, FLOAT8OID, FLOAT8OID},
{ALTFUNC_EXPR_NROWS,
ALTFUNC_EXPR_PCOV_X,
ALTFUNC_EXPR_PCOV_X2,
ALTFUNC_EXPR_PCOV_Y,
ALTFUNC_EXPR_PCOV_Y2,
ALTFUNC_EXPR_PCOV_XY}, 0},
};
static const aggfunc_catalog_t *
aggfunc_lookup_by_oid(Oid aggfnoid)
{
Form_pg_proc proform;
HeapTuple htup;
int i;
htup = SearchSysCache1(PROCOID, ObjectIdGetDatum(aggfnoid));
if (!HeapTupleIsValid(htup))
elog(ERROR, "cache lookup failed for function %u", aggfnoid);
proform = (Form_pg_proc) GETSTRUCT(htup);
for (i=0; i < lengthof(aggfunc_catalog); i++)
{
aggfunc_catalog_t *catalog = &aggfunc_catalog[i];
if (strcmp(catalog->aggfn_name, NameStr(proform->proname)) == 0 &&
catalog->aggfn_nargs == proform->pronargs &&
memcmp(catalog->aggfn_argtypes,
proform->proargtypes.values,
sizeof(Oid) * catalog->aggfn_nargs) == 0)
{
ReleaseSysCache(htup);
return catalog;
}
}
ReleaseSysCache(htup);
return NULL;
}
/*
* cost_gpupreagg
*
* cost estimation of Aggregate if GpuPreAgg is injected
*/
#define LOG2(x) (log(x) / 0.693147180559945)
static void
cost_gpupreagg(const Agg *agg, const Sort *sort, const Plan *outer_plan,
AggStrategy new_agg_strategy,
List *gpupreagg_tlist,
AggClauseCosts *agg_clause_costs,
Plan *p_newcost_agg,
Plan *p_newcost_sort,
Plan *p_newcost_gpreagg)
{
Cost startup_cost;
Cost run_cost;
Cost comparison_cost;
QualCost pagg_cost;
int pagg_width;
int outer_width;
double outer_rows;
double rows_per_chunk;
double num_chunks;
double num_groups = Max(agg->plan.plan_rows, 1.0);
ListCell *cell;
Path dummy;
Assert(outer_plan != NULL);
/*
* GpuPreAgg internally takes partial sort and aggregation
* on GPU devices. It is a factor of additional calculation,
* but reduce number of rows to be processed on the later
* stage.
* Items to be considered is:
* - cost for sorting by GPU
* - cost for aggregation by GPU
* - number of rows being reduced.
*/
startup_cost = outer_plan->startup_cost;
run_cost = outer_plan->total_cost - startup_cost;
outer_rows = outer_plan->plan_rows;
outer_width = outer_plan->plan_width;
/*
* fixed cost to launch GPU feature
*/
startup_cost += pgstrom_gpu_setup_cost;
/*
* cost estimation of internal sorting by GPU.
*/
rows_per_chunk =
((double)((pgstrom_chunk_size << 20) / BLCKSZ)) *
((double)(BLCKSZ - MAXALIGN(SizeOfPageHeaderData))) /
((double)(sizeof(ItemIdData) +
MAXALIGN(sizeof(HeapTupleHeaderData) +
outer_width)));
num_chunks = outer_rows / rows_per_chunk;
if (num_chunks < 1.0)
num_chunks = 1.0;
comparison_cost = 2.0 * pgstrom_gpu_operator_cost;
startup_cost += (comparison_cost *
LOG2(rows_per_chunk * rows_per_chunk) *
num_chunks);
run_cost += pgstrom_gpu_operator_cost * outer_rows;
/*
* cost estimation of partial aggregate by GPU
*/
memset(&pagg_cost, 0, sizeof(QualCost));
pagg_width = 0;
foreach (cell, gpupreagg_tlist)
{
TargetEntry *tle = lfirst(cell);
QualCost cost;
/* no code uses PlannerInfo here. NULL may be OK */
cost_qual_eval_node(&cost, (Node *) tle->expr, NULL);
pagg_cost.startup += cost.startup;
pagg_cost.per_tuple += cost.per_tuple;
pagg_width += get_typavgwidth(exprType((Node *) tle->expr),
exprTypmod((Node *) tle->expr));
}
startup_cost += pagg_cost.startup;
run_cost += (pagg_cost.per_tuple *
pgstrom_gpu_operator_cost /
cpu_operator_cost *
LOG2(rows_per_chunk) *
num_chunks);
/*
* set cost values on GpuPreAgg
*/
p_newcost_gpreagg->startup_cost = startup_cost;
p_newcost_gpreagg->total_cost = startup_cost + run_cost;
p_newcost_gpreagg->plan_rows = num_groups * num_chunks;
p_newcost_gpreagg->plan_width = pagg_width;
/*
* Update estimated sorting cost, if any.
*/
if (sort != NULL)
{
cost_sort(&dummy,
NULL, /* PlannerInfo is not referenced! */
NIL, /* NIL is acceptable */
p_newcost_gpreagg->total_cost,
p_newcost_gpreagg->plan_rows,
p_newcost_gpreagg->plan_width,
0.0,
work_mem,
-1.0);
p_newcost_sort->startup_cost = dummy.startup_cost;
p_newcost_sort->total_cost = dummy.total_cost;
p_newcost_sort->plan_rows = p_newcost_gpreagg->plan_rows;
p_newcost_sort->plan_width = p_newcost_gpreagg->plan_width;
/*
* increase of startup_cost/run_cost according to the Sort
* to be injected between Agg and GpuPreAgg.
*/
startup_cost = dummy.startup_cost;
run_cost = dummy.total_cost - dummy.startup_cost;
}
/*
* Update estimated aggregate cost.
* Calculation logic is cost_agg() as built-in code doing.
*/
cost_agg(&dummy,
NULL, /* PlannerInfo is not referenced! */
new_agg_strategy,
agg_clause_costs,
agg->numCols,
(double) agg->numGroups,
startup_cost,
startup_cost + run_cost,
p_newcost_gpreagg->plan_rows);
p_newcost_agg->startup_cost = dummy.startup_cost;
p_newcost_agg->total_cost = dummy.total_cost;
p_newcost_agg->plan_rows = agg->plan.plan_rows;
p_newcost_agg->plan_width = agg->plan.plan_width;
}
/*
* makeZeroConst - create zero constant
*/
static Const *
makeZeroConst(Oid consttype, int32 consttypmod, Oid constcollid)
{
int16 typlen;
bool typbyval;
Datum zero_datum;
get_typlenbyval(consttype, &typlen, &typbyval);
switch (consttype)
{
case INT4OID:
zero_datum = Int32GetDatum(0);
break;
case INT8OID:
zero_datum = Int64GetDatum(0);
break;
case FLOAT4OID:
zero_datum = Float4GetDatum(0.0);
break;
case FLOAT8OID:
zero_datum = Float8GetDatum(0.0);
break;
default:
elog(ERROR, "type (%u) is not expected", consttype);
break;
}
return makeConst(consttype,
consttypmod,
constcollid,
(int) typlen,
zero_datum,
false,
typbyval);
}
/*
* functions to make expression node of alternative aggregate/functions
*
* make_expr_conditional() - makes the supplied expression conditional
* using CASE WHEN ... THEN ... ELSE ... END clause.
* make_altfunc_expr() - makes alternative function expression
* make_altfunc_nrows_expr() - makes expression node of number or rows.
* make_altfunc_expr_pcov() - makes expression node of covariances.
*/
static Expr *
make_expr_typecast(Expr *expr, Oid target_type)
{
Oid source_type = exprType((Node *) expr);
HeapTuple tup;
Form_pg_cast cast;
if (source_type == target_type)
return expr;
tup = SearchSysCache2(CASTSOURCETARGET,
ObjectIdGetDatum(source_type),
ObjectIdGetDatum(target_type));
if (!HeapTupleIsValid(tup))
elog(ERROR, "could not find tuple for cast (%u,%u)",
source_type, target_type);
cast = (Form_pg_cast) GETSTRUCT(tup);
if (cast->castmethod == COERCION_METHOD_FUNCTION)
{
FuncExpr *func;
Assert(OidIsValid(cast->castfunc));
func = makeFuncExpr(cast->castfunc,
target_type,
list_make1(expr),
InvalidOid, /* always right? */
exprCollation((Node *) expr),
COERCE_EXPLICIT_CAST);
expr = (Expr *) func;
}
else if (cast->castmethod == COERCION_METHOD_BINARY)
{
RelabelType *relabel = makeNode(RelabelType);
relabel->arg = expr;
relabel->resulttype = target_type;
relabel->resulttypmod = exprTypmod((Node *) expr);
relabel->resultcollid = exprCollation((Node *) expr);
relabel->relabelformat = COERCE_EXPLICIT_CAST;
relabel->location = -1;
expr = (Expr *) relabel;
}
else
{
elog(ERROR, "cast-method '%c' is not supported in opencl kernel",
cast->castmethod);
}
ReleaseSysCache(tup);
return expr;
}
static Expr *
make_expr_conditional(Expr *expr, Expr *filter, Expr *defresult)
{
CaseWhen *case_when;
CaseExpr *case_expr;
Assert(exprType((Node *) filter) == BOOLOID);
if (defresult)
defresult = copyObject(defresult);
else
{
defresult = (Expr *) makeNullConst(exprType((Node *) expr),
exprTypmod((Node *) expr),
exprCollation((Node *) expr));
}
Assert(exprType((Node *) expr) == exprType((Node *) defresult));
/* in case when the 'filter' is matched */
case_when = makeNode(CaseWhen);
case_when->expr = copyObject(filter);
case_when->result = copyObject(expr);
case_when->location = -1;
/* case body */
case_expr = makeNode(CaseExpr);
case_expr->casetype = exprType((Node *) expr);
case_expr->arg = NULL;
case_expr->args = list_make1(case_when);
case_expr->defresult = defresult;
case_expr->location = -1;
return (Expr *) case_expr;
}
static Expr *
make_altfunc_expr(const char *func_name, List *args)
{
Oid namespace_oid = get_namespace_oid("pgstrom", false);
Oid typebuf[8];
oidvector *func_argtypes;
HeapTuple tuple;
Form_pg_proc proc_form;
Expr *expr;
ListCell *cell;
int i = 0;
/* set up oidvector */
foreach (cell, args)
typebuf[i++] = exprType((Node *) lfirst(cell));
func_argtypes = buildoidvector(typebuf, i);
/* find an alternative aggregate function */
tuple = SearchSysCache3(PROCNAMEARGSNSP,
PointerGetDatum(func_name),
PointerGetDatum(func_argtypes),
ObjectIdGetDatum(namespace_oid));
if (!HeapTupleIsValid(tuple))
return NULL;
proc_form = (Form_pg_proc) GETSTRUCT(tuple);
expr = (Expr *) makeFuncExpr(HeapTupleGetOid(tuple),
proc_form->prorettype,
args,
InvalidOid,
InvalidOid,
COERCE_EXPLICIT_CALL);
ReleaseSysCache(tuple);
return expr;
}
static Expr *
make_altfunc_nrows_expr(Aggref *aggref)
{
List *nrows_args = NIL;
ListCell *cell;
if (aggref->aggfilter)
nrows_args = lappend(nrows_args, copyObject(aggref->aggfilter));
foreach (cell, aggref->args)
{
TargetEntry *tle = lfirst(cell);
NullTest *ntest = makeNode(NullTest);
Assert(IsA(tle, TargetEntry));
ntest->arg = copyObject(tle->expr);
ntest->nulltesttype = IS_NOT_NULL;
ntest->argisrow = false;
nrows_args = lappend(nrows_args, ntest);
}
return make_altfunc_expr("nrows", nrows_args);
}
/*
* make_altfunc_pcov_expr - constructs an expression node for partial
* covariance aggregates.
*/
static Expr *
make_altfunc_pcov_expr(Aggref *aggref, const char *func_name)
{
Expr *filter;
TargetEntry *tle_1 = linitial(aggref->args);
TargetEntry *tle_2 = lsecond(aggref->args);
Assert(IsA(tle_1, TargetEntry) && IsA(tle_2, TargetEntry));
if (!aggref->aggfilter)
filter = (Expr *) makeBoolConst(true, false);
else
filter = copyObject(aggref->aggfilter);
return make_altfunc_expr(func_name,
list_make3(filter, tle_1->expr, tle_2->expr));
}
/*
* make_gpupreagg_refnode
*
* It tries to construct an alternative Aggref node that references
* partially aggregated results on the target-list of GpuPreAgg node.
*/
static Aggref *
make_gpupreagg_refnode(Aggref *aggref, List **prep_tlist, int *extra_flags)
{
const aggfunc_catalog_t *aggfn_cat;
const char *altfn_name;
oidvector *altfn_argtypes;
Aggref *altnode;
ListCell *cell;
Oid namespace_oid;
HeapTuple tuple;
Form_pg_proc proc_form;
int i;
/* Only aggregated functions listed on the catalog above is supported. */
aggfn_cat = aggfunc_lookup_by_oid(aggref->aggfnoid);
if (!aggfn_cat)
return NULL;
/* MEMO: Right now, functions below are not supported, so should not
* be on the aggfunc_catalog.
* - ordered-set aggregate function
* - aggregate function that takes VARIADIC argument
* - length of arguments are less than 2.
*/
Assert(!aggref->aggdirectargs &&
!aggref->aggvariadic &&
list_length(aggref->args) <= 2);
/* update extra flags */
*extra_flags |= aggfn_cat->altfn_flags;
/*
* Expression node that is executed in the device kernel has to be
* supported by codegen.c
*/
foreach (cell, aggref->args)
{
TargetEntry *tle = lfirst(cell);
if (!pgstrom_codegen_available_expression(tle->expr))
return NULL;
}
if (!pgstrom_codegen_available_expression(aggref->aggfilter))
return NULL;
/*
* pulls the definition of alternative aggregate functions from
* the catalog. we expect these are installed in "pgstrom" schema.
*/
if (strncmp(aggfn_cat->altfn_name, "c:", 2) == 0)
namespace_oid = PG_CATALOG_NAMESPACE;
else if (strncmp(aggfn_cat->altfn_name, "s:", 2) == 0)
{
namespace_oid = get_namespace_oid("pgstrom", true);
if (!OidIsValid(namespace_oid))
{
ereport(NOTICE,
(errcode(ERRCODE_UNDEFINED_SCHEMA),
errmsg("schema \"pgstrom\" was not found"),
errhint("Try to run: CREATE EXTENSION pg_strom")));
return NULL;
}
}
else
elog(ERROR, "Bug? unexpected namespace of alternative aggregate");
altfn_name = aggfn_cat->altfn_name + 2;
altfn_argtypes = buildoidvector(aggfn_cat->altfn_argtypes,
aggfn_cat->altfn_nargs);
tuple = SearchSysCache3(PROCNAMEARGSNSP,
PointerGetDatum(altfn_name),
PointerGetDatum(altfn_argtypes),
ObjectIdGetDatum(namespace_oid));
if (!HeapTupleIsValid(tuple))
{
ereport(NOTICE,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("no alternative aggregate function \"%s\" exists",
funcname_signature_string(altfn_name,
aggfn_cat->altfn_nargs,
NIL,
aggfn_cat->altfn_argtypes)),
errhint("Try to run: CREATE EXTENSION pg_strom")));
return NULL;
}
proc_form = (Form_pg_proc) GETSTRUCT(tuple);
/* sanity checks */
if (proc_form->prorettype != aggref->aggtype)
elog(ERROR, "bug? alternative function has different result type");
/*
* construct an Aggref node that represent alternative aggregate
* function with preprocessed arguments.
*/
altnode = makeNode(Aggref);
altnode->aggfnoid = HeapTupleGetOid(tuple);
altnode->aggtype = aggref->aggtype;
altnode->aggcollid = aggref->aggcollid;
altnode->inputcollid = aggref->inputcollid;
altnode->aggdirectargs = NIL; /* see the checks above */
altnode->args = NIL; /* to be set below */
altnode->aggorder = aggref->aggorder;
altnode->aggdistinct = aggref->aggdistinct;
altnode->aggfilter = NULL; /* moved to GpuPreAgg */
altnode->aggstar = false; /* all the alt-agg takes arguments */
altnode->aggvariadic = false; /* see the checks above */
altnode->aggkind = aggref->aggkind;
altnode->agglevelsup = aggref->agglevelsup;
altnode->location = aggref->location;
ReleaseSysCache(tuple);
/*
* construct arguments of alternative aggregate function. It references
* an entry of prep_tlist, so we put expression node on the tlist on
* demand.
*/
for (i=0; i < aggfn_cat->altfn_nargs; i++)
{
int code = aggfn_cat->altfn_argexprs[i];
Oid argtype_oid = aggfn_cat->altfn_argtypes[i];
TargetEntry *tle;
Expr *expr;
Var *varref;
AttrNumber resno;
switch (code)
{
case ALTFUNC_EXPR_NROWS:
expr = make_altfunc_nrows_expr(aggref);
break;
case ALTFUNC_EXPR_PMIN:
tle = linitial(aggref->args);
Assert(IsA(tle, TargetEntry));
expr = tle->expr;
if (aggref->aggfilter)
expr = make_expr_conditional(expr, aggref->aggfilter,
NULL);
expr = make_altfunc_expr("pmin", list_make1(expr));
break;
case ALTFUNC_EXPR_PMAX:
tle = linitial(aggref->args);
Assert(IsA(tle, TargetEntry));
expr = tle->expr;
if (aggref->aggfilter)
expr = make_expr_conditional(expr, aggref->aggfilter,
NULL);
expr = make_altfunc_expr("pmax", list_make1(expr));
break;
case ALTFUNC_EXPR_PSUM:
tle = linitial(aggref->args);
Assert(IsA(tle, TargetEntry));
expr = tle->expr;
if (exprType((Node *) expr) != argtype_oid)
expr = make_expr_typecast(expr, argtype_oid);
if (aggref->aggfilter)
{
Expr *defresult
= (Expr *) makeZeroConst(exprType((Node *) expr),
exprTypmod((Node *) expr),
exprCollation((Node *) expr));
expr = make_expr_conditional(expr,
aggref->aggfilter,
defresult);
}
expr = make_altfunc_expr("psum", list_make1(expr));
break;
case ALTFUNC_EXPR_PSUM_X2:
tle = linitial(aggref->args);
Assert(IsA(tle, TargetEntry));
expr = tle->expr;
if (exprType((Node *) expr) != argtype_oid)
expr = make_expr_typecast(expr, argtype_oid);
if (aggref->aggfilter)
{
Expr *defresult
= (Expr *) makeZeroConst(exprType((Node *) expr),
exprTypmod((Node *) expr),
exprCollation((Node *) expr));
expr = make_expr_conditional(expr,
aggref->aggfilter,
defresult);
}
expr = make_altfunc_expr("psum_x2", list_make1(expr));
break;
case ALTFUNC_EXPR_PCOV_X:
expr = make_altfunc_pcov_expr(aggref, "pcov_x");
break;
case ALTFUNC_EXPR_PCOV_Y:
expr = make_altfunc_pcov_expr(aggref, "pcov_y");
break;
case ALTFUNC_EXPR_PCOV_X2:
expr = make_altfunc_pcov_expr(aggref, "pcov_x2");
break;
case ALTFUNC_EXPR_PCOV_Y2:
expr = make_altfunc_pcov_expr(aggref, "pcov_y2");
break;
case ALTFUNC_EXPR_PCOV_XY:
expr = make_altfunc_pcov_expr(aggref, "pcov_xy");
break;
default:
elog(ERROR, "Bug? unexpected ALTFUNC_EXPR_* label");
}
/* does aggregate function contained unsupported expression? */
if (!expr)
return NULL;
/* check return type of the alternative functions */
if (argtype_oid != exprType((Node *) expr))
{
elog(NOTICE, "Bug? result type is \"%s\", but \"%s\" is expected",
format_type_be(exprType((Node *) expr)),
format_type_be(argtype_oid));
return NULL;
}
/* add this expression node on the prep_tlist */
foreach (cell, *prep_tlist)
{
tle = lfirst(cell);
if (equal(tle->expr, expr))
{
resno = tle->resno;
break;
}
}
if (!cell)
{
tle = makeTargetEntry(expr,
list_length(*prep_tlist) + 1,
NULL,
false);
*prep_tlist = lappend(*prep_tlist, tle);
resno = tle->resno;
}
/*
* alternative aggregate function shall reference this resource.
*/
varref = makeVar(OUTER_VAR,
resno,
exprType((Node *) expr),
exprTypmod((Node *) expr),
exprCollation((Node *) expr),
(Index) 0);
tle = makeTargetEntry((Expr *) varref,
list_length(altnode->args) + 1,
NULL,
false);
altnode->args = lappend(altnode->args, tle);
}
return altnode;
}
typedef struct
{
Agg *agg;
List *pre_tlist;
Bitmapset *attr_refs;
int extra_flags;
bool gpupreagg_invalid;
} gpupreagg_rewrite_context;
static Node *
gpupreagg_rewrite_mutator(Node *node, gpupreagg_rewrite_context *context)
{
if (!node)
return NULL;
if (IsA(node, Aggref))
{
Aggref *orgagg = (Aggref *) node;
Aggref *altagg = NULL;