ccgthreadvars.nim 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Thread var support for architectures that lack native support for
  10. ## thread local storage.
  11. # included from cgen.nim
  12. proc emulatedThreadVars(conf: ConfigRef): bool =
  13. result = {optThreads, optTlsEmulation} <= conf.globalOptions
  14. proc accessThreadLocalVar(p: BProc, s: PSym) =
  15. if emulatedThreadVars(p.config) and threadVarAccessed notin p.flags:
  16. p.flags.incl threadVarAccessed
  17. incl p.module.flags, usesThreadVars
  18. p.procSec(cpsLocals).addf("\tNimThreadVars* NimTV_;$n", [])
  19. p.procSec(cpsInit).add(
  20. ropecg(p.module, "\tNimTV_ = (NimThreadVars*) #GetThreadLocalVars();$n", []))
  21. proc declareThreadVar(m: BModule, s: PSym, isExtern: bool) =
  22. if emulatedThreadVars(m.config):
  23. # we gather all thread locals var into a struct; we need to allocate
  24. # storage for that somehow, can't use the thread local storage
  25. # allocator for it :-(
  26. if not containsOrIncl(m.g.nimtvDeclared, s.id):
  27. m.g.nimtvDeps.add(s.loc.t)
  28. m.g.nimtv.addf("$1 $2;$n", [getTypeDesc(m, s.loc.t), s.loc.r])
  29. else:
  30. if isExtern: m.s[cfsVars].add("extern ")
  31. elif lfExportLib in s.loc.flags: m.s[cfsVars].add("N_LIB_EXPORT_VAR ")
  32. else: m.s[cfsVars].add("N_LIB_PRIVATE ")
  33. if optThreads in m.config.globalOptions:
  34. let sym = s.typ.sym
  35. if sym != nil and sfCppNonPod in sym.flags:
  36. m.s[cfsVars].add("NIM_THREAD_LOCAL ")
  37. else: m.s[cfsVars].add("NIM_THREADVAR ")
  38. m.s[cfsVars].add(getTypeDesc(m, s.loc.t))
  39. m.s[cfsVars].addf(" $1;$n", [s.loc.r])
  40. proc generateThreadLocalStorage(m: BModule) =
  41. if m.g.nimtv != "" and (usesThreadVars in m.flags or sfMainModule in m.module.flags):
  42. for t in items(m.g.nimtvDeps): discard getTypeDesc(m, t)
  43. finishTypeDescriptions(m)
  44. m.s[cfsSeqTypes].addf("typedef struct {$1} NimThreadVars;$n", [m.g.nimtv])
  45. proc generateThreadVarsSize(m: BModule) =
  46. if m.g.nimtv != "":
  47. let externc = if m.config.backend == backendCpp or
  48. sfCompileToCpp in m.module.flags: "extern \"C\" "
  49. else: ""
  50. m.s[cfsProcs].addf(
  51. "$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n",
  52. [externc.rope])