sandbox/bugs/gpu_fp64_literal_truncation.c
DOUBLE_PRECISION=1
silently truncates GPU kernel literals to FP32
When compiling a GPU program with -DDOUBLE_PRECISION=1,
qcc still appends f suffixes to every
floating-point literal inside generated GPU kernels
(e.g. (1.0 + 1e-12) - 1.0 is emitted as
(1.0f + 1e-12f) - 1.0f), and grid/gpu/grid.h
hardcodes pi and nodata as float
literals (3.14159265359f and (1e30f)).
Compile and inspect the generated kernel, or run on the GPU:
qcc -source gpu_fp64_literal_truncation.c
grep -n "1e-12\|3\.14159\|1e30f" _gpu_fp64_literal_truncation.c
make gpu_fp64_literal_truncation.tstInspecting _gpu_fp64_literal_truncation.c produced by
qcc -source shows that the GPU kernel string was emitted
with f suffixes while the CPU fallback kept
double literals:
// GPU kernel string:
val_out_(a,0,0,0) = (1.0f + 1e-12f) - 1.0f;
#define pi 3.14159265359f
#define nodata (1e30f)
// CPU fallback:
val(a,0,0,0) = (1.0 + 1e-12) - 1.0;Running on the GPU
(make gpu_fp64_literal_truncation.tst) fails with:
opengl.c:692: error: OpenGl 00000502 for 'glUniform2iv (0, 1, csOrigin);'
#define DOUBLE_PRECISION 1
#include "grid/gpu/multigrid.h"
int main()
{
init_grid (4);
scalar a[];
foreach()
a[] = (1.0 + 1e-12) - 1.0;
double v = interpolate (a, 0.5, 0.5);
fprintf (stderr, "v = %.16e (expected 1.0000000000000000e-12)\n", v);
assert (fabs (v - 1e-12) < 1e-15);
}Root cause
In /src/include.lex (line 328),
qccscans the raw, unpreprocessed text of included headers for:^{SP}*#{SP}*define{SP}+SINGLE_PRECISION{WS}+1{SP}*$ { fp32 = 1; }Because /src/grid/gpu-multigrid.h contains
# define SINGLE_PRECISION 1in its#elsebranch,include.lexmatches it unconditionally even when-DDOUBLE_PRECISION=1is passed, setting.fp32 = 1inqcc(ast/kernels.cthen appendsfto every floating-point literal in every generated GPU kernel).In /src/grid/gpu/grid.h (lines 618–619),
piandnodataare hardcoded withfsuffixes regardless ofSINGLE_PRECISION:"#define pi 3.14159265359f\n" "#define nodata (1e30f)\n"
Proposed fix
In
/src/include.lex(or/src/qcc.c), clearfp32 = 0when-DDOUBLE_PRECISIONis defined (or evaluateDOUBLE_PRECISIONbefore settingfp32).In
/src/grid/gpu/grid.h, guardpiandnodatawith#if SINGLE_PRECISION ... #else ... #endif:#if SINGLE_PRECISION "#define pi 3.14159265359f\n" "#define nodata (1e30f)\n" #else "#define pi 3.14159265358979323846\n" "#define nodata (1e30)\n" #endif
