{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TupleSections #-}

-- | Code generation for CUDA.
module Futhark.CodeGen.Backends.CCUDA
  ( compileProg,
    GC.CParts (..),
    GC.asLibrary,
    GC.asExecutable,
    GC.asServer,
  )
where

import Control.Monad
import Data.Maybe (catMaybes)
import qualified Data.Text as T
import Futhark.CodeGen.Backends.CCUDA.Boilerplate
import Futhark.CodeGen.Backends.COpenCL.Boilerplate (commonOptions, sizeLoggingCode)
import qualified Futhark.CodeGen.Backends.GenericC as GC
import Futhark.CodeGen.Backends.GenericC.Options
import Futhark.CodeGen.Backends.SimpleRep (primStorageType, toStorage)
import Futhark.CodeGen.ImpCode.OpenCL
import qualified Futhark.CodeGen.ImpGen.CUDA as ImpGen
import Futhark.IR.GPUMem hiding
  ( CmpSizeLe,
    GetSize,
    GetSizeMax,
  )
import Futhark.MonadFreshNames
import qualified Language.C.Quote.OpenCL as C
import qualified Language.C.Syntax as C
import NeatInterpolation (untrimming)

-- | Compile the program to C with calls to CUDA.
compileProg :: MonadFreshNames m => T.Text -> Prog GPUMem -> m (ImpGen.Warnings, GC.CParts)
compileProg :: Text -> Prog GPUMem -> m (Warnings, CParts)
compileProg Text
version Prog GPUMem
prog = do
  (Warnings
ws, Program Text
cuda_code Text
cuda_prelude Map KernelName KernelSafety
kernels [PrimType]
_ Map KernelName SizeClass
sizes [FailureMsg]
failures Definitions OpenCL
prog') <-
    Prog GPUMem -> m (Warnings, Program)
forall (m :: * -> *).
MonadFreshNames m =>
Prog GPUMem -> m (Warnings, Program)
ImpGen.compileProg Prog GPUMem
prog
  let cost_centres :: [KernelName]
cost_centres =
        [ KernelName
copyDevToDev,
          KernelName
copyDevToHost,
          KernelName
copyHostToDev,
          KernelName
copyScalarToDev,
          KernelName
copyScalarFromDev
        ]
      extra :: CompilerM OpenCL () ()
extra =
        Text
-> Text
-> [KernelName]
-> Map KernelName KernelSafety
-> Map KernelName SizeClass
-> [FailureMsg]
-> CompilerM OpenCL () ()
generateBoilerplate
          Text
cuda_code
          Text
cuda_prelude
          [KernelName]
cost_centres
          Map KernelName KernelSafety
kernels
          Map KernelName SizeClass
sizes
          [FailureMsg]
failures
  (Warnings
ws,)
    (CParts -> (Warnings, CParts)) -> m CParts -> m (Warnings, CParts)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text
-> Text
-> Operations OpenCL ()
-> CompilerM OpenCL () ()
-> Text
-> [Space]
-> [Option]
-> Definitions OpenCL
-> m CParts
forall (m :: * -> *) op.
MonadFreshNames m =>
Text
-> Text
-> Operations op ()
-> CompilerM op () ()
-> Text
-> [Space]
-> [Option]
-> Definitions op
-> m CParts
GC.compileProg
      Text
"cuda"
      Text
version
      Operations OpenCL ()
operations
      CompilerM OpenCL () ()
extra
      Text
cuda_includes
      [SpaceId -> Space
Space SpaceId
"device", Space
DefaultSpace]
      [Option]
cliOptions
      Definitions OpenCL
prog'
  where
    operations :: GC.Operations OpenCL ()
    operations :: Operations OpenCL ()
operations =
      Operations OpenCL ()
forall op s. Operations op s
GC.defaultOperations
        { opsWriteScalar :: WriteScalar OpenCL ()
GC.opsWriteScalar = WriteScalar OpenCL ()
writeCUDAScalar,
          opsReadScalar :: ReadScalar OpenCL ()
GC.opsReadScalar = ReadScalar OpenCL ()
readCUDAScalar,
          opsAllocate :: Allocate OpenCL ()
GC.opsAllocate = Allocate OpenCL ()
allocateCUDABuffer,
          opsDeallocate :: Deallocate OpenCL ()
GC.opsDeallocate = Deallocate OpenCL ()
deallocateCUDABuffer,
          opsCopy :: Copy OpenCL ()
GC.opsCopy = Copy OpenCL ()
copyCUDAMemory,
          opsStaticArray :: StaticArray OpenCL ()
GC.opsStaticArray = StaticArray OpenCL ()
staticCUDAArray,
          opsMemoryType :: MemoryType OpenCL ()
GC.opsMemoryType = MemoryType OpenCL ()
cudaMemoryType,
          opsCompiler :: OpCompiler OpenCL ()
GC.opsCompiler = OpCompiler OpenCL ()
callKernel,
          opsFatMemory :: Bool
GC.opsFatMemory = Bool
True,
          opsCritical :: ([BlockItem], [BlockItem])
GC.opsCritical =
            ( [C.citems|CUDA_SUCCEED_FATAL(cuCtxPushCurrent(ctx->cuda.cu_ctx));|],
              [C.citems|CUDA_SUCCEED_FATAL(cuCtxPopCurrent(&ctx->cuda.cu_ctx));|]
            )
        }
    cuda_includes :: Text
cuda_includes =
      [untrimming|
       #include <cuda.h>
       #include <cuda_runtime.h>
       #include <nvrtc.h>
      |]

cliOptions :: [Option]
cliOptions :: [Option]
cliOptions =
  [Option]
commonOptions
    [Option] -> [Option] -> [Option]
forall a. [a] -> [a] -> [a]
++ [ Option :: SpaceId -> Maybe Char -> OptionArgument -> SpaceId -> Stm -> Option
Option
           { optionLongName :: SpaceId
optionLongName = SpaceId
"dump-cuda",
             optionShortName :: Maybe Char
optionShortName = Maybe Char
forall a. Maybe a
Nothing,
             optionArgument :: OptionArgument
optionArgument = SpaceId -> OptionArgument
RequiredArgument SpaceId
"FILE",
             optionDescription :: SpaceId
optionDescription = SpaceId
"Dump the embedded CUDA kernels to the indicated file.",
             optionAction :: Stm
optionAction =
               [C.cstm|{futhark_context_config_dump_program_to(cfg, optarg);
                                     entry_point = NULL;}|]
           },
         Option :: SpaceId -> Maybe Char -> OptionArgument -> SpaceId -> Stm -> Option
Option
           { optionLongName :: SpaceId
optionLongName = SpaceId
"load-cuda",
             optionShortName :: Maybe Char
optionShortName = Maybe Char
forall a. Maybe a
Nothing,
             optionArgument :: OptionArgument
optionArgument = SpaceId -> OptionArgument
RequiredArgument SpaceId
"FILE",
             optionDescription :: SpaceId
optionDescription = SpaceId
"Instead of using the embedded CUDA kernels, load them from the indicated file.",
             optionAction :: Stm
optionAction = [C.cstm|futhark_context_config_load_program_from(cfg, optarg);|]
           },
         Option :: SpaceId -> Maybe Char -> OptionArgument -> SpaceId -> Stm -> Option
Option
           { optionLongName :: SpaceId
optionLongName = SpaceId
"dump-ptx",
             optionShortName :: Maybe Char
optionShortName = Maybe Char
forall a. Maybe a
Nothing,
             optionArgument :: OptionArgument
optionArgument = SpaceId -> OptionArgument
RequiredArgument SpaceId
"FILE",
             optionDescription :: SpaceId
optionDescription = SpaceId
"Dump the PTX-compiled version of the embedded kernels to the indicated file.",
             optionAction :: Stm
optionAction =
               [C.cstm|{futhark_context_config_dump_ptx_to(cfg, optarg);
                                     entry_point = NULL;}|]
           },
         Option :: SpaceId -> Maybe Char -> OptionArgument -> SpaceId -> Stm -> Option
Option
           { optionLongName :: SpaceId
optionLongName = SpaceId
"load-ptx",
             optionShortName :: Maybe Char
optionShortName = Maybe Char
forall a. Maybe a
Nothing,
             optionArgument :: OptionArgument
optionArgument = SpaceId -> OptionArgument
RequiredArgument SpaceId
"FILE",
             optionDescription :: SpaceId
optionDescription = SpaceId
"Load PTX code from the indicated file.",
             optionAction :: Stm
optionAction = [C.cstm|futhark_context_config_load_ptx_from(cfg, optarg);|]
           },
         Option :: SpaceId -> Maybe Char -> OptionArgument -> SpaceId -> Stm -> Option
Option
           { optionLongName :: SpaceId
optionLongName = SpaceId
"nvrtc-option",
             optionShortName :: Maybe Char
optionShortName = Maybe Char
forall a. Maybe a
Nothing,
             optionArgument :: OptionArgument
optionArgument = SpaceId -> OptionArgument
RequiredArgument SpaceId
"OPT",
             optionDescription :: SpaceId
optionDescription = SpaceId
"Add an additional build option to the string passed to NVRTC.",
             optionAction :: Stm
optionAction = [C.cstm|futhark_context_config_add_nvrtc_option(cfg, optarg);|]
           },
         Option :: SpaceId -> Maybe Char -> OptionArgument -> SpaceId -> Stm -> Option
Option
           { optionLongName :: SpaceId
optionLongName = SpaceId
"profile",
             optionShortName :: Maybe Char
optionShortName = Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'P',
             optionArgument :: OptionArgument
optionArgument = OptionArgument
NoArgument,
             optionDescription :: SpaceId
optionDescription = SpaceId
"Gather profiling data while executing and print out a summary at the end.",
             optionAction :: Stm
optionAction = [C.cstm|futhark_context_config_set_profiling(cfg, 1);|]
           }
       ]

-- We detect the special case of writing a constant and turn it into a
-- non-blocking write.  This may be slightly faster, as it prevents
-- unnecessary synchronisation of the context, and writing a constant
-- is fairly common.  This is only possible because we can give the
-- constant infinite lifetime (with 'static'), which is not the case
-- for ordinary variables.
writeCUDAScalar :: GC.WriteScalar OpenCL ()
writeCUDAScalar :: WriteScalar OpenCL ()
writeCUDAScalar Exp
mem Exp
idx Type
t SpaceId
"device" Volatility
_ val :: Exp
val@C.Const {} = do
  VName
val' <- SpaceId -> CompilerM OpenCL () VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"write_static"
  let ([BlockItem]
bef, [BlockItem]
aft) = KernelName -> ([BlockItem], [BlockItem])
profilingEnclosure KernelName
copyScalarToDev
  BlockItem -> CompilerM OpenCL () ()
forall op s. BlockItem -> CompilerM op s ()
GC.item
    [C.citem|{static $ty:t $id:val' = $exp:val;
              $items:bef
              CUDA_SUCCEED_OR_RETURN(
                cuMemcpyHtoDAsync($exp:mem + $exp:idx * sizeof($ty:t),
                                  &$id:val',
                                  sizeof($ty:t),
                                  0));
              $items:aft
             }|]
writeCUDAScalar Exp
mem Exp
idx Type
t SpaceId
"device" Volatility
_ Exp
val = do
  VName
val' <- SpaceId -> CompilerM OpenCL () VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"write_tmp"
  let ([BlockItem]
bef, [BlockItem]
aft) = KernelName -> ([BlockItem], [BlockItem])
profilingEnclosure KernelName
copyScalarToDev
  BlockItem -> CompilerM OpenCL () ()
forall op s. BlockItem -> CompilerM op s ()
GC.item
    [C.citem|{$ty:t $id:val' = $exp:val;
                  $items:bef
                  CUDA_SUCCEED_OR_RETURN(
                    cuMemcpyHtoD($exp:mem + $exp:idx * sizeof($ty:t),
                                 &$id:val',
                                 sizeof($ty:t)));
                  $items:aft
                 }|]
writeCUDAScalar Exp
_ Exp
_ Type
_ SpaceId
space Volatility
_ Exp
_ =
  SpaceId -> CompilerM OpenCL () ()
forall a. HasCallStack => SpaceId -> a
error (SpaceId -> CompilerM OpenCL () ())
-> SpaceId -> CompilerM OpenCL () ()
forall a b. (a -> b) -> a -> b
$ SpaceId
"Cannot write to '" SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
space SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
"' memory space."

readCUDAScalar :: GC.ReadScalar OpenCL ()
readCUDAScalar :: ReadScalar OpenCL ()
readCUDAScalar Exp
mem Exp
idx Type
t SpaceId
"device" Volatility
_ = do
  VName
val <- SpaceId -> CompilerM OpenCL () VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"read_res"
  let ([BlockItem]
bef, [BlockItem]
aft) = KernelName -> ([BlockItem], [BlockItem])
profilingEnclosure KernelName
copyScalarFromDev
  (BlockItem -> CompilerM OpenCL () ())
-> [BlockItem] -> CompilerM OpenCL () ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_
    BlockItem -> CompilerM OpenCL () ()
forall op s. BlockItem -> CompilerM op s ()
GC.item
    [C.citems|
       $ty:t $id:val;
       {
       $items:bef
       CUDA_SUCCEED_OR_RETURN(
          cuMemcpyDtoH(&$id:val,
                       $exp:mem + $exp:idx * sizeof($ty:t),
                       sizeof($ty:t)));
       $items:aft
       }
       |]
  Stm -> CompilerM OpenCL () ()
forall op s. Stm -> CompilerM op s ()
GC.stm
    [C.cstm|if (ctx->failure_is_an_option && futhark_context_sync(ctx) != 0)
            { return 1; }|]
  Exp -> CompilerM OpenCL () Exp
forall (f :: * -> *) a. Applicative f => a -> f a
pure [C.cexp|$id:val|]
readCUDAScalar Exp
_ Exp
_ Type
_ SpaceId
space Volatility
_ =
  SpaceId -> CompilerM OpenCL () Exp
forall a. HasCallStack => SpaceId -> a
error (SpaceId -> CompilerM OpenCL () Exp)
-> SpaceId -> CompilerM OpenCL () Exp
forall a b. (a -> b) -> a -> b
$ SpaceId
"Cannot write to '" SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
space SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
"' memory space."

allocateCUDABuffer :: GC.Allocate OpenCL ()
allocateCUDABuffer :: Allocate OpenCL ()
allocateCUDABuffer Exp
mem Exp
size Exp
tag SpaceId
"device" =
  Stm -> CompilerM OpenCL () ()
forall op s. Stm -> CompilerM op s ()
GC.stm
    [C.cstm|ctx->error =
     CUDA_SUCCEED_NONFATAL(cuda_alloc(&ctx->cuda, ctx->log,
                                      (size_t)$exp:size, $exp:tag, &$exp:mem));|]
allocateCUDABuffer Exp
_ Exp
_ Exp
_ SpaceId
space =
  SpaceId -> CompilerM OpenCL () ()
forall a. HasCallStack => SpaceId -> a
error (SpaceId -> CompilerM OpenCL () ())
-> SpaceId -> CompilerM OpenCL () ()
forall a b. (a -> b) -> a -> b
$ SpaceId
"Cannot allocate in '" SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
space SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
"' memory space."

deallocateCUDABuffer :: GC.Deallocate OpenCL ()
deallocateCUDABuffer :: Deallocate OpenCL ()
deallocateCUDABuffer Exp
mem Exp
tag SpaceId
"device" =
  Stm -> CompilerM OpenCL () ()
forall op s. Stm -> CompilerM op s ()
GC.stm [C.cstm|CUDA_SUCCEED_OR_RETURN(cuda_free(&ctx->cuda, $exp:mem, $exp:tag));|]
deallocateCUDABuffer Exp
_ Exp
_ SpaceId
space =
  SpaceId -> CompilerM OpenCL () ()
forall a. HasCallStack => SpaceId -> a
error (SpaceId -> CompilerM OpenCL () ())
-> SpaceId -> CompilerM OpenCL () ()
forall a b. (a -> b) -> a -> b
$ SpaceId
"Cannot deallocate in '" SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
space SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
"' memory space."

copyCUDAMemory :: GC.Copy OpenCL ()
copyCUDAMemory :: Copy OpenCL ()
copyCUDAMemory Exp
dstmem Exp
dstidx Space
dstSpace Exp
srcmem Exp
srcidx Space
srcSpace Exp
nbytes = do
  let (SpaceId
fn, KernelName
prof) = Space -> Space -> (SpaceId, KernelName)
memcpyFun Space
dstSpace Space
srcSpace
      ([BlockItem]
bef, [BlockItem]
aft) = KernelName -> ([BlockItem], [BlockItem])
profilingEnclosure KernelName
prof
  BlockItem -> CompilerM OpenCL () ()
forall op s. BlockItem -> CompilerM op s ()
GC.item
    [C.citem|{
                $items:bef
                CUDA_SUCCEED_OR_RETURN(
                  $id:fn($exp:dstmem + $exp:dstidx,
                         $exp:srcmem + $exp:srcidx,
                         $exp:nbytes));
                $items:aft
                }
                |]
  where
    memcpyFun :: Space -> Space -> (SpaceId, KernelName)
memcpyFun Space
DefaultSpace (Space SpaceId
"device") = (SpaceId
"cuMemcpyDtoH" :: String, KernelName
copyDevToHost)
    memcpyFun (Space SpaceId
"device") Space
DefaultSpace = (SpaceId
"cuMemcpyHtoD", KernelName
copyHostToDev)
    memcpyFun (Space SpaceId
"device") (Space SpaceId
"device") = (SpaceId
"cuMemcpy", KernelName
copyDevToDev)
    memcpyFun Space
_ Space
_ =
      SpaceId -> (SpaceId, KernelName)
forall a. HasCallStack => SpaceId -> a
error (SpaceId -> (SpaceId, KernelName))
-> SpaceId -> (SpaceId, KernelName)
forall a b. (a -> b) -> a -> b
$
        SpaceId
"Cannot copy to '" SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ Space -> SpaceId
forall a. Show a => a -> SpaceId
show Space
dstSpace
          SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
"' from '"
          SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ Space -> SpaceId
forall a. Show a => a -> SpaceId
show Space
srcSpace
          SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
"'."

staticCUDAArray :: GC.StaticArray OpenCL ()
staticCUDAArray :: StaticArray OpenCL ()
staticCUDAArray VName
name SpaceId
"device" PrimType
t ArrayContents
vs = do
  let ct :: Type
ct = PrimType -> Type
GC.primTypeToCType PrimType
t
  VName
name_realtype <- SpaceId -> CompilerM OpenCL () VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName (SpaceId -> CompilerM OpenCL () VName)
-> SpaceId -> CompilerM OpenCL () VName
forall a b. (a -> b) -> a -> b
$ VName -> SpaceId
baseString VName
name SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
"_realtype"
  Int
num_elems <- case ArrayContents
vs of
    ArrayValues [PrimValue]
vs' -> do
      let vs'' :: [Initializer]
vs'' = [[C.cinit|$exp:v|] | PrimValue
v <- [PrimValue]
vs']
      Definition -> CompilerM OpenCL () ()
forall op s. Definition -> CompilerM op s ()
GC.earlyDecl [C.cedecl|static $ty:ct $id:name_realtype[$int:(length vs'')] = {$inits:vs''};|]
      Int -> CompilerM OpenCL () Int
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Int -> CompilerM OpenCL () Int) -> Int -> CompilerM OpenCL () Int
forall a b. (a -> b) -> a -> b
$ [Initializer] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Initializer]
vs''
    ArrayZeros Int
n -> do
      Definition -> CompilerM OpenCL () ()
forall op s. Definition -> CompilerM op s ()
GC.earlyDecl [C.cedecl|static $ty:ct $id:name_realtype[$int:n];|]
      Int -> CompilerM OpenCL () Int
forall (f :: * -> *) a. Applicative f => a -> f a
pure Int
n
  -- Fake a memory block.
  Id -> Type -> Maybe Exp -> Stm -> CompilerM OpenCL () ()
forall op s. Id -> Type -> Maybe Exp -> Stm -> CompilerM op s ()
GC.contextFieldDyn
    (VName -> SrcLoc -> Id
forall a. ToIdent a => a -> SrcLoc -> Id
C.toIdent VName
name SrcLoc
forall a. Monoid a => a
mempty)
    [C.cty|struct memblock_device|]
    Maybe Exp
forall a. Maybe a
Nothing
    [C.cstm|cuMemFree(ctx->$id:name.mem);|]
  -- During startup, copy the data to where we need it.
  Stm -> CompilerM OpenCL () ()
forall op s. Stm -> CompilerM op s ()
GC.atInit
    [C.cstm|{
    ctx->$id:name.references = NULL;
    ctx->$id:name.size = 0;
    CUDA_SUCCEED_FATAL(cuMemAlloc(&ctx->$id:name.mem,
                            ($int:num_elems > 0 ? $int:num_elems : 1)*sizeof($ty:ct)));
    if ($int:num_elems > 0) {
      CUDA_SUCCEED_FATAL(cuMemcpyHtoD(ctx->$id:name.mem, $id:name_realtype,
                                $int:num_elems*sizeof($ty:ct)));
    }
  }|]
  BlockItem -> CompilerM OpenCL () ()
forall op s. BlockItem -> CompilerM op s ()
GC.item [C.citem|struct memblock_device $id:name = ctx->$id:name;|]
staticCUDAArray VName
_ SpaceId
space PrimType
_ ArrayContents
_ =
  SpaceId -> CompilerM OpenCL () ()
forall a. HasCallStack => SpaceId -> a
error (SpaceId -> CompilerM OpenCL () ())
-> SpaceId -> CompilerM OpenCL () ()
forall a b. (a -> b) -> a -> b
$
    SpaceId
"CUDA backend cannot create static array in '" SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
space
      SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
"' memory space"

cudaMemoryType :: GC.MemoryType OpenCL ()
cudaMemoryType :: MemoryType OpenCL ()
cudaMemoryType SpaceId
"device" = Type -> CompilerM OpenCL () Type
forall (f :: * -> *) a. Applicative f => a -> f a
pure [C.cty|typename CUdeviceptr|]
cudaMemoryType SpaceId
space =
  MemoryType OpenCL ()
forall a. HasCallStack => SpaceId -> a
error MemoryType OpenCL () -> MemoryType OpenCL ()
forall a b. (a -> b) -> a -> b
$ SpaceId
"CUDA backend does not support '" SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
space SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SpaceId
"' memory space."

callKernel :: GC.OpCompiler OpenCL ()
callKernel :: OpCompiler OpenCL ()
callKernel (GetSize VName
v KernelName
key) =
  Stm -> CompilerM OpenCL () ()
forall op s. Stm -> CompilerM op s ()
GC.stm [C.cstm|$id:v = *ctx->tuning_params.$id:key;|]
callKernel (CmpSizeLe VName
v KernelName
key Exp
x) = do
  Exp
x' <- Exp -> CompilerM OpenCL () Exp
forall op s. Exp -> CompilerM op s Exp
GC.compileExp Exp
x
  Stm -> CompilerM OpenCL () ()
forall op s. Stm -> CompilerM op s ()
GC.stm [C.cstm|$id:v = *ctx->tuning_params.$id:key <= $exp:x';|]
  VName -> KernelName -> Exp -> CompilerM OpenCL () ()
forall op. VName -> KernelName -> Exp -> CompilerM op () ()
sizeLoggingCode VName
v KernelName
key Exp
x'
callKernel (GetSizeMax VName
v SizeClass
size_class) =
  let field :: SpaceId
field = SpaceId
"max_" SpaceId -> SpaceId -> SpaceId
forall a. [a] -> [a] -> [a]
++ SizeClass -> SpaceId
cudaSizeClass SizeClass
size_class
   in Stm -> CompilerM OpenCL () ()
forall op s. Stm -> CompilerM op s ()
GC.stm [C.cstm|$id:v = ctx->cuda.$id:field;|]
  where
    cudaSizeClass :: SizeClass -> SpaceId
cudaSizeClass SizeThreshold {} = SpaceId
"threshold"
    cudaSizeClass SizeClass
SizeGroup = SpaceId
"block_size"
    cudaSizeClass SizeClass
SizeNumGroups = SpaceId
"grid_size"
    cudaSizeClass SizeClass
SizeTile = SpaceId
"tile_size"
    cudaSizeClass SizeClass
SizeRegTile = SpaceId
"reg_tile_size"
    cudaSizeClass SizeClass
SizeLocalMemory = SpaceId
"shared_memory"
    cudaSizeClass (SizeBespoke KernelName
x Int64
_) = KernelName -> SpaceId
forall a. Pretty a => a -> SpaceId
pretty KernelName
x
callKernel (LaunchKernel KernelSafety
safety KernelName
kernel_name [KernelArg]
args [Exp]
num_blocks [Exp]
block_size) = do
  VName
args_arr <- SpaceId -> CompilerM OpenCL () VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"kernel_args"
  VName
time_start <- SpaceId -> CompilerM OpenCL () VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"time_start"
  VName
time_end <- SpaceId -> CompilerM OpenCL () VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"time_end"
  ([VName]
args', [Maybe (VName, VName)]
shared_vars) <- [(VName, Maybe (VName, VName))]
-> ([VName], [Maybe (VName, VName)])
forall a b. [(a, b)] -> ([a], [b])
unzip ([(VName, Maybe (VName, VName))]
 -> ([VName], [Maybe (VName, VName)]))
-> CompilerM OpenCL () [(VName, Maybe (VName, VName))]
-> CompilerM OpenCL () ([VName], [Maybe (VName, VName)])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (KernelArg -> CompilerM OpenCL () (VName, Maybe (VName, VName)))
-> [KernelArg]
-> CompilerM OpenCL () [(VName, Maybe (VName, VName))]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM KernelArg -> CompilerM OpenCL () (VName, Maybe (VName, VName))
forall op s.
KernelArg -> CompilerM op s (VName, Maybe (VName, VName))
mkArgs [KernelArg]
args
  let ([VName]
shared_sizes, [VName]
shared_offsets) = [(VName, VName)] -> ([VName], [VName])
forall a b. [(a, b)] -> ([a], [b])
unzip ([(VName, VName)] -> ([VName], [VName]))
-> [(VName, VName)] -> ([VName], [VName])
forall a b. (a -> b) -> a -> b
$ [Maybe (VName, VName)] -> [(VName, VName)]
forall a. [Maybe a] -> [a]
catMaybes [Maybe (VName, VName)]
shared_vars
      shared_offsets_sc :: [Exp]
shared_offsets_sc = [VName] -> [Exp]
mkOffsets [VName]
shared_sizes
      shared_args :: [(VName, Exp)]
shared_args = [VName] -> [Exp] -> [(VName, Exp)]
forall a b. [a] -> [b] -> [(a, b)]
zip [VName]
shared_offsets [Exp]
shared_offsets_sc
      shared_tot :: Exp
shared_tot = [Exp] -> Exp
forall a. [a] -> a
last [Exp]
shared_offsets_sc
  [(VName, Exp)]
-> ((VName, Exp) -> CompilerM OpenCL () ())
-> CompilerM OpenCL () ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [(VName, Exp)]
shared_args (((VName, Exp) -> CompilerM OpenCL () ())
 -> CompilerM OpenCL () ())
-> ((VName, Exp) -> CompilerM OpenCL () ())
-> CompilerM OpenCL () ()
forall a b. (a -> b) -> a -> b
$ \(VName
arg, Exp
offset) ->
    InitGroup -> CompilerM OpenCL () ()
forall op s. InitGroup -> CompilerM op s ()
GC.decl [C.cdecl|unsigned int $id:arg = $exp:offset;|]

  (Exp
grid_x, Exp
grid_y, Exp
grid_z) <- [Exp] -> (Exp, Exp, Exp)
mkDims ([Exp] -> (Exp, Exp, Exp))
-> CompilerM OpenCL () [Exp] -> CompilerM OpenCL () (Exp, Exp, Exp)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Exp -> CompilerM OpenCL () Exp)
-> [Exp] -> CompilerM OpenCL () [Exp]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Exp -> CompilerM OpenCL () Exp
forall op s. Exp -> CompilerM op s Exp
GC.compileExp [Exp]
num_blocks
  (Exp
block_x, Exp
block_y, Exp
block_z) <- [Exp] -> (Exp, Exp, Exp)
mkDims ([Exp] -> (Exp, Exp, Exp))
-> CompilerM OpenCL () [Exp] -> CompilerM OpenCL () (Exp, Exp, Exp)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Exp -> CompilerM OpenCL () Exp)
-> [Exp] -> CompilerM OpenCL () [Exp]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Exp -> CompilerM OpenCL () Exp
forall op s. Exp -> CompilerM op s Exp
GC.compileExp [Exp]
block_size
  let perm_args :: [Initializer]
perm_args
        | [Exp] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Exp]
num_blocks Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
3 = [[C.cinit|&perm[0]|], [C.cinit|&perm[1]|], [C.cinit|&perm[2]|]]
        | Bool
otherwise = []
      failure_args :: [Initializer]
failure_args =
        Int -> [Initializer] -> [Initializer]
forall a. Int -> [a] -> [a]
take
          (KernelSafety -> Int
numFailureParams KernelSafety
safety)
          [ [C.cinit|&ctx->global_failure|],
            [C.cinit|&ctx->failure_is_an_option|],
            [C.cinit|&ctx->global_failure_args|]
          ]
      args'' :: [Initializer]
args'' = [Initializer]
perm_args [Initializer] -> [Initializer] -> [Initializer]
forall a. [a] -> [a] -> [a]
++ [Initializer]
failure_args [Initializer] -> [Initializer] -> [Initializer]
forall a. [a] -> [a] -> [a]
++ [[C.cinit|&$id:a|] | VName
a <- [VName]
args']
      sizes_nonzero :: Exp
sizes_nonzero =
        [Exp] -> Exp
expsNotZero
          [ Exp
grid_x,
            Exp
grid_y,
            Exp
grid_z,
            Exp
block_x,
            Exp
block_y,
            Exp
block_z
          ]
      ([BlockItem]
bef, [BlockItem]
aft) = KernelName -> ([BlockItem], [BlockItem])
profilingEnclosure KernelName
kernel_name

  Stm -> CompilerM OpenCL () ()
forall op s. Stm -> CompilerM op s ()
GC.stm
    [C.cstm|
    if ($exp:sizes_nonzero) {
      int perm[3] = { 0, 1, 2 };

      if ($exp:grid_y >= (1<<16)) {
        perm[1] = perm[0];
        perm[0] = 1;
      }

      if ($exp:grid_z >= (1<<16)) {
        perm[2] = perm[0];
        perm[0] = 2;
      }

      size_t grid[3];
      grid[perm[0]] = $exp:grid_x;
      grid[perm[1]] = $exp:grid_y;
      grid[perm[2]] = $exp:grid_z;

      void *$id:args_arr[] = { $inits:args'' };
      typename int64_t $id:time_start = 0, $id:time_end = 0;
      if (ctx->debugging) {
        fprintf(ctx->log, "Launching %s with grid size [%ld, %ld, %ld] and block size [%ld, %ld, %ld]; shared memory: %d bytes.\n",
                $string:(pretty kernel_name),
                (long int)$exp:grid_x, (long int)$exp:grid_y, (long int)$exp:grid_z,
                (long int)$exp:block_x, (long int)$exp:block_y, (long int)$exp:block_z,
                (int)$exp:shared_tot);
        $id:time_start = get_wall_time();
      }
      $items:bef
      CUDA_SUCCEED_OR_RETURN(
        cuLaunchKernel(ctx->$id:kernel_name,
                       grid[0], grid[1], grid[2],
                       $exp:block_x, $exp:block_y, $exp:block_z,
                       $exp:shared_tot, NULL,
                       $id:args_arr, NULL));
      $items:aft
      if (ctx->debugging) {
        CUDA_SUCCEED_FATAL(cuCtxSynchronize());
        $id:time_end = get_wall_time();
        fprintf(ctx->log, "Kernel %s runtime: %ldus\n",
                $string:(pretty kernel_name), $id:time_end - $id:time_start);
      }
    }|]

  Bool -> CompilerM OpenCL () () -> CompilerM OpenCL () ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (KernelSafety
safety KernelSafety -> KernelSafety -> Bool
forall a. Ord a => a -> a -> Bool
>= KernelSafety
SafetyFull) (CompilerM OpenCL () () -> CompilerM OpenCL () ())
-> CompilerM OpenCL () () -> CompilerM OpenCL () ()
forall a b. (a -> b) -> a -> b
$
    Stm -> CompilerM OpenCL () ()
forall op s. Stm -> CompilerM op s ()
GC.stm [C.cstm|ctx->failure_is_an_option = 1;|]
  where
    mkDims :: [Exp] -> (Exp, Exp, Exp)
mkDims [] = ([C.cexp|0|], [C.cexp|0|], [C.cexp|0|])
    mkDims [Exp
x] = (Exp
x, [C.cexp|1|], [C.cexp|1|])
    mkDims [Exp
x, Exp
y] = (Exp
x, Exp
y, [C.cexp|1|])
    mkDims (Exp
x : Exp
y : Exp
z : [Exp]
_) = (Exp
x, Exp
y, Exp
z)
    addExp :: a -> a -> Exp
addExp a
x a
y = [C.cexp|$exp:x + $exp:y|]
    alignExp :: a -> Exp
alignExp a
e = [C.cexp|$exp:e + ((8 - ($exp:e % 8)) % 8)|]
    mkOffsets :: [VName] -> [Exp]
mkOffsets = (Exp -> VName -> Exp) -> Exp -> [VName] -> [Exp]
forall b a. (b -> a -> b) -> b -> [a] -> [b]
scanl (\Exp
a VName
b -> Exp
a Exp -> Exp -> Exp
forall a a. (ToExp a, ToExp a) => a -> a -> Exp
`addExp` VName -> Exp
forall a. ToExp a => a -> Exp
alignExp VName
b) [C.cexp|0|]
    expNotZero :: a -> Exp
expNotZero a
e = [C.cexp|$exp:e != 0|]
    expAnd :: a -> a -> Exp
expAnd a
a a
b = [C.cexp|$exp:a && $exp:b|]
    expsNotZero :: [Exp] -> Exp
expsNotZero = (Exp -> Exp -> Exp) -> Exp -> [Exp] -> Exp
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl Exp -> Exp -> Exp
forall a a. (ToExp a, ToExp a) => a -> a -> Exp
expAnd [C.cexp|1|] ([Exp] -> Exp) -> ([Exp] -> [Exp]) -> [Exp] -> Exp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Exp -> Exp) -> [Exp] -> [Exp]
forall a b. (a -> b) -> [a] -> [b]
map Exp -> Exp
forall a. ToExp a => a -> Exp
expNotZero
    mkArgs :: KernelArg -> CompilerM op s (VName, Maybe (VName, VName))
mkArgs (ValueKArg Exp
e t :: PrimType
t@(FloatType FloatType
Float16)) = do
      VName
arg <- SpaceId -> CompilerM op s VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"kernel_arg"
      Exp
e' <- Exp -> CompilerM op s Exp
forall op s. Exp -> CompilerM op s Exp
GC.compileExp Exp
e
      BlockItem -> CompilerM op s ()
forall op s. BlockItem -> CompilerM op s ()
GC.item [C.citem|$ty:(primStorageType t) $id:arg = $exp:(toStorage t e');|]
      (VName, Maybe (VName, VName))
-> CompilerM op s (VName, Maybe (VName, VName))
forall (f :: * -> *) a. Applicative f => a -> f a
pure (VName
arg, Maybe (VName, VName)
forall a. Maybe a
Nothing)
    mkArgs (ValueKArg Exp
e PrimType
t) =
      (,Maybe (VName, VName)
forall a. Maybe a
Nothing) (VName -> (VName, Maybe (VName, VName)))
-> CompilerM op s VName
-> CompilerM op s (VName, Maybe (VName, VName))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SpaceId -> PrimType -> Exp -> CompilerM op s VName
forall op s. SpaceId -> PrimType -> Exp -> CompilerM op s VName
GC.compileExpToName SpaceId
"kernel_arg" PrimType
t Exp
e
    mkArgs (MemKArg VName
v) = do
      Exp
v' <- VName -> CompilerM op s Exp
forall op s. VName -> CompilerM op s Exp
GC.rawMem VName
v
      VName
arg <- SpaceId -> CompilerM op s VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"kernel_arg"
      InitGroup -> CompilerM op s ()
forall op s. InitGroup -> CompilerM op s ()
GC.decl [C.cdecl|typename CUdeviceptr $id:arg = $exp:v';|]
      (VName, Maybe (VName, VName))
-> CompilerM op s (VName, Maybe (VName, VName))
forall (f :: * -> *) a. Applicative f => a -> f a
pure (VName
arg, Maybe (VName, VName)
forall a. Maybe a
Nothing)
    mkArgs (SharedMemoryKArg (Count Exp
c)) = do
      Exp
num_bytes <- Exp -> CompilerM op s Exp
forall op s. Exp -> CompilerM op s Exp
GC.compileExp Exp
c
      VName
size <- SpaceId -> CompilerM op s VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"shared_size"
      VName
offset <- SpaceId -> CompilerM op s VName
forall (m :: * -> *). MonadFreshNames m => SpaceId -> m VName
newVName SpaceId
"shared_offset"
      InitGroup -> CompilerM op s ()
forall op s. InitGroup -> CompilerM op s ()
GC.decl [C.cdecl|unsigned int $id:size = $exp:num_bytes;|]
      (VName, Maybe (VName, VName))
-> CompilerM op s (VName, Maybe (VName, VName))
forall (f :: * -> *) a. Applicative f => a -> f a
pure (VName
offset, (VName, VName) -> Maybe (VName, VName)
forall a. a -> Maybe a
Just (VName
size, VName
offset))