Skip to content

Commit

Permalink
Add volatile load/store
Browse files Browse the repository at this point in the history
Adds volatile load/store capability to the impure part of the standard
library.  This makes use of two new C macros stored in the nimbase.h
file and some macro trickery to perform type checking on the nim side.
Note that this currently only supports numerical types.

Should resolve nim-lang#3382
  • Loading branch information
Jeff-Ciesielski committed Jan 23, 2017
1 parent b85898c commit 84c1222
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
49 changes: 49 additions & 0 deletions lib/impure/volatile.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#
#
# Nim's Runtime Library
# (c) Copyright 2017 Jeff Ciesielski
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
import strutils
import macros

# Keeps track of the total number of casts in the module (used to
# generate unique function names used for aliasing)
var totalCasts {.compiletime.} = 0

const
vStoreDecl = """
proc volatileStore_$1(dest: ptr $2, val: $2) {.importc: "VSTORE", nodecl.}
volatileStore_$1
"""
vLoadDecl = """
proc volatileLoad_$1(s: ptr $2): $2 {.importc: "VLOAD", nodecl.}
volatileLoad_$1
"""

macro genVolatileStore(varType: string): untyped =
result = parseStmt(vStoreDecl.format(`totalCasts`, varType))
totalCasts += 1

template volatileStore*[T: SomeNumber](dest: ptr T, val: T) =
## Generates a volatile store into the container `dest` of the value
## `val`. Note that this only effects code generation on `C` like
## backends
when defined(js):
dest[] = val
else:
genVolatileStore(T.name)(dest, val)

macro genVolatileLoad(varType: string): untyped =
result = parseStmt(vLoadDecl.format(`totalCasts`, varType))
totalCasts += 1

template volatileLoad*[T: SomeNumber](src: ptr T): T =
## Generates a volatile load of the value stored in the container `src`.
## Note that this only effects code generation on `C` like backends
when defined(js):
src[]
else:
genVolatileLoad(T.name)(src)
4 changes: 4 additions & 0 deletions lib/nimbase.h
Original file line number Diff line number Diff line change
Expand Up @@ -463,3 +463,7 @@ typedef int Nim_and_C_compiler_disagree_on_target_architecture[sizeof(NI) == siz
/* Compile with -d:checkAbi and a sufficiently C11:ish compiler to enable */
#define NIM_CHECK_SIZE(typ, sz) \
_Static_assert(sizeof(typ) == sz, "Nim & C disagree on type size")

/* ---------------- Volatile Load/Store casts ----------------------- */
#define VLOAD(x) *(typeof(*x) volatile *)(x)
#define VSTORE(x, y) *(typeof(*x) *)(x) = (y)

0 comments on commit 84c1222

Please sign in to comment.