MuCtx.scala 25.8 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1 2 3 4 5 6 7 8 9 10 11 12 13
package uvm.refimpl

import java.io.Reader
import java.nio.charset.Charset

import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.HashSet

import org.slf4j.LoggerFactory

import com.typesafe.scalalogging.Logger

import uvm._
14
import uvm.ir.irbuilder.IRBuilder
Kunshan Wang's avatar
Kunshan Wang committed
15 16 17 18 19
import uvm.refimpl.itpr._
import uvm.refimpl.mem._
import uvm.refimpl.mem.TypeSizes._
import uvm.ssavariables._
import uvm.ssavariables.AtomicRMWOptr._
20
import uvm.ssavariables.HasKeepaliveClause
Kunshan Wang's avatar
Kunshan Wang committed
21 22
import uvm.ssavariables.MemoryOrder._
import uvm.types._
Kunshan Wang's avatar
Kunshan Wang committed
23 24
import uvm.refimpl.bootimg.FieldAndSymbol
import uvm.refimpl.bootimg.PrimordialInfo
Kunshan Wang's avatar
Kunshan Wang committed
25 26 27 28 29 30 31 32 33 34 35

object MuCtx {
  val logger = Logger(LoggerFactory.getLogger(getClass.getName))

  val US_ASCII = Charset.forName("US-ASCII")
}

/**
 * A client context. The main part of the API. It keeps thread-local states, including a set of handles. It provides
 * operations on the Mu VM.
 */
36
class MuCtx(val ctxID: MuInternalID, _mutator: Mutator)(
Kunshan Wang's avatar
Kunshan Wang committed
37
  implicit protected val microVM: MicroVM, memorySupport: MemorySupport)
Kunshan Wang's avatar
Kunshan Wang committed
38
    extends ObjectPinner with AutoCloseable {
39 40 41
  
  private val predefinedEntities = microVM.staticAnalyzer.predefinedEntities
  private val internalEntityPool = microVM.staticAnalyzer.internalEntityPool
Kunshan Wang's avatar
Kunshan Wang committed
42 43 44 45 46 47 48 49

  implicit def mutator = _mutator

  val handles = new HashSet[MuValue]()

  val pinSet = new ArrayBuffer[Word]

  /** Given a name, get the ID of an identified entity. */
Kunshan Wang's avatar
Kunshan Wang committed
50
  def idOf(name: MuName): MuID = microVM.idOf(name)
Kunshan Wang's avatar
Kunshan Wang committed
51 52

  /** Given an ID, get the name of an identified entity. */
Kunshan Wang's avatar
Kunshan Wang committed
53
  def nameOf(id: MuID): MuName = microVM.nameOf(id)
Kunshan Wang's avatar
Kunshan Wang committed
54 55 56 57 58 59 60

  /** Close the context. */
  def closeContext(): Unit = {
    handles.clear()
    mutator.close()
    microVM.contexts.remove(this)
  }
Kunshan Wang's avatar
Kunshan Wang committed
61

62 63
  /** Synonym of closeContext, for AutoCloseable. */
  override def close(): Unit = closeContext()
Kunshan Wang's avatar
Kunshan Wang committed
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

  /** Load a Mu IR bundle */
  def loadBundle(r: Reader): Unit = {
    MetaOperations.loadBundle(r)
  }

  /** Load a Mu IR bundle */
  def loadBundle(s: String): Unit = {
    MetaOperations.loadBundle(s)
  }

  /** Load a HAIL script */
  def loadHail(r: Reader): Unit = {
    MetaOperations.loadHail(r)
  }

  /** Load a HAIL script */
  def loadHail(s: String): Unit = {
    MetaOperations.loadHail(s)
  }

  protected def addHandle[T <: MuValue](h: T): T = {
    handles.add(h)
    h
  }

  /** Convert any int (BigInt) to a handle. */
  def handleFromInt(num: BigInt, len: Int): MuIntValue = {
92
    val t = internalEntityPool.intOf(len)
Kunshan Wang's avatar
Kunshan Wang committed
93 94 95 96 97 98
    val v = OpHelper.unprepare(num, len)
    addHandle(MuIntValue(t, BoxInt(v)))
  }

  /** Convert float to a handle. */
  def handleFromFloat(num: Float): MuFloatValue = {
99
    val t = predefinedEntities.FLOAT
Kunshan Wang's avatar
Kunshan Wang committed
100 101 102 103 104
    addHandle(MuFloatValue(t, BoxFloat(num)))
  }

  /** Convert double to a handle. */
  def handleFromDouble(num: Double): MuDoubleValue = {
105
    val t = predefinedEntities.DOUBLE
Kunshan Wang's avatar
Kunshan Wang committed
106 107 108 109
    addHandle(MuDoubleValue(t, BoxDouble(num)))
  }

  /** Convert pointer (Long) to a handle. */
Kunshan Wang's avatar
Kunshan Wang committed
110
  def handleFromPtr(muType: MuID, v: Word): MuUPtrValue = {
Kunshan Wang's avatar
Kunshan Wang committed
111 112 113 114 115
    val t = microVM.globalBundle.typeNs(muType).asInstanceOf[TypeUPtr]
    addHandle(MuUPtrValue(t, BoxPointer(v)))
  }

  /** Convert function pointer (Long) to a handle. */
Kunshan Wang's avatar
Kunshan Wang committed
116
  def handleFromFP(muType: MuID, v: Word): MuUFPValue = {
Kunshan Wang's avatar
Kunshan Wang committed
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
    val t = microVM.globalBundle.typeNs(muType).asInstanceOf[TypeUFuncPtr]
    addHandle(MuUFPValue(t, BoxPointer(v)))
  }

  /** Convert handle to an integer (BigInt). */
  def handleToInt(opnd: MuIntValue, signExt: Boolean): BigInt = {
    val t = opnd.ty
    val ib = opnd.vb
    if (signExt) OpHelper.prepareSigned(ib.value, t.length) else OpHelper.prepareUnsigned(ib.value, t.length)
  }

  /** Convert handle to integer (BigInt), assume signed. */
  def handleToSInt(opnd: MuIntValue) = handleToInt(opnd, true)

  /** Convert handle to integer (BigInt), assume unsigned. */
  def handleToUInt(opnd: MuIntValue) = handleToInt(opnd, false)

  /** Convert handle to float. */
  def handleToFloat(opnd: MuFloatValue): Float = {
    opnd.vb.value
  }

  /** Convert handle to double. */
  def handleToDouble(opnd: MuDoubleValue): Double = {
    opnd.vb.value
  }

  /** Convert handle to pointer (Long). */
  def handleToPtr(opnd: MuUPtrValue): Word = {
    opnd.vb.addr
  }

  /** Convert handle to function pointer (Long). */
  def handleToFP(opnd: MuUFPValue): Word = {
    opnd.vb.addr
  }

  /** Make a handle for a constant. */
Kunshan Wang's avatar
Kunshan Wang committed
155
  def handleFromConst(id: MuID): MuValue = {
Kunshan Wang's avatar
Kunshan Wang committed
156 157 158 159 160 161 162
    val c = microVM.globalBundle.constantNs(id)
    val t = c.constTy
    val box = microVM.constantPool.getGlobalVarBox(c)
    addHandle(MuValue(t, box))
  }

  /** Make a handle for a global cell (its iref). */
Kunshan Wang's avatar
Kunshan Wang committed
163
  def handleFromGlobal(id: MuID): MuIRefValue = {
Kunshan Wang's avatar
Kunshan Wang committed
164
    val g = microVM.globalBundle.globalCellNs(id)
165
    val t = internalEntityPool.irefOf(g.cellTy)
Kunshan Wang's avatar
Kunshan Wang committed
166 167 168 169 170 171
    val a = microVM.memoryManager.globalMemory.addrForGlobalCell(g)
    val box = BoxIRef(0L, a)
    addHandle(MuIRefValue(t, box))
  }

  /** Make a handle for a function (funcref). */
Kunshan Wang's avatar
Kunshan Wang committed
172
  def handleFromFunc(id: MuID): MuFuncRefValue = {
Kunshan Wang's avatar
Kunshan Wang committed
173
    val f = microVM.globalBundle.funcNs(id)
174
    val t = internalEntityPool.funcOf(f.sig)
Kunshan Wang's avatar
Kunshan Wang committed
175 176 177 178 179 180 181 182
    val box = BoxFunc(Some(f))
    addHandle(MuFuncRefValue(t, box))
  }

  /**
   * Make a handle for an exposed function. In this implementation, the type is ufuncptr, but other implementations
   * may be different.
   */
Kunshan Wang's avatar
Kunshan Wang committed
183
  def handleFromExpose(id: MuID): MuUFPValue = {
Kunshan Wang's avatar
Kunshan Wang committed
184
    val ef = microVM.globalBundle.expFuncNs(id)
185
    val t = internalEntityPool.funcPtrOf(ef.func.sig)
Kunshan Wang's avatar
Kunshan Wang committed
186 187 188 189 190 191 192 193 194 195 196
    val box = BoxPointer(microVM.nativeCallHelper.getStaticExpFuncAddr(ef))
    addHandle(MuUFPValue(t, box))
  }

  /** Delete a handle. */
  def deleteValue(opnd: MuValue): Unit = {
    handles.remove(opnd)
  }

  /** Compare general reference types for equality. */
  def refEq(lhs: MuGenRefValue, rhs: MuGenRefValue): Boolean = (lhs, rhs) match {
Kunshan Wang's avatar
Kunshan Wang committed
197 198 199
    case (l: MuRefValue, r: MuRefValue)                   => l.vb.objRef == r.vb.objRef
    case (l: MuIRefValue, r: MuIRefValue)                 => l.vb.oo == r.vb.oo
    case (l: MuOpaqueRefValue[_], r: MuOpaqueRefValue[_]) => l.vb.obj == r.vb.obj
Kunshan Wang's avatar
Kunshan Wang committed
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
    case (l, r) => {
      throw new IllegalArgumentException("Bad types for refEq: %s and %s".format(
        l.showTy, r.showTy))
    }
  }

  /** Compare general reference types for less-than. */
  def refUlt(lhs: MuIRefValue, rhs: MuIRefValue): Boolean = {
    if (lhs.vb.objRef != rhs.vb.objRef) {
      val (lb, lo) = lhs.vb.oo
      val (rb, ro) = rhs.vb.oo
      throw new UvmRefImplException(("Two operands refer to different objects. This is an undefined behaviour. " +
        "lhs: %d+%d (0x%x+0x%x); rhs: %d+%d (0x%x+0x%x)".format(lb, lo, lb, lo, rb, ro, rb, ro)))
    }
    lhs.vb.offset < rhs.vb.offset
  }

  /** Get the value of a field of a struct value. */
  def extractValue(str: MuStructValue, index: Int): MuValue = {
    val st = str.ty
    val sb = str.vb
    val ft = st.fieldTys(index)
    val fb = sb.values(index)
    addHandle(MuValue(ft, fb))
  }

  /** Copy a struct value, replacing one of its fields. */
  def insertValue(str: MuStructValue, index: Int, newval: MuValue): MuStructValue = {
    val st = str.ty
    val sb = str.vb
    val nsb = BoxSeq(for ((b, i) <- sb.values.zipWithIndex) yield if (i == index) newval.vb else b)
    addHandle(MuStructValue(st, nsb))
  }

  /** Get the value of an element of an array or value. */
  def extractElement[T <: MuSeqValue](seq: T, index: MuIntValue): MuValue = {
    val indexVal = handleToUInt(index).toInt

    val et = seq.ty.elemTy
    val eb = seq.vb.values(indexVal)
    addHandle(MuValue(et, eb))
  }

  /** Copy an array or vector value, replacing one of its elements. */
  def insertElement[T <: MuSeqValue](seq: T, index: MuIntValue, newval: MuValue): T = {
    val indexVal = handleToUInt(index).toInt

    val st = seq.ty
    val sb = seq.vb
    val nsb = BoxSeq(for ((b, i) <- sb.values.zipWithIndex) yield if (i == indexVal) newval.vb else b)
    addHandle(MuValue(st, nsb).asInstanceOf[T])
  }

  /** Allocate a fixed object in the heap. */
Kunshan Wang's avatar
Kunshan Wang committed
254
  def newFixed(muType: MuID): MuRefValue = {
Kunshan Wang's avatar
Kunshan Wang committed
255 256 257
    val t = microVM.globalBundle.typeNs(muType)
    val objRef = mutator.newScalar(t)
    val b = BoxRef(objRef)
258
    val rt = internalEntityPool.refOf(t)
Kunshan Wang's avatar
Kunshan Wang committed
259 260 261 262
    addHandle(MuRefValue(rt, b))
  }

  /** Allocate a hybrid object in the heap. */
Kunshan Wang's avatar
Kunshan Wang committed
263
  def newHybrid(tid: MuID, length: MuIntValue): MuRefValue = {
Kunshan Wang's avatar
Kunshan Wang committed
264 265 266 267
    val t = microVM.globalBundle.typeNs(tid).asInstanceOf[TypeHybrid]
    val len = handleToUInt(length).longValue
    val objRef = mutator.newHybrid(t, len)
    val b = BoxRef(objRef)
268
    val rt = internalEntityPool.refOf(t)
Kunshan Wang's avatar
Kunshan Wang committed
269 270 271 272
    addHandle(MuRefValue(rt, b))
  }

  /** Cast between two refs, two irefs or two funcrefs */
Kunshan Wang's avatar
Kunshan Wang committed
273
  def refcast[T <: MuGenRefValue](opnd: T, newType: MuID): T = {
Kunshan Wang's avatar
Kunshan Wang committed
274 275 276
    val nt = microVM.globalBundle.typeNs(newType)

    val nh = (opnd, nt) match {
Kunshan Wang's avatar
Kunshan Wang committed
277 278
      case (MuRefValue(ty, vb), ty2 @ TypeRef(_))   => MuRefValue(ty2, vb)
      case (MuIRefValue(ty, vb), ty2 @ TypeIRef(_)) => MuIRefValue(ty2, vb)
Kunshan Wang's avatar
Kunshan Wang committed
279 280
      case (MuOpaqueRefValue(ty, vb), ty2 @ TypeFuncRef(_)) => {
        require(ty.isInstanceOf[TypeFuncRef] && vb.isInstanceOf[BoxOpaque[_]],
Kunshan Wang's avatar
Kunshan Wang committed
281
          "Attempt to cast %s to funcref. funcref value required".format(opnd.showTy))
Kunshan Wang's avatar
Kunshan Wang committed
282 283
        MuFuncRefValue(ty2, vb.asInstanceOf[BoxFunc])
      }
Kunshan Wang's avatar
Kunshan Wang committed
284 285 286 287 288 289 290 291 292 293 294
      case _ => {
        throw new IllegalArgumentException("Bad types for refcast: opnd:%s, newType:%s".format(
          opnd.showTy, nt.repr))
      }
    }

    addHandle(nh.asInstanceOf[T])
  }

  /** Convert ref to iref */
  def getIRef(opnd: MuRefValue): MuIRefValue = {
295
    val nt = internalEntityPool.irefOf(opnd.ty.ty)
Kunshan Wang's avatar
Kunshan Wang committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309
    val nb = BoxIRef(opnd.vb.objRef, 0L)
    addHandle(MuIRefValue(nt, nb))
  }

  /** Get the iref to a field of a struct or hybrid location */
  def getFieldIRef(opnd: MuIRefValue, field: Int): MuIRefValue = {
    val st = try {
      opnd.ty.ty.asInstanceOf[AbstractStructType]
    } catch {
      case e: ClassCastException => throw new IllegalArgumentException(
        "opnd must refer to a struct or hybrid location. Actual referenct type: %s".format(opnd.ty.ty.repr), e)
    }

    val ft = st.fieldTys(field)
310
    val nt = internalEntityPool.irefOf(ft)
Kunshan Wang's avatar
Kunshan Wang committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    val ob = opnd.vb
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.fieldOffsetOf(st, field))
    addHandle(MuIRefValue(nt, nb))
  }

  /** Get the iref to an element of an array or vector location. */
  def getElemIRef(opnd: MuIRefValue, index: MuIntValue): MuIRefValue = {
    val st = try {
      opnd.ty.ty.asInstanceOf[AbstractSeqType]
    } catch {
      case e: ClassCastException => throw new IllegalArgumentException(
        "opnd must refer to an array or vector location. Actual referenct type: %s".format(opnd.ty.ty.repr), e)
    }
    val i = handleToUInt(index).longValue
    val et = st.elemTy
326
    val nt = internalEntityPool.irefOf(et)
Kunshan Wang's avatar
Kunshan Wang committed
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
    val ob = opnd.vb
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.elemOffsetOf(st, i))
    addHandle(MuIRefValue(nt, nb))
  }

  /** Shift an iref to an array element by offset elements. */
  def shiftIRef(opnd: MuIRefValue, offset: MuIntValue): MuIRefValue = {
    val ot = opnd.ty
    val ob = opnd.vb
    val rt = ot.ty
    val nt = ot
    val off = handleToSInt(offset).longValue
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.shiftOffsetOf(rt, off))
    addHandle(MuIRefValue(nt, nb))
  }

  /** Get the iref to the 0-th element of the variable part of a hybrid location. */
  def getVarPartIRef(opnd: MuIRefValue): MuIRefValue = {
    val ht = try {
      opnd.ty.ty.asInstanceOf[TypeHybrid]
    } catch {
      case e: ClassCastException => throw new IllegalArgumentException(
        "opnd must refer to a hybrid location. Actual referenct type: %s".format(opnd.ty.ty.repr), e)
    }
    val vt = ht.varTy
352
    val nt = internalEntityPool.irefOf(vt)
Kunshan Wang's avatar
Kunshan Wang committed
353 354 355 356 357 358 359 360 361 362 363
    val ob = opnd.vb
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.varPartOffsetOf(ht))
    addHandle(MuIRefValue(nt, nb))
  }

  /** Load from a location. */
  def load(ord: MemoryOrder, loc: MuIRefValue): MuValue = {
    val (ptr, ty) = loc.ty match {
      case TypeIRef(t) => (false, t)
    }

364
    val uty = internalEntityPool.unmarkedOf(ty)
Kunshan Wang's avatar
Kunshan Wang committed
365 366 367 368 369
    val addr = MemoryOperations.addressOf(ptr, loc.vb)
    val nb = ValueBox.makeBoxForType(uty)

    MemoryOperations.load(ptr, uty, addr, nb)

370 371
    print("Loading: " + nb + "\n")

Kunshan Wang's avatar
Kunshan Wang committed
372 373 374 375 376
    addHandle(MuValue(uty, nb))
  }

  /** Store to a location. */
  def store(ord: MemoryOrder, loc: MuIRefValue, newVal: MuValue): Unit = {
377
    print("Storing: " + newVal + "\n")
Kunshan Wang's avatar
Kunshan Wang committed
378 379 380
    val (ptr, ty) = loc.ty match {
      case TypeIRef(t) => (false, t)
    }
381
    val uty = internalEntityPool.unmarkedOf(ty)
Kunshan Wang's avatar
Kunshan Wang committed
382 383 384 385 386 387 388 389 390 391 392 393
    val addr = MemoryOperations.addressOf(ptr, loc.vb)
    val nvb = newVal.vb

    MemoryOperations.store(ptr, uty, addr, nvb)
  }

  /** Perform compare exchange on a location. */
  def cmpXchg(ordSucc: MemoryOrder, ordFail: MemoryOrder, weak: Boolean,
    loc: MuIRefValue, expected: MuValue, desired: MuValue): (MuValue, Boolean) = {
    val (ptr, ty) = loc.ty match {
      case TypeIRef(t) => (false, t)
    }
394
    val uty = internalEntityPool.unmarkedOf(ty)
Kunshan Wang's avatar
Kunshan Wang committed
395 396 397 398 399 400 401 402 403 404 405 406 407
    val addr = MemoryOperations.addressOf(ptr, loc.vb)
    val eb = expected.vb
    val db = desired.vb
    val br = ValueBox.makeBoxForType(uty)
    val succ = MemoryOperations.cmpXchg(ptr, uty, addr, eb, db, br)
    (addHandle(MuValue(uty, br)), succ)
  }

  /** Perform an atomic read-modify-write operation on a location. */
  def atomicRMW(ord: MemoryOrder, op: AtomicRMWOptr, loc: MuIRefValue, opnd: MuValue): MuValue = {
    val (ptr, ty) = loc.ty match {
      case TypeIRef(t) => (false, t)
    }
408
    val uty = internalEntityPool.unmarkedOf(ty)
Kunshan Wang's avatar
Kunshan Wang committed
409 410 411 412 413 414 415 416 417 418 419 420 421 422
    val addr = MemoryOperations.addressOf(ptr, loc.vb)
    val ob = opnd.vb
    val br = ValueBox.makeBoxForType(uty)
    MemoryOperations.atomicRMW(ptr, uty, op, addr, ob, br)
    addHandle(MuValue(uty, br))
  }

  /** Memory fence */
  def fence(ord: MemoryOrder): Unit = {
    // No-op
  }

  /** Create a Mu stack with fa stack-bottom function */
  def newStack(func: MuFuncRefValue): MuStackRefValue = {
Kunshan Wang's avatar
Kunshan Wang committed
423
    val funcVal = func.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
424 425 426 427 428 429
      throw new UvmRuntimeException("Stack-bottom function must not be NULL")
    }

    val sta = microVM.threadStackManager.newStack(funcVal, mutator)

    val nb = BoxStack(Some(sta))
430
    addHandle(MuStackRefValue(predefinedEntities.STACKREF, nb))
Kunshan Wang's avatar
Kunshan Wang committed
431 432 433
  }

  private def getStackNotNull(stack: MuStackRefValue): InterpreterStack = {
Kunshan Wang's avatar
Kunshan Wang committed
434
    stack.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
435 436 437 438 439
      throw new UvmRuntimeException("Stack argument cannot be a NULL stackref value.")
    }
  }

  private def getThreadNotNull(thread: MuThreadRefValue): InterpreterThread = {
Kunshan Wang's avatar
Kunshan Wang committed
440
    thread.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
      throw new UvmRuntimeException("Thread argument cannot be a NULL threadref value.")
    }
  }

  /** Create a Mu thread and bind it to a Mu stack. */
  def newThread(stack: MuStackRefValue, threadLocal: Option[MuRefValue], htr: HowToResume): MuThreadRefValue = {
    val sv = getStackNotNull(stack)
    val itprHtr = htr match {
      case HowToResume.PassValues(values) => itpr.HowToResume.PassValues(values.map(_.vb))
      case HowToResume.ThrowExc(exc)      => itpr.HowToResume.ThrowExc(exc.vb.objRef)
    }

    val threadLocalAddr = threadLocal.map(tl => tl.vb.objRef).getOrElse(0L)
    val thr = microVM.threadStackManager.newThread(sv, threadLocalAddr, itprHtr)

    val nb = BoxThread(Some(thr))
457
    addHandle(MuThreadRefValue(predefinedEntities.THREADREF, nb))
Kunshan Wang's avatar
Kunshan Wang committed
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  }

  /** Kill a Mu stack. */
  def killStack(stack: MuStackRefValue): Unit = {
    val sv = getStackNotNull(stack)

    sv.kill()
  }

  /** Set the thread-local object reference */
  def setThreadlocal(thread: MuThreadRefValue, threadLocal: MuRefValue): Unit = {
    val th = getThreadNotNull(thread)
    val threadLocalAddr = threadLocal.vb.objRef

    th.threadLocal.objRef = threadLocalAddr
  }

  /** Get the thread-local object reference */
  def getThreadlocal(thread: MuThreadRefValue): MuRefValue = {
    val th = getThreadNotNull(thread)
    val threadLocalAddr = th.threadLocal.objRef

    val nb = BoxRef(threadLocalAddr)
481
    addHandle(MuRefValue(predefinedEntities.REF_VOID, nb))
Kunshan Wang's avatar
Kunshan Wang committed
482 483 484
  }

  private def getCursorNotNull(cursor: MuFCRefValue): FrameCursor = {
Kunshan Wang's avatar
Kunshan Wang committed
485
    cursor.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
486 487 488 489 490 491 492 493 494
      throw new UvmRuntimeException("Frame cursor argument cannot be a NULL framecursorref value.")
    }
  }

  /** Create a frame cursor. */
  def newCursor(stack: MuStackRefValue): MuFCRefValue = {
    val s = getStackNotNull(stack)
    val c = microVM.threadStackManager.newFrameCursor(s)
    val nb = BoxFrameCursor(Some(c))
495
    addHandle(MuFCRefValue(predefinedEntities.FRAMECURSORREF, nb))
Kunshan Wang's avatar
Kunshan Wang committed
496 497 498 499 500 501 502 503 504 505 506 507
  }

  /** Move cursor to the frame below the current frame. */
  def nextFrame(cursor: MuFCRefValue): Unit = {
    getCursorNotNull(cursor).nextFrame()
  }

  /** Copy a frame cursor. */
  def copyCursor(cursor: MuFCRefValue): MuFCRefValue = {
    val c = getCursorNotNull(cursor)
    val nc = microVM.threadStackManager.copyCursor(c)
    val nb = BoxFrameCursor(Some(nc))
508
    addHandle(MuFCRefValue(predefinedEntities.FRAMECURSORREF, nb))
Kunshan Wang's avatar
Kunshan Wang committed
509 510 511 512 513 514 515 516 517
  }

  /** Close a frame cursor. */
  def closeCursor(cursor: MuFCRefValue): Unit = {
    val c = getCursorNotNull(cursor)
    microVM.threadStackManager.closeCursor(c)
  }

  /** Get the ID of the current function of a frame. Return 0 for native frames. */
Kunshan Wang's avatar
Kunshan Wang committed
518
  def curFunc(cursor: MuFCRefValue): MuID = {
Kunshan Wang's avatar
Kunshan Wang committed
519 520 521 522 523 524 525 526
    val c = getCursorNotNull(cursor)
    c.frame.curFuncID
  }

  /**
   * Get the ID of the current function version of a frame. Return 0 for native frames
   *  or Mu frames of undefined functions
   */
Kunshan Wang's avatar
Kunshan Wang committed
527
  def curFuncVer(cursor: MuFCRefValue): MuID = {
Kunshan Wang's avatar
Kunshan Wang committed
528 529 530 531 532 533 534 535
    val c = getCursorNotNull(cursor)
    c.frame.curFuncVerID
  }

  /**
   * Get the ID of the current instruction of a frame. Return 0 for native frames, Mu frames for undefined
   *  functions, or if the frame is just created by newStack or pushFrame.
   */
Kunshan Wang's avatar
Kunshan Wang committed
536
  def curInst(cursor: MuFCRefValue): MuID = {
Kunshan Wang's avatar
Kunshan Wang committed
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    val c = getCursorNotNull(cursor)
    c.frame.curInstID
  }

  /** Dump keep-alive variables of the current instruction. */
  def dumpKeepalives(cursor: MuFCRefValue): Seq[MuValue] = {
    val c = getCursorNotNull(cursor)
    val fr = c.frame
    fr match {
      case f: NativeFrame => {
        throw new UvmRefImplException("Attempt to dump keepalives from a native frame. Funciton 0x%x".format(f.func))
      }
      case f: UndefinedMuFrame => {
        for ((ty, box) <- f.func.sig.paramTys zip f.boxes) yield {
          addHandle(MuValue(ty, box))
        }
      }
      case f: DefinedMuFrame => {
        val i = f.curInst
        i match {
557 558
          case hkac: HasKeepaliveClause => {
            val kas = hkac.keepalives
Kunshan Wang's avatar
Kunshan Wang committed
559 560
            for (ka <- kas) yield {
              val box = f.boxes(ka)
561
              val ty = ka.inferredType
Kunshan Wang's avatar
Kunshan Wang committed
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
              addHandle(MuValue(ty, box))
            }
          }
          case _ => {
            throw new UvmRuntimeException("The current instruction %s does not have keep-alive clause.".format(i.repr))
          }
        }
      }
    }
  }

  /** Pop the top frame of a Mu stack. */
  def popFramesTo(cursor: MuFCRefValue): Unit = {
    val c = getCursorNotNull(cursor)

    c.stack.popFramesTo(c)
  }

  /** Create a new frame for a Mu function and push it to the top of a stack. */
581 582
  def pushFrame(cursor: MuFCRefValue, func: MuFuncRefValue): Unit = {
    val c = getCursorNotNull(cursor)
Kunshan Wang's avatar
Kunshan Wang committed
583

Kunshan Wang's avatar
Kunshan Wang committed
584
    val funcVal = func.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
585 586 587
      throw new UvmRuntimeException("Stack-bottom function must not be NULL")
    }

588
    val st = c.stack
Kunshan Wang's avatar
Kunshan Wang committed
589 590 591 592
    st.pushFrame(funcVal)
  }

  /** Test if a tagref64 holds a double. */
593 594
  def tr64IsFP(value: MuTagRef64Value): Boolean = {
    OpHelper.tr64IsFP(value.vb.raw)
Kunshan Wang's avatar
Kunshan Wang committed
595 596 597 598 599 600 601 602 603 604 605 606 607
  }

  /** Test if a tagref64 holds an int. */
  def tr64IsInt(value: MuTagRef64Value): Boolean = {
    OpHelper.tr64IsInt(value.vb.raw)
  }

  /** Test if a tagref64 holds a ref. */
  def tr64IsRef(value: MuTagRef64Value): Boolean = {
    OpHelper.tr64IsRef(value.vb.raw)
  }

  /** Extract the double held by a tagref64. */
608
  def tr64ToFP(value: MuTagRef64Value): MuDoubleValue = {
Kunshan Wang's avatar
Kunshan Wang committed
609
    val raw = value.vb.raw
610
    val box = new BoxDouble(OpHelper.tr64ToFP(raw))
611
    addHandle(MuDoubleValue(predefinedEntities.DOUBLE, box))
Kunshan Wang's avatar
Kunshan Wang committed
612 613 614 615 616 617
  }

  /** Extract the int held by a tagref64. */
  def tr64ToInt(value: MuTagRef64Value): MuIntValue = {
    val raw = value.vb.raw
    val box = new BoxInt(OpHelper.tr64ToInt(raw))
618
    addHandle(MuIntValue(predefinedEntities.I52, box))
Kunshan Wang's avatar
Kunshan Wang committed
619 620 621 622 623 624
  }

  /** Extract the object ref held by a tagref64. */
  def tr64ToRef(value: MuTagRef64Value): MuRefValue = {
    val raw = value.vb.raw
    val box = new BoxRef(OpHelper.tr64ToRef(raw))
625
    addHandle(MuRefValue(predefinedEntities.REF_VOID, box))
Kunshan Wang's avatar
Kunshan Wang committed
626 627 628 629 630 631
  }

  /** Extract the tag held by a tagref64. */
  def tr64ToTag(value: MuTagRef64Value): MuIntValue = {
    val raw = value.vb.raw
    val box = new BoxInt(OpHelper.tr64ToTag(raw))
632
    addHandle(MuIntValue(predefinedEntities.I6, box))
Kunshan Wang's avatar
Kunshan Wang committed
633 634 635
  }

  /** Convert a double to a tagref64. */
636
  def tr64FromFP(value: MuDoubleValue): MuTagRef64Value = {
Kunshan Wang's avatar
Kunshan Wang committed
637 638
    val fp = value.vb.value
    val box = new BoxTagRef64(OpHelper.fpToTr64(fp))
639
    addHandle(MuTagRef64Value(predefinedEntities.TAGREF64, box))
Kunshan Wang's avatar
Kunshan Wang committed
640 641 642 643 644 645 646
  }

  /** Convert an int to a tagref64. */
  def tr64FromInt(value: MuIntValue): MuTagRef64Value = {
    if (value.ty.length != 52) throw new IllegalArgumentException("Expect int<52>, found %s".format(value.ty.repr))
    val i = value.vb.value
    val box = new BoxTagRef64(OpHelper.intToTr64(i.longValue))
647
    addHandle(MuTagRef64Value(predefinedEntities.TAGREF64, box))
Kunshan Wang's avatar
Kunshan Wang committed
648 649 650 651 652 653 654 655
  }

  /** Convert an object ref and a tag to a tagref64. */
  def tr64FromRef(ref: MuRefValue, tag: MuIntValue): MuTagRef64Value = {
    if (tag.ty.length != 6) throw new IllegalArgumentException("Expect int<6> tag, found %s".format(tag.ty.repr))
    val refv = ref.vb.objRef
    val tagv = tag.vb.value
    val box = new BoxTagRef64(OpHelper.refToTr64(refv, tagv.longValue))
656
    addHandle(MuTagRef64Value(predefinedEntities.TAGREF64, box))
Kunshan Wang's avatar
Kunshan Wang committed
657 658
  }

Kunshan Wang's avatar
Kunshan Wang committed
659
  def enableWatchPoint(wpID: MuID): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
660 661 662
    microVM.trapManager.enableWatchPoint(wpID)
  }

Kunshan Wang's avatar
Kunshan Wang committed
663
  def disableWatchPoint(wpID: MuID): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
664 665 666 667 668 669 670 671 672 673 674 675
    microVM.trapManager.disableWatchPoint(wpID)
  }

  def pin(loc: MuValue): MuUPtrValue = {
    val (objTy, (objRef, offset)) = loc match {
      case MuRefValue(t, vb)  => (t, (vb.objRef, 0L))
      case MuIRefValue(t, vb) => (t, vb.oo)
      case _ => {
        throw new IllegalArgumentException("loc must be ref or iref. Found %s".format(loc.ty))
      }
    }
    pin(objRef)
676
    val ptrTy = internalEntityPool.ptrOf(objTy)
Kunshan Wang's avatar
Kunshan Wang committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690
    val box = new BoxPointer(objRef + offset)
    addHandle(MuUPtrValue(ptrTy, box))
  }

  def unpin(loc: MuValue): Unit = {
    val (objTy, objRef) = loc match {
      case MuRefValue(t, vb)  => (t, vb.objRef)
      case MuIRefValue(t, vb) => (t, vb.objRef)
      case _ => {
        throw new IllegalArgumentException("loc must be ref or iref. Found %s".format(loc.ty))
      }
    }
    unpin(objRef)
  }
Kunshan Wang's avatar
Kunshan Wang committed
691

692 693 694 695 696 697 698 699 700
  def getAddr(loc: MuValue): MuUPtrValue = {
    val (objTy, (objRef, offset)) = loc match {
      case MuRefValue(t, vb)  => (t, (vb.objRef, 0L))
      case MuIRefValue(t, vb) => (t, vb.oo)
      case _ => {
        throw new IllegalArgumentException("loc must be ref or iref. Found %s".format(loc.ty))
      }
    }
    // do nothing
Kunshan Wang's avatar
Kunshan Wang committed
701 702
    val addr = objRef + offset
    assert(microVM.memoryManager.globalMemory.isInSpace(addr) || pinSet.contains(objRef),
Kunshan Wang's avatar
Kunshan Wang committed
703 704
      "Attempt to get address of objref %d 0x%x, offset %d, 0x%x, which is neither a global cell nor pinned by the current thread.".format(
        objRef, objRef, offset, offset))
705
    val ptrTy = internalEntityPool.ptrOf(objTy)
Kunshan Wang's avatar
Kunshan Wang committed
706
    val box = new BoxPointer(addr)
707 708
    addHandle(MuUPtrValue(ptrTy, box))
  }
Kunshan Wang's avatar
Kunshan Wang committed
709 710 711

  def expose(func: MuFuncRefValue, callConv: Flag, cookie: MuIntValue): MuUFPValue = {
    val TypeFuncRef(sig) = func.ty
Kunshan Wang's avatar
Kunshan Wang committed
712
    val f = func.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
713 714 715 716 717 718
      throw new UvmRuntimeException("Attempt to expose NULL Mu function")
    }

    val c = cookie.vb.value.toLong

    val addr = microVM.nativeCallHelper.exposeFuncDynamic(f, c)
719
    addHandle(MuUFPValue(internalEntityPool.funcPtrOf(sig), BoxPointer(addr)))
Kunshan Wang's avatar
Kunshan Wang committed
720 721 722 723 724 725
  }

  def unexpose(callConv: Flag, addr: MuUFPValue): Unit = {
    val a = addr.vb.addr
    microVM.nativeCallHelper.unexposeFunc(a)
  }
Kunshan Wang's avatar
Kunshan Wang committed
726

Kunshan Wang's avatar
Kunshan Wang committed
727
  def newIRBuilder(): IRBuilder = {
728
    microVM.newIRBuilder()
Kunshan Wang's avatar
Kunshan Wang committed
729
  }
Kunshan Wang's avatar
Kunshan Wang committed
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

  def makeBootImage(whiteList: Seq[MuID],
    primordialFunc: Option[MuFuncRefValue], primordialStack: Option[MuStackRefValue], primordialThreadLocal: Option[MuRefValue],
    symFields: Seq[MuIRefValue], symStrings: Seq[String], relocFields: Seq[MuIRefValue], relocStrings: Seq[String],
    outputFile: String): Unit = {
    
    val whiteListObjs = whiteList.map(microVM.globalBundle.topLevelNs.apply)
    
    val maybePF = primordialFunc.flatMap(_.vb.obj)
    val maybePS = primordialStack.flatMap(_.vb.obj)
    val maybeTL = primordialThreadLocal.flatMap { h =>
      h.vb.objRef match {
        case 0 => None
        case a => Some(a)
      }
    }
    
    val primordial = PrimordialInfo(maybePF, maybePS, maybeTL)

    val symFlds = symFields.map { h => (h.vb.objRef, h.vb.offset) }
    val relocFlds = relocFields.map { h =>
      assert(h.ty.ty.isInstanceOf[AbstractPointerType], "Reloc field %d 0x%x is not a pointer field. field type: %s".format(
        h.vb.addr, h.vb.addr, h.ty.ty))
      (h.vb.objRef, h.vb.offset)
    }
    
    val syms = for (((obj, off), name) <- symFlds zip symStrings) yield FieldAndSymbol(obj, off, name)
    val relocs = for (((obj, off), name) <- relocFlds zip relocStrings) yield FieldAndSymbol(obj, off, name)
    
    microVM.bootImageBuilder.makeBootImage(whiteListObjs, primordial, syms, relocs, outputFile)
760
  }
Kunshan Wang's avatar
Kunshan Wang committed
761 762 763 764

  // Internal methods for the micro VM

  def handleFromInterpreterThread(thr: Option[InterpreterThread]): MuThreadRefValue = {
765
    val t = predefinedEntities.THREADREF
Kunshan Wang's avatar
Kunshan Wang committed
766 767 768 769 770
    val box = BoxThread(thr)
    addHandle(MuThreadRefValue(t, box))
  }

  def handleFromInterpreterStack(sta: Option[InterpreterStack]): MuStackRefValue = {
771
    val s = predefinedEntities.STACKREF
Kunshan Wang's avatar
Kunshan Wang committed
772 773 774 775 776
    val box = BoxStack(sta)
    addHandle(MuStackRefValue(s, box))
  }

  def handleFromAddr(addr: Long): MuRefValue = {
777
    val t = predefinedEntities.REF_VOID
Kunshan Wang's avatar
Kunshan Wang committed
778 779 780 781 782
    val box = BoxRef(addr)
    addHandle(MuRefValue(t, box))
  }
}